{"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hw2fw.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 08:18:28 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_transex3.hxx\"\n#include \n\nstruct hw_pair\n{\n sal_Unicode nFrom;\n sal_Unicode nTo;\n};\n\n#define MAKE_PAIR(a,b) { a, b }\n\nstatic struct hw_pair aHWPairs[] =\n{\n MAKE_PAIR( 0xFF65, 0x30FB ), \/\/ HALFWIDTH KATAKANA MIDDLE DOT --> KATAKANA MIDDLE DOT\n MAKE_PAIR( 0xFF66, 0x30F2 ), \/\/ HALFWIDTH KATAKANA LETTER WO --> KATAKANA LETTER WO\n MAKE_PAIR( 0xFF67, 0x30A1 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL A --> KATAKANA LETTER SMALL A\n MAKE_PAIR( 0xFF68, 0x30A3 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL I --> KATAKANA LETTER SMALL I\n MAKE_PAIR( 0xFF69, 0x30A5 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL U --> KATAKANA LETTER SMALL U\n MAKE_PAIR( 0xFF6A, 0x30A7 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL E --> KATAKANA LETTER SMALL E\n MAKE_PAIR( 0xFF6B, 0x30A9 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL O --> KATAKANA LETTER SMALL O\n MAKE_PAIR( 0xFF6C, 0x30E3 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL YA --> KATAKANA LETTER SMALL YA\n MAKE_PAIR( 0xFF6D, 0x30E5 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL YU --> KATAKANA LETTER SMALL YU\n MAKE_PAIR( 0xFF6E, 0x30E7 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL YO --> KATAKANA LETTER SMALL YO\n MAKE_PAIR( 0xFF6F, 0x30C3 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL TU --> KATAKANA LETTER SMALL TU\n MAKE_PAIR( 0xFF70, 0x30FC ), \/\/ HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK --> KATAKANA-HIRAGANA PROLONGED SOUND MARK\n MAKE_PAIR( 0xFF71, 0x30A2 ), \/\/ HALFWIDTH KATAKANA LETTER A --> KATAKANA LETTER A\n MAKE_PAIR( 0xFF72, 0x30A4 ), \/\/ HALFWIDTH KATAKANA LETTER I --> KATAKANA LETTER I\n MAKE_PAIR( 0xFF73, 0x30A6 ), \/\/ HALFWIDTH KATAKANA LETTER U --> KATAKANA LETTER U\n MAKE_PAIR( 0xFF74, 0x30A8 ), \/\/ HALFWIDTH KATAKANA LETTER E --> KATAKANA LETTER E\n MAKE_PAIR( 0xFF75, 0x30AA ), \/\/ HALFWIDTH KATAKANA LETTER O --> KATAKANA LETTER O\n MAKE_PAIR( 0xFF76, 0x30AB ), \/\/ HALFWIDTH KATAKANA LETTER KA --> KATAKANA LETTER KA\n MAKE_PAIR( 0xFF77, 0x30AD ), \/\/ HALFWIDTH KATAKANA LETTER KI --> KATAKANA LETTER KI\n MAKE_PAIR( 0xFF78, 0x30AF ), \/\/ HALFWIDTH KATAKANA LETTER KU --> KATAKANA LETTER KU\n MAKE_PAIR( 0xFF79, 0x30B1 ), \/\/ HALFWIDTH KATAKANA LETTER KE --> KATAKANA LETTER KE\n MAKE_PAIR( 0xFF7A, 0x30B3 ), \/\/ HALFWIDTH KATAKANA LETTER KO --> KATAKANA LETTER KO\n MAKE_PAIR( 0xFF7B, 0x30B5 ), \/\/ HALFWIDTH KATAKANA LETTER SA --> KATAKANA LETTER SA\n MAKE_PAIR( 0xFF7C, 0x30B7 ), \/\/ HALFWIDTH KATAKANA LETTER SI --> KATAKANA LETTER SI\n MAKE_PAIR( 0xFF7D, 0x30B9 ), \/\/ HALFWIDTH KATAKANA LETTER SU --> KATAKANA LETTER SU\n MAKE_PAIR( 0xFF7E, 0x30BB ), \/\/ HALFWIDTH KATAKANA LETTER SE --> KATAKANA LETTER SE\n MAKE_PAIR( 0xFF7F, 0x30BD ), \/\/ HALFWIDTH KATAKANA LETTER SO --> KATAKANA LETTER SO\n MAKE_PAIR( 0xFF80, 0x30BF ), \/\/ HALFWIDTH KATAKANA LETTER TA --> KATAKANA LETTER TA\n MAKE_PAIR( 0xFF81, 0x30C1 ), \/\/ HALFWIDTH KATAKANA LETTER TI --> KATAKANA LETTER TI\n MAKE_PAIR( 0xFF82, 0x30C4 ), \/\/ HALFWIDTH KATAKANA LETTER TU --> KATAKANA LETTER TU\n MAKE_PAIR( 0xFF83, 0x30C6 ), \/\/ HALFWIDTH KATAKANA LETTER TE --> KATAKANA LETTER TE\n MAKE_PAIR( 0xFF84, 0x30C8 ), \/\/ HALFWIDTH KATAKANA LETTER TO --> KATAKANA LETTER TO\n MAKE_PAIR( 0xFF85, 0x30CA ), \/\/ HALFWIDTH KATAKANA LETTER NA --> KATAKANA LETTER NA\n MAKE_PAIR( 0xFF86, 0x30CB ), \/\/ HALFWIDTH KATAKANA LETTER NI --> KATAKANA LETTER NI\n MAKE_PAIR( 0xFF87, 0x30CC ), \/\/ HALFWIDTH KATAKANA LETTER NU --> KATAKANA LETTER NU\n MAKE_PAIR( 0xFF88, 0x30CD ), \/\/ HALFWIDTH KATAKANA LETTER NE --> KATAKANA LETTER NE\n MAKE_PAIR( 0xFF89, 0x30CE ), \/\/ HALFWIDTH KATAKANA LETTER NO --> KATAKANA LETTER NO\n MAKE_PAIR( 0xFF8A, 0x30CF ), \/\/ HALFWIDTH KATAKANA LETTER HA --> KATAKANA LETTER HA\n MAKE_PAIR( 0xFF8B, 0x30D2 ), \/\/ HALFWIDTH KATAKANA LETTER HI --> KATAKANA LETTER HI\n MAKE_PAIR( 0xFF8C, 0x30D5 ), \/\/ HALFWIDTH KATAKANA LETTER HU --> KATAKANA LETTER HU\n MAKE_PAIR( 0xFF8D, 0x30D8 ), \/\/ HALFWIDTH KATAKANA LETTER HE --> KATAKANA LETTER HE\n MAKE_PAIR( 0xFF8E, 0x30DB ), \/\/ HALFWIDTH KATAKANA LETTER HO --> KATAKANA LETTER HO\n MAKE_PAIR( 0xFF8F, 0x30DE ), \/\/ HALFWIDTH KATAKANA LETTER MA --> KATAKANA LETTER MA\n MAKE_PAIR( 0xFF90, 0x30DF ), \/\/ HALFWIDTH KATAKANA LETTER MI --> KATAKANA LETTER MI\n MAKE_PAIR( 0xFF91, 0x30E0 ), \/\/ HALFWIDTH KATAKANA LETTER MU --> KATAKANA LETTER MU\n MAKE_PAIR( 0xFF92, 0x30E1 ), \/\/ HALFWIDTH KATAKANA LETTER ME --> KATAKANA LETTER ME\n MAKE_PAIR( 0xFF93, 0x30E2 ), \/\/ HALFWIDTH KATAKANA LETTER MO --> KATAKANA LETTER MO\n MAKE_PAIR( 0xFF94, 0x30E4 ), \/\/ HALFWIDTH KATAKANA LETTER YA --> KATAKANA LETTER YA\n MAKE_PAIR( 0xFF95, 0x30E6 ), \/\/ HALFWIDTH KATAKANA LETTER YU --> KATAKANA LETTER YU\n MAKE_PAIR( 0xFF96, 0x30E8 ), \/\/ HALFWIDTH KATAKANA LETTER YO --> KATAKANA LETTER YO\n MAKE_PAIR( 0xFF97, 0x30E9 ), \/\/ HALFWIDTH KATAKANA LETTER RA --> KATAKANA LETTER RA\n MAKE_PAIR( 0xFF98, 0x30EA ), \/\/ HALFWIDTH KATAKANA LETTER RI --> KATAKANA LETTER RI\n MAKE_PAIR( 0xFF99, 0x30EB ), \/\/ HALFWIDTH KATAKANA LETTER RU --> KATAKANA LETTER RU\n MAKE_PAIR( 0xFF9A, 0x30EC ), \/\/ HALFWIDTH KATAKANA LETTER RE --> KATAKANA LETTER RE\n MAKE_PAIR( 0xFF9B, 0x30ED ), \/\/ HALFWIDTH KATAKANA LETTER RO --> KATAKANA LETTER RO\n MAKE_PAIR( 0xFF9C, 0x30EF ), \/\/ HALFWIDTH KATAKANA LETTER WA --> KATAKANA LETTER WA\n MAKE_PAIR( 0xFF9D, 0x30F3 ), \/\/ HALFWIDTH KATAKANA LETTER N --> KATAKANA LETTER N\n MAKE_PAIR( 0xFF9E, 0x3099 ), \/\/ HALFWIDTH KATAKANA VOICED SOUND MARK --> COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK\n MAKE_PAIR( 0xFF9F, 0x309A ) \/\/ HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK --> COMBINING KATAKANA-\n};\n\n\nstatic struct hw_pair aCombine3099[] =\n{\n { 0x30a6, 0x30f4 },\n { 0x30ab, 0x30ac },\n { 0x30ad, 0x30ae },\n { 0x30af, 0x30b0 },\n { 0x30b1, 0x30b2 },\n { 0x30b3, 0x30b4 },\n { 0x30b5, 0x30b6 },\n { 0x30b7, 0x30b8 },\n { 0x30b9, 0x30ba },\n { 0x30bb, 0x30bc },\n { 0x30bd, 0x30be },\n { 0x30bf, 0x30c0 },\n { 0x30c1, 0x30c2 },\n { 0x30c4, 0x30c5 },\n { 0x30c6, 0x30c7 },\n { 0x30c8, 0x30c9 },\n { 0x30cf, 0x30d0 },\n { 0x30d2, 0x30d3 },\n { 0x30d5, 0x30d6 },\n { 0x30d8, 0x30d9 },\n { 0x30db, 0x30dc },\n { 0x30ef, 0x30f7 },\n { 0x30f0, 0x30f8 },\n { 0x30f1, 0x30f9 },\n { 0x30f2, 0x30fa },\n { 0x30fd, 0x30fe }\n};\n\nstatic struct hw_pair aCombine309A[] =\n{\n { 0x30cf, 0x30d1 },\n { 0x30d2, 0x30d4 },\n { 0x30d5, 0x30d7 },\n { 0x30d8, 0x30da },\n { 0x30db, 0x30dd }\n};\n\nUSHORT ImplReplaceFullWidth( sal_Unicode* pString, USHORT nLen )\n{\n sal_Unicode* pRead = pString;\n sal_Unicode* pWrite = pRead;\n USHORT nNewLen = nLen;\n\n while( (pRead - pString) < nLen )\n {\n if( pWrite != pRead )\n *pWrite = *pRead;\n\n if( *pRead >= 0xff65 && *pRead <= 0xff9f )\n {\n *pWrite = aHWPairs[ *pRead - 0xff65 ].nTo;\n\n struct hw_pair* pTable = NULL;\n int nTableEntries = 0;\n if( *pWrite == 0x3099 )\n {\n \/\/ replace 0x3099 combinations\n pTable = aCombine3099;\n nTableEntries = sizeof(aCombine3099)\/sizeof(aCombine3099[0]);\n }\n else if( *pWrite == 0x309a )\n {\n \/\/ replace 0x309a combinations\n pTable = aCombine309A;\n nTableEntries = sizeof(aCombine309A)\/sizeof(aCombine309A[0]);\n }\n if( pTable )\n {\n sal_Unicode c = pWrite[-1];\n for( int i = 0; i < nTableEntries; i++ )\n if( c == pTable[i].nFrom )\n {\n pWrite--;\n *pWrite = pTable[i].nTo;\n nNewLen--;\n break;\n }\n }\n }\n pRead++;\n pWrite++;\n }\n if( pWrite < pRead )\n *pWrite = 0;\n\n return nNewLen;\n}\n\nvoid ConvertHalfwitdhToFullwidth( String& rString )\n{\n USHORT nNewLen = ImplReplaceFullWidth( rString.GetBufferAccess(), rString.Len() );\n rString.ReleaseBufferAccess( nNewLen );\n}\nINTEGRATION: 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.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hw2fw.cxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_transex3.hxx\"\n#include \n\nstruct hw_pair\n{\n sal_Unicode nFrom;\n sal_Unicode nTo;\n};\n\n#define MAKE_PAIR(a,b) { a, b }\n\nstatic struct hw_pair aHWPairs[] =\n{\n MAKE_PAIR( 0xFF65, 0x30FB ), \/\/ HALFWIDTH KATAKANA MIDDLE DOT --> KATAKANA MIDDLE DOT\n MAKE_PAIR( 0xFF66, 0x30F2 ), \/\/ HALFWIDTH KATAKANA LETTER WO --> KATAKANA LETTER WO\n MAKE_PAIR( 0xFF67, 0x30A1 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL A --> KATAKANA LETTER SMALL A\n MAKE_PAIR( 0xFF68, 0x30A3 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL I --> KATAKANA LETTER SMALL I\n MAKE_PAIR( 0xFF69, 0x30A5 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL U --> KATAKANA LETTER SMALL U\n MAKE_PAIR( 0xFF6A, 0x30A7 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL E --> KATAKANA LETTER SMALL E\n MAKE_PAIR( 0xFF6B, 0x30A9 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL O --> KATAKANA LETTER SMALL O\n MAKE_PAIR( 0xFF6C, 0x30E3 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL YA --> KATAKANA LETTER SMALL YA\n MAKE_PAIR( 0xFF6D, 0x30E5 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL YU --> KATAKANA LETTER SMALL YU\n MAKE_PAIR( 0xFF6E, 0x30E7 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL YO --> KATAKANA LETTER SMALL YO\n MAKE_PAIR( 0xFF6F, 0x30C3 ), \/\/ HALFWIDTH KATAKANA LETTER SMALL TU --> KATAKANA LETTER SMALL TU\n MAKE_PAIR( 0xFF70, 0x30FC ), \/\/ HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK --> KATAKANA-HIRAGANA PROLONGED SOUND MARK\n MAKE_PAIR( 0xFF71, 0x30A2 ), \/\/ HALFWIDTH KATAKANA LETTER A --> KATAKANA LETTER A\n MAKE_PAIR( 0xFF72, 0x30A4 ), \/\/ HALFWIDTH KATAKANA LETTER I --> KATAKANA LETTER I\n MAKE_PAIR( 0xFF73, 0x30A6 ), \/\/ HALFWIDTH KATAKANA LETTER U --> KATAKANA LETTER U\n MAKE_PAIR( 0xFF74, 0x30A8 ), \/\/ HALFWIDTH KATAKANA LETTER E --> KATAKANA LETTER E\n MAKE_PAIR( 0xFF75, 0x30AA ), \/\/ HALFWIDTH KATAKANA LETTER O --> KATAKANA LETTER O\n MAKE_PAIR( 0xFF76, 0x30AB ), \/\/ HALFWIDTH KATAKANA LETTER KA --> KATAKANA LETTER KA\n MAKE_PAIR( 0xFF77, 0x30AD ), \/\/ HALFWIDTH KATAKANA LETTER KI --> KATAKANA LETTER KI\n MAKE_PAIR( 0xFF78, 0x30AF ), \/\/ HALFWIDTH KATAKANA LETTER KU --> KATAKANA LETTER KU\n MAKE_PAIR( 0xFF79, 0x30B1 ), \/\/ HALFWIDTH KATAKANA LETTER KE --> KATAKANA LETTER KE\n MAKE_PAIR( 0xFF7A, 0x30B3 ), \/\/ HALFWIDTH KATAKANA LETTER KO --> KATAKANA LETTER KO\n MAKE_PAIR( 0xFF7B, 0x30B5 ), \/\/ HALFWIDTH KATAKANA LETTER SA --> KATAKANA LETTER SA\n MAKE_PAIR( 0xFF7C, 0x30B7 ), \/\/ HALFWIDTH KATAKANA LETTER SI --> KATAKANA LETTER SI\n MAKE_PAIR( 0xFF7D, 0x30B9 ), \/\/ HALFWIDTH KATAKANA LETTER SU --> KATAKANA LETTER SU\n MAKE_PAIR( 0xFF7E, 0x30BB ), \/\/ HALFWIDTH KATAKANA LETTER SE --> KATAKANA LETTER SE\n MAKE_PAIR( 0xFF7F, 0x30BD ), \/\/ HALFWIDTH KATAKANA LETTER SO --> KATAKANA LETTER SO\n MAKE_PAIR( 0xFF80, 0x30BF ), \/\/ HALFWIDTH KATAKANA LETTER TA --> KATAKANA LETTER TA\n MAKE_PAIR( 0xFF81, 0x30C1 ), \/\/ HALFWIDTH KATAKANA LETTER TI --> KATAKANA LETTER TI\n MAKE_PAIR( 0xFF82, 0x30C4 ), \/\/ HALFWIDTH KATAKANA LETTER TU --> KATAKANA LETTER TU\n MAKE_PAIR( 0xFF83, 0x30C6 ), \/\/ HALFWIDTH KATAKANA LETTER TE --> KATAKANA LETTER TE\n MAKE_PAIR( 0xFF84, 0x30C8 ), \/\/ HALFWIDTH KATAKANA LETTER TO --> KATAKANA LETTER TO\n MAKE_PAIR( 0xFF85, 0x30CA ), \/\/ HALFWIDTH KATAKANA LETTER NA --> KATAKANA LETTER NA\n MAKE_PAIR( 0xFF86, 0x30CB ), \/\/ HALFWIDTH KATAKANA LETTER NI --> KATAKANA LETTER NI\n MAKE_PAIR( 0xFF87, 0x30CC ), \/\/ HALFWIDTH KATAKANA LETTER NU --> KATAKANA LETTER NU\n MAKE_PAIR( 0xFF88, 0x30CD ), \/\/ HALFWIDTH KATAKANA LETTER NE --> KATAKANA LETTER NE\n MAKE_PAIR( 0xFF89, 0x30CE ), \/\/ HALFWIDTH KATAKANA LETTER NO --> KATAKANA LETTER NO\n MAKE_PAIR( 0xFF8A, 0x30CF ), \/\/ HALFWIDTH KATAKANA LETTER HA --> KATAKANA LETTER HA\n MAKE_PAIR( 0xFF8B, 0x30D2 ), \/\/ HALFWIDTH KATAKANA LETTER HI --> KATAKANA LETTER HI\n MAKE_PAIR( 0xFF8C, 0x30D5 ), \/\/ HALFWIDTH KATAKANA LETTER HU --> KATAKANA LETTER HU\n MAKE_PAIR( 0xFF8D, 0x30D8 ), \/\/ HALFWIDTH KATAKANA LETTER HE --> KATAKANA LETTER HE\n MAKE_PAIR( 0xFF8E, 0x30DB ), \/\/ HALFWIDTH KATAKANA LETTER HO --> KATAKANA LETTER HO\n MAKE_PAIR( 0xFF8F, 0x30DE ), \/\/ HALFWIDTH KATAKANA LETTER MA --> KATAKANA LETTER MA\n MAKE_PAIR( 0xFF90, 0x30DF ), \/\/ HALFWIDTH KATAKANA LETTER MI --> KATAKANA LETTER MI\n MAKE_PAIR( 0xFF91, 0x30E0 ), \/\/ HALFWIDTH KATAKANA LETTER MU --> KATAKANA LETTER MU\n MAKE_PAIR( 0xFF92, 0x30E1 ), \/\/ HALFWIDTH KATAKANA LETTER ME --> KATAKANA LETTER ME\n MAKE_PAIR( 0xFF93, 0x30E2 ), \/\/ HALFWIDTH KATAKANA LETTER MO --> KATAKANA LETTER MO\n MAKE_PAIR( 0xFF94, 0x30E4 ), \/\/ HALFWIDTH KATAKANA LETTER YA --> KATAKANA LETTER YA\n MAKE_PAIR( 0xFF95, 0x30E6 ), \/\/ HALFWIDTH KATAKANA LETTER YU --> KATAKANA LETTER YU\n MAKE_PAIR( 0xFF96, 0x30E8 ), \/\/ HALFWIDTH KATAKANA LETTER YO --> KATAKANA LETTER YO\n MAKE_PAIR( 0xFF97, 0x30E9 ), \/\/ HALFWIDTH KATAKANA LETTER RA --> KATAKANA LETTER RA\n MAKE_PAIR( 0xFF98, 0x30EA ), \/\/ HALFWIDTH KATAKANA LETTER RI --> KATAKANA LETTER RI\n MAKE_PAIR( 0xFF99, 0x30EB ), \/\/ HALFWIDTH KATAKANA LETTER RU --> KATAKANA LETTER RU\n MAKE_PAIR( 0xFF9A, 0x30EC ), \/\/ HALFWIDTH KATAKANA LETTER RE --> KATAKANA LETTER RE\n MAKE_PAIR( 0xFF9B, 0x30ED ), \/\/ HALFWIDTH KATAKANA LETTER RO --> KATAKANA LETTER RO\n MAKE_PAIR( 0xFF9C, 0x30EF ), \/\/ HALFWIDTH KATAKANA LETTER WA --> KATAKANA LETTER WA\n MAKE_PAIR( 0xFF9D, 0x30F3 ), \/\/ HALFWIDTH KATAKANA LETTER N --> KATAKANA LETTER N\n MAKE_PAIR( 0xFF9E, 0x3099 ), \/\/ HALFWIDTH KATAKANA VOICED SOUND MARK --> COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK\n MAKE_PAIR( 0xFF9F, 0x309A ) \/\/ HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK --> COMBINING KATAKANA-\n};\n\n\nstatic struct hw_pair aCombine3099[] =\n{\n { 0x30a6, 0x30f4 },\n { 0x30ab, 0x30ac },\n { 0x30ad, 0x30ae },\n { 0x30af, 0x30b0 },\n { 0x30b1, 0x30b2 },\n { 0x30b3, 0x30b4 },\n { 0x30b5, 0x30b6 },\n { 0x30b7, 0x30b8 },\n { 0x30b9, 0x30ba },\n { 0x30bb, 0x30bc },\n { 0x30bd, 0x30be },\n { 0x30bf, 0x30c0 },\n { 0x30c1, 0x30c2 },\n { 0x30c4, 0x30c5 },\n { 0x30c6, 0x30c7 },\n { 0x30c8, 0x30c9 },\n { 0x30cf, 0x30d0 },\n { 0x30d2, 0x30d3 },\n { 0x30d5, 0x30d6 },\n { 0x30d8, 0x30d9 },\n { 0x30db, 0x30dc },\n { 0x30ef, 0x30f7 },\n { 0x30f0, 0x30f8 },\n { 0x30f1, 0x30f9 },\n { 0x30f2, 0x30fa },\n { 0x30fd, 0x30fe }\n};\n\nstatic struct hw_pair aCombine309A[] =\n{\n { 0x30cf, 0x30d1 },\n { 0x30d2, 0x30d4 },\n { 0x30d5, 0x30d7 },\n { 0x30d8, 0x30da },\n { 0x30db, 0x30dd }\n};\n\nUSHORT ImplReplaceFullWidth( sal_Unicode* pString, USHORT nLen )\n{\n sal_Unicode* pRead = pString;\n sal_Unicode* pWrite = pRead;\n USHORT nNewLen = nLen;\n\n while( (pRead - pString) < nLen )\n {\n if( pWrite != pRead )\n *pWrite = *pRead;\n\n if( *pRead >= 0xff65 && *pRead <= 0xff9f )\n {\n *pWrite = aHWPairs[ *pRead - 0xff65 ].nTo;\n\n struct hw_pair* pTable = NULL;\n int nTableEntries = 0;\n if( *pWrite == 0x3099 )\n {\n \/\/ replace 0x3099 combinations\n pTable = aCombine3099;\n nTableEntries = sizeof(aCombine3099)\/sizeof(aCombine3099[0]);\n }\n else if( *pWrite == 0x309a )\n {\n \/\/ replace 0x309a combinations\n pTable = aCombine309A;\n nTableEntries = sizeof(aCombine309A)\/sizeof(aCombine309A[0]);\n }\n if( pTable )\n {\n sal_Unicode c = pWrite[-1];\n for( int i = 0; i < nTableEntries; i++ )\n if( c == pTable[i].nFrom )\n {\n pWrite--;\n *pWrite = pTable[i].nTo;\n nNewLen--;\n break;\n }\n }\n }\n pRead++;\n pWrite++;\n }\n if( pWrite < pRead )\n *pWrite = 0;\n\n return nNewLen;\n}\n\nvoid ConvertHalfwitdhToFullwidth( String& rString )\n{\n USHORT nNewLen = ImplReplaceFullWidth( rString.GetBufferAccess(), rString.Len() );\n rString.ReleaseBufferAccess( nNewLen );\n}\n<|endoftext|>"} {"text":"\/*\n * Joey Button\n * Felix Wang\n * Peter Wang\n *\/\n\n#include \n#include \n#include \"opencv2\/opencv.hpp\"\n#include \"physics.h\"\n\nusing namespace cv;\nusing namespace std;\n\nconst char *win = \"Flying Pancake\";\nstatic bool reverseMirror = false;\n\nint main(int argc, char **argv)\n{\n if (argc > 2) {\n fprintf(stderr, \"Error: Please limit arguments to 1 or none.\\n\");\n exit(1);\n }\n else if (argc == 2) {\n if (!strcmp(argv[1], \"-m\"))\n reverseMirror = true;\n else {\n fprintf(stderr, \"Usage: videoBall [-m]\\n\");\n exit(1); \n }\n }\n \n int cam = 0; \/\/ default camera\n VideoCapture cap(cam);\n if (!cap.isOpened()) {\n fprintf(stderr, \"Error: Cannot open camera %d\\n\", cam);\n exit(1);\n }\n\n namedWindow(win, CV_WINDOW_AUTOSIZE);\n\n Mat fgMaskMOG; \/\/ foreground mask generated by MOG method\n Mat inputFrame, outFrame;\n Mat circ;\n Point pt; \/\/ center of the ball\n\n BackgroundSubtractorMOG2 MOG;\n\n pt.x = 500;\n pt.y = 0;\n\n Point momentum;\n momentum.x = 10;\n momentum.y = 50;\n\n cap >> inputFrame;\n cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);\n cvtColor(inputFrame, circ, CV_BGR2GRAY);\n\n int height = inputFrame.rows - 2 * RADIUS;\n int width = inputFrame.cols - 2 * RADIUS;\n\n \/\/ double overlap;\n int count = 0;\n int sum;\n Point small;\n Mat ballFrame, handFrame;\n Mat foregroundMask, backgroundMask;\n Mat reverseFrame;\n while (++count) {\n cap >> inputFrame;\n \n if (reverseMirror) {\n inputFrame.copyTo(reverseFrame);\n flip(reverseFrame, inputFrame, 1); \/\/ 1 ~ flip against y axis\n }\n\n calcDir(&momentum, &pt, height, width);\n\n MOG(inputFrame, fgMaskMOG);\n \n \/\/ blank canvas\n circ.setTo(Scalar(0,0,0));\n\n Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS);\n ballFrame = circ(ballRegion);\n\n foregroundMask = fgMaskMOG > THRESH; \/\/ have to put here otherwise floating point exception\n backgroundMask = fgMaskMOG <= THRESH;\n fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask); \/\/ clean up\n fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask);\n handFrame = fgMaskMOG(ballRegion); \/\/ cut to small size\n\n int halfRad = RADIUS \/ 2;\n \/\/ top left\n small.x = halfRad; small.y = halfRad;\n sum = getOverlap(&ballFrame, &handFrame, &small);\n momentum.x += sum*3; momentum.y += sum*3;\n\n \/\/ top right\n small.x = 3 * halfRad; small.y = halfRad;\n sum = getOverlap(&ballFrame, &handFrame, &small);\n momentum.x -= sum*2; momentum.y += sum*3;\n\n\n \/\/ bottom left\n small.x = halfRad; small.y = 3 * halfRad;\n sum = getOverlap(&ballFrame, &handFrame, &small);\n momentum.x += sum*3; momentum.y -= sum*2;\n\n \/\/ bottom right\n small.x = 3 * halfRad; small.y = 3 * halfRad;\n sum = getOverlap(&ballFrame, &handFrame, &small);\n momentum.x -= sum*2; momentum.y -= sum*2;\n\n \/\/ EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame\n outFrame.setTo(Scalar(0,0,0)); \/\/ set all of outFrame to be black\n outFrame.setTo(Scalar(255, 255, 255), foregroundMask);\n\n drawCircle(outFrame, pt, RADIUS);\n\n imshow(win, outFrame);\n if (count%30 == 0){\n printf(\"m.x: %d\\tm.y: %d\\n\",momentum.x,momentum.y);\n }\n if (waitKey(1) >= 0) \/\/ listening for key press\n\t break;\n }\n\n return 0;\n}\nRemoving print statement\/*\n * Joey Button\n * Felix Wang\n * Peter Wang\n *\/\n\n#include \n#include \n#include \"opencv2\/opencv.hpp\"\n#include \"physics.h\"\n\nusing namespace cv;\nusing namespace std;\n\nconst char *win = \"Flying Pancake\";\nstatic bool reverseMirror = false;\n\nint main(int argc, char **argv)\n{\n if (argc > 2) {\n fprintf(stderr, \"Error: Please limit arguments to 1 or none.\\n\");\n exit(1);\n }\n else if (argc == 2) {\n if (!strcmp(argv[1], \"-m\"))\n reverseMirror = true;\n else {\n fprintf(stderr, \"Usage: videoBall [-m]\\n\");\n exit(1);\n }\n }\n\n int cam = 0; \/\/ default camera\n VideoCapture cap(cam);\n if (!cap.isOpened()) {\n fprintf(stderr, \"Error: Cannot open camera %d\\n\", cam);\n exit(1);\n }\n\n namedWindow(win, CV_WINDOW_AUTOSIZE);\n\n Mat fgMaskMOG; \/\/ foreground mask generated by MOG method\n Mat inputFrame, outFrame;\n Mat circ;\n Point pt; \/\/ center of the ball\n\n BackgroundSubtractorMOG2 MOG;\n\n pt.x = 500;\n pt.y = 0;\n\n Point momentum;\n momentum.x = 10;\n momentum.y = 50;\n\n cap >> inputFrame;\n cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);\n cvtColor(inputFrame, circ, CV_BGR2GRAY);\n\n int height = inputFrame.rows - 2 * RADIUS;\n int width = inputFrame.cols - 2 * RADIUS;\n\n \/\/ double overlap;\n int count = 0;\n int sum;\n Point small;\n Mat ballFrame, handFrame;\n Mat foregroundMask, backgroundMask;\n Mat reverseFrame;\n while (++count) {\n cap >> inputFrame;\n\n if (reverseMirror) {\n inputFrame.copyTo(reverseFrame);\n flip(reverseFrame, inputFrame, 1); \/\/ 1 ~ flip against y axis\n }\n\n calcDir(&momentum, &pt, height, width);\n\n MOG(inputFrame, fgMaskMOG);\n\n \/\/ blank canvas\n circ.setTo(Scalar(0,0,0));\n\n Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS);\n ballFrame = circ(ballRegion);\n\n foregroundMask = fgMaskMOG > THRESH; \/\/ have to put here otherwise floating point exception\n backgroundMask = fgMaskMOG <= THRESH;\n fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask); \/\/ clean up\n fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask);\n handFrame = fgMaskMOG(ballRegion); \/\/ cut to small size\n\n int halfRad = RADIUS \/ 2;\n \/\/ top left\n small.x = halfRad; small.y = halfRad;\n sum = getOverlap(&ballFrame, &handFrame, &small);\n momentum.x += sum*3; momentum.y += sum*3;\n\n \/\/ top right\n small.x = 3 * halfRad; small.y = halfRad;\n sum = getOverlap(&ballFrame, &handFrame, &small);\n momentum.x -= sum*2; momentum.y += sum*3;\n\n\n \/\/ bottom left\n small.x = halfRad; small.y = 3 * halfRad;\n sum = getOverlap(&ballFrame, &handFrame, &small);\n momentum.x += sum*3; momentum.y -= sum*2;\n\n \/\/ bottom right\n small.x = 3 * halfRad; small.y = 3 * halfRad;\n sum = getOverlap(&ballFrame, &handFrame, &small);\n momentum.x -= sum*2; momentum.y -= sum*2;\n\n \/\/ EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame\n outFrame.setTo(Scalar(0,0,0)); \/\/ set all of outFrame to be black\n outFrame.setTo(Scalar(255, 255, 255), foregroundMask);\n\n drawCircle(outFrame, pt, RADIUS);\n\n imshow(win, outFrame);\n\n if (waitKey(1) >= 0) \/\/ listening for key press\n\t break;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n screen.cpp\n Classic Invaders\n\n Copyright (c) 2013, Todd Steinackle, Simon Que\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted\n provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions\n and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the documentation and\/or other\n materials provided with the distribution.\n\n * Neither the name of The No Quarter Arcade (http:\/\/www.noquarterarcade.com\/) nor the names of\n its contributors may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"screen.h\"\n\n#include \n\n#include \n\n#include \"game_entity.h\"\n#include \"printf.h\"\n\n\/\/ TODO: This should be included from a ChronoCube library file.\n#define MAX_NUM_SPRITES 128\n\n#define DEFAULT_COLOR_KEY 0xff\n\n#define SPRITE_LAYER_INDEX 3\n\nextern uint16_t g_vram_offsets[];\n\nnamespace {\n\n \/\/ Values of the sprite dimension fields in the sprite control register.\n enum {\n SPRITE_DIMENSION_8,\n SPRITE_DIMENSION_16,\n SPRITE_DIMENSION_32,\n SPRITE_DIMENSION_64,\n };\n\n \/\/ Gets the sprite dimension code for a given dimension that is one of:\n \/\/ 8, 16, 32, 64.\n \/\/ If it doesn't match any of these, returns the code for 8.\n uint8_t get_sprite_dimension(uint8_t size) {\n switch(size) {\n case 64:\n return SPRITE_DIMENSION_64;\n case 32:\n return SPRITE_DIMENSION_32;\n case 16:\n return SPRITE_DIMENSION_16;\n case 8:\n default:\n return SPRITE_DIMENSION_8;\n }\n }\n\n}\n\nnamespace Graphics {\n Screen::Screen() : allocated_vram_size(0) {}\n\n bool Screen::init() {\n memset(num_sprites_per_type, 0, sizeof(num_sprites_per_type));\n memset(sprite_index_bases, 0, sizeof(sprite_index_bases));\n\n DC.Core.writeWord(REG_SPRITE_Z, SPRITE_LAYER_INDEX);\n\n return true;\n }\n\n void Screen::begin_update() {\n \/\/ Wait for the start of vertical blank, at which point it is safe to\n \/\/ modify the contents of the video controller.\n while (!(DC.Core.readWord(REG_OUTPUT_STATUS) & (1 << REG_VBLANK)));\n }\n\n void Screen::update() {\n \/\/ Wait for the end of vertical blank. This is when the drawing\n \/\/ actually begins.\n while ((DC.Core.readWord(REG_OUTPUT_STATUS) & (1 << REG_VBLANK)));\n }\n\n void Screen::allocate_sprites(const int* num_objects_per_type) {\n uint16_t sprite_index = 0;\n for (int type = 0;\n type < NUM_GAME_ENTITY_TYPES && sprite_index < MAX_NUM_SPRITES;\n ++type) {\n \/\/ Store the number of sprites and first sprite index for each type.\n int num_objects_of_type = num_objects_per_type[type];\n num_sprites_per_type[type] = num_objects_of_type;\n sprite_index_bases[type] = sprite_index;\n printf_P(\"Allocated %u sprites starting at %u for object type %d\\n\",\n num_objects_of_type, sprite_index, type);\n\n if (num_objects_of_type == 0)\n continue;\n\n const GameEntities::GameEntityTypeProperties* properties =\n GameEntities::GameEntity::get_type_property(type);\n\n uint8_t sprite_w = get_sprite_dimension(properties->sprite_w);\n uint8_t sprite_h = get_sprite_dimension(properties->sprite_h);\n \/\/ Initialize each sprite's dimensions, color key, and data offset.\n for (int i = 0; i < num_objects_of_type; ++i) {\n DC.Core.writeWord(SPRITE_REG(i, SPRITE_CTRL_1),\n (sprite_w << SPRITE_HSIZE_0) |\n (sprite_h << SPRITE_VSIZE_0));\n DC.Core.writeWord(SPRITE_REG(i, SPRITE_COLOR_KEY),\n DEFAULT_COLOR_KEY);\n DC.Core.writeWord(SPRITE_REG(i, SPRITE_DATA_OFFSET),\n get_image_offset(type));\n }\n\n sprite_index += num_objects_of_type;\n }\n if (sprite_index == MAX_NUM_SPRITES) {\n printf_P(\"Attempted to allocate too many sprites: %d\\n\",\n sprite_index);\n }\n }\n\n void Screen::set_palette_data(uint8_t palette, const void* palette_data,\n uint16_t size) {\n DC.Core.writeData(PALETTE(palette), palette_data, size);\n }\n\n void Screen::set_palette_entry(uint8_t palette, uint8_t entry,\n uint8_t r, uint8_t g, uint8_t b) {\n struct {\n uint8_t r;\n uint8_t g;\n uint8_t b;\n uint8_t padding;\n } palette_entry;\n palette_entry.r = r;\n palette_entry.g = g;\n palette_entry.b = b;\n palette_entry.padding = 0;\n DC.Core.writeData(PALETTE(palette) + sizeof(palette_entry) * entry,\n &palette_entry, sizeof(palette_entry));\n }\n\n void Screen::setup_tile_layer(uint8_t layer, bool enabled, uint8_t palette,\n uint16_t data_offset, uint16_t color_key) {\n uint16_t tile_ctrl0_value =\n ((enabled ? 1 : 0) << TILE_LAYER_ENABLED) |\n (1 << TILE_ENABLE_NOP) |\n (1 << TILE_ENABLE_TRANSP) |\n (1 << TILE_ENABLE_FLIP) |\n (palette << TILE_PALETTE_START);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_CTRL_0), tile_ctrl0_value);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_DATA_OFFSET), data_offset);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_EMPTY_VALUE), 0);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_COLOR_KEY), color_key);\n }\n\n void Screen::scroll_tile_layer(uint8_t layer, int16_t x, int16_t y) {\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_OFFSET_X), x);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_OFFSET_Y), y);\n }\n\n void Screen::set_tilemap_data(uint8_t layer, uint8_t x, uint8_t y,\n const void* tilemap_data, uint16_t size) {\n#define TILEMAP_WIDTH 32\n uint16_t offset = (x + y * TILEMAP_WIDTH) * sizeof(uint16_t);\n DC.Core.writeData(TILEMAP(layer) + offset, tilemap_data, size);\n#undef TILEMAP_WIDTH;\n }\n\n uint16_t Screen::get_image_offset(int type) const {\n return g_vram_offsets[type];\n }\n\n void Screen::update_sprite(const GameEntities::GameEntity* object) {\n uint8_t type = object->get_type();\n if (num_sprites_per_type[type] == 0)\n return;\n uint8_t index = object->get_index();\n\n int x = object->get_x();\n int y = object->get_y();\n\n const GameEntities::GameEntityTypeProperties* properties =\n GameEntities::GameEntity::get_type_property(type);\n uint8_t sprite_w = properties->sprite_w;\n uint8_t sprite_h = properties->sprite_h;\n uint16_t offset = get_image_offset(type) +\n (sprite_w * sprite_h) * object->get_current_image();\n uint16_t sprite_index = sprite_index_bases[type] + index;\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_CTRL_0),\n object->is_alive() |\n (1 << SPRITE_ENABLE_TRANSP));\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_DATA_OFFSET), offset);\n \/\/ TODO: this needs to be faster.\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_OFFSET_X), x);\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_OFFSET_Y), y);\n }\n\n}\nFix sprite assignments in Screen\/*\n screen.cpp\n Classic Invaders\n\n Copyright (c) 2013, Todd Steinackle, Simon Que\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted\n provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions\n and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the documentation and\/or other\n materials provided with the distribution.\n\n * Neither the name of The No Quarter Arcade (http:\/\/www.noquarterarcade.com\/) nor the names of\n its contributors may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"screen.h\"\n\n#include \n\n#include \n\n#include \"game_entity.h\"\n#include \"printf.h\"\n\n\/\/ TODO: This should be included from a ChronoCube library file.\n#define MAX_NUM_SPRITES 128\n\n#define DEFAULT_COLOR_KEY 0xff\n\n#define SPRITE_LAYER_INDEX 3\n\nextern uint16_t g_vram_offsets[];\n\nnamespace {\n\n \/\/ Values of the sprite dimension fields in the sprite control register.\n enum {\n SPRITE_DIMENSION_8,\n SPRITE_DIMENSION_16,\n SPRITE_DIMENSION_32,\n SPRITE_DIMENSION_64,\n };\n\n \/\/ Gets the sprite dimension code for a given dimension that is one of:\n \/\/ 8, 16, 32, 64.\n \/\/ If it doesn't match any of these, returns the code for 8.\n uint8_t get_sprite_dimension(uint8_t size) {\n switch(size) {\n case 64:\n return SPRITE_DIMENSION_64;\n case 32:\n return SPRITE_DIMENSION_32;\n case 16:\n return SPRITE_DIMENSION_16;\n case 8:\n default:\n return SPRITE_DIMENSION_8;\n }\n }\n\n}\n\nnamespace Graphics {\n Screen::Screen() : allocated_vram_size(0) {}\n\n bool Screen::init() {\n memset(num_sprites_per_type, 0, sizeof(num_sprites_per_type));\n memset(sprite_index_bases, 0, sizeof(sprite_index_bases));\n\n DC.Core.writeWord(REG_SPRITE_Z, SPRITE_LAYER_INDEX);\n\n return true;\n }\n\n void Screen::begin_update() {\n \/\/ Wait for the start of vertical blank, at which point it is safe to\n \/\/ modify the contents of the video controller.\n while (!(DC.Core.readWord(REG_OUTPUT_STATUS) & (1 << REG_VBLANK)));\n }\n\n void Screen::update() {\n \/\/ Wait for the end of vertical blank. This is when the drawing\n \/\/ actually begins.\n while ((DC.Core.readWord(REG_OUTPUT_STATUS) & (1 << REG_VBLANK)));\n }\n\n void Screen::allocate_sprites(const int* num_objects_per_type) {\n uint16_t sprite_index = 0;\n for (int type = 0; type < NUM_GAME_ENTITY_TYPES; ++type) {\n int num_objects_of_type = num_objects_per_type[type];\n\n \/\/ Make sure there's enough room for these sprites.\n if (sprite_index + num_objects_of_type >= MAX_NUM_SPRITES) {\n printf_P(\"Attempted to allocate too many sprites: %d\\n\",\n sprite_index);\n break;\n }\n\n \/\/ Store the number of sprites and first sprite index for each type.\n num_sprites_per_type[type] = num_objects_of_type;\n sprite_index_bases[type] = sprite_index;\n printf_P(\"Allocated %u sprites starting at %u for object type %d\\n\",\n num_objects_of_type, sprite_index, type);\n\n if (num_objects_of_type == 0)\n continue;\n\n const GameEntities::GameEntityTypeProperties* properties =\n GameEntities::GameEntity::get_type_property(type);\n\n uint8_t sprite_w = get_sprite_dimension(properties->sprite_w);\n uint8_t sprite_h = get_sprite_dimension(properties->sprite_h);\n \/\/ Initialize each sprite's dimensions, color key, and data offset.\n for (int i = 0; i < num_objects_of_type; ++i, ++sprite_index) {\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_CTRL_1),\n (sprite_w << SPRITE_HSIZE_0) |\n (sprite_h << SPRITE_VSIZE_0));\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_COLOR_KEY),\n DEFAULT_COLOR_KEY);\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_DATA_OFFSET),\n get_image_offset(type));\n }\n }\n }\n\n void Screen::set_palette_data(uint8_t palette, const void* palette_data,\n uint16_t size) {\n DC.Core.writeData(PALETTE(palette), palette_data, size);\n }\n\n void Screen::set_palette_entry(uint8_t palette, uint8_t entry,\n uint8_t r, uint8_t g, uint8_t b) {\n struct {\n uint8_t r;\n uint8_t g;\n uint8_t b;\n uint8_t padding;\n } palette_entry;\n palette_entry.r = r;\n palette_entry.g = g;\n palette_entry.b = b;\n palette_entry.padding = 0;\n DC.Core.writeData(PALETTE(palette) + sizeof(palette_entry) * entry,\n &palette_entry, sizeof(palette_entry));\n }\n\n void Screen::setup_tile_layer(uint8_t layer, bool enabled, uint8_t palette,\n uint16_t data_offset, uint16_t color_key) {\n uint16_t tile_ctrl0_value =\n ((enabled ? 1 : 0) << TILE_LAYER_ENABLED) |\n (1 << TILE_ENABLE_NOP) |\n (1 << TILE_ENABLE_TRANSP) |\n (1 << TILE_ENABLE_FLIP) |\n (palette << TILE_PALETTE_START);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_CTRL_0), tile_ctrl0_value);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_DATA_OFFSET), data_offset);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_EMPTY_VALUE), 0);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_COLOR_KEY), color_key);\n }\n\n void Screen::scroll_tile_layer(uint8_t layer, int16_t x, int16_t y) {\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_OFFSET_X), x);\n DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_OFFSET_Y), y);\n }\n\n void Screen::set_tilemap_data(uint8_t layer, uint8_t x, uint8_t y,\n const void* tilemap_data, uint16_t size) {\n#define TILEMAP_WIDTH 32\n uint16_t offset = (x + y * TILEMAP_WIDTH) * sizeof(uint16_t);\n DC.Core.writeData(TILEMAP(layer) + offset, tilemap_data, size);\n#undef TILEMAP_WIDTH;\n }\n\n uint16_t Screen::get_image_offset(int type) const {\n return g_vram_offsets[type];\n }\n\n void Screen::update_sprite(const GameEntities::GameEntity* object) {\n uint8_t type = object->get_type();\n if (num_sprites_per_type[type] == 0)\n return;\n uint8_t index = object->get_index();\n\n int x = object->get_x();\n int y = object->get_y();\n\n const GameEntities::GameEntityTypeProperties* properties =\n GameEntities::GameEntity::get_type_property(type);\n uint8_t sprite_w = properties->sprite_w;\n uint8_t sprite_h = properties->sprite_h;\n uint16_t offset = get_image_offset(type) +\n (sprite_w * sprite_h) * object->get_current_image();\n uint16_t sprite_index = sprite_index_bases[type] + index;\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_CTRL_0),\n object->is_alive() |\n (1 << SPRITE_ENABLE_TRANSP));\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_DATA_OFFSET), offset);\n \/\/ TODO: this needs to be faster.\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_OFFSET_X), x);\n DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_OFFSET_Y), y);\n }\n\n}\n<|endoftext|>"} {"text":"\/* This file is part of the KDE project\n Copyright (C) 2005-2006 Matthias Kretz \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n#include \"videopath.h\"\n#include \"videopath_p.h\"\n#include \"factory.h\"\n\n#include \"videoeffect.h\"\n#include \"abstractvideooutput.h\"\n\n#define PHONON_CLASSNAME VideoPath\n\nnamespace Phonon\n{\nPHONON_OBJECT_IMPL\n\nVideoPath::~VideoPath()\n{\n\tK_D( VideoPath );\n foreach(AbstractVideoOutput* vo, d->outputs)\n d->removeDestructionHandler(vo, d);\n foreach(VideoEffect* ve, d->effects)\n d->removeDestructionHandler(ve, d);\n}\n\nbool VideoPath::addOutput( AbstractVideoOutput* videoOutput )\n{\n\tK_D( VideoPath );\n\tif( d->outputs.contains( videoOutput ) )\n\t\treturn false;\n\n\tif( iface() )\n\t{\n\t\tbool success;\n\t\tBACKEND_GET1( bool, success, \"addOutput\", QObject*, videoOutput->iface() );\n\t\tif( success )\n\t\t{\n d->addDestructionHandler(videoOutput, d);\n\t\t\td->outputs << videoOutput;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool VideoPath::removeOutput( AbstractVideoOutput* videoOutput )\n{\n\tK_D( VideoPath );\n\tif( !d->outputs.contains( videoOutput ) )\n\t\treturn false;\n\n\tif( d->backendObject )\n\t{\n\t\tbool success;\n\t\tBACKEND_GET1( bool, success, \"removeOutput\", QObject*, videoOutput->iface() );\n\t\tif( success )\n\t\t{\n\t\t\td->outputs.removeAll( videoOutput );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nconst QList& VideoPath::outputs() const\n{\n\tK_D( const VideoPath );\n\treturn d->outputs;\n}\n\nbool VideoPath::insertEffect( VideoEffect* newEffect, VideoEffect* insertBefore )\n{\n\t\/\/ effects may be added multiple times, but that means the objects are\n\t\/\/ different (the class is still the same)\n\tK_D( VideoPath );\n\tif( d->effects.contains( newEffect ) )\n\t\treturn false;\n\n\tif( iface() )\n\t{\n\t\tbool success;\n\t\tBACKEND_GET2( bool, success, \"insertEffect\", QObject*, newEffect->iface(), QObject*, insertBefore ? insertBefore->iface() : 0 );\n\t\tif( success )\n\t\t{\n d->addDestructionHandler(newEffect, d);\n\t\t\tif( insertBefore )\n\t\t\t\td->effects.insert( d->effects.indexOf( insertBefore ), newEffect );\n\t\t\telse\n\t\t\t\td->effects << newEffect;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool VideoPath::removeEffect( VideoEffect* effect )\n{\n\tK_D( VideoPath );\n\tif( !d->effects.contains( effect ) )\n\t\treturn false;\n\n\tif( d->backendObject )\n\t{\n\t\tbool success;\n\t\tBACKEND_GET1( bool, success, \"removeEffect\", QObject*, effect->iface() );\n\t\tif( success )\n\t\t{\n\t\t\td->effects.removeAll( effect );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nconst QList& VideoPath::effects() const\n{\n\tK_D( const VideoPath );\n\treturn d->effects;\n}\n\nbool VideoPathPrivate::aboutToDeleteIface()\n{\n\treturn true;\n}\n\nvoid VideoPath::setupIface()\n{\n\tK_D( VideoPath );\n\tQ_ASSERT( d->backendObject );\n\n\t\/\/ set up attributes\n\tbool success;\n\tQList outputList = d->outputs;\n\tforeach( AbstractVideoOutput* output, outputList )\n\t{\n\t\tBACKEND_GET1( bool, success, \"addOutput\", QObject*, output->iface() );\n\t\tif( !success )\n\t\t\td->outputs.removeAll( output );\n\t}\n\n\tQList effectList = d->effects;\n\tforeach( VideoEffect* effect, effectList )\n\t{\n\t\tBACKEND_GET1( bool, success, \"insertEffect\", QObject*, effect->iface() );\n\t\tif( !success )\n\t\t\td->effects.removeAll( effect );\n\t}\n}\n\nvoid VideoPathPrivate::phononObjectDestroyed( Base* o )\n{\n\t\/\/ this method is called from Phonon::Base::~Base(), meaning the VideoEffect\n\t\/\/ dtor has already been called, also virtual functions don't work anymore\n\t\/\/ (therefore qobject_cast can only downcast from Base)\n\tQ_ASSERT( o );\n\tAbstractVideoOutput* output = static_cast( o );\n\tVideoEffect* videoEffect = static_cast( o );\n\tif( outputs.contains( output ) )\n\t{\n\t\tif( backendObject )\n\t\t\tpBACKEND_CALL1( \"removeOutput\", QObject*, output->iface() );\n\t\toutputs.removeAll( output );\n\t}\n\telse if( effects.contains( videoEffect ) )\n\t{\n\t\tif( backendObject )\n\t\t\tpBACKEND_CALL1( \"removeEffect\", QObject*, videoEffect->iface() );\n\t\teffects.removeAll( videoEffect );\n\t}\n}\n\n} \/\/namespace Phonon\n\n#include \"videopath.moc\"\n\n#undef PHONON_CLASSNAME\n\/\/ vim: sw=4 ts=4 tw=80\ndon't call the backend for invalid frontend objects (a frontend object is !isValid() if there's no backend object, and none can be created)\/* This file is part of the KDE project\n Copyright (C) 2005-2006 Matthias Kretz \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n#include \"videopath.h\"\n#include \"videopath_p.h\"\n#include \"factory.h\"\n\n#include \"videoeffect.h\"\n#include \"abstractvideooutput.h\"\n\n#define PHONON_CLASSNAME VideoPath\n\nnamespace Phonon\n{\nPHONON_OBJECT_IMPL\n\nVideoPath::~VideoPath()\n{\n\tK_D( VideoPath );\n foreach(AbstractVideoOutput* vo, d->outputs)\n d->removeDestructionHandler(vo, d);\n foreach(VideoEffect* ve, d->effects)\n d->removeDestructionHandler(ve, d);\n}\n\nbool VideoPath::addOutput( AbstractVideoOutput* videoOutput )\n{\n\tK_D( VideoPath );\n\tif( d->outputs.contains( videoOutput ) )\n\t\treturn false;\n\n if (iface() && videoOutput->iface()) {\n\t\tbool success;\n\t\tBACKEND_GET1( bool, success, \"addOutput\", QObject*, videoOutput->iface() );\n\t\tif( success )\n\t\t{\n d->addDestructionHandler(videoOutput, d);\n\t\t\td->outputs << videoOutput;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool VideoPath::removeOutput( AbstractVideoOutput* videoOutput )\n{\n\tK_D( VideoPath );\n\tif( !d->outputs.contains( videoOutput ) )\n\t\treturn false;\n\n if (d->backendObject && videoOutput->iface()) {\n\t\tbool success;\n\t\tBACKEND_GET1( bool, success, \"removeOutput\", QObject*, videoOutput->iface() );\n\t\tif( success )\n\t\t{\n\t\t\td->outputs.removeAll( videoOutput );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nconst QList& VideoPath::outputs() const\n{\n\tK_D( const VideoPath );\n\treturn d->outputs;\n}\n\nbool VideoPath::insertEffect( VideoEffect* newEffect, VideoEffect* insertBefore )\n{\n\t\/\/ effects may be added multiple times, but that means the objects are\n\t\/\/ different (the class is still the same)\n\tK_D( VideoPath );\n\tif( d->effects.contains( newEffect ) )\n\t\treturn false;\n\n if (iface() && newEffect->iface()) {\n\t\tbool success;\n\t\tBACKEND_GET2( bool, success, \"insertEffect\", QObject*, newEffect->iface(), QObject*, insertBefore ? insertBefore->iface() : 0 );\n\t\tif( success )\n\t\t{\n d->addDestructionHandler(newEffect, d);\n\t\t\tif( insertBefore )\n\t\t\t\td->effects.insert( d->effects.indexOf( insertBefore ), newEffect );\n\t\t\telse\n\t\t\t\td->effects << newEffect;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool VideoPath::removeEffect( VideoEffect* effect )\n{\n\tK_D( VideoPath );\n\tif( !d->effects.contains( effect ) )\n\t\treturn false;\n\n\tif( d->backendObject )\n\t{\n\t\tbool success;\n\t\tBACKEND_GET1( bool, success, \"removeEffect\", QObject*, effect->iface() );\n\t\tif( success )\n\t\t{\n\t\t\td->effects.removeAll( effect );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nconst QList& VideoPath::effects() const\n{\n\tK_D( const VideoPath );\n\treturn d->effects;\n}\n\nbool VideoPathPrivate::aboutToDeleteIface()\n{\n\treturn true;\n}\n\nvoid VideoPath::setupIface()\n{\n\tK_D( VideoPath );\n\tQ_ASSERT( d->backendObject );\n\n\t\/\/ set up attributes\n\tbool success;\n\tQList outputList = d->outputs;\n\tforeach( AbstractVideoOutput* output, outputList )\n\t{\n if (output->iface()) {\n BACKEND_GET1(bool, success, \"addOutput\", QObject*, output->iface());\n } else {\n success = false;\n }\n\t\tif( !success )\n\t\t\td->outputs.removeAll( output );\n\t}\n\n\tQList effectList = d->effects;\n\tforeach( VideoEffect* effect, effectList )\n\t{\n if (effect->iface()) {\n BACKEND_GET1( bool, success, \"insertEffect\", QObject*, effect->iface() );\n } else {\n success = false;\n }\n\t\tif( !success )\n\t\t\td->effects.removeAll( effect );\n\t}\n}\n\nvoid VideoPathPrivate::phononObjectDestroyed( Base* o )\n{\n\t\/\/ this method is called from Phonon::Base::~Base(), meaning the VideoEffect\n\t\/\/ dtor has already been called, also virtual functions don't work anymore\n\t\/\/ (therefore qobject_cast can only downcast from Base)\n\tQ_ASSERT( o );\n\tAbstractVideoOutput* output = static_cast( o );\n\tVideoEffect* videoEffect = static_cast( o );\n\tif( outputs.contains( output ) )\n\t{\n if (backendObject && output->iface()) {\n\t\t\tpBACKEND_CALL1( \"removeOutput\", QObject*, output->iface() );\n }\n\t\toutputs.removeAll( output );\n\t}\n\telse if( effects.contains( videoEffect ) )\n\t{\n if (backendObject && videoEffect->iface()) {\n\t\t\tpBACKEND_CALL1( \"removeEffect\", QObject*, videoEffect->iface() );\n }\n\t\teffects.removeAll( videoEffect );\n\t}\n}\n\n} \/\/namespace Phonon\n\n#include \"videopath.moc\"\n\n#undef PHONON_CLASSNAME\n\/\/ vim: sw=4 ts=4 tw=80\n<|endoftext|>"} {"text":"\/* \n * OSG Keyboard handler\n *\n * Copyright (c) 2015 Jérémie Decock\n *\n * See \"OpenSceneGraph 3.0\" by Rui Wang and Xuelei Qian (ed. Packt publishing) p.232\n * and http:\/\/jeux.developpez.com\/tutoriels\/openscenegraph\/evenements\/\n *\/\n\n#include \n#include \n\n#include \n\nclass KeyboardEventHandler : public osgGA::GUIEventHandler {\n public:\n KeyboardEventHandler() {\n \/\/ Put here the data to manipulate...\n }\n\n \/**\n * osgGA::GUIEventAdapter supplies the received events\n * osgGA::GUIActionAdapter parameter for feedback\n *\/\n virtual bool handle(const osgGA::GUIEventAdapter& event_adapter, osgGA::GUIActionAdapter& action_adapter) {\n\n switch(event_adapter.getEventType()) {\n\n case(osgGA::GUIEventAdapter::KEYDOWN):\n {\n switch(event_adapter.getKey()) {\n \/\/ See http:\/\/trac.openscenegraph.org\/documentation\/OpenSceneGraphReferenceDocs\/a00359.html for the list of OSG key symbols\n \n case 'q':\n std::cout << \"q key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Escape:\n std::cout << \"Escape key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Space:\n std::cout << \"Space key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Up:\n std::cout << \"Up key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Down:\n std::cout << \"Down key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Left:\n std::cout << \"Left key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Right:\n std::cout << \"Right key pressed (KEYDOWN)\" << std::endl;\n break;\n } \n }\n break;\n\n case(osgGA::GUIEventAdapter::KEYUP):\n {\n switch(event_adapter.getKey()) {\n case 'q':\n std::cout << \"q key pressed (KEYUP)\" << std::endl;\n break;\n } \n }\n break;\n\n default: \/\/ To avoid a warning during compilation\n break;\n }\n\n return false;\n }\n};\n\nint main(int, char **) {\n\n \/\/ Create an empty scene\n osg::ref_ptr root = new osg::Group;\n\n \/\/ Viewer\n osgViewer::Viewer viewer;\n viewer.setSceneData(root);\n\n \/\/ Set the keyboard handler\n osg::ref_ptr keyboard_event_handler = new KeyboardEventHandler();\n viewer.addEventHandler(keyboard_event_handler);\n\n \/\/ Run the viewer\n viewer.run();\n\n return 0;\n}\nAdd comments.\/* \n * OSG Keyboard handler\n *\n * Copyright (c) 2015 Jérémie Decock\n *\n * See \"OpenSceneGraph 3.0\" by Rui Wang and Xuelei Qian (ed. Packt publishing) p.232\n * and http:\/\/jeux.developpez.com\/tutoriels\/openscenegraph\/evenements\/\n *\/\n\n#include \n#include \n\n#include \n\nclass KeyboardEventHandler : public osgGA::GUIEventHandler {\n public:\n KeyboardEventHandler() {\n \/\/ Put here the data to manipulate...\n }\n\n \/**\n * osgGA::GUIEventAdapter supplies the received events\n * osgGA::GUIActionAdapter parameter for feedback\n *\/\n virtual bool handle(const osgGA::GUIEventAdapter& event_adapter, osgGA::GUIActionAdapter& action_adapter) {\n\n switch(event_adapter.getEventType()) {\n\n case(osgGA::GUIEventAdapter::KEYDOWN): \/\/ KEYDOWN == key pressed\n {\n switch(event_adapter.getKey()) {\n \/\/ See http:\/\/trac.openscenegraph.org\/documentation\/OpenSceneGraphReferenceDocs\/a00359.html for the list of OSG key symbols\n \n case 'q':\n std::cout << \"q key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Escape:\n std::cout << \"Escape key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Space:\n std::cout << \"Space key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Up:\n std::cout << \"Up key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Down:\n std::cout << \"Down key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Left:\n std::cout << \"Left key pressed (KEYDOWN)\" << std::endl;\n break;\n\n case osgGA::GUIEventAdapter::KEY_Right:\n std::cout << \"Right key pressed (KEYDOWN)\" << std::endl;\n break;\n } \n }\n break;\n\n case(osgGA::GUIEventAdapter::KEYUP): \/\/ KEYUP == key released\n {\n switch(event_adapter.getKey()) {\n case 'q':\n std::cout << \"q key pressed (KEYUP)\" << std::endl;\n break;\n } \n }\n break;\n\n default: \/\/ To avoid a warning during compilation\n break;\n }\n\n return false;\n }\n};\n\nint main(int, char **) {\n\n \/\/ Create an empty scene\n osg::ref_ptr root = new osg::Group;\n\n \/\/ Viewer\n osgViewer::Viewer viewer;\n viewer.setSceneData(root);\n\n \/\/ Set the keyboard handler\n osg::ref_ptr keyboard_event_handler = new KeyboardEventHandler();\n viewer.addEventHandler(keyboard_event_handler);\n\n \/\/ Run the viewer\n viewer.run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2006 Volker Krause \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"searchproviderbase.h\"\n#include \"searchprovideradaptor.h\"\n\n#include \n#include \n#include \n#include \n\nclass Akonadi::SearchProviderBasePrivate\n{\n public:\n};\n\nAkonadi::SearchProviderBase::SearchProviderBase( const QString &id ) :\n d( new SearchProviderBasePrivate )\n{\n new SearchProviderAdaptor( this );\n Q_ASSERT( QDBusConnection::sessionBus().registerService( \"org.kde.Akonadi.SearchProvider.\" + id ) );\n Q_ASSERT( QDBusConnection::sessionBus().registerObject( \"\/\", this, QDBusConnection::ExportAdaptors ) );\n}\n\nAkonadi::SearchProviderBase::~ SearchProviderBase()\n{\n delete d;\n}\n\nvoid Akonadi::SearchProviderBase::quit()\n{\n QCoreApplication::quit();\n}\n\n#include \"searchproviderbase.moc\"\nGuys, this code will be compiled in release mode one day...\/*\n Copyright (c) 2006 Volker Krause \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"searchproviderbase.h\"\n#include \"searchprovideradaptor.h\"\n\n#include \n#include \n#include \n#include \n\nclass Akonadi::SearchProviderBasePrivate\n{\n public:\n};\n\nAkonadi::SearchProviderBase::SearchProviderBase( const QString &id ) :\n d( new SearchProviderBasePrivate )\n{\n new SearchProviderAdaptor( this );\n bool ok = QDBusConnection::sessionBus().registerService( \"org.kde.Akonadi.SearchProvider.\" + id );\n Q_ASSERT( ok );\n ok = QDBusConnection::sessionBus().registerObject( \"\/\", this, QDBusConnection::ExportAdaptors );\n Q_ASSERT( ok );\n}\n\nAkonadi::SearchProviderBase::~ SearchProviderBase()\n{\n delete d;\n}\n\nvoid Akonadi::SearchProviderBase::quit()\n{\n QCoreApplication::quit();\n}\n\n#include \"searchproviderbase.moc\"\n<|endoftext|>"} {"text":"#ifndef INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP\n#define INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP\n\n\/*\tAllocore --\n\tMultimedia \/ virtual environment application class library\n\n\tCopyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.\n\tCopyright (C) 2012. The Regents of the University of California.\n\tAll rights reserved.\n\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\n\t\tRedistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t\tRedistributions in binary form must reproduce the above copyright\n\t\tnotice, this list of conditions and the following disclaimer in the\n\t\tdocumentation and\/or other materials provided with the distribution.\n\n\t\tNeither the name of the University of California nor the names of its\n\t\tcontributors may be used to endorse or promote products derived from\n\t\tthis software without specific prior written permission.\n\n\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\tAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\tIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\tARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\tLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\tCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\tSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\tINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\tCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\tARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\tPOSSIBILITY OF SUCH DAMAGE.\n\n\n\tFile description:\n\tGPU buffer object helper\n\n\tFile author(s):\n\tLance Putnam, 2010, putnam.lance@gmail.com\n*\/\n\n#include \n#include \"allocore\/graphics\/al_GPUObject.hpp\"\n#include \"allocore\/graphics\/al_Graphics.hpp\"\n\nnamespace al{\n\n\/\/\/ Generic buffer object\n\/\/\/ @ingroup allocore\n\n\/**\nVertex Buffer Objects (VBOs) create buffer memory for vertex attributes in\nhigh-performance memory (in contrast, Vertex Arrays store buffer memory in the\nclient CPU, incurring the overhead of data transfer). If the buffer object is\nused to store pixel data, it is called Pixel Buffer Object (PBO).\n\nVBOs provide an interface to access these buffers in a similar fashion to vertex\narrays. Hints of 'target' and 'mode' help the implementation determine whether\nto use system, AGP or video memory.\n\nUnlike display lists, the data in vertex buffer object can be read and updated\nby mapping the buffer into client's memory space.\n\nAnother important advantage of VBO is sharing the buffer objects with many\nclients, like display lists and textures. Since VBO is on the server's side,\nmultiple clients will be able to access the same buffer with the corresponding\nidentifier.\n*\/\nclass BufferObject : public GPUObject {\npublic:\n\n\t\/\/\/ Buffer access mode\n\tenum AccessMode{\n\t\tREAD_ONLY\t\t\t\t= GL_READ_ONLY,\n\t\tWRITE_ONLY\t\t\t\t= GL_WRITE_ONLY,\n\t\tREAD_WRITE\t\t\t\t= GL_READ_WRITE\n\t};\n\n\t\/\/\/ Array type\n\tenum ArrayType{\n\t\tVERTEX_ARRAY\t\t\t= GL_VERTEX_ARRAY,\n\t\tNORMAL_ARRAY\t\t\t= GL_NORMAL_ARRAY,\n\t\tCOLOR_ARRAY\t\t\t\t= GL_COLOR_ARRAY,\n\t\tINDEX_ARRAY\t\t\t\t= GL_INDEX_ARRAY,\n\t\tTEXTURE_COORD_ARRAY\t\t= GL_TEXTURE_COORD_ARRAY,\n\t\tEDGE_FLAG_ARRAY\t\t\t= GL_EDGE_FLAG_ARRAY\n\t};\n\n\t\/\/\/ Buffer type\n\tenum BufferType{\n\t\tARRAY_BUFFER\t\t\t= GL_ARRAY_BUFFER,\n\t\tELEMENT_ARRAY_BUFFER\t= GL_ELEMENT_ARRAY_BUFFER,\n\t\tPIXEL_PACK_BUFFER\t\t= GL_PIXEL_PACK_BUFFER,\t\t\t\/**< Transfer to PBO *\/\n\t\tPIXEL_UNPACK_BUFFER\t\t= GL_PIXEL_UNPACK_BUFFER\t\t\/**< Transfer from PBO *\/\n\t};\n\n\n\t\/*\n\t\"Static\" means the data in VBO will not be changed, \"Dynamic\" means the data\n\twill be changed frequently, and \"Stream\" means the data will be changed every\n\tframe. \"Draw\" means the data will be sent to the GPU from the application,\n\t\"Read\" means the data will be read by the application from the GPU, and \"Copy\"\n\tmeans the data will be copied internally on the GPU.\n\t*\/\n\tenum BufferUsage{\n\t\tSTREAM_DRAW\t\t= GL_STREAM_DRAW,\n\t\t\/\/STREAM_READ\t\t= GL_STREAM_READ,\n\t\t\/\/STREAM_COPY\t\t= GL_STREAM_COPY,\n\t\tSTATIC_DRAW\t\t= GL_STATIC_DRAW,\n\t\t\/\/STATIC_READ\t\t= GL_STATIC_READ,\n\t\t\/\/STATIC_COPY\t\t= GL_STATIC_COPY,\n\t\tDYNAMIC_DRAW\t= GL_DYNAMIC_DRAW,\n\t\t\/\/DYNAMIC_READ\t= GL_DYNAMIC_READ,\n\t\t\/\/DYNAMIC_COPY\t= GL_DYNAMIC_COPY\n\t};\n\n\t\/\/\/ @param[in] bufType\tbuffer type (array, element, etc.)\n\t\/\/\/ @param[in] bufUsage\tbuffer usage (stream, static, etc.)\n\tBufferObject(BufferType bufType, BufferUsage bufUsage);\n\n\tvirtual ~BufferObject();\n\n\n\t\/\/\/ Get buffer store size, in bytes\n\tint size() const;\n\n\n\t\/\/\/ Set buffer type\n\tvoid bufferType(BufferType v);\n\n\t\/\/\/ Set buffer usage\n\tvoid usage(BufferUsage v);\n\n\t\/\/\/ Set size, in bytes, of buffer without sending data\n\tvoid resize(int numBytes);\n\n\t\/\/\/ Set buffer data store and copy over client data\n\tvoid data(const void * src, Graphics::DataType dataType, int numElems, int numComps=1);\n\n\t\/\/\/ Set buffer data store and copy over client data\n\ttemplate \n\tvoid data(const T * src, int numElems, int numComps=1);\n\n\t\/\/\/ Set buffer data store without copying client data\n\tvoid data(Graphics::DataType dataType, int numElems, int numComps=1);\n\n\t\/\/\/ Set buffer data store using cached values\n\tvoid data();\n\n\t\/\/\/ Set subregion of buffer store\n\ttemplate \n\tint subData(const T * src, int numElems, int byteOffset=0);\n\n\n\t\/\/\/ Bind buffer\n\tvoid bind();\n\n\t\/\/\/ Unbind buffer\n\tvoid unbind() const;\n\n\tvoid operator()();\n\tvoid send();\n\n\n\tvoid print() const;\n\n\n\t#ifdef AL_GRAPHICS_USE_OPENGL\n\t\/* Warning: these are not supported in OpenGL ES *\/\n\n\t\/\/\/ Set map mode\n\tvoid mapMode(AccessMode v);\n\n\t\/\/\/ Map data store to client address space\n\n\t\/\/\/ If successful, returns a valid pointer to the data, otherwise, it returns\n\t\/\/\/ NULL.\n\t\/\/\/ After using the pointer, call unmap() as soon as possible\n\tvoid * map();\n\n\t\/\/\/ Map data store to client address space\n\n\t\/\/\/ If successful, returns true and sets argument to address of data,\n\t\/\/\/ otherwise, returns false and leaves argument unaffected.\n\t\/\/\/ After using the pointer, call unmap() as soon as possible\n\ttemplate \n\tbool map(T *& buf){\n\t\tif(Graphics::toDataType() == mDataType){\n\t\t\tvoid * r = map();\n\t\t\tif(r){ buf=(T *)r; return true; }\n\t\t}\n\t\treturn false;\n\t}\n\n\t\/\/\/ Unmaps data store from client address\n\t\/\/\/ After unmap(), the mapped pointer is invalid\n\tbool unmap();\n\t#endif\n\nprotected:\n\tAccessMode mMapMode;\n\tBufferType mType;\n\tBufferUsage mUsage;\n\tGraphics::DataType mDataType;\n\tint mNumComps;\n\tint mNumElems;\n\tvoid * mData;\n\tstruct SubData{\n\t\tSubData(const void * data_=NULL, unsigned size_=0, unsigned offset_=0)\n\t\t:\tdata(data_), size(size_), offset(offset_){}\n\t\tconst void * data;\n\t\tunsigned size;\n\t\tunsigned offset;\n\t};\n\tstd::vector mSubData;\n\n\tvirtual void onCreate();\n\tvirtual void onDestroy();\n\tvirtual void onPointerFunc(){};\n};\n\n\n\/\/\/ Vertex buffer object\nclass VBO : public BufferObject {\npublic:\n\tVBO(BufferUsage usage=STREAM_DRAW);\n\n\tstatic void enable();\n\tstatic void disable();\n\nprotected:\n\tvirtual void onPointerFunc();\n};\n\n\n\/\/\/ Color buffer object\nclass CBO : public BufferObject {\npublic:\n\tCBO(BufferUsage usage=STREAM_DRAW);\n\n\tstatic void enable();\n\tstatic void disable();\n\nprotected:\n\tvirtual void onPointerFunc();\n};\n\n\n\/\/\/ Pixel buffer object\nclass PBO : public BufferObject {\npublic:\n\tPBO(bool packMode, BufferUsage usage=STREAM_DRAW);\n\nprotected:\n\tvirtual void onPointerFunc();\n};\n\n\n\/\/\/ Element object buffer\nclass EBO : public BufferObject {\npublic:\n\tEBO(Graphics::Primitive prim=Graphics::POINTS, BufferUsage usage=STATIC_DRAW);\n\n\tEBO& primitive(Graphics::Primitive v);\n\tEBO& range(int start, int end);\n\nprotected:\n\tGraphics::Primitive mPrim;\n\tint mStart, mEnd;\n\n\tvirtual void onPointerFunc();\n};\n\nconst char * toString(BufferObject::BufferType v);\nconst char * toString(BufferObject::BufferUsage v);\n\n\/\/ IMPLEMENTATION --------------------------------------------------------------\n\ntemplate \nvoid BufferObject::data(const T * src, int numElems, int numComps){\n\tdata(src, Graphics::toDataType(), numElems, numComps);\n}\n\ntemplate \nint BufferObject::subData(const T * src, int numElems, int byteOffset){\n\tif(numElems){\n\t\tbind();\n\t\tglBufferSubData(mType, byteOffset, numElems*sizeof(T), src);\n\t\tunbind();\n\t\tmSubData.push_back(SubData(src, numElems*sizeof(T), byteOffset));\n\t}\n\treturn numElems*sizeof(T) + byteOffset;\n}\n\n\n\n} \/\/ al::\n#endif\nBufferObject: add some getters#ifndef INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP\n#define INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP\n\n\/*\tAllocore --\n\tMultimedia \/ virtual environment application class library\n\n\tCopyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.\n\tCopyright (C) 2012. The Regents of the University of California.\n\tAll rights reserved.\n\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\n\t\tRedistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t\tRedistributions in binary form must reproduce the above copyright\n\t\tnotice, this list of conditions and the following disclaimer in the\n\t\tdocumentation and\/or other materials provided with the distribution.\n\n\t\tNeither the name of the University of California nor the names of its\n\t\tcontributors may be used to endorse or promote products derived from\n\t\tthis software without specific prior written permission.\n\n\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\tAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\tIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\tARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\tLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\tCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\tSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\tINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\tCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\tARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\tPOSSIBILITY OF SUCH DAMAGE.\n\n\n\tFile description:\n\tGPU buffer object helper\n\n\tFile author(s):\n\tLance Putnam, 2010, putnam.lance@gmail.com\n*\/\n\n#include \n#include \"allocore\/graphics\/al_GPUObject.hpp\"\n#include \"allocore\/graphics\/al_Graphics.hpp\"\n\nnamespace al{\n\n\/\/\/ Generic buffer object\n\/\/\/ @ingroup allocore\n\n\/**\nVertex Buffer Objects (VBOs) create buffer memory for vertex attributes in\nhigh-performance memory (in contrast, Vertex Arrays store buffer memory in the\nclient CPU, incurring the overhead of data transfer). If the buffer object is\nused to store pixel data, it is called Pixel Buffer Object (PBO).\n\nVBOs provide an interface to access these buffers in a similar fashion to vertex\narrays. Hints of 'target' and 'mode' help the implementation determine whether\nto use system, AGP or video memory.\n\nUnlike display lists, the data in vertex buffer object can be read and updated\nby mapping the buffer into client's memory space.\n\nAnother important advantage of VBO is sharing the buffer objects with many\nclients, like display lists and textures. Since VBO is on the server's side,\nmultiple clients will be able to access the same buffer with the corresponding\nidentifier.\n*\/\nclass BufferObject : public GPUObject {\npublic:\n\n\t\/\/\/ Buffer access mode\n\tenum AccessMode{\n\t\tREAD_ONLY\t\t\t\t= GL_READ_ONLY,\n\t\tWRITE_ONLY\t\t\t\t= GL_WRITE_ONLY,\n\t\tREAD_WRITE\t\t\t\t= GL_READ_WRITE\n\t};\n\n\t\/\/\/ Array type\n\tenum ArrayType{\n\t\tVERTEX_ARRAY\t\t\t= GL_VERTEX_ARRAY,\n\t\tNORMAL_ARRAY\t\t\t= GL_NORMAL_ARRAY,\n\t\tCOLOR_ARRAY\t\t\t\t= GL_COLOR_ARRAY,\n\t\tINDEX_ARRAY\t\t\t\t= GL_INDEX_ARRAY,\n\t\tTEXTURE_COORD_ARRAY\t\t= GL_TEXTURE_COORD_ARRAY,\n\t\tEDGE_FLAG_ARRAY\t\t\t= GL_EDGE_FLAG_ARRAY\n\t};\n\n\t\/\/\/ Buffer type\n\tenum BufferType{\n\t\tARRAY_BUFFER\t\t\t= GL_ARRAY_BUFFER,\n\t\tELEMENT_ARRAY_BUFFER\t= GL_ELEMENT_ARRAY_BUFFER,\n\t\tPIXEL_PACK_BUFFER\t\t= GL_PIXEL_PACK_BUFFER,\t\t\t\/**< Transfer to PBO *\/\n\t\tPIXEL_UNPACK_BUFFER\t\t= GL_PIXEL_UNPACK_BUFFER\t\t\/**< Transfer from PBO *\/\n\t};\n\n\n\t\/*\n\t\"Static\" means the data in VBO will not be changed, \"Dynamic\" means the data\n\twill be changed frequently, and \"Stream\" means the data will be changed every\n\tframe. \"Draw\" means the data will be sent to the GPU from the application,\n\t\"Read\" means the data will be read by the application from the GPU, and \"Copy\"\n\tmeans the data will be copied internally on the GPU.\n\t*\/\n\tenum BufferUsage{\n\t\tSTREAM_DRAW\t\t= GL_STREAM_DRAW,\n\t\t\/\/STREAM_READ\t\t= GL_STREAM_READ,\n\t\t\/\/STREAM_COPY\t\t= GL_STREAM_COPY,\n\t\tSTATIC_DRAW\t\t= GL_STATIC_DRAW,\n\t\t\/\/STATIC_READ\t\t= GL_STATIC_READ,\n\t\t\/\/STATIC_COPY\t\t= GL_STATIC_COPY,\n\t\tDYNAMIC_DRAW\t= GL_DYNAMIC_DRAW,\n\t\t\/\/DYNAMIC_READ\t= GL_DYNAMIC_READ,\n\t\t\/\/DYNAMIC_COPY\t= GL_DYNAMIC_COPY\n\t};\n\n\t\/\/\/ @param[in] bufType\tbuffer type (array, element, etc.)\n\t\/\/\/ @param[in] bufUsage\tbuffer usage (stream, static, etc.)\n\tBufferObject(BufferType bufType, BufferUsage bufUsage);\n\n\tvirtual ~BufferObject();\n\n\n\t\/\/\/ Get buffer store size, in bytes\n\tint size() const;\n\n\t\/\/\/ Get data type\n\tGraphics::DataType dataType() const { return mDataType; }\n\n\t\/\/\/ Get number of components in each data element (e.g., 4 for RGBA)\n\tint numComps() const { return mNumComps; }\n\n\t\/\/\/ Get number of elements (e.g., colors)\n\tint numElems() const { return mNumElems; }\n\n\n\t\/\/\/ Set buffer type\n\tvoid bufferType(BufferType v);\n\n\t\/\/\/ Set buffer usage\n\tvoid usage(BufferUsage v);\n\n\t\/\/\/ Set size, in bytes, of buffer without sending data\n\tvoid resize(int numBytes);\n\n\t\/\/\/ Set buffer data store and copy over client data\n\tvoid data(const void * src, Graphics::DataType dataType, int numElems, int numComps=1);\n\n\t\/\/\/ Set buffer data store and copy over client data\n\ttemplate \n\tvoid data(const T * src, int numElems, int numComps=1);\n\n\t\/\/\/ Set buffer data store without copying client data\n\tvoid data(Graphics::DataType dataType, int numElems, int numComps=1);\n\n\t\/\/\/ Set buffer data store using cached values\n\tvoid data();\n\n\t\/\/\/ Set subregion of buffer store\n\ttemplate \n\tint subData(const T * src, int numElems, int byteOffset=0);\n\n\n\t\/\/\/ Bind buffer\n\tvoid bind();\n\n\t\/\/\/ Unbind buffer\n\tvoid unbind() const;\n\n\tvoid operator()();\n\tvoid send();\n\n\n\tvoid print() const;\n\n\n\t#ifdef AL_GRAPHICS_USE_OPENGL\n\t\/* Warning: these are not supported in OpenGL ES *\/\n\n\t\/\/\/ Set map mode\n\tvoid mapMode(AccessMode v);\n\n\t\/\/\/ Map data store to client address space\n\n\t\/\/\/ If successful, returns a valid pointer to the data, otherwise, it returns\n\t\/\/\/ NULL.\n\t\/\/\/ After using the pointer, call unmap() as soon as possible\n\tvoid * map();\n\n\t\/\/\/ Map data store to client address space\n\n\t\/\/\/ If successful, returns true and sets argument to address of data,\n\t\/\/\/ otherwise, returns false and leaves argument unaffected.\n\t\/\/\/ After using the pointer, call unmap() as soon as possible\n\ttemplate \n\tbool map(T *& buf){\n\t\tif(Graphics::toDataType() == mDataType){\n\t\t\tvoid * r = map();\n\t\t\tif(r){ buf=(T *)r; return true; }\n\t\t}\n\t\treturn false;\n\t}\n\n\t\/\/\/ Unmaps data store from client address\n\t\/\/\/ After unmap(), the mapped pointer is invalid\n\tbool unmap();\n\t#endif\n\nprotected:\n\tAccessMode mMapMode;\n\tBufferType mType;\n\tBufferUsage mUsage;\n\tGraphics::DataType mDataType;\n\tint mNumComps;\n\tint mNumElems;\n\tvoid * mData;\n\tstruct SubData{\n\t\tSubData(const void * data_=NULL, unsigned size_=0, unsigned offset_=0)\n\t\t:\tdata(data_), size(size_), offset(offset_){}\n\t\tconst void * data;\n\t\tunsigned size;\n\t\tunsigned offset;\n\t};\n\tstd::vector mSubData;\n\n\tvirtual void onCreate();\n\tvirtual void onDestroy();\n\tvirtual void onPointerFunc(){};\n};\n\n\n\/\/\/ Vertex buffer object\nclass VBO : public BufferObject {\npublic:\n\tVBO(BufferUsage usage=STREAM_DRAW);\n\n\tstatic void enable();\n\tstatic void disable();\n\nprotected:\n\tvirtual void onPointerFunc();\n};\n\n\n\/\/\/ Color buffer object\nclass CBO : public BufferObject {\npublic:\n\tCBO(BufferUsage usage=STREAM_DRAW);\n\n\tstatic void enable();\n\tstatic void disable();\n\nprotected:\n\tvirtual void onPointerFunc();\n};\n\n\n\/\/\/ Pixel buffer object\nclass PBO : public BufferObject {\npublic:\n\tPBO(bool packMode, BufferUsage usage=STREAM_DRAW);\n\nprotected:\n\tvirtual void onPointerFunc();\n};\n\n\n\/\/\/ Element object buffer\nclass EBO : public BufferObject {\npublic:\n\tEBO(Graphics::Primitive prim=Graphics::POINTS, BufferUsage usage=STATIC_DRAW);\n\n\tEBO& primitive(Graphics::Primitive v);\n\tEBO& range(int start, int end);\n\nprotected:\n\tGraphics::Primitive mPrim;\n\tint mStart, mEnd;\n\n\tvirtual void onPointerFunc();\n};\n\nconst char * toString(BufferObject::BufferType v);\nconst char * toString(BufferObject::BufferUsage v);\n\n\/\/ IMPLEMENTATION --------------------------------------------------------------\n\ntemplate \nvoid BufferObject::data(const T * src, int numElems, int numComps){\n\tdata(src, Graphics::toDataType(), numElems, numComps);\n}\n\ntemplate \nint BufferObject::subData(const T * src, int numElems, int byteOffset){\n\tif(numElems){\n\t\tbind();\n\t\tglBufferSubData(mType, byteOffset, numElems*sizeof(T), src);\n\t\tunbind();\n\t\tmSubData.push_back(SubData(src, numElems*sizeof(T), byteOffset));\n\t}\n\treturn numElems*sizeof(T) + byteOffset;\n}\n\n\n\n} \/\/ al::\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n\n\/\/ http:\/\/thenewcpp.wordpress.com\/2011\/11\/23\/variadic-templates-part-1-2\/\n\n\ntemplate \/\/ forward declare\nclass TinyFixMap;\n\ntemplate \nclass TinyFixMap\n{\n T val[1];\n int as_index(char c) {\n return c == current ? 0 : -1;\n }\n};\n\ntemplate \nsize_t get_index(char c) {\n return c == curent ? 0 : -1;\n}\ntemplate \nsize_t get_index(char c) {\n return c == current ? sizeof ... (par) : get_index(c);\n}\n\ntemplate \/\/ actual declare\nclass TinyFixMap\n{\n \/\/typedef typename TinyFixMap next;\n T val[sizeof...(others) + 1];\n\/\/ int as_index(char c) {\n \/\/ return c == current ? 0 : nt::as_index(c);\n\npublic:\n T& operator[](char c) {\n int i = get_index(c);\n if ( i != -1) {\n return vals[i];\n } \n else {\n throw std::out_of_range(\"Not a valid index\");\n }\n }\n};\n\n\n \/\/: TinyFixMap\n\n\/\/template \n\n\n#if 0\ntemplate \nstruct find_biggest;\n \n\/\/the biggest of one thing is that one thing\ntemplate \nstruct find_biggest\n{\n typedef First type;\n};\n \n\/\/the biggest of everything in Args and First\ntemplate \nstruct find_biggest\n{\n typedef typename find_biggest::type next;\n typedef typename std::conditional\n <\n sizeof(First) >= sizeof(next),\n First,\n next\n >::type type;\n};\n\n\n\/\/ TinyFixMap var;\n\/\/ printf(\"var['a'] = %f \\n\", var['a']);\n#endif \n\n#if 0\ntemplate \nclass TinyFixMap\n{\nprotected:\n T val[1];\n\n int as_index(char c) {\n if (c == index) {\n return 0;\n } else {\n return -1;\n }\n }\n\npublic \n T& operator[char c] {\n if ( as_index(c) !== -1 ) {\n return val[as_index(c)]\n } else {\n throw std::out_of_range();\n }\n }\n}\ntemplate \nclass TinyFixMap;\n#endif\n\/\/ auto it = std::find(std::begin(index...), std::end(index...), c);\n\/\/ return it != std::end(index...) ? it - std::begin(index...) : -1 ;\n\n\n\/\/ ? vals[as_index(c)] : vals[-1];\n\n#if 0\ntemplate \nclass TinyFixMap \n{\n\n}\n\ntemplate \nclass TinyFixMap2\n{\n\n};\n#endif\n\n#if 0\ntemplate \nclass TinyFixMap \n{\n T vals[sizeof ...(index) ];\n int as_index(char c) {\n auto list = {index...};\n auto it = std::find(list.begin(), list.end(), c);\n return it != list.end() ? it - list.begin() : -1;\n }\npublic:\n T& operator[](char c) {\n int i = as_index(c);\n if ( i != -1) {\n return vals[i];\n } \n else {\n throw std::out_of_range(\"Not a valid index\");\n }\n }\n};\n#endif\n\nint main()\n{\n#if 0\n TinyFixMap var;\n var['a'] = 10.2;\n var['b'] = 13;\n using namespace std;\n\n cout << \"var['a'] = \" << var['a'] << endl;\n cout << \"var['b'] = \" << var['b'] << endl;\n cout << \"var['c'] = \" << var['c'] << endl;\n cout << \"var['d'] = \" << var['d'] << endl;\n#endif\n}\n\n\n\nback mobile phone editting#include \n#include \n\n#include \n#include \n#include \n\n\/\/ http:\/\/thenewcpp.wordpress.com\/2011\/11\/23\/variadic-templates-part-1-2\/\n\n\ntemplate \/\/ forward declare\nclass TinyFixMap;\n\ntemplate \nclass TinyFixMap\n{\n T val[1];\n int as_index(char c) {\n return c == current ? 0 : -1;\n }\n};\n\n\/\/ 一般式,对 N 成立(之形式)\ntemplate \nsize_t find_index(char);\n\n\/\/ 特殊式,对 1 成立\ntemplate <>\nsite_t find_index(char c)\n{\n \n}\n\n\ntemplate \nsize_t get_index(char c) {\n return c == curent ? 0 : -1;\n}\ntemplate \nsize_t get_index(char c) {\n return c == current ? sizeof ... (par) : get_index(c);\n}\n\ntemplate \/\/ actual declare\nclass TinyFixMap\n{\n \/\/typedef typename TinyFixMap next;\n T val[sizeof...(others) + 1];\n\/\/ int as_index(char c) {\n \/\/ return c == current ? 0 : nt::as_index(c);\n\npublic:\n T& operator[](char c) {\n int i = get_index(c);\n if ( i != -1) {\n return vals[i];\n } \n else {\n throw std::out_of_range(\"Not a valid index\");\n }\n }\n};\n\n\n \/\/: TinyFixMap\n\n\/\/template \n\n\n#if 0\ntemplate \nstruct find_biggest;\n \n\/\/the biggest of one thing is that one thing\ntemplate \nstruct find_biggest\n{\n typedef First type;\n};\n \n\/\/the biggest of everything in Args and First\ntemplate \nstruct find_biggest\n{\n typedef typename find_biggest::type next;\n typedef typename std::conditional\n <\n sizeof(First) >= sizeof(next),\n First,\n next\n >::type type;\n};\n\n\n\/\/ TinyFixMap var;\n\/\/ printf(\"var['a'] = %f \\n\", var['a']);\n#endif \n\n#if 0\ntemplate \nclass TinyFixMap\n{\nprotected:\n T val[1];\n\n int as_index(char c) {\n if (c == index) {\n return 0;\n } else {\n return -1;\n }\n }\n\npublic \n T& operator[char c] {\n if ( as_index(c) !== -1 ) {\n return val[as_index(c)]\n } else {\n throw std::out_of_range();\n }\n }\n}\ntemplate \nclass TinyFixMap;\n#endif\n\/\/ auto it = std::find(std::begin(index...), std::end(index...), c);\n\/\/ return it != std::end(index...) ? it - std::begin(index...) : -1 ;\n\n\n\/\/ ? vals[as_index(c)] : vals[-1];\n\n#if 0\ntemplate \nclass TinyFixMap \n{\n\n}\n\ntemplate \nclass TinyFixMap2\n{\n\n};\n#endif\n\n#if 0\ntemplate \nclass TinyFixMap \n{\n T vals[sizeof ...(index) ];\n int as_index(char c) {\n auto list = {index...};\n auto it = std::find(list.begin(), list.end(), c);\n return it != list.end() ? it - list.begin() : -1;\n }\npublic:\n T& operator[](char c) {\n int i = as_index(c);\n if ( i != -1) {\n return vals[i];\n } \n else {\n throw std::out_of_range(\"Not a valid index\");\n }\n }\n};\n#endif\n\nint main()\n{\n#if 0\n TinyFixMap var;\n var['a'] = 10.2;\n var['b'] = 13;\n using namespace std;\n\n cout << \"var['a'] = \" << var['a'] << endl;\n cout << \"var['b'] = \" << var['b'] << endl;\n cout << \"var['c'] = \" << var['c'] << endl;\n cout << \"var['d'] = \" << var['d'] << endl;\n#endif\n}\n\n\n\n<|endoftext|>"} {"text":"\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_hist\n\/\/\/ Illustrates the advantages of a TH1K histogram\n\/\/\/\n\/\/\/ \\macro_image\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\author Victor Perevovchikov\n\nvoid padRefresh(TPad *pad,int flag=0);\nvoid hksimple()\n{\n\/\/ Create a new canvas.\n c1 = new TCanvas(\"c1\",\"Dynamic Filling Example\",200,10,600,900);\n c1->SetFillColor(42);\n\n\/\/ Create a normal histogram and two TH1K histograms\n TH1 *hpx[3];\n hpx[0] = new TH1F(\"hp0\",\"Normal histogram\",1000,-4,4);\n hpx[1] = new TH1K(\"hk1\",\"Nearest Neighbour of order 3\",1000,-4,4);\n hpx[2] = new TH1K(\"hk2\",\"Nearest Neighbour of order 16\",1000,-4,4,16);\n c1->Divide(1,3);\n Int_t j;\n for (j=0;j<3;j++) {\n c1->cd(j+1);\n gPad->SetFrameFillColor(33);\n hpx[j]->SetFillColor(48);\n hpx[j]->Draw();\n }\n\n\/\/ Fill histograms randomly\n gRandom->SetSeed();\n Float_t px, py, pz;\n const Int_t kUPDATE = 10;\n for (Int_t i = 0; i <= 300; i++) {\n gRandom->Rannor(px,py);\n for (j=0;j<3;j++) {hpx[j]->Fill(px);}\n if (i && (i%kUPDATE) == 0) {\n padRefresh(c1);\n }\n }\n\n for (j=0;j<3;j++) hpx[j]->Fit(\"gaus\");\n padRefresh(c1);\n}\nvoid padRefresh(TPad *pad,int flag)\n{\n if (!pad) return;\n pad->Modified();\n pad->Update();\n TList *tl = pad->GetListOfPrimitives();\n if (!tl) return;\n TListIter next(tl);\n TObject *to;\n while ((to=next())) {\n if (to->InheritsFrom(TPad::Class())) padRefresh((TPad*)to,1);}\n if (flag) return;\n gSystem->ProcessEvents();\n}\nDo not randomize the test results\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_hist\n\/\/\/ Illustrates the advantages of a TH1K histogram\n\/\/\/\n\/\/\/ \\macro_image\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\author Victor Perevovchikov\n\nvoid padRefresh(TPad *pad,int flag=0);\nvoid hksimple()\n{\n\/\/ Create a new canvas.\n c1 = new TCanvas(\"c1\",\"Dynamic Filling Example\",200,10,600,900);\n c1->SetFillColor(42);\n\n\/\/ Create a normal histogram and two TH1K histograms\n TH1 *hpx[3];\n hpx[0] = new TH1F(\"hp0\",\"Normal histogram\",1000,-4,4);\n hpx[1] = new TH1K(\"hk1\",\"Nearest Neighbour of order 3\",1000,-4,4);\n hpx[2] = new TH1K(\"hk2\",\"Nearest Neighbour of order 16\",1000,-4,4,16);\n c1->Divide(1,3);\n Int_t j;\n for (j=0;j<3;j++) {\n c1->cd(j+1);\n gPad->SetFrameFillColor(33);\n hpx[j]->SetFillColor(48);\n hpx[j]->Draw();\n }\n\n\/\/ Fill histograms randomly\n gRandom->SetSeed(12345);\n Float_t px, py, pz;\n const Int_t kUPDATE = 10;\n for (Int_t i = 0; i <= 300; i++) {\n gRandom->Rannor(px,py);\n for (j=0;j<3;j++) {hpx[j]->Fill(px);}\n if (i && (i%kUPDATE) == 0) {\n padRefresh(c1);\n }\n }\n\n for (j=0;j<3;j++) hpx[j]->Fit(\"gaus\");\n padRefresh(c1);\n}\nvoid padRefresh(TPad *pad,int flag)\n{\n if (!pad) return;\n pad->Modified();\n pad->Update();\n TList *tl = pad->GetListOfPrimitives();\n if (!tl) return;\n TListIter next(tl);\n TObject *to;\n while ((to=next())) {\n if (to->InheritsFrom(TPad::Class())) padRefresh((TPad*)to,1);}\n if (flag) return;\n gSystem->ProcessEvents();\n}\n<|endoftext|>"} {"text":"#ifndef DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH\n#define DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH\n\n\/\/ dunefem-functionals include\n#include \"localvector.hh\"\n\nnamespace Dune\n{\n\nnamespace Functionals\n{\n\nnamespace Common\n{\n\n\/**\n * \\brief This class represents a local DoF Matrix.\n *\n * It is based upon std::vector and should be replaced by something clever in the future!\n *\n * \\todo Doc me, please!\n **\/\ntemplate< class ElementType >\nclass LocalMatrix\n{\npublic:\n \/**\n * \\brief Initializes an empty matrix, according to the given size.\n **\/\n LocalMatrix( const unsigned int rows, const unsigned int cols )\n : rows_( rows ),\n cols_( cols )\n {\n \/\/ resize\n storage_.resize( rows_ * cols_, 0.0 );\n }\n\n\/\/ \/**\n\/\/ * @brief Resizes the storage size (rows*cols).\n\/\/ *\/\n\/\/ void resize( const unsigned int rows, const unsigned int cols )\n\/\/ {\n\/\/ storage_.resize( rows * cols, 0.0 );\n\/\/ }\n\n \/**\n * \\brief Returns the storage size (n*m).\n *\/\n const unsigned int size() const\n {\n return rows_*cols_;\n }\n\n ElementType get( const unsigned int i, const unsigned int j ) const\n {\n return storage_[i*cols_+j];\n }\n\n void set( const unsigned int i, const unsigned int j, ElementType val )\n {\n storage_[i*cols_+j] = val;\n }\n\n \/**\n * \\brief Matrix product with a local DoF vector.\n **\/\n LocalVector< ElementType > operator*( const LocalVector< ElementType >& other ) const\n {\n assert( cols_ == other.size() );\n\n LocalVector< ElementType > result( rows_ );\n\n for( unsigned ii = 0; ii < rows_; ++ii )\n {\n\n for( unsigned jj = 0; jj < cols_; ++jj )\n {\n\n result[ii] += get( ii, jj ) * other[jj];\n\n }\n\n }\n\n return result;\n }\n\n \/**\n * @brief Return number of rows.\n *\/\n unsigned int N() const\n {\n return rows_;\n }\n\n \/**\n * @brief Return number of cols.\n *\/\n unsigned int M() const\n {\n return cols_;\n }\n\nprivate:\n std::vector< ElementType > storage_;\n unsigned int rows_;\n unsigned int cols_;\n\n}; \/\/ end class LocalDoFVector\n\n} \/\/ end namespace Functionals\n\n} \/\/ end namespace Common\n\n} \/\/ end namespace Dune\n\n#endif \/\/ end of include guard: DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH\nsome Doxygen docu in Common::LocalMatrix#ifndef DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH\n#define DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH\n\n\/\/ dunefem-functionals include\n#include \"localvector.hh\"\n\nnamespace Dune\n{\n\nnamespace Functionals\n{\n\nnamespace Common\n{\n\n\/**\n * \\brief This class represents a local DoF Matrix.\n * It is based upon std::vector and should be replaced by something clever in the future!\n *\n * \\tparam ElementType\n * Type of one element, usually double or RangeFieldType.\n *\n * \\todo Doc me, please!\n **\/\ntemplate< class ElementType >\nclass LocalMatrix\n{\npublic:\n\n \/**\n * \\brief Initializes an empty matrix, according to the given size.\n *\n * \\param[in] rows\n * Number of rows, the matrix will have.\n *\n * \\param[in] cols\n * Number of collumns, the matrix will have.\n **\/\n LocalMatrix( const unsigned int rows, const unsigned int cols )\n : rows_( rows ),\n cols_( cols )\n {\n \/\/ resize\n storage_.resize( rows_ * cols_, 0.0 );\n }\n\n \/**\n * \\brief Returns the storage size (n*m).\n *\/\n const unsigned int size() const\n {\n return rows_*cols_;\n }\n\n ElementType get( const unsigned int i, const unsigned int j ) const\n {\n return storage_[i*cols_+j];\n }\n\n void set( const unsigned int i, const unsigned int j, ElementType val )\n {\n storage_[i*cols_+j] = val;\n }\n\n \/**\n * \\brief Matrix product with a local DoF vector.\n **\/\n LocalVector< ElementType > operator*( const LocalVector< ElementType >& other ) const\n {\n assert( cols_ == other.size() );\n\n LocalVector< ElementType > result( rows_ );\n\n for( unsigned ii = 0; ii < rows_; ++ii )\n {\n\n for( unsigned jj = 0; jj < cols_; ++jj )\n {\n\n result[ii] += get( ii, jj ) * other[jj];\n\n }\n\n }\n\n return result;\n }\n\n \/**\n * @brief Return number of rows.\n *\/\n unsigned int N() const\n {\n return rows_;\n }\n\n \/**\n * @brief Return number of cols.\n *\/\n unsigned int M() const\n {\n return cols_;\n }\n\nprivate:\n std::vector< ElementType > storage_;\n unsigned int rows_;\n unsigned int cols_;\n\n}; \/\/ end class LocalDoFVector\n\n} \/\/ end namespace Functionals\n\n} \/\/ end namespace Common\n\n} \/\/ end namespace Dune\n\n#endif \/\/ end of include guard: DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH\n<|endoftext|>"} {"text":"#define _USE_MATH_DEFINES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace std;\n\nstruct point{\n\tdouble _x, _y;\n\tpoint(double x=0.0, double y=0.0) :_x(x), _y(y){};\n\tbool in(double x1,double x2, double y1,double y2) const{\n\t\treturn _x >= x1&&_x <= x2&&_y >= y1&&_y <= y2;\n\t}\n\tpoint operator*(const point& p) const{\n\t\treturn point(_x*p._x, _y*p._y);\n\t}\n\tpoint operator*(double d) const{\n\t\treturn point(_x*d, _y*d);\n\t}\n\tpoint operator+(const point& p) const{\n\t\treturn point(_x+p._x, _y+p._y);\n\t}\n};\n\npoint operator*(double d, const point& p) {\n\treturn p*d;\n}\n\ntemplate \nclass RV{\npublic:\n\tvirtual T generate() = 0;\n\tvirtual double pdf(const T &) = 0;\n\tvirtual double cdf(const T &) = 0;\n};\n\nclass uniform2d :public RV{\n\tdouble _a1, _b1,_a2, _b2;\npublic:\n\tuniform2d(double a1 = 0.0, double b1 = 1.0, double a2 = 0.0, double b2 = 1.0) :\n\t\t_a1(a1), _b1(b1), _a2(a2), _b2(b2){\n\t\tassert(a1 < b1 && \"a(rand()) \/ RAND_MAX*(_b1 - _a1) + _a1;\n\t\tdouble y = static_cast(rand()) \/ RAND_MAX*(_b2 - _a2) + _a2;\n\t\treturn point(x,y);\n\t};\n\tdouble pdf(const point& p){\n\t\treturn (p._x >= _a1 && p._x <= _b1 && p._y >= _a2 && p._y <= _b2) ? 1.0 \/ (_b1 - _a1) \/ (_b2 - _a2) : 0.0;\n\t};\n\tdouble cdf(const point& p) {\n\t\tassert(false && \"looooool it's a joke. i don't know how to do that\");\n\t\treturn 0;\n\t};\n};\n\nclass normal2d : public RV{\n\tuniform2d _gen;\n\tpoint _u, _s;\npublic:\n\tnormal2d(const point& u = point(), const point& s = point(1,1)) :_u(u), _s(s){};\n\tpoint generate(){\n\t\tconst double epsilon = numeric_limits::min();\n\t\tpoint u1, u2;\n\t\tdo\n\t\t{\n\t\t\tu1 = _gen.generate();\n\t\t\tu2 = _gen.generate();\n\t\t} while (u2._x <= epsilon || u2._y <= epsilon);\n\t\tpoint r = -2.0*point(log(u2._x), log(u2._y));\n\t\treturn point(sqrt(r._x),sqrt(r._y))*point(cos(2 * M_PI*u1._x), cos(2 * M_PI*u1._y))*_s + _u;\n\t};\n\tdouble pdf(const point & p){\n\t\treturn 1.0 \/ 2.0 \/ _s._x \/ _s._y*exp(-0.5*((p._x - _u._x)*(p._x - _u._x) \/ _s._x \/ _s._x + (p._y - _u._y)*(p._y - _u._y) \/ _s._y \/ _s._y));\n\t};\n\tdouble cdf(const point & x) {\n\t\tassert(false && \"that's impossible!\");\n\t\treturn 0;\n\t};\n};\n\ndouble indicator(const point& p, double x1, double x2, double y1, double y2){\n\treturn p.in(x1, x2, y1, y2);\n}\n\ntemplate \ndouble mc(double(*f)(const T&), RV& dist, \n\tdouble x1 = 0.0, double x2 = 1.0, double y1 = 0.0, double y2 = 1.0, unsigned int n = 1000){\n\tdouble s = 0.0;\n\tfor (size_t i = 0; i < n; i++)\n\t{\n\t\tT x = dist.generate();\n\t\ts += f(x) \/ dist.pdf(x)*indicator(x, x1, x2, y1, y2);\n\t}\n\treturn s \/ n;\n}\n\ndouble c(const point& x){\n\treturn 1.0;\n}\n\ndouble nexp(const point& p){ \/\/ change variable\n\treturn (exp(-p._x) + exp(-1.0 \/ p._x) \/ p._x \/ p._x)*p._y;\n}\n\ndouble mean(const vector& v){\n\tdouble sum = accumulate(v.begin(), v.end(), 0.0);\n\treturn sum \/ v.size();\n}\n\ndouble var(const vector& v){\n\tdouble m = mean(v);\n\tdouble var = 0.0;\n\tfor (size_t i = 0; i < v.size(); i++)\n\t{\n\t\tvar += (v[i] - m)*(v[i] - m);\n\t}\n\treturn var \/ v.size();\n}\n\ndouble h(const point& p){\n\tdouble x = p._x;\n\tdouble y = p._y;\n\treturn exp(-x*x+x*y)*cos(x*M_PI)*sin(y*M_PI);\n}\n\nvoid monte_carlo(vector& v, RV& dist, double x1 = 0.0, double x2 = 1.0, double y1 = 0.0, double y2 = 1.0, unsigned int n=1000){\n\tv.clear();\n\tfor (size_t i = 0; i < 100; i++)\n\t{\n\t\tv.push_back(mc(h, dist, x1, x2, y1, y2, n));\n\t}\n\tcout << mean(v) << endl;\n\tcout << var(v) << endl;\n}\n\nint main(){\n\tuniform2d u_c(-4.0, 4.0, 0.25, 1.0);\n\tcout << mc(c, u_c,-4.0,4.0,0.25,1.0) << endl;\n\n\tuniform2d u_nexp;\n\tcout << mc(nexp, u_nexp, 0,1,0,1,10000) << endl;\n\n\tuniform2d u_f(-3.0, 3.0,-1.0,1.0);\n\tvector w;\n\tmonte_carlo(w, u_f, -3.0, 3.0, -1.0, 1.0, 100);\n\tmonte_carlo(w, u_f, -3.0, 3.0, -1.0, 1.0, 1000);\n\tmonte_carlo(w, u_f, -3.0, 3.0, -1.0, 1.0, 10000);\n\t\n\tnormal2d n_std;\n\tmonte_carlo(w, n_std, -3.0, 3.0, -1.0, 1.0, 100);\n\tmonte_carlo(w, n_std, -3.0, 3.0, -1.0, 1.0, 1000);\n\tmonte_carlo(w, n_std, -3.0, 3.0, -1.0, 1.0, 10000);\n\n\tnormal2d n_pi(point(M_PI \/ 2.0, M_PI \/ 2.0), point(1, 1));\n\tmonte_carlo(w, n_pi, -3.0, 3.0, -1.0, 1.0, 100);\n\tmonte_carlo(w, n_pi, -3.0, 3.0, -1.0, 1.0, 1000);\n\tmonte_carlo(w, n_pi, -3.0, 3.0, -1.0, 1.0, 10000);\n\n\treturn 0;\n}pi was missing in pdf#define _USE_MATH_DEFINES\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nusing namespace std;\r\n\r\nstruct point{\r\n\tdouble _x, _y;\r\n\tpoint(double x=0.0, double y=0.0) :_x(x), _y(y){};\r\n\tbool in(double x1,double x2, double y1,double y2) const{\r\n\t\treturn _x >= x1&&_x <= x2&&_y >= y1&&_y <= y2;\r\n\t}\r\n\tpoint operator*(const point& p) const{\r\n\t\treturn point(_x*p._x, _y*p._y);\r\n\t}\r\n\tpoint operator*(double d) const{\r\n\t\treturn point(_x*d, _y*d);\r\n\t}\r\n\tpoint operator+(const point& p) const{\r\n\t\treturn point(_x+p._x, _y+p._y);\r\n\t}\r\n};\r\n\r\npoint operator*(double d, const point& p) {\r\n\treturn p*d;\r\n}\r\n\r\ntemplate \r\nclass RV{\r\npublic:\r\n\tvirtual T generate() = 0;\r\n\tvirtual double pdf(const T &) = 0;\r\n\tvirtual double cdf(const T &) = 0;\r\n};\r\n\r\nclass uniform2d :public RV{\r\n\tdouble _a1, _b1,_a2, _b2;\r\npublic:\r\n\tuniform2d(double a1 = 0.0, double b1 = 1.0, double a2 = 0.0, double b2 = 1.0) :\r\n\t\t_a1(a1), _b1(b1), _a2(a2), _b2(b2){\r\n\t\tassert(a1 < b1 && \"a(rand()) \/ RAND_MAX*(_b1 - _a1) + _a1;\r\n\t\tdouble y = static_cast(rand()) \/ RAND_MAX*(_b2 - _a2) + _a2;\r\n\t\treturn point(x,y);\r\n\t};\r\n\tdouble pdf(const point& p){\r\n\t\treturn (p._x >= _a1 && p._x <= _b1 && p._y >= _a2 && p._y <= _b2) ? 1.0 \/ (_b1 - _a1) \/ (_b2 - _a2) : 0.0;\r\n\t};\r\n\tdouble cdf(const point& p) {\r\n\t\tassert(false && \"looooool it's a joke. i don't know how to do that\");\r\n\t\treturn 0;\r\n\t};\r\n};\r\n\r\nclass normal2d : public RV{\r\n\tuniform2d _gen;\r\n\tpoint _u, _s;\r\npublic:\r\n\tnormal2d(const point& u = point(), const point& s = point(1,1)) :_u(u), _s(s){};\r\n\tpoint generate(){\r\n\t\tconst double epsilon = numeric_limits::min();\r\n\t\tpoint u1, u2;\r\n\t\tdo\r\n\t\t{\r\n\t\t\tu1 = _gen.generate();\r\n\t\t\tu2 = _gen.generate();\r\n\t\t} while (u2._x <= epsilon || u2._y <= epsilon);\r\n\t\tpoint r = -2.0*point(log(u2._x), log(u2._y));\r\n\t\treturn point(sqrt(r._x),sqrt(r._y))*point(cos(2 * M_PI*u1._x), cos(2 * M_PI*u1._y))*_s + _u;\r\n\t};\r\n\tdouble pdf(const point & p){\r\n\t\treturn 1.0 \/ 2.0 \/ M_PI\/ _s._x \/ _s._y*exp(-0.5*((p._x - _u._x)*(p._x - _u._x) \/ _s._x \/ _s._x + (p._y - _u._y)*(p._y - _u._y) \/ _s._y \/ _s._y));\r\n\t};\r\n\tdouble cdf(const point & x) {\r\n\t\tassert(false && \"that's impossible!\");\r\n\t\treturn 0;\r\n\t};\r\n};\r\n\r\ndouble indicator(const point& p, double x1, double x2, double y1, double y2){\r\n\treturn p.in(x1, x2, y1, y2);\r\n}\r\n\r\ntemplate \r\ndouble mc(double(*f)(const T&), RV& dist, \r\n\tdouble x1 = 0.0, double x2 = 1.0, double y1 = 0.0, double y2 = 1.0, unsigned int n = 1000){\r\n\tdouble s = 0.0;\r\n\tfor (size_t i = 0; i < n; i++)\r\n\t{\r\n\t\tT x = dist.generate();\r\n\t\ts += f(x) \/ dist.pdf(x)*indicator(x, x1, x2, y1, y2);\r\n\t}\r\n\treturn s \/ n;\r\n}\r\n\r\ndouble c(const point& x){\r\n\treturn 1.0;\r\n}\r\n\r\ndouble nexp(const point& p){ \/\/ change variable\r\n\treturn (exp(-p._x) + exp(-1.0 \/ p._x) \/ p._x \/ p._x)*p._y;\r\n}\r\n\r\ndouble mean(const vector& v){\r\n\tdouble sum = accumulate(v.begin(), v.end(), 0.0);\r\n\treturn sum \/ v.size();\r\n}\r\n\r\ndouble var(const vector& v){\r\n\tdouble m = mean(v);\r\n\tdouble var = 0.0;\r\n\tfor (size_t i = 0; i < v.size(); i++)\r\n\t{\r\n\t\tvar += (v[i] - m)*(v[i] - m);\r\n\t}\r\n\treturn var \/ v.size();\r\n}\r\n\r\ndouble h(const point& p){\r\n\tdouble x = p._x;\r\n\tdouble y = p._y;\r\n\treturn exp(-x*x+x*y)*cos(x*M_PI)*sin(y*M_PI);\r\n}\r\n\r\nvoid monte_carlo(vector& v, RV& dist, double x1 = 0.0, double x2 = 1.0, double y1 = 0.0, double y2 = 1.0, unsigned int n=1000){\r\n\tv.clear();\r\n\tfor (size_t i = 0; i < 100; i++)\r\n\t{\r\n\t\tv.push_back(mc(h, dist, x1, x2, y1, y2, n));\r\n\t}\r\n\tcout << mean(v) << endl;\r\n\tcout << var(v) << endl;\r\n}\r\n\r\nint main(){\r\n\tuniform2d u_c(-4.0, 4.0, 0.25, 1.0);\r\n\tcout << mc(c, u_c,-4.0,4.0,0.25,1.0) << endl;\r\n\r\n\tuniform2d u_nexp;\r\n\tcout << mc(nexp, u_nexp, 0,1,0,1,10000) << endl;\r\n\r\n\tuniform2d u_f(-3.0, 3.0,-1.0,1.0);\r\n\tvector w;\r\n\tmonte_carlo(w, u_f, -3.0, 3.0, -1.0, 1.0, 100);\r\n\tmonte_carlo(w, u_f, -3.0, 3.0, -1.0, 1.0, 1000);\r\n\tmonte_carlo(w, u_f, -3.0, 3.0, -1.0, 1.0, 10000);\r\n\t\r\n\tnormal2d n_std;\r\n\tmonte_carlo(w, n_std, -3.0, 3.0, -1.0, 1.0, 100);\r\n\tmonte_carlo(w, n_std, -3.0, 3.0, -1.0, 1.0, 1000);\r\n\tmonte_carlo(w, n_std, -3.0, 3.0, -1.0, 1.0, 10000);\r\n\r\n\tnormal2d n_pi(point(M_PI \/ 2.0, M_PI \/ 2.0), point(1, 1));\r\n\tmonte_carlo(w, n_pi, -3.0, 3.0, -1.0, 1.0, 100);\r\n\tmonte_carlo(w, n_pi, -3.0, 3.0, -1.0, 1.0, 1000);\r\n\tmonte_carlo(w, n_pi, -3.0, 3.0, -1.0, 1.0, 10000);\r\n\r\n\treturn 0;\r\n}<|endoftext|>"} {"text":"#include \"HTTPSession.h\"\n#include \"Application\/HTTP\/UrlParam.h\"\n#include \"Application\/HTTP\/HTTPRequest.h\"\n#include \"Application\/HTTP\/HTTPConnection.h\"\n#include \"Application\/HTTP\/HTTPConsts.h\"\n\n#define MSG_FAIL \"Unable to process your request at this time\"\n\nHTTPSession::HTTPSession()\n{\n headerSent = false;\n conn = NULL;\n type = PLAIN;\n}\n\nvoid HTTPSession::SetConnection(HTTPConnection* conn_)\n{\n conn = conn_;\n if (conn != NULL)\n json.Init(conn);\n}\n\nbool HTTPSession::ParseRequest(HTTPRequest& request, ReadBuffer& cmd, UrlParam& params)\n{\n char* qmark;\n ReadBuffer rb;\n ReadBuffer jsonCallback;\n \n rb = request.line.uri;\n if (rb.GetCharAt(0) == '\/')\n rb.Advance(1);\n \n ParseType(rb);\n cmd = rb;\n\n qmark = NULL;\n if (rb.GetLength() > 0)\n qmark = FindInBuffer(rb.GetBuffer(), rb.GetLength() - 1, '?');\n\n if (qmark)\n {\n rb.Advance(qmark - rb.GetBuffer() + 1);\n params.Init(rb.GetBuffer(), rb.GetLength(), '&');\n cmd.SetLength(qmark - cmd.GetBuffer());\n \n if (type == JSON)\n {\n HTTP_GET_OPT_PARAM(params, \"callback\", jsonCallback);\n json.SetCallbackPrefix(jsonCallback);\n }\n }\n \n return true;\n}\n\nvoid HTTPSession::ParseType(ReadBuffer& rb)\n{\n const char JSON_PREFIX[] = \"json\/\";\n const char HTML_PREFIX[] = \"html\/\";\n \n type = PLAIN;\n \n if (HTTP_MATCH_COMMAND(rb, JSON_PREFIX))\n {\n type = JSON;\n rb.Advance(sizeof(JSON_PREFIX) - 1);\n }\n else if (HTTP_MATCH_COMMAND(rb, HTML_PREFIX))\n {\n type = HTML;\n rb.Advance(sizeof(HTML_PREFIX) - 1);\n }\n}\n\nvoid HTTPSession::ResponseFail()\n{\n assert(headerSent == false);\n if (!conn)\n return;\n \n if (type == JSON)\n json.PrintStatus(\"error\", MSG_FAIL);\n else\n conn->Response(HTTP_STATUS_CODE_OK, MSG_FAIL, sizeof(MSG_FAIL) - 1);\n}\n\nvoid HTTPSession::PrintLine(const ReadBuffer& line)\n{\n if (!conn)\n return;\n\n if (!headerSent)\n {\n if (type == JSON)\n json.Start();\n else\n conn->ResponseHeader(HTTP_STATUS_CODE_OK, false);\n\n headerSent = true;\n }\n \n if (type == JSON)\n json.PrintString(line.GetBuffer(), line.GetLength());\n else\n conn->Write(line.GetBuffer(), line.GetLength());\n}\n\nvoid HTTPSession::PrintPair(const ReadBuffer& key, const ReadBuffer& value)\n{\n if (!conn)\n return;\n\n if (!headerSent)\n {\n if (type == JSON)\n json.Start();\n else\n conn->ResponseHeader(HTTP_STATUS_CODE_OK, false);\n\n headerSent = true;\n }\n\n if (type == JSON)\n json.PrintPair(key.GetBuffer(), key.GetLength(), value.GetBuffer(), value.GetLength());\n else\n {\n conn->Write(key.GetBuffer(), key.GetLength());\n conn->Print(\": \");\n conn->Write(value.GetBuffer(), value.GetLength());\n conn->Print(\"\\n\");\n }\n}\n\nvoid HTTPSession::PrintPair(const char* key, const char* value)\n{\n PrintPair(ReadBuffer(key), ReadBuffer(value));\n}\n\nvoid HTTPSession::Flush()\n{\n if (!conn)\n return;\n\n if (type == JSON)\n json.End();\n \n conn->Flush(true);\n}\n\nFixed HTTP content type in HTTPSession.#include \"HTTPSession.h\"\n#include \"Application\/HTTP\/UrlParam.h\"\n#include \"Application\/HTTP\/HTTPRequest.h\"\n#include \"Application\/HTTP\/HTTPConnection.h\"\n#include \"Application\/HTTP\/HTTPConsts.h\"\n#include \"Application\/HTTP\/Mime.h\"\n\n#define MSG_FAIL \"Unable to process your request at this time\"\n#define CONTENT_TYPE_PLAIN HTTP_HEADER_CONTENT_TYPE \": \" MIME_TYPE_TEXT_PLAIN HTTP_CS_CRLF\n#define CONTENT_TYPE_HTML HTTP_HEADER_CONTENT_TYPE \": \" MIME_TYPE_TEXT_HTML HTTP_CS_CRLF\n\nHTTPSession::HTTPSession()\n{\n headerSent = false;\n conn = NULL;\n type = PLAIN;\n}\n\nvoid HTTPSession::SetConnection(HTTPConnection* conn_)\n{\n conn = conn_;\n if (conn != NULL)\n json.Init(conn);\n}\n\nbool HTTPSession::ParseRequest(HTTPRequest& request, ReadBuffer& cmd, UrlParam& params)\n{\n char* qmark;\n ReadBuffer rb;\n ReadBuffer jsonCallback;\n \n rb = request.line.uri;\n if (rb.GetCharAt(0) == '\/')\n rb.Advance(1);\n \n ParseType(rb);\n cmd = rb;\n\n qmark = NULL;\n if (rb.GetLength() > 0)\n qmark = FindInBuffer(rb.GetBuffer(), rb.GetLength() - 1, '?');\n\n if (qmark)\n {\n rb.Advance(qmark - rb.GetBuffer() + 1);\n params.Init(rb.GetBuffer(), rb.GetLength(), '&');\n cmd.SetLength(qmark - cmd.GetBuffer());\n \n if (type == JSON)\n {\n HTTP_GET_OPT_PARAM(params, \"callback\", jsonCallback);\n json.SetCallbackPrefix(jsonCallback);\n }\n }\n \n return true;\n}\n\nvoid HTTPSession::ParseType(ReadBuffer& rb)\n{\n const char JSON_PREFIX[] = \"json\/\";\n const char HTML_PREFIX[] = \"html\/\";\n \n type = PLAIN;\n \n if (HTTP_MATCH_COMMAND(rb, JSON_PREFIX))\n {\n type = JSON;\n rb.Advance(sizeof(JSON_PREFIX) - 1);\n }\n else if (HTTP_MATCH_COMMAND(rb, HTML_PREFIX))\n {\n type = HTML;\n rb.Advance(sizeof(HTML_PREFIX) - 1);\n }\n}\n\nvoid HTTPSession::ResponseFail()\n{\n assert(headerSent == false);\n if (!conn)\n return;\n \n if (type == JSON)\n json.PrintStatus(\"error\", MSG_FAIL);\n else\n conn->Response(HTTP_STATUS_CODE_OK, MSG_FAIL, sizeof(MSG_FAIL) - 1);\n}\n\nvoid HTTPSession::PrintLine(const ReadBuffer& line)\n{\n Buffer header;\n \n if (!conn)\n return;\n\n if (!headerSent)\n {\n if (type == JSON)\n json.Start();\n else\n conn->ResponseHeader(HTTP_STATUS_CODE_OK, false, \n type == PLAIN ? CONTENT_TYPE_PLAIN : CONTENT_TYPE_HTML);\n\n headerSent = true;\n }\n \n if (type == JSON)\n json.PrintString(line.GetBuffer(), line.GetLength());\n else\n conn->Write(line.GetBuffer(), line.GetLength());\n}\n\nvoid HTTPSession::PrintPair(const ReadBuffer& key, const ReadBuffer& value)\n{\n if (!conn)\n return;\n\n if (!headerSent)\n {\n if (type == JSON)\n json.Start();\n else\n conn->ResponseHeader(HTTP_STATUS_CODE_OK, false, \n type == PLAIN ? CONTENT_TYPE_PLAIN : CONTENT_TYPE_HTML);\n\n headerSent = true;\n }\n\n if (type == JSON)\n json.PrintPair(key.GetBuffer(), key.GetLength(), value.GetBuffer(), value.GetLength());\n else\n {\n conn->Write(key.GetBuffer(), key.GetLength());\n conn->Print(\": \");\n conn->Write(value.GetBuffer(), value.GetLength());\n conn->Print(\"\\n\");\n }\n}\n\nvoid HTTPSession::PrintPair(const char* key, const char* value)\n{\n PrintPair(ReadBuffer(key), ReadBuffer(value));\n}\n\nvoid HTTPSession::Flush()\n{\n if (!conn)\n return;\n\n if (type == JSON)\n json.End();\n \n conn->Flush(true);\n}\n\n<|endoftext|>"} {"text":"#include \"elsa_parser.h\"\n\nnamespace elsa {\n\tnamespace compiler {\n\n\t\tElsaParser::ElsaParser(Lexer* lexer)\n\t\t\t:\n\t\t\tlexer_(std::unique_ptr(lexer)),\n\t\t\tcurrent_scope_(nullptr),\n\t\t\ttype_checker_(this),\n\t\t\tprogram_(std::make_unique()),\n\t\t\tstruct_table_ext_(nullptr),\n\t\t\tfunction_table_ext_(nullptr),\n\t\t\tcurrent_type_(nullptr)\n\t\t{\n\t\t\tinitialize_grammar();\n\t\t\tnext_token();\n\t\t\tBuiltin::init(&struct_table_);\n\t\t}\n\n\t\tstd::unique_ptr ElsaParser::parse()\n\t\t{\n\t\t\twhile (current_token_->get_type() != TokenType::END)\n\t\t\t{\n\t\t\t\tprogram_->add_statement(parse_statement());\n\t\t\t}\n\n\t\t\treturn std::move(program_);\n\t\t}\n\n\t\tstd::unique_ptr ElsaParser::parse_statement()\n\t\t{\n\t\t\tif (current_token_->get_type() == TokenType::Import)\n\t\t\t\tparse_import_statement();\n\n\t\t\tauto parser = get_statement_parser(current_token_->get_type());\n\n\t\t\tif (parser == nullptr)\n\t\t\t\tthrow ParsingException(L\"Invalid token\", current_token_.get());\n\n\t\t\treturn parser->parse(this);\n\t\t}\n\n\t\tstd::unique_ptr ElsaParser::parse_expression()\n\t\t{\n\t\t\treturn parse_expression(0);\n\t\t}\n\n\t\tstd::unique_ptr ElsaParser::parse_expression(int precedence)\n\t\t{\n\t\t\tParser* parser = nullptr;\n\n\t\t\tparser = get_ll2_expression_parser(current_token_->get_type(), peek_token()->get_type());\n\t\t\tif (parser == nullptr)\n\t\t\t\tparser = get_expression_parser(current_token_->get_type());\n\n\t\t\tif (parser == nullptr)\n\t\t\t\tthrow ParsingException(L\"Invalid token\", current_token_.get());\n\n\t\t\tauto left = std::unique_ptr(parser->parse(this));\n\n\t\t\twhile (precedence < get_precedence())\n\t\t\t{\n\t\t\t\tauto infix_parser = get_infix_parser(current_token()->get_type());\n\t\t\t\tleft = std::unique_ptr(infix_parser->parse(this, std::move(left)));\n\t\t\t}\n\n\t\t\treturn left;\n\t\t}\n\n\t\tScopedExpression* ElsaParser::current_scope()\n\t\t{\n\t\t\tif (current_scope_ == nullptr)\n\t\t\t\tthrow ParsingException(L\"No scope defined\", current_token_.get());\n\n\t\t\treturn current_scope_;\n\t\t}\n\n\t\tvoid ElsaParser::set_current_scope(ScopedExpression* scope)\n\t\t{\n\t\t\tcurrent_scope_ = scope;\n\t\t}\n\n\t\tvoid ElsaParser::reset_current_scope()\n\t\t{\n\t\t\tcurrent_scope_ = nullptr;\n\t\t}\n\n\t\tStructTable& ElsaParser::struct_table()\n\t\t{\n\t\t\tif (struct_table_ext_ != nullptr)\n\t\t\t\treturn *struct_table_ext_;\n\n\t\t\treturn struct_table_;\n\t\t}\n\n\t\tFunctionTable& ElsaParser::function_table()\n\t\t{\n\t\t\tif (function_table_ext_ != nullptr)\n\t\t\t\treturn *function_table_ext_;\n\n\t\t\treturn function_table_;\n\t\t}\n\n\t\tTypeChecker & ElsaParser::type_checker()\n\t\t{\n\t\t\treturn type_checker_;\n\t\t}\n\n\t\tvoid ElsaParser::consume(TokenType type)\n\t\t{\n\t\t\tif(current_token()->get_type() != type)\n\t\t\t\tthrow ParsingException(L\"Unexpected token\", current_token_.get());\n\n\t\t\tnext_token();\n\t\t}\n\n\t\tvoid ElsaParser::consume()\n\t\t{\n\t\t\tnext_token();\n\t\t}\n\n\t\tToken* ElsaParser::current_token()\n\t\t{\n\t\t\treturn current_token_.get();\n\t\t}\n\n\t\tToken* ElsaParser::peek_token()\n\t\t{\n\t\t\treturn lexer_->peek_token();\n\t\t}\n\n\t\tvoid ElsaParser::set_current_type(const ElsaType* type)\n\t\t{\n\t\t\tcurrent_type_ = type;\n\t\t}\n\n\t\tconst ElsaType* ElsaParser::current_type() const\n\t\t{\n\t\t\treturn current_type_;\n\t\t}\n\n\t\tElsaParser::ElsaParser(Lexer* lexer, StructTable* struct_table, FunctionTable* function_table)\n\t\t\t:\n\t\t\tlexer_(std::unique_ptr(lexer)),\n\t\t\tcurrent_scope_(nullptr),\n\t\t\ttype_checker_(this),\n\t\t\tprogram_(std::make_unique()),\n\t\t\tstruct_table_ext_(struct_table),\n\t\t\tfunction_table_ext_(function_table),\n\t\t\tcurrent_type_(nullptr)\n\t\t{\n\t\t\tinitialize_grammar();\n\t\t\tnext_token();\n\t\t}\n\n\t\tvoid ElsaParser::next_token()\n\t\t{\n\t\t\tcurrent_token_ = lexer_->next_token();\n\t\t}\n\n\t\tParser* ElsaParser::get_expression_parser(TokenType type)\n\t\t{\n\t\t\tauto it = expression_parsers_.find(type);\n\t\t\tif (it != expression_parsers_.end())\n\t\t\t{\n\t\t\t\treturn it->second.get();\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tParser* ElsaParser::get_ll2_expression_parser(TokenType first, TokenType second)\n\t\t{\n\t\t\tfor (auto& entry : ll2_expression_parsers_)\n\t\t\t{\n\t\t\t\tif (entry->first == first && entry->second == second)\n\t\t\t\t\treturn entry->parser.get();\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tParser* ElsaParser::get_statement_parser(TokenType type)\n\t\t{\n\t\t\tauto it = statement_parsers_.find(type);\n\t\t\tif (it != statement_parsers_.end())\n\t\t\t{\n\t\t\t\treturn it->second.get();\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tInfixParser* ElsaParser::get_infix_parser(TokenType type)\n\t\t{\n\t\t\tauto it = infix_parsers_.find(type);\n\t\t\tif (it != infix_parsers_.end())\n\t\t\t{\n\t\t\t\treturn it->second.get();\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tint ElsaParser::get_precedence()\n\t\t{\n\t\t\tauto infix_parser = get_infix_parser(current_token()->get_type());\n\t\t\tif (infix_parser != nullptr)\n\t\t\t\treturn infix_parser->precedence();\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tvoid ElsaParser::register_expression_parser(TokenType type, Parser* parser)\n\t\t{\n\t\t\texpression_parsers_.insert(std::pair>(type, std::unique_ptr(parser)));\n\t\t}\n\n\t\tvoid ElsaParser::register_ll2_expression_parser(TokenType first, TokenType second, Parser* parser)\n\t\t{\n\t\t\tll2_expression_parsers_.push_back(std::make_unique(first, second, parser));\n\t\t}\n\n\t\tvoid ElsaParser::register_statement_parser(TokenType type, Parser* parser)\n\t\t{\n\t\t\tstatement_parsers_.insert(std::pair>(type, std::unique_ptr(parser)));\n\t\t}\n\n\t\tvoid ElsaParser::register_infix_parser(TokenType type, InfixParser* parser)\n\t\t{\n\t\t\tinfix_parsers_.insert(std::pair>(type, std::unique_ptr(parser)));\n\t\t}\n\n\t\tvoid ElsaParser::register_prefix_parser(TokenType type)\n\t\t{\n\t\t\tregister_expression_parser(type, new PrefixOperatorParser());\n\t\t}\n\n\t\tvoid ElsaParser::register_postfix_parser(TokenType type, InfixParser* parser)\n\t\t{\n\t\t\tregister_infix_parser(type, parser);\n\t\t}\n\n\t\tvoid ElsaParser::initialize_grammar()\n\t\t{\n\t\t\t\/\/ Statements\n\t\t\tregister_statement_parser(TokenType::Func, new FuncDeclarationParser());\n\t\t\tregister_statement_parser(TokenType::Struct, new StructDeclarationParser());\n\n\t\t\t\/\/ LL2 Expressions\n\t\t\tregister_ll2_expression_parser(TokenType::Identifier, TokenType::Dot, new StructAccessParser());\n\t\t\tregister_ll2_expression_parser(TokenType::Identifier, TokenType::LParen, new FuncCallParser());\n\t\t\tregister_ll2_expression_parser(TokenType::Identifier, TokenType::LSBracket, new ArrayAccessParser());\n\t\t\tregister_ll2_expression_parser(TokenType::Identifier, TokenType::Identifier, new VariableDeclarationParser());\n\n\t\t\t\/\/ Expressions\n\t\t\tregister_expression_parser(TokenType::Var, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Int, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Float, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Char, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Bool, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Identifier, new IdentifierParser());\n\t\t\tregister_expression_parser(TokenType::IntegerLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::FloatLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::CharLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::BoolLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::StringLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::Elsa, new ElsaInvokeParser());\n\t\t\tregister_expression_parser(TokenType::New, new CreateStructParser());\n\t\t\tregister_expression_parser(TokenType::If, new ConditionalParser());\n\t\t\tregister_expression_parser(TokenType::Loop, new LoopParser());\n\t\t\tregister_expression_parser(TokenType::Return, new ReturnParser());\n\n\t\t\t\/\/ Prefix\n\t\t\tregister_prefix_parser(TokenType::Exclamation);\n\n\t\t\t\/\/ Infix\n\t\t\tregister_infix_parser(TokenType::Plus, new BinaryOperatorParser(Precedence::Sum));\n\t\t\tregister_infix_parser(TokenType::Minus, new BinaryOperatorParser(Precedence::Sum));\n\t\t\tregister_infix_parser(TokenType::Slash, new BinaryOperatorParser(Precedence::Product));\n\t\t\tregister_infix_parser(TokenType::Asterix, new BinaryOperatorParser(Precedence::Product));\n\t\t\tregister_infix_parser(TokenType::DoubleAmpersand, new BinaryOperatorParser(Precedence::ConditionalAnd));\n\t\t\tregister_infix_parser(TokenType::DoubleVerticalBar, new BinaryOperatorParser(Precedence::ConditionalOr));\n\n\t\t\tregister_infix_parser(TokenType::DoubleEquals, new BinaryOperatorParser(Precedence::Equality));\n\t\t\tregister_infix_parser(TokenType::NotEquals, new BinaryOperatorParser(Precedence::Equality));\n\n\t\t\tregister_infix_parser(TokenType::LessThan, new BinaryOperatorParser(Precedence::Relational));\n\t\t\tregister_infix_parser(TokenType::GreaterThan, new BinaryOperatorParser(Precedence::Relational));\n\t\t\tregister_infix_parser(TokenType::LessThanEquals, new BinaryOperatorParser(Precedence::Relational));\n\t\t\tregister_infix_parser(TokenType::GreaterThanEquals, new BinaryOperatorParser(Precedence::Relational));\n\n\t\t\tregister_infix_parser(TokenType::Equals, new AssignmentParser());\n\n\t\t\t\/\/ Postfix\n\t\t\tregister_postfix_parser(TokenType::PlusPlus, new PostfixOperatorParser(Precedence::Unary));\n\t\t\tregister_postfix_parser(TokenType::MinusMinus, new PostfixOperatorParser(Precedence::Unary));\n\t\t}\n\n\t\tvoid ElsaParser::parse_import_statement()\n\t\t{\n\t\t\tconsume(TokenType::Import);\n\t\t\tauto filename = current_token_->get_value();\n\t\t\tconsume(TokenType::StringLiteral);\n\t\t\tconsume(TokenType::Semicolon);\n\t\t\timport_source_file(filename);\n\t\t}\n\n\t\tvoid ElsaParser::import_source_file(const std::wstring& filename)\n\t\t{\n\t\t\tauto filename_with_extension = filename + L\".elsa\";\n\t\t\tauto parser = ElsaParser(new Lexer(new SourceFile(filename_with_extension.c_str())), &struct_table_, &function_table_);\n\t\t\tparser.parse(program_.get());\n\t\t}\n\n\t\tvoid ElsaParser::parse(Program* program)\n\t\t{\n\t\t\twhile (current_token_->get_type() != TokenType::END)\n\t\t\t{\n\t\t\t\tprogram->add_statement(parse_statement());\n\t\t\t}\n\t\t}\n\t}\n}\nadded support for multiple import statements#include \"elsa_parser.h\"\n\nnamespace elsa {\n\tnamespace compiler {\n\n\t\tElsaParser::ElsaParser(Lexer* lexer)\n\t\t\t:\n\t\t\tlexer_(std::unique_ptr(lexer)),\n\t\t\tcurrent_scope_(nullptr),\n\t\t\ttype_checker_(this),\n\t\t\tprogram_(std::make_unique()),\n\t\t\tstruct_table_ext_(nullptr),\n\t\t\tfunction_table_ext_(nullptr),\n\t\t\tcurrent_type_(nullptr)\n\t\t{\n\t\t\tinitialize_grammar();\n\t\t\tnext_token();\n\t\t\tBuiltin::init(&struct_table_);\n\t\t}\n\n\t\tstd::unique_ptr ElsaParser::parse()\n\t\t{\n\t\t\twhile (current_token_->get_type() != TokenType::END)\n\t\t\t{\n\t\t\t\tprogram_->add_statement(parse_statement());\n\t\t\t}\n\n\t\t\treturn std::move(program_);\n\t\t}\n\n\t\tstd::unique_ptr ElsaParser::parse_statement()\n\t\t{\n\t\t\twhile(current_token_->get_type() == TokenType::Import)\n\t\t\t\tparse_import_statement();\n\n\t\t\tauto parser = get_statement_parser(current_token_->get_type());\n\n\t\t\tif (parser == nullptr)\n\t\t\t\tthrow ParsingException(L\"Invalid token\", current_token_.get());\n\n\t\t\treturn parser->parse(this);\n\t\t}\n\n\t\tstd::unique_ptr ElsaParser::parse_expression()\n\t\t{\n\t\t\treturn parse_expression(0);\n\t\t}\n\n\t\tstd::unique_ptr ElsaParser::parse_expression(int precedence)\n\t\t{\n\t\t\tParser* parser = nullptr;\n\n\t\t\tparser = get_ll2_expression_parser(current_token_->get_type(), peek_token()->get_type());\n\t\t\tif (parser == nullptr)\n\t\t\t\tparser = get_expression_parser(current_token_->get_type());\n\n\t\t\tif (parser == nullptr)\n\t\t\t\tthrow ParsingException(L\"Invalid token\", current_token_.get());\n\n\t\t\tauto left = std::unique_ptr(parser->parse(this));\n\n\t\t\twhile (precedence < get_precedence())\n\t\t\t{\n\t\t\t\tauto infix_parser = get_infix_parser(current_token()->get_type());\n\t\t\t\tleft = std::unique_ptr(infix_parser->parse(this, std::move(left)));\n\t\t\t}\n\n\t\t\treturn left;\n\t\t}\n\n\t\tScopedExpression* ElsaParser::current_scope()\n\t\t{\n\t\t\tif (current_scope_ == nullptr)\n\t\t\t\tthrow ParsingException(L\"No scope defined\", current_token_.get());\n\n\t\t\treturn current_scope_;\n\t\t}\n\n\t\tvoid ElsaParser::set_current_scope(ScopedExpression* scope)\n\t\t{\n\t\t\tcurrent_scope_ = scope;\n\t\t}\n\n\t\tvoid ElsaParser::reset_current_scope()\n\t\t{\n\t\t\tcurrent_scope_ = nullptr;\n\t\t}\n\n\t\tStructTable& ElsaParser::struct_table()\n\t\t{\n\t\t\tif (struct_table_ext_ != nullptr)\n\t\t\t\treturn *struct_table_ext_;\n\n\t\t\treturn struct_table_;\n\t\t}\n\n\t\tFunctionTable& ElsaParser::function_table()\n\t\t{\n\t\t\tif (function_table_ext_ != nullptr)\n\t\t\t\treturn *function_table_ext_;\n\n\t\t\treturn function_table_;\n\t\t}\n\n\t\tTypeChecker & ElsaParser::type_checker()\n\t\t{\n\t\t\treturn type_checker_;\n\t\t}\n\n\t\tvoid ElsaParser::consume(TokenType type)\n\t\t{\n\t\t\tif(current_token()->get_type() != type)\n\t\t\t\tthrow ParsingException(L\"Unexpected token\", current_token_.get());\n\n\t\t\tnext_token();\n\t\t}\n\n\t\tvoid ElsaParser::consume()\n\t\t{\n\t\t\tnext_token();\n\t\t}\n\n\t\tToken* ElsaParser::current_token()\n\t\t{\n\t\t\treturn current_token_.get();\n\t\t}\n\n\t\tToken* ElsaParser::peek_token()\n\t\t{\n\t\t\treturn lexer_->peek_token();\n\t\t}\n\n\t\tvoid ElsaParser::set_current_type(const ElsaType* type)\n\t\t{\n\t\t\tcurrent_type_ = type;\n\t\t}\n\n\t\tconst ElsaType* ElsaParser::current_type() const\n\t\t{\n\t\t\treturn current_type_;\n\t\t}\n\n\t\tElsaParser::ElsaParser(Lexer* lexer, StructTable* struct_table, FunctionTable* function_table)\n\t\t\t:\n\t\t\tlexer_(std::unique_ptr(lexer)),\n\t\t\tcurrent_scope_(nullptr),\n\t\t\ttype_checker_(this),\n\t\t\tprogram_(std::make_unique()),\n\t\t\tstruct_table_ext_(struct_table),\n\t\t\tfunction_table_ext_(function_table),\n\t\t\tcurrent_type_(nullptr)\n\t\t{\n\t\t\tinitialize_grammar();\n\t\t\tnext_token();\n\t\t}\n\n\t\tvoid ElsaParser::next_token()\n\t\t{\n\t\t\tcurrent_token_ = lexer_->next_token();\n\t\t}\n\n\t\tParser* ElsaParser::get_expression_parser(TokenType type)\n\t\t{\n\t\t\tauto it = expression_parsers_.find(type);\n\t\t\tif (it != expression_parsers_.end())\n\t\t\t{\n\t\t\t\treturn it->second.get();\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tParser* ElsaParser::get_ll2_expression_parser(TokenType first, TokenType second)\n\t\t{\n\t\t\tfor (auto& entry : ll2_expression_parsers_)\n\t\t\t{\n\t\t\t\tif (entry->first == first && entry->second == second)\n\t\t\t\t\treturn entry->parser.get();\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tParser* ElsaParser::get_statement_parser(TokenType type)\n\t\t{\n\t\t\tauto it = statement_parsers_.find(type);\n\t\t\tif (it != statement_parsers_.end())\n\t\t\t{\n\t\t\t\treturn it->second.get();\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tInfixParser* ElsaParser::get_infix_parser(TokenType type)\n\t\t{\n\t\t\tauto it = infix_parsers_.find(type);\n\t\t\tif (it != infix_parsers_.end())\n\t\t\t{\n\t\t\t\treturn it->second.get();\n\t\t\t}\n\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tint ElsaParser::get_precedence()\n\t\t{\n\t\t\tauto infix_parser = get_infix_parser(current_token()->get_type());\n\t\t\tif (infix_parser != nullptr)\n\t\t\t\treturn infix_parser->precedence();\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tvoid ElsaParser::register_expression_parser(TokenType type, Parser* parser)\n\t\t{\n\t\t\texpression_parsers_.insert(std::pair>(type, std::unique_ptr(parser)));\n\t\t}\n\n\t\tvoid ElsaParser::register_ll2_expression_parser(TokenType first, TokenType second, Parser* parser)\n\t\t{\n\t\t\tll2_expression_parsers_.push_back(std::make_unique(first, second, parser));\n\t\t}\n\n\t\tvoid ElsaParser::register_statement_parser(TokenType type, Parser* parser)\n\t\t{\n\t\t\tstatement_parsers_.insert(std::pair>(type, std::unique_ptr(parser)));\n\t\t}\n\n\t\tvoid ElsaParser::register_infix_parser(TokenType type, InfixParser* parser)\n\t\t{\n\t\t\tinfix_parsers_.insert(std::pair>(type, std::unique_ptr(parser)));\n\t\t}\n\n\t\tvoid ElsaParser::register_prefix_parser(TokenType type)\n\t\t{\n\t\t\tregister_expression_parser(type, new PrefixOperatorParser());\n\t\t}\n\n\t\tvoid ElsaParser::register_postfix_parser(TokenType type, InfixParser* parser)\n\t\t{\n\t\t\tregister_infix_parser(type, parser);\n\t\t}\n\n\t\tvoid ElsaParser::initialize_grammar()\n\t\t{\n\t\t\t\/\/ Statements\n\t\t\tregister_statement_parser(TokenType::Func, new FuncDeclarationParser());\n\t\t\tregister_statement_parser(TokenType::Struct, new StructDeclarationParser());\n\n\t\t\t\/\/ LL2 Expressions\n\t\t\tregister_ll2_expression_parser(TokenType::Identifier, TokenType::Dot, new StructAccessParser());\n\t\t\tregister_ll2_expression_parser(TokenType::Identifier, TokenType::LParen, new FuncCallParser());\n\t\t\tregister_ll2_expression_parser(TokenType::Identifier, TokenType::LSBracket, new ArrayAccessParser());\n\t\t\tregister_ll2_expression_parser(TokenType::Identifier, TokenType::Identifier, new VariableDeclarationParser());\n\n\t\t\t\/\/ Expressions\n\t\t\tregister_expression_parser(TokenType::Var, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Int, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Float, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Char, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Bool, new VariableDeclarationParser());\n\t\t\tregister_expression_parser(TokenType::Identifier, new IdentifierParser());\n\t\t\tregister_expression_parser(TokenType::IntegerLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::FloatLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::CharLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::BoolLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::StringLiteral, new LiteralParser());\n\t\t\tregister_expression_parser(TokenType::Elsa, new ElsaInvokeParser());\n\t\t\tregister_expression_parser(TokenType::New, new CreateStructParser());\n\t\t\tregister_expression_parser(TokenType::If, new ConditionalParser());\n\t\t\tregister_expression_parser(TokenType::Loop, new LoopParser());\n\t\t\tregister_expression_parser(TokenType::Return, new ReturnParser());\n\n\t\t\t\/\/ Prefix\n\t\t\tregister_prefix_parser(TokenType::Exclamation);\n\n\t\t\t\/\/ Infix\n\t\t\tregister_infix_parser(TokenType::Plus, new BinaryOperatorParser(Precedence::Sum));\n\t\t\tregister_infix_parser(TokenType::Minus, new BinaryOperatorParser(Precedence::Sum));\n\t\t\tregister_infix_parser(TokenType::Slash, new BinaryOperatorParser(Precedence::Product));\n\t\t\tregister_infix_parser(TokenType::Asterix, new BinaryOperatorParser(Precedence::Product));\n\t\t\tregister_infix_parser(TokenType::DoubleAmpersand, new BinaryOperatorParser(Precedence::ConditionalAnd));\n\t\t\tregister_infix_parser(TokenType::DoubleVerticalBar, new BinaryOperatorParser(Precedence::ConditionalOr));\n\n\t\t\tregister_infix_parser(TokenType::DoubleEquals, new BinaryOperatorParser(Precedence::Equality));\n\t\t\tregister_infix_parser(TokenType::NotEquals, new BinaryOperatorParser(Precedence::Equality));\n\n\t\t\tregister_infix_parser(TokenType::LessThan, new BinaryOperatorParser(Precedence::Relational));\n\t\t\tregister_infix_parser(TokenType::GreaterThan, new BinaryOperatorParser(Precedence::Relational));\n\t\t\tregister_infix_parser(TokenType::LessThanEquals, new BinaryOperatorParser(Precedence::Relational));\n\t\t\tregister_infix_parser(TokenType::GreaterThanEquals, new BinaryOperatorParser(Precedence::Relational));\n\n\t\t\tregister_infix_parser(TokenType::Equals, new AssignmentParser());\n\n\t\t\t\/\/ Postfix\n\t\t\tregister_postfix_parser(TokenType::PlusPlus, new PostfixOperatorParser(Precedence::Unary));\n\t\t\tregister_postfix_parser(TokenType::MinusMinus, new PostfixOperatorParser(Precedence::Unary));\n\t\t}\n\n\t\tvoid ElsaParser::parse_import_statement()\n\t\t{\n\t\t\tconsume(TokenType::Import);\n\t\t\tauto filename = current_token_->get_value();\n\t\t\tconsume(TokenType::StringLiteral);\n\t\t\tconsume(TokenType::Semicolon);\n\t\t\timport_source_file(filename);\n\t\t}\n\n\t\tvoid ElsaParser::import_source_file(const std::wstring& filename)\n\t\t{\n\t\t\tauto filename_with_extension = filename + L\".elsa\";\n\t\t\tauto parser = ElsaParser(new Lexer(new SourceFile(filename_with_extension.c_str())), &struct_table_, &function_table_);\n\t\t\tparser.parse(program_.get());\n\t\t}\n\n\t\tvoid ElsaParser::parse(Program* program)\n\t\t{\n\t\t\twhile (current_token_->get_type() != TokenType::END)\n\t\t\t{\n\t\t\t\tprogram->add_statement(parse_statement());\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008, 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \n#include \n#include \"fileutils.h\"\n#include \"infocdbbackend.h\"\n#include \"cdbwriter.h\"\n\nclass InfoCdbBackendUnitTest : public QObject\n{\n Q_OBJECT\n InfoCdbBackend *backend;\n\nprivate:\n void createBaseDatabase(QString path);\n void createAlternateDatabase(QString path);\n\nprivate slots:\n void initTestCase();\n void name();\n void databaseExists();\n void databaseDirectory();\n void listKeys();\n void typeForKey();\n void docForKey();\n void keyDeclared();\n void providersForKey();\n void dynamics();\n void removed();\n void cleanupTestCase();\n};\n\nvoid InfoCdbBackendUnitTest::createBaseDatabase(QString path)\n{\n CDBWriter writer(path);\n\n if (! writer.isWritable())\n qFatal(\"Failed to open %s for reading!\", path.toLocal8Bit().data());\n\n writer.add(\"KEYS\", \"Battery.Charging\");\n writer.add(\"KEYS\", \"Internet.BytesOut\");\n writer.add(\"Battery.Charging:KEYTYPE\", \"TRUTH\");\n writer.add(\"Internet.BytesOut:KEYTYPE\", \"INTEGER\");\n writer.add(\"Battery.Charging:KEYDOC\", \"doc1\");\n\n QVariantList providers1;\n QHash provider1;\n provider1.insert(\"plugin\", \"contextkit-dbus\");\n provider1.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextd1\");\n providers1 << QVariant(provider1);\n writer.add(\"Battery.Charging:PROVIDERS\", QVariant(providers1));\n\n QVariantList providers2;\n QHash provider2;\n provider2.insert(\"plugin\", \"contextkit-dbus\");\n provider2.insert(\"constructionString\", \"session:org.freedesktop.ContextKit.contextd2\");\n providers2 << QVariant(provider2);\n writer.add(\"Internet.BytesOut:PROVIDERS\", QVariant(providers2));\n\n writer.close();\n}\n\nvoid InfoCdbBackendUnitTest::createAlternateDatabase(QString path)\n{\n CDBWriter writer(path);\n\n if (! writer.isWritable())\n qFatal(\"Failed to open %s for reading!\", path.toLocal8Bit().data());\n\n writer.add(\"KEYS\", \"Battery.Charging\");\n writer.add(\"KEYS\", \"Battery.Capacity\");\n writer.add(\"Battery.Charging:KEYTYPE\", \"INTEGER\");\n writer.add(\"Battery.Charging:KEYDOC\", \"doc1\");\n writer.add(\"Battery.Capacity:KEYTYPE\", \"INTEGER\");\n writer.add(\"Battery.Capacity:KEYDOC\", \"doc3\");\n\n QVariantList providers1;\n QHash provider1;\n provider1.insert(\"plugin\", \"contextkit-dbus\");\n provider1.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextd1\");\n providers1 << QVariant(provider1);\n writer.add(\"Battery.Charging:PROVIDERS\", QVariant(providers1));\n\n QVariantList providers2;\n QHash provider2;\n QHash provider3;\n provider2.insert(\"plugin\", \"contextkit-dbus\");\n provider2.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextd1\");\n provider3.insert(\"plugin\", \"contextkit-dbus\");\n provider3.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextdX\");\n providers2 << QVariant(provider2);\n providers2 << QVariant(provider3);\n writer.add(\"Battery.Capacity:PROVIDERS\", providers2);\n\n writer.close();\n}\n\nvoid InfoCdbBackendUnitTest::initTestCase()\n{\n createBaseDatabase(\"cache.cdb\");\n\n utilSetEnv(\"CONTEXT_PROVIDERS\", \".\/\");\n utilSetEnv(\"CONTEXT_CORE_DECLARATIONS\", \"\/dev\/null\");\n backend = new InfoCdbBackend();\n}\n\nvoid InfoCdbBackendUnitTest::name()\n{\n QCOMPARE(backend->name(), QString(\"cdb\"));\n}\n\nvoid InfoCdbBackendUnitTest::databaseDirectory()\n{\n QVERIFY(backend->databaseDirectory() == QString(\".\/\") ||\n backend->databaseDirectory() == QString(\".\"));\n}\n\nvoid InfoCdbBackendUnitTest::databaseExists()\n{\n QCOMPARE(backend->databaseExists(), true);\n}\n\nvoid InfoCdbBackendUnitTest::listKeys()\n{\n QStringList keys = backend->listKeys();\n QCOMPARE(keys.count(), 2);\n QVERIFY(keys.contains(\"Battery.Charging\"));\n QVERIFY(keys.contains(\"Internet.BytesOut\"));\n}\n\nvoid InfoCdbBackendUnitTest::typeForKey()\n{\n QCOMPARE(backend->typeForKey(\"Internet.BytesOut\"), QString(\"INTEGER\"));\n QCOMPARE(backend->typeForKey(\"Battery.Charging\"), QString(\"TRUTH\"));\n QCOMPARE(backend->typeForKey(\"Does.Not.Exist\"), QString());\n}\n\nvoid InfoCdbBackendUnitTest::docForKey()\n{\n QCOMPARE(backend->docForKey(\"Internet.BytesOut\"), QString());\n QCOMPARE(backend->docForKey(\"Battery.Charging\"), QString(\"doc1\"));\n QCOMPARE(backend->docForKey(\"Does.Not.Exist\"), QString());\n}\n\nvoid InfoCdbBackendUnitTest::keyDeclared()\n{\n foreach (QString key, backend->listKeys())\n QCOMPARE(backend->keyDeclared(key), true);\n\n QCOMPARE(backend->keyDeclared(\"Does.Not.Exist\"), false);\n QCOMPARE(backend->keyDeclared(\"Battery.Charging\"), true);\n}\n\nvoid InfoCdbBackendUnitTest::providersForKey()\n{\n QList list1 = backend->providersForKey(\"Battery.Charging\");\n QCOMPARE(list1.count(), 1);\n QCOMPARE(list1.at(0).plugin, QString(\"contextkit-dbus\"));\n QCOMPARE(list1.at(0).constructionString, QString(\"system:org.freedesktop.ContextKit.contextd1\"));\n\n QList list2 = backend->providersForKey(\"Does.Not.Exist\");\n QCOMPARE(list2.count(), 0);\n}\n\nvoid InfoCdbBackendUnitTest::dynamics()\n{\n backend->connectNotify(\"-\"); \/\/ Fake it. Spy does something fishy here.\n\n \/\/ Setup the spy observers\n QSignalSpy spy1(backend, SIGNAL(keysRemoved(QStringList)));\n QSignalSpy spy2(backend, SIGNAL(keysChanged(QStringList)));\n QSignalSpy spy3(backend, SIGNAL(keyChanged(QString)));\n QSignalSpy spy4(backend, SIGNAL(keysAdded(QStringList)));\n\n createAlternateDatabase(\"cache-next.cdb\");\n QFile::remove(\"cache.cdb\");\n QFile::copy(\"cache-next.cdb\", \"cache.cdb\");\n QTest::qWait(DEFAULT_WAIT_PERIOD);\n\n \/\/ Test the new values\n QCOMPARE(backend->databaseExists(), true);\n QCOMPARE(backend->listKeys().count(), 2);\n QVERIFY(backend->listKeys().contains(\"Battery.Charging\"));\n QVERIFY(backend->listKeys().contains(\"Battery.Capacity\"));\n QCOMPARE(backend->typeForKey(\"Battery.Charging\"), QString(\"INTEGER\"));\n QCOMPARE(backend->docForKey(\"Battery.Charging\"), QString(\"doc1\"));\n\n \/\/ Check providers\n QList list1 = backend->providersForKey(\"Battery.Charging\");\n QCOMPARE(list1.count(), 1);\n QCOMPARE(list1.at(0).plugin, QString(\"contextkit-dbus\"));\n QCOMPARE(list1.at(0).constructionString, QString(\"system:org.freedesktop.ContextKit.contextd1\"));\n QList list2 = backend->providersForKey(\"Battery.Capacity\");\n QCOMPARE(list2.count(), 2);\n QCOMPARE(list2.at(0).plugin, QString(\"contextkit-dbus\"));\n QCOMPARE(list2.at(0).constructionString, QString(\"system:org.freedesktop.ContextKit.contextd1\"));\n QCOMPARE(list2.at(1).plugin, QString(\"contextkit-dbus\"));\n QCOMPARE(list2.at(1).constructionString, QString(\"system:org.freedesktop.ContextKit.contextdX\"));\n\n \/\/ Test emissions\n QCOMPARE(spy1.count(), 1);\n QList args1 = spy1.takeFirst();\n QCOMPARE(args1.at(0).toList().size(), 1);\n QCOMPARE(args1.at(0).toStringList().at(0), QString(\"Internet.BytesOut\"));\n\n QCOMPARE(spy2.count(), 1);\n QList args2 = spy2.takeFirst();\n QCOMPARE(args2.at(0).toList().size(), 2);\n QCOMPARE(args2.at(0).toStringList().at(0), QString(\"Battery.Charging\"));\n QCOMPARE(args2.at(0).toStringList().at(1), QString(\"Battery.Capacity\"));\n\n QCOMPARE(spy3.count(), 3);\n\n QCOMPARE(spy4.count(), 1);\n QList args4 = spy4.takeFirst();\n QCOMPARE(args4.at(0).toList().size(), 1);\n QCOMPARE(args4.at(0).toStringList().at(0), QString(\"Battery.Capacity\"));\n\n backend->disconnectNotify(\"-\"); \/\/ Fake it. Spy does something fishy here.\n}\n\nvoid InfoCdbBackendUnitTest::removed()\n{\n backend->connectNotify(\"-\"); \/\/ Fake it. Spy does something fishy here.\n QSignalSpy spy(backend, SIGNAL(keysRemoved(QStringList)));\n\n QFile::remove(\"cache.cdb\");\n\n QTest::qWait(DEFAULT_WAIT_PERIOD);\n\n QCOMPARE(spy.count(), 1);\n QList args = spy.takeFirst();\n QCOMPARE(args.at(0).toList().size(), 2);\n\n backend->disconnectNotify(\"-\"); \/\/ Fake it. Spy does something fishy here.\n}\n\nvoid InfoCdbBackendUnitTest::cleanupTestCase()\n{\n QFile::remove(\"cache.cdb\");\n QFile::remove(\"cache-next.cdb\");\n}\n\n#include \"infocdbbackendunittest.moc\"\nQTEST_MAIN(InfoCdbBackendUnitTest);\nVersion compatibility unit test for cdb backend.\/*\n * Copyright (C) 2008, 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \n#include \n#include \"fileutils.h\"\n#include \"infocdbbackend.h\"\n#include \"cdbwriter.h\"\n\nclass InfoCdbBackendUnitTest : public QObject\n{\n Q_OBJECT\n InfoCdbBackend *backend;\n\nprivate:\n void createBaseDatabase(QString path);\n void createAlternateDatabase(QString path);\n void createIncompatibleDatabase(QString path);\n\nprivate slots:\n void initTestCase();\n void name();\n void databaseExists();\n void databaseDirectory();\n void listKeys();\n void typeForKey();\n void docForKey();\n void keyDeclared();\n void providersForKey();\n void dynamics();\n void removed();\n void incompatibleDatabase();\n void cleanupTestCase();\n};\n\nvoid InfoCdbBackendUnitTest::createBaseDatabase(QString path)\n{\n CDBWriter writer(path);\n\n if (! writer.isWritable())\n qFatal(\"Failed to open %s for reading!\", path.toLocal8Bit().data());\n\n writer.add(\"KEYS\", \"Battery.Charging\");\n writer.add(\"KEYS\", \"Internet.BytesOut\");\n writer.add(\"Battery.Charging:KEYTYPE\", \"TRUTH\");\n writer.add(\"Internet.BytesOut:KEYTYPE\", \"INTEGER\");\n writer.add(\"Battery.Charging:KEYDOC\", \"doc1\");\n\n QVariantList providers1;\n QHash provider1;\n provider1.insert(\"plugin\", \"contextkit-dbus\");\n provider1.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextd1\");\n providers1 << QVariant(provider1);\n writer.add(\"Battery.Charging:PROVIDERS\", QVariant(providers1));\n\n QVariantList providers2;\n QHash provider2;\n provider2.insert(\"plugin\", \"contextkit-dbus\");\n provider2.insert(\"constructionString\", \"session:org.freedesktop.ContextKit.contextd2\");\n providers2 << QVariant(provider2);\n writer.add(\"Internet.BytesOut:PROVIDERS\", QVariant(providers2));\n\n writer.close();\n}\n\nvoid InfoCdbBackendUnitTest::createAlternateDatabase(QString path)\n{\n CDBWriter writer(path);\n\n if (! writer.isWritable())\n qFatal(\"Failed to open %s for reading!\", path.toLocal8Bit().data());\n\n writer.add(\"KEYS\", \"Battery.Charging\");\n writer.add(\"KEYS\", \"Battery.Capacity\");\n writer.add(\"Battery.Charging:KEYTYPE\", \"INTEGER\");\n writer.add(\"Battery.Charging:KEYDOC\", \"doc1\");\n writer.add(\"Battery.Capacity:KEYTYPE\", \"INTEGER\");\n writer.add(\"Battery.Capacity:KEYDOC\", \"doc3\");\n\n QVariantList providers1;\n QHash provider1;\n provider1.insert(\"plugin\", \"contextkit-dbus\");\n provider1.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextd1\");\n providers1 << QVariant(provider1);\n writer.add(\"Battery.Charging:PROVIDERS\", QVariant(providers1));\n\n QVariantList providers2;\n QHash provider2;\n QHash provider3;\n provider2.insert(\"plugin\", \"contextkit-dbus\");\n provider2.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextd1\");\n provider3.insert(\"plugin\", \"contextkit-dbus\");\n provider3.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextdX\");\n providers2 << QVariant(provider2);\n providers2 << QVariant(provider3);\n writer.add(\"Battery.Capacity:PROVIDERS\", providers2);\n\n writer.close();\n}\n\nvoid InfoCdbBackendUnitTest::createIncompatibleDatabase(QString path)\n{\n CDBWriter writer(path);\n\n if (! writer.isWritable())\n qFatal(\"Failed to open %s for reading!\", path.toLocal8Bit().data());\n\n writer.add(\"KEYS\", \"Battery.Charging\");\n writer.add(\"Battery.Charging:KEYTYPE\", \"INTEGER\");\n writer.add(\"Battery.Charging:KEYDOC\", \"doc1\");\n\n QVariantList providers;\n QHash provider1;\n provider1.insert(\"plugin\", \"contextkit-dbus\");\n provider1.insert(\"constructionString\", \"system:org.freedesktop.ContextKit.contextd1\");\n providers << QVariant(provider1);\n writer.add(\"Battery.Charging:PROVIDERS\", QVariant(providers));\n writer.add(\"VERSION\", \"bull\");\n\n writer.close();\n}\n\nvoid InfoCdbBackendUnitTest::initTestCase()\n{\n createBaseDatabase(\"cache.cdb\");\n\n utilSetEnv(\"CONTEXT_PROVIDERS\", \".\/\");\n utilSetEnv(\"CONTEXT_CORE_DECLARATIONS\", \"\/dev\/null\");\n backend = new InfoCdbBackend();\n}\n\nvoid InfoCdbBackendUnitTest::name()\n{\n QCOMPARE(backend->name(), QString(\"cdb\"));\n}\n\nvoid InfoCdbBackendUnitTest::databaseDirectory()\n{\n QVERIFY(backend->databaseDirectory() == QString(\".\/\") ||\n backend->databaseDirectory() == QString(\".\"));\n}\n\nvoid InfoCdbBackendUnitTest::databaseExists()\n{\n QCOMPARE(backend->databaseExists(), true);\n}\n\nvoid InfoCdbBackendUnitTest::listKeys()\n{\n QStringList keys = backend->listKeys();\n QCOMPARE(keys.count(), 2);\n QVERIFY(keys.contains(\"Battery.Charging\"));\n QVERIFY(keys.contains(\"Internet.BytesOut\"));\n}\n\nvoid InfoCdbBackendUnitTest::typeForKey()\n{\n QCOMPARE(backend->typeForKey(\"Internet.BytesOut\"), QString(\"INTEGER\"));\n QCOMPARE(backend->typeForKey(\"Battery.Charging\"), QString(\"TRUTH\"));\n QCOMPARE(backend->typeForKey(\"Does.Not.Exist\"), QString());\n}\n\nvoid InfoCdbBackendUnitTest::docForKey()\n{\n QCOMPARE(backend->docForKey(\"Internet.BytesOut\"), QString());\n QCOMPARE(backend->docForKey(\"Battery.Charging\"), QString(\"doc1\"));\n QCOMPARE(backend->docForKey(\"Does.Not.Exist\"), QString());\n}\n\nvoid InfoCdbBackendUnitTest::keyDeclared()\n{\n foreach (QString key, backend->listKeys())\n QCOMPARE(backend->keyDeclared(key), true);\n\n QCOMPARE(backend->keyDeclared(\"Does.Not.Exist\"), false);\n QCOMPARE(backend->keyDeclared(\"Battery.Charging\"), true);\n}\n\nvoid InfoCdbBackendUnitTest::providersForKey()\n{\n QList list1 = backend->providersForKey(\"Battery.Charging\");\n QCOMPARE(list1.count(), 1);\n QCOMPARE(list1.at(0).plugin, QString(\"contextkit-dbus\"));\n QCOMPARE(list1.at(0).constructionString, QString(\"system:org.freedesktop.ContextKit.contextd1\"));\n\n QList list2 = backend->providersForKey(\"Does.Not.Exist\");\n QCOMPARE(list2.count(), 0);\n}\n\nvoid InfoCdbBackendUnitTest::dynamics()\n{\n backend->connectNotify(\"-\"); \/\/ Fake it. Spy does something fishy here.\n\n \/\/ Setup the spy observers\n QSignalSpy spy1(backend, SIGNAL(keysRemoved(QStringList)));\n QSignalSpy spy2(backend, SIGNAL(keysChanged(QStringList)));\n QSignalSpy spy3(backend, SIGNAL(keyChanged(QString)));\n QSignalSpy spy4(backend, SIGNAL(keysAdded(QStringList)));\n\n createAlternateDatabase(\"cache-next.cdb\");\n QFile::remove(\"cache.cdb\");\n QFile::copy(\"cache-next.cdb\", \"cache.cdb\");\n QTest::qWait(DEFAULT_WAIT_PERIOD);\n\n \/\/ Test the new values\n QCOMPARE(backend->databaseExists(), true);\n QCOMPARE(backend->listKeys().count(), 2);\n QVERIFY(backend->listKeys().contains(\"Battery.Charging\"));\n QVERIFY(backend->listKeys().contains(\"Battery.Capacity\"));\n QCOMPARE(backend->typeForKey(\"Battery.Charging\"), QString(\"INTEGER\"));\n QCOMPARE(backend->docForKey(\"Battery.Charging\"), QString(\"doc1\"));\n\n \/\/ Check providers\n QList list1 = backend->providersForKey(\"Battery.Charging\");\n QCOMPARE(list1.count(), 1);\n QCOMPARE(list1.at(0).plugin, QString(\"contextkit-dbus\"));\n QCOMPARE(list1.at(0).constructionString, QString(\"system:org.freedesktop.ContextKit.contextd1\"));\n QList list2 = backend->providersForKey(\"Battery.Capacity\");\n QCOMPARE(list2.count(), 2);\n QCOMPARE(list2.at(0).plugin, QString(\"contextkit-dbus\"));\n QCOMPARE(list2.at(0).constructionString, QString(\"system:org.freedesktop.ContextKit.contextd1\"));\n QCOMPARE(list2.at(1).plugin, QString(\"contextkit-dbus\"));\n QCOMPARE(list2.at(1).constructionString, QString(\"system:org.freedesktop.ContextKit.contextdX\"));\n\n \/\/ Test emissions\n QCOMPARE(spy1.count(), 1);\n QList args1 = spy1.takeFirst();\n QCOMPARE(args1.at(0).toList().size(), 1);\n QCOMPARE(args1.at(0).toStringList().at(0), QString(\"Internet.BytesOut\"));\n\n QCOMPARE(spy2.count(), 1);\n QList args2 = spy2.takeFirst();\n QCOMPARE(args2.at(0).toList().size(), 2);\n QCOMPARE(args2.at(0).toStringList().at(0), QString(\"Battery.Charging\"));\n QCOMPARE(args2.at(0).toStringList().at(1), QString(\"Battery.Capacity\"));\n\n QCOMPARE(spy3.count(), 3);\n\n QCOMPARE(spy4.count(), 1);\n QList args4 = spy4.takeFirst();\n QCOMPARE(args4.at(0).toList().size(), 1);\n QCOMPARE(args4.at(0).toStringList().at(0), QString(\"Battery.Capacity\"));\n\n backend->disconnectNotify(\"-\"); \/\/ Fake it. Spy does something fishy here.\n}\n\nvoid InfoCdbBackendUnitTest::removed()\n{\n backend->connectNotify(\"-\"); \/\/ Fake it. Spy does something fishy here.\n QSignalSpy spy(backend, SIGNAL(keysRemoved(QStringList)));\n\n QFile::remove(\"cache.cdb\");\n\n QTest::qWait(DEFAULT_WAIT_PERIOD);\n\n QCOMPARE(spy.count(), 1);\n QList args = spy.takeFirst();\n QCOMPARE(args.at(0).toList().size(), 2);\n\n backend->disconnectNotify(\"-\"); \/\/ Fake it. Spy does something fishy here.\n}\n\nvoid InfoCdbBackendUnitTest::incompatibleDatabase()\n{\n QFile::remove(\"cache.cdb\");\n QTest::qWait(DEFAULT_WAIT_PERIOD);\n createIncompatibleDatabase(\"cache.cdb\");\n QTest::qWait(DEFAULT_WAIT_PERIOD);\n\n QCOMPARE(backend->databaseExists(), true);\n QCOMPARE(backend->listKeys().count(), 0);\n QCOMPARE(backend->typeForKey(\"Battery.Charging\"), QString());\n QCOMPARE(backend->docForKey(\"Battery.Charging\"), QString());\n QCOMPARE(backend->providersForKey(\"Battery.Charging\").size(), 0);\n}\n\nvoid InfoCdbBackendUnitTest::cleanupTestCase()\n{\n QFile::remove(\"cache.cdb\");\n QFile::remove(\"cache-next.cdb\");\n}\n\n#include \"infocdbbackendunittest.moc\"\nQTEST_MAIN(InfoCdbBackendUnitTest);\n<|endoftext|>"} {"text":"\/***************************************************************************\r\n * Copyright (c) 2008 Werner Mayer *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include \r\n# include \r\n# include \r\n# include \r\n#endif\r\n\r\n#include \r\n\r\n#include \"FeatureFillet.h\"\r\n\r\n\r\nusing namespace PartDesign;\r\n\r\n\r\nPROPERTY_SOURCE(PartDesign::Fillet, PartDesign::DressUp)\r\n\r\nconst App::PropertyFloatConstraint::Constraints floatRadius = {0.0f,FLT_MAX,0.1f};\r\n\r\nFillet::Fillet()\r\n{\r\n ADD_PROPERTY(Radius,(1.0f));\r\n Radius.setConstraints(&floatRadius);\r\n}\r\n\r\nshort Fillet::mustExecute() const\r\n{\r\n if (Base.isTouched() || Radius.isTouched())\r\n return 1;\r\n if (Base.getValue() && Base.getValue()->isTouched())\r\n return 1;\r\n return 0;\r\n}\r\n\r\nApp::DocumentObjectExecReturn *Fillet::execute(void)\r\n{\r\n App::DocumentObject* link = Base.getValue();\r\n if (!link)\r\n return new App::DocumentObjectExecReturn(\"No object linked\");\r\n if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))\r\n return new App::DocumentObjectExecReturn(\"Linked object is not a Part object\");\r\n Part::Feature *base = static_cast(Base.getValue());\r\n const Part::TopoShape& TopShape = base->Shape.getShape();\r\n if (TopShape._Shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Cannot fillet invalid shape\");\r\n\r\n const std::vector& SubVals = Base.getSubValuesStartsWith(\"Edge\");\r\n if (SubVals.size() == 0)\r\n return new App::DocumentObjectExecReturn(\"No edges specified\");\r\n\r\n float radius = Radius.getValue();\r\n\r\n try {\r\n BRepFilletAPI_MakeFillet mkFillet(base->Shape.getValue());\r\n\r\n for (std::vector::const_iterator it= SubVals.begin();it!=SubVals.end();++it) {\r\n TopoDS_Edge edge = TopoDS::Edge(TopShape.getSubShape(it->c_str()));\r\n mkFillet.Add(radius, radius, edge);\r\n }\r\n\r\n if (!mkFillet.IsDone())\r\n return new App::DocumentObjectExecReturn(\"Failed to create fillet\");\r\n\r\n TopoDS_Shape shape = mkFillet.Shape();\r\n if (shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Resulting shape is null\");\r\n this->Shape.setValue(shape);\r\n return App::DocumentObject::StdReturn;\r\n }\r\n catch (Standard_Failure) {\r\n Handle_Standard_Failure e = Standard_Failure::Caught();\r\n return new App::DocumentObjectExecReturn(e->GetMessageString());\r\n }\r\n}\r\n0000532: fillet command in Part Design shows only partial dialog\/***************************************************************************\r\n * Copyright (c) 2008 Werner Mayer *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include \r\n# include \r\n# include \r\n# include \r\n#endif\r\n\r\n#include \r\n\r\n#include \"FeatureFillet.h\"\r\n\r\n\r\nusing namespace PartDesign;\r\n\r\n\r\nPROPERTY_SOURCE(PartDesign::Fillet, PartDesign::DressUp)\r\n\r\nconst App::PropertyFloatConstraint::Constraints floatRadius = {0.0f,FLT_MAX,0.1f};\r\n\r\nFillet::Fillet()\r\n{\r\n ADD_PROPERTY(Radius,(1.0f));\r\n Radius.setConstraints(&floatRadius);\r\n}\r\n\r\nshort Fillet::mustExecute() const\r\n{\r\n if (Base.isTouched() || Radius.isTouched())\r\n return 1;\r\n if (Base.getValue() && Base.getValue()->isTouched())\r\n return 1;\r\n return 0;\r\n}\r\n\r\nApp::DocumentObjectExecReturn *Fillet::execute(void)\r\n{\r\n App::DocumentObject* link = Base.getValue();\r\n if (!link)\r\n return new App::DocumentObjectExecReturn(\"No object linked\");\r\n if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))\r\n return new App::DocumentObjectExecReturn(\"Linked object is not a Part object\");\r\n Part::Feature *base = static_cast(Base.getValue());\r\n const Part::TopoShape& TopShape = base->Shape.getShape();\r\n if (TopShape._Shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Cannot fillet invalid shape\");\r\n\r\n const std::vector& SubVals = Base.getSubValuesStartsWith(\"Edge\");\r\n if (SubVals.size() == 0)\r\n return new App::DocumentObjectExecReturn(\"No edges specified\");\r\n\r\n float radius = Radius.getValue();\r\n\r\n try {\r\n BRepFilletAPI_MakeFillet mkFillet(base->Shape.getValue());\r\n\r\n for (std::vector::const_iterator it= SubVals.begin();it!=SubVals.end();++it) {\r\n TopoDS_Edge edge = TopoDS::Edge(TopShape.getSubShape(it->c_str()));\r\n mkFillet.Add(radius, radius, edge);\r\n }\r\n\r\n mkFillet.Build();\r\n if (!mkFillet.IsDone())\r\n return new App::DocumentObjectExecReturn(\"Failed to create fillet\");\r\n\r\n TopoDS_Shape shape = mkFillet.Shape();\r\n if (shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Resulting shape is null\");\r\n this->Shape.setValue(shape);\r\n return App::DocumentObject::StdReturn;\r\n }\r\n catch (Standard_Failure) {\r\n Handle_Standard_Failure e = Standard_Failure::Caught();\r\n return new App::DocumentObjectExecReturn(e->GetMessageString());\r\n }\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * Qumulus UML editor\n * Author: Frank Erens\n * Author: Randy Thiemann\n *\n *\/\n\n#include \"PackageShape.h\"\n#include \n#include \n\n#include \n\nQUML_BEGIN_NAMESPACE_GD\n\nPackageShape::PackageShape(QuUK::Element* e, \n DiagramElement* p) :\n SelectableShape(e, p) {\n constexpr int kPackageZOrdering = -2;\n setZValue(kPackageZOrdering);\n updateSizeConstraints();\n resize(0, 0);\n}\n\nPackageShape::PackageShape(const PackageShape& c) :\n SelectableShape(c) {}\n\nvoid PackageShape::updateSizeConstraints() {\n setMinimumSize({100, 10 + std::max(packageNameWidth(), 50)});\n}\n\nvoid PackageShape::resize(double w, double h) {\n w = minimumSize().width() == -1 ? w : std::max(w, minimumSize().width());\n h = minimumSize().height() == -1 ? h : std::max(h, minimumSize().height());\n\n setSize({w, h});\n}\n\nvoid PackageShape::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, \n QWidget* widget) {\n painter->setBrush(Qt::white);\n\n painter->drawRect(0, 0, 30, 10);\n painter->drawRect(0, 10, width(), height() - 10);\n\n int twidth = packageNameWidth();\n\n painter->setFont(font);\n painter->drawText((width() \/ 2) - (twidth \/ 2), 25, packageName());\n\n SelectableShape::paint(painter, option, widget);\n}\n\nQString PackageShape::packageName() const {\n return *(dynamic_cast(modelElement())->name());\n}\n\nint PackageShape::packageNameWidth() const {\n QFont font = sharedStyle()->font();\n font.setBold(true);\n\n QFontMetrics m(font);\n return m.width(packageName());\n}\n\nQUML_END_NAMESPACE_GD\n\nUpdate size constraint in paint.\/*\n * Qumulus UML editor\n * Author: Frank Erens\n * Author: Randy Thiemann\n *\n *\/\n\n#include \"PackageShape.h\"\n#include \n#include \n\n#include \n\nQUML_BEGIN_NAMESPACE_GD\n\nPackageShape::PackageShape(QuUK::Element* e, \n DiagramElement* p) :\n SelectableShape(e, p) {\n constexpr int kPackageZOrdering = -2;\n setZValue(kPackageZOrdering);\n updateSizeConstraints();\n resize(0, 0);\n}\n\nPackageShape::PackageShape(const PackageShape& c) :\n SelectableShape(c) {}\n\nvoid PackageShape::updateSizeConstraints() {\n setMinimumSize({100, 10 + std::max(packageNameWidth(), 50)});\n}\n\nvoid PackageShape::resize(double w, double h) {\n w = minimumSize().width() == -1 ? w : std::max(w, minimumSize().width());\n h = minimumSize().height() == -1 ? h : std::max(h, minimumSize().height());\n\n setSize({w, h});\n}\n\nvoid PackageShape::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, \n QWidget* widget) {\n updateSizeConstraints();\n resize(size());\n\n painter->setBrush(Qt::white);\n\n painter->drawRect(0, 0, 30, 10);\n painter->drawRect(0, 10, width(), height() - 10);\n\n int twidth = packageNameWidth();\n\n painter->setFont(font);\n painter->drawText((width() \/ 2) - (twidth \/ 2), 25, packageName());\n\n SelectableShape::paint(painter, option, widget);\n}\n\nQString PackageShape::packageName() const {\n return *(dynamic_cast(modelElement())->name());\n}\n\nint PackageShape::packageNameWidth() const {\n QFont font = sharedStyle()->font();\n font.setBold(true);\n\n QFontMetrics m(font);\n return m.width(packageName());\n}\n\nQUML_END_NAMESPACE_GD\n\n<|endoftext|>"} {"text":"\/*\n\nopenfx-arena - https:\/\/github.com\/olear\/openfx-arena\n\nCopyright (c) 2015, Ole-André Rodlie \nCopyright (c) 2015, FxArena DA \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Neither the name of FxArena DA nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"ReadPSD.h\"\n#include \n#include \n#include \n#include \"GenericReader.h\"\n#include \"GenericOCIO.h\"\n#include \"ofxsMacros.h\"\n\n#ifdef OFX_IO_USING_OCIO\n#include \n#endif\n\n#define kPluginName \"ReadPSD\"\n#define kPluginGrouping \"Image\/Readers\"\n#define kPluginIdentifier \"net.fxarena.openfx.ReadPSD\"\n#define kPluginVersionMajor 1\n#define kPluginVersionMinor 3\n\n#define kSupportsRGBA true\n#define kSupportsRGB false\n#define kSupportsAlpha false\n#define kSupportsTiles false\n#define kIsMultiPlanar true\n\n#define DEBUG_MAGICK false\n\nclass ReadPSDPlugin : public GenericReaderPlugin\n{\npublic:\n ReadPSDPlugin(OfxImageEffectHandle handle);\n virtual ~ReadPSDPlugin();\nprivate:\n virtual bool isVideoStream(const std::string& \/*filename*\/) OVERRIDE FINAL { return false; }\n virtual void decode(const std::string& filename, OfxTime time, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds,\n OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, int rowBytes) OVERRIDE FINAL\n {\n std::string rawComps;\n switch (pixelComponents) {\n case OFX::ePixelComponentAlpha:\n rawComps = kOfxImageComponentAlpha;\n break;\n case OFX::ePixelComponentRGB:\n rawComps = kOfxImageComponentRGB;\n break;\n case OFX::ePixelComponentRGBA:\n rawComps = kOfxImageComponentRGBA;\n break;\n default:\n OFX::throwSuiteStatusException(kOfxStatFailed);\n return;\n }\n decodePlane(filename, time, renderWindow, pixelData, bounds, pixelComponents, pixelComponentCount, rawComps, rowBytes);\n }\n virtual void getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents) OVERRIDE FINAL;\n virtual void decodePlane(const std::string& filename, OfxTime time, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds, OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, const std::string& rawComponents, int rowBytes) OVERRIDE FINAL;\n virtual bool getFrameBounds(const std::string& filename, OfxTime time, OfxRectI *bounds, double *par, std::string *error) OVERRIDE FINAL;\n virtual void restoreState(const std::string& filename) OVERRIDE FINAL;\n virtual void onInputFileChanged(const std::string& newFile, OFX::PreMultiplicationEnum *premult, OFX::PixelComponentEnum *components, int *componentCount) OVERRIDE FINAL;\n int getImageLayers(const std::string& filename);\n int _imageLayers;\n int _imageWidth;\n int _imageHeight;\n};\n\nReadPSDPlugin::ReadPSDPlugin(OfxImageEffectHandle handle)\n: GenericReaderPlugin(handle, kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles,\n#ifdef OFX_EXTENSIONS_NUKE\n(OFX::getImageEffectHostDescription() && OFX::getImageEffectHostDescription()->isMultiPlanar) ? kIsMultiPlanar : false\n#else\nfalse\n#endif\n)\n,_imageLayers(0)\n,_imageWidth(0)\n,_imageHeight(0)\n{\n Magick::InitializeMagick(NULL);\n assert(_outputComponents);\n}\n\nReadPSDPlugin::~ReadPSDPlugin()\n{\n}\n\nint ReadPSDPlugin::getImageLayers(const std::string &filename)\n{\n #ifdef DEBUG\n std::cout << \"getImageLayers ...\" << std::endl;\n #endif\n int layers = 0;\n int max = 999;\n Magick::Image image;\n #ifdef DEBUG\n image.debug(DEBUG_MAGICK);\n #endif\n while (layers0)\n layers--;\n #ifdef DEBUG\n std::cout << \"found \" << layers << \" layers\" << std::endl;\n #endif\n return layers;\n}\n\nvoid ReadPSDPlugin::getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents)\n{\n #ifdef DEBUG\n std::cout << \"getClipComponents ...\" << std::endl;\n #endif\n assert(isMultiPlanar());\n clipComponents.addClipComponents(*_outputClip, getOutputComponents());\n clipComponents.setPassThroughClip(NULL, args.time, args.view);\n if (_imageLayers>0) {\n for(int i = 1; i<_imageLayers+1;i++) {\n std::string component(kNatronOfxImageComponentsPlane);\n std::ostringstream layerName;\n layerName << \"Layer#\" << i;\n component.append(layerName.str());\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"R\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"G\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"B\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"A\");\n clipComponents.addClipComponents(*_outputClip, component);\n }\n }\n}\n\nvoid ReadPSDPlugin::decodePlane(const std::string& filename, OfxTime \/*time*\/, const OfxRectI& \/*renderWindow*\/, float *pixelData, const OfxRectI& bounds,\n OFX::PixelComponentEnum \/*pixelComponents*\/, int \/*pixelComponentCount*\/, const std::string& rawComponents, int \/*rowBytes*\/)\n{\n #ifdef DEBUG\n std::cout << \"decodePlane ...\" << std::endl;\n #endif\n int layer = 0;\n std::string layerInfo = rawComponents;\n std::replace(layerInfo.begin(), layerInfo.end(), '_', ' ');\n std::stringstream stream(layerInfo);\n std::string streamInfo;\n while (stream>>streamInfo) {\n std::string findLayer = \"Layer#\";\n if (streamInfo.find(findLayer) != std::string::npos) {\n streamInfo.erase(streamInfo.find(findLayer),findLayer.length());\n layer = std::atoi(streamInfo.c_str());\n }\n }\n Magick::Image image;\n #ifdef DEBUG\n image.debug(DEBUG_MAGICK);\n #endif\n image.backgroundColor(\"none\");\n std::ostringstream file;\n file << filename.c_str() << \"[\" << layer << \"]\";\n image.read(file.str());\n if (image.columns()>0 && image.rows()>0) {\n Magick::Image container(Magick::Geometry(bounds.x2,bounds.y2),Magick::Color(\"rgba(0,0,0,0)\"));\n #ifdef DEBUG\n container.debug(DEBUG_MAGICK);\n #endif\n container.composite(image,image.page().xOff(),image.page().yOff(),Magick::OverCompositeOp);\n container.flip();\n container.write(0,0,bounds.x2,bounds.y2,\"RGBA\",Magick::FloatPixel,pixelData);\n }\n else {\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n}\n\nbool ReadPSDPlugin::getFrameBounds(const std::string& \/*filename*\/,\n OfxTime \/*time*\/,\n OfxRectI *bounds,\n double *par,\n std::string *\/*error*\/)\n{\n #ifdef DEBUG\n std::cout << \"getFrameBounds ...\" << std::endl;\n #endif\n if (_imageWidth>0 && _imageHeight>0) {\n bounds->x1 = 0;\n bounds->x2 = _imageWidth;\n bounds->y1 = 0;\n bounds->y2 = _imageHeight;\n *par = 1.0;\n }\n return true;\n}\n\nvoid ReadPSDPlugin::restoreState(const std::string& filename)\n{\n #ifdef DEBUG\n std::cout << \"restoreState ...\" << std::endl;\n #endif\n Magick::Image image;\n #ifdef DEBUG\n image.debug(DEBUG_MAGICK);\n #endif\n image.read(filename);\n if (image.columns()>0 && image.rows()>0) {\n _imageWidth = image.columns();\n _imageHeight = image.rows();\n _imageLayers = getImageLayers(filename);\n }\n else {\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n}\n\nvoid ReadPSDPlugin::onInputFileChanged(const std::string& newFile,\n OFX::PreMultiplicationEnum *premult,\n OFX::PixelComponentEnum *components,int *\/*componentCount*\/)\n{\n #ifdef DEBUG\n std::cout << \"onInputFileChanged ...\" << std::endl;\n #endif\n assert(premult && components);\n Magick::Image image;\n #ifdef DEBUG\n image.debug(DEBUG_MAGICK);\n #endif\n image.read(newFile);\n if (image.columns()>0 && image.rows()>0) {\n _imageWidth = image.columns();\n _imageHeight = image.rows();\n _imageLayers = getImageLayers(newFile);\n # ifdef OFX_IO_USING_OCIO\n switch(image.colorSpace()) {\n case Magick::RGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::sRGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::scRGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::Rec709LumaColorspace:\n _ocio->setInputColorspace(\"Rec709\");\n break;\n case Magick::Rec709YCbCrColorspace:\n _ocio->setInputColorspace(\"Rec709\");\n break;\n default:\n _ocio->setInputColorspace(\"Linear\");\n break;\n }\n # endif \/\/ OFX_IO_USING_OCIO\n }\n else {\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n *components = OFX::ePixelComponentRGBA;\n *premult = OFX::eImageOpaque;\n}\n\nusing namespace OFX;\n\nmDeclareReaderPluginFactory(ReadPSDPluginFactory, {}, {}, false);\n\n\/** @brief The basic describe function, passed a plugin descriptor *\/\nvoid ReadPSDPluginFactory::describe(OFX::ImageEffectDescriptor &desc)\n{\n GenericReaderDescribe(desc, kSupportsTiles, kIsMultiPlanar);\n desc.setLabel(kPluginName);\n\n #ifdef OFX_EXTENSIONS_TUTTLE\n const char* extensions[] = {\"psd\", NULL};\n desc.addSupportedExtensions(extensions);\n desc.setPluginEvaluation(92);\n #endif\n\n std::string magickV = MagickCore::GetMagickVersion(NULL);\n desc.setPluginDescription(\"Read PSD image format.\\n\\nWritten by Ole-André Rodlie \\n\\nPowered by \"+magickV);\n}\n\n\/** @brief The describe in context function, passed a plugin descriptor and a context *\/\nvoid ReadPSDPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum context)\n{\n PageParamDescriptor *page = GenericReaderDescribeInContextBegin(desc, context, isVideoStreamPlugin(), kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles);\n GenericReaderDescribeInContextEnd(desc, context, page, \"reference\", \"reference\");\n}\n\n\/** @brief The create instance function, the plugin must return an object derived from the \\ref OFX::ImageEffect class *\/\nImageEffect* ReadPSDPluginFactory::createInstance(OfxImageEffectHandle handle,\n ContextEnum \/*context*\/)\n{\n ReadPSDPlugin* ret = new ReadPSDPlugin(handle);\n ret->restoreStateFromParameters();\n return ret;\n}\n\nvoid getReadPSDPluginID(OFX::PluginFactoryArray &ids)\n{\n static ReadPSDPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);\n ids.push_back(&p);\n}\nReadPSD: faster layer count, issue #120\/*\n\nopenfx-arena - https:\/\/github.com\/olear\/openfx-arena\n\nCopyright (c) 2015, Ole-André Rodlie \nCopyright (c) 2015, FxArena DA \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Neither the name of FxArena DA nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"ReadPSD.h\"\n#include \n#include \n#include \n#include \"GenericReader.h\"\n#include \"GenericOCIO.h\"\n#include \"ofxsMacros.h\"\n\n#ifdef OFX_IO_USING_OCIO\n#include \n#endif\n\n#define kPluginName \"ReadPSD\"\n#define kPluginGrouping \"Image\/Readers\"\n#define kPluginIdentifier \"net.fxarena.openfx.ReadPSD\"\n#define kPluginVersionMajor 1\n#define kPluginVersionMinor 3\n\n#define kSupportsRGBA true\n#define kSupportsRGB false\n#define kSupportsAlpha false\n#define kSupportsTiles false\n#define kIsMultiPlanar true\n\n#define DEBUG_MAGICK false\n\nclass ReadPSDPlugin : public GenericReaderPlugin\n{\npublic:\n ReadPSDPlugin(OfxImageEffectHandle handle);\n virtual ~ReadPSDPlugin();\nprivate:\n virtual bool isVideoStream(const std::string& \/*filename*\/) OVERRIDE FINAL { return false; }\n virtual void decode(const std::string& filename, OfxTime time, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds,\n OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, int rowBytes) OVERRIDE FINAL\n {\n std::string rawComps;\n switch (pixelComponents) {\n case OFX::ePixelComponentAlpha:\n rawComps = kOfxImageComponentAlpha;\n break;\n case OFX::ePixelComponentRGB:\n rawComps = kOfxImageComponentRGB;\n break;\n case OFX::ePixelComponentRGBA:\n rawComps = kOfxImageComponentRGBA;\n break;\n default:\n OFX::throwSuiteStatusException(kOfxStatFailed);\n return;\n }\n decodePlane(filename, time, renderWindow, pixelData, bounds, pixelComponents, pixelComponentCount, rawComps, rowBytes);\n }\n virtual void getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents) OVERRIDE FINAL;\n virtual void decodePlane(const std::string& filename, OfxTime time, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds, OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, const std::string& rawComponents, int rowBytes) OVERRIDE FINAL;\n virtual bool getFrameBounds(const std::string& filename, OfxTime time, OfxRectI *bounds, double *par, std::string *error) OVERRIDE FINAL;\n virtual void restoreState(const std::string& filename) OVERRIDE FINAL;\n virtual void onInputFileChanged(const std::string& newFile, OFX::PreMultiplicationEnum *premult, OFX::PixelComponentEnum *components, int *componentCount) OVERRIDE FINAL;\n int getImageLayers(const std::string& filename);\n int _imageLayers;\n int _imageWidth;\n int _imageHeight;\n};\n\nReadPSDPlugin::ReadPSDPlugin(OfxImageEffectHandle handle)\n: GenericReaderPlugin(handle, kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles,\n#ifdef OFX_EXTENSIONS_NUKE\n(OFX::getImageEffectHostDescription() && OFX::getImageEffectHostDescription()->isMultiPlanar) ? kIsMultiPlanar : false\n#else\nfalse\n#endif\n)\n,_imageLayers(0)\n,_imageWidth(0)\n,_imageHeight(0)\n{\n Magick::InitializeMagick(NULL);\n assert(_outputComponents);\n}\n\nReadPSDPlugin::~ReadPSDPlugin()\n{\n}\n\nint ReadPSDPlugin::getImageLayers(const std::string &filename)\n{\n #ifdef DEBUG\n std::cout << \"getImageLayers ...\" << std::endl;\n #endif\n int layers;\n std::list image;\n Magick::readImages(&image, filename);\n layers = image.size();\n if (layers>0)\n layers--;\n #ifdef DEBUG\n std::cout << \"found \" << layers << \" layers\" << std::endl;\n #endif\n return layers;\n}\n\nvoid ReadPSDPlugin::getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents)\n{\n #ifdef DEBUG\n std::cout << \"getClipComponents ...\" << std::endl;\n #endif\n assert(isMultiPlanar());\n clipComponents.addClipComponents(*_outputClip, getOutputComponents());\n clipComponents.setPassThroughClip(NULL, args.time, args.view);\n if (_imageLayers>0) {\n for(int i = 1; i<_imageLayers+1;i++) {\n std::string component(kNatronOfxImageComponentsPlane);\n std::ostringstream layerName;\n layerName << \"Layer#\" << i;\n component.append(layerName.str());\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"R\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"G\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"B\");\n component.append(kNatronOfxImageComponentsPlaneChannel);\n component.append(\"A\");\n clipComponents.addClipComponents(*_outputClip, component);\n }\n }\n}\n\nvoid ReadPSDPlugin::decodePlane(const std::string& filename, OfxTime \/*time*\/, const OfxRectI& \/*renderWindow*\/, float *pixelData, const OfxRectI& bounds,\n OFX::PixelComponentEnum \/*pixelComponents*\/, int \/*pixelComponentCount*\/, const std::string& rawComponents, int \/*rowBytes*\/)\n{\n #ifdef DEBUG\n std::cout << \"decodePlane ...\" << std::endl;\n #endif\n int layer = 0;\n std::string layerInfo = rawComponents;\n std::replace(layerInfo.begin(), layerInfo.end(), '_', ' ');\n std::stringstream stream(layerInfo);\n std::string streamInfo;\n while (stream>>streamInfo) {\n std::string findLayer = \"Layer#\";\n if (streamInfo.find(findLayer) != std::string::npos) {\n streamInfo.erase(streamInfo.find(findLayer),findLayer.length());\n layer = std::atoi(streamInfo.c_str());\n }\n }\n Magick::Image image;\n #ifdef DEBUG\n image.debug(DEBUG_MAGICK);\n #endif\n image.backgroundColor(\"none\");\n std::ostringstream file;\n file << filename.c_str() << \"[\" << layer << \"]\";\n image.read(file.str());\n if (image.columns()>0 && image.rows()>0) {\n Magick::Image container(Magick::Geometry(bounds.x2,bounds.y2),Magick::Color(\"rgba(0,0,0,0)\"));\n #ifdef DEBUG\n container.debug(DEBUG_MAGICK);\n #endif\n container.composite(image,image.page().xOff(),image.page().yOff(),Magick::OverCompositeOp);\n container.flip();\n container.write(0,0,bounds.x2,bounds.y2,\"RGBA\",Magick::FloatPixel,pixelData);\n }\n else {\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n}\n\nbool ReadPSDPlugin::getFrameBounds(const std::string& \/*filename*\/,\n OfxTime \/*time*\/,\n OfxRectI *bounds,\n double *par,\n std::string *\/*error*\/)\n{\n #ifdef DEBUG\n std::cout << \"getFrameBounds ...\" << std::endl;\n #endif\n if (_imageWidth>0 && _imageHeight>0) {\n bounds->x1 = 0;\n bounds->x2 = _imageWidth;\n bounds->y1 = 0;\n bounds->y2 = _imageHeight;\n *par = 1.0;\n }\n return true;\n}\n\nvoid ReadPSDPlugin::restoreState(const std::string& filename)\n{\n #ifdef DEBUG\n std::cout << \"restoreState ...\" << std::endl;\n #endif\n Magick::Image image;\n #ifdef DEBUG\n image.debug(DEBUG_MAGICK);\n #endif\n image.read(filename);\n if (image.columns()>0 && image.rows()>0) {\n _imageWidth = image.columns();\n _imageHeight = image.rows();\n _imageLayers = getImageLayers(filename);\n }\n else {\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n}\n\nvoid ReadPSDPlugin::onInputFileChanged(const std::string& newFile,\n OFX::PreMultiplicationEnum *premult,\n OFX::PixelComponentEnum *components,int *\/*componentCount*\/)\n{\n #ifdef DEBUG\n std::cout << \"onInputFileChanged ...\" << std::endl;\n #endif\n assert(premult && components);\n Magick::Image image;\n #ifdef DEBUG\n image.debug(DEBUG_MAGICK);\n #endif\n image.read(newFile);\n if (image.columns()>0 && image.rows()>0) {\n _imageWidth = image.columns();\n _imageHeight = image.rows();\n _imageLayers = getImageLayers(newFile);\n # ifdef OFX_IO_USING_OCIO\n switch(image.colorSpace()) {\n case Magick::RGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::sRGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::scRGBColorspace:\n _ocio->setInputColorspace(\"sRGB\");\n break;\n case Magick::Rec709LumaColorspace:\n _ocio->setInputColorspace(\"Rec709\");\n break;\n case Magick::Rec709YCbCrColorspace:\n _ocio->setInputColorspace(\"Rec709\");\n break;\n default:\n _ocio->setInputColorspace(\"Linear\");\n break;\n }\n # endif \/\/ OFX_IO_USING_OCIO\n }\n else {\n setPersistentMessage(OFX::Message::eMessageError, \"\", \"Unable to read image\");\n OFX::throwSuiteStatusException(kOfxStatErrFormat);\n }\n *components = OFX::ePixelComponentRGBA;\n *premult = OFX::eImageOpaque;\n}\n\nusing namespace OFX;\n\nmDeclareReaderPluginFactory(ReadPSDPluginFactory, {}, {}, false);\n\n\/** @brief The basic describe function, passed a plugin descriptor *\/\nvoid ReadPSDPluginFactory::describe(OFX::ImageEffectDescriptor &desc)\n{\n GenericReaderDescribe(desc, kSupportsTiles, kIsMultiPlanar);\n desc.setLabel(kPluginName);\n\n #ifdef OFX_EXTENSIONS_TUTTLE\n const char* extensions[] = {\"psd\", NULL};\n desc.addSupportedExtensions(extensions);\n desc.setPluginEvaluation(92);\n #endif\n\n std::string magickV = MagickCore::GetMagickVersion(NULL);\n desc.setPluginDescription(\"Read PSD image format.\\n\\nWritten by Ole-André Rodlie \\n\\nPowered by \"+magickV);\n}\n\n\/** @brief The describe in context function, passed a plugin descriptor and a context *\/\nvoid ReadPSDPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum context)\n{\n PageParamDescriptor *page = GenericReaderDescribeInContextBegin(desc, context, isVideoStreamPlugin(), kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles);\n GenericReaderDescribeInContextEnd(desc, context, page, \"reference\", \"reference\");\n}\n\n\/** @brief The create instance function, the plugin must return an object derived from the \\ref OFX::ImageEffect class *\/\nImageEffect* ReadPSDPluginFactory::createInstance(OfxImageEffectHandle handle,\n ContextEnum \/*context*\/)\n{\n ReadPSDPlugin* ret = new ReadPSDPlugin(handle);\n ret->restoreStateFromParameters();\n return ret;\n}\n\nvoid getReadPSDPluginID(OFX::PluginFactoryArray &ids)\n{\n static ReadPSDPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);\n ids.push_back(&p);\n}\n<|endoftext|>"} {"text":"#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tR8C メイン・ヘッダー\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"M120AN\/port.hpp\"\n#include \"common\/intr_utils.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/trb_io.hpp\"\n#include \"common\/trc_io.hpp\"\n#include \"common\/adc_io.hpp\"\n#include \"common\/flash_io.hpp\"\n#include \"common\/ds1371_io.hpp\"\n#include \"common\/lcd_io.hpp\"\n#include \"common\/monograph.hpp\"\n#include \"port_def.hpp\"\n\ntypedef device::uart_io uart0;\n\ntypedef device::trb_io timer_b;\n\ntypedef device::trc_io timer_c;\n\ntypedef device::adc_io adc;\n\ntypedef device::flash_io flash;\n\ntypedef graphics::monograph mono_graph;\n\ntypedef device::ds1371_io ds1371;\n\ntypedef device::lcd_io lcd;\ndelete file<|endoftext|>"} {"text":"Suppress a GTK warning and file a bug for it.<|endoftext|>"} {"text":"Adding commandline option to gm to make it write image results for tests that fails due to pixel mismatches. Review URL: https:\/\/codereview.appspot.com\/7100043<|endoftext|>"} {"text":"\/*\n * FogLAMP storage service.\n *\n * Copyright (c) 2017-2018 OSisoft, LLC\n *\n * Released under the Apache 2.0 Licence\n *\n * Author: Mark Riddoch, Massimiliano Pinto\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nLogger *Logger::instance = 0;\n\nLogger::Logger(const string& application)\n{\n\tm_app_name = new string(application);\n\topenlog(m_app_name->c_str(), LOG_PID|LOG_CONS, LOG_USER);\n\tinstance = this;\n}\n\nLogger::~Logger()\n{\n\tcloselog();\n\tdelete m_app_name;\n}\n\nLogger *Logger::getLogger()\n{\n\treturn instance;\n}\n\nvoid Logger::debug(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_DEBUG, \"DEBUG: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nvoid Logger::info(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_INFO, \"INFO: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nvoid Logger::warn(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_WARNING, \"WARNING: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nvoid Logger::error(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_ERR, \"ERROR: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nvoid Logger::fatal(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_CRIT, \"FATAL: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nstring *Logger::format( const std::string& format, va_list args)\n{\nchar\tbuf[1000];\n\n\t vsnprintf(buf, sizeof(buf), format.c_str(), args);\n\t return new string(buf);\n}\nAdded support for adding usec level timestamps to info logs, if required\/*\n * FogLAMP storage service.\n *\n * Copyright (c) 2017-2018 OSisoft, LLC\n *\n * Released under the Apache 2.0 Licence\n *\n * Author: Mark Riddoch, Massimiliano Pinto\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ uncomment line below to get uSec level timestamps\n\/\/#define ADD_USEC_TS\n\ninline long getCurrTimeUsec()\n{\n\tstruct timeval m_timestamp;\n\tgettimeofday(&m_timestamp, NULL);\n\treturn m_timestamp.tv_usec;\n}\n\nLogger *Logger::instance = 0;\n\nLogger::Logger(const string& application)\n{\n\tm_app_name = new string(application);\n\topenlog(m_app_name->c_str(), LOG_PID|LOG_CONS, LOG_USER);\n\tinstance = this;\n}\n\nLogger::~Logger()\n{\n\tcloselog();\n\tdelete m_app_name;\n}\n\nLogger *Logger::getLogger()\n{\n\treturn instance;\n}\n\nvoid Logger::debug(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_DEBUG, \"DEBUG: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nvoid Logger::info(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n#ifdef ADD_USEC_TS\n\tsyslog(LOG_INFO, \"[.%06ld] INFO: %s\", getCurrTimeUsec(), fmt->c_str());\n#else\n\tsyslog(LOG_INFO, \"INFO: %s\", fmt->c_str());\n#endif\n\tdelete fmt;\n\tva_end(args);\n}\n\nvoid Logger::warn(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_WARNING, \"WARNING: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nvoid Logger::error(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_ERR, \"ERROR: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nvoid Logger::fatal(const string& msg, ...)\n{\n\tva_list args;\n\tva_start(args, msg);\n\tstring *fmt = format(msg, args);\n\tsyslog(LOG_CRIT, \"FATAL: %s\", fmt->c_str());\n\tdelete fmt;\n\tva_end(args);\n}\n\nstring *Logger::format( const std::string& format, va_list args)\n{\nchar\tbuf[1000];\n\n\t vsnprintf(buf, sizeof(buf), format.c_str(), args);\n\t return new string(buf);\n}\n<|endoftext|>"} {"text":"\/\/---------------------------------------------------------------------------\n\/\/ E L E N A p r o j e c t\n\/\/ Command line DSA script terminal main file\n\/\/ (C)2011-2020, by Alexei Rakov\n\/\/---------------------------------------------------------------------------\n\n#include \"elena.h\"\n\/\/---------------------------------------------------------------------------\n#include \n#include \"elenamachine.h\"\n#include \"elenasm.h\"\n#include \"elenavm.h\"\n\nusing namespace _ELENA_;\n\n#define MAX_LINE 256\n#define MAX_SCRIPT 4096\n#define ELT_BUILD_NUMBER 13\n \n\/\/ global variables\nProgramHeader _header;\nint _encoding = feAnsi;\npos_t _tlsIndex = 0;\nGCTable _table = { 0 };\nSystemEnv _env = { 0 };\nint _sehTable = 0;\n\nIdentifierString prefix;\nIdentifierString postfix;\n\nDynamicString body;\n\nvoid loadTemplate(path_t path)\n{\n char buff[512];\n\n TextFileReader reader(path, feUTF8, false);\n\n if (reader.isOpened()) {\n IdentifierString content;\n reader.readAll(content, buff);\n\n int index = content.ident().find(\"$1\");\n if (index != NOTFOUND_POS) {\n prefix.copy(content.ident(), index);\n postfix.copy(content.c_str() + index + 2);\n }\n else prefix.copy(content.ident());\n }\n}\n\nvoid print(const char* str, ...)\n{\n va_list argptr;\n va_start(argptr, str);\n\n vprintf(str, argptr);\n va_end(argptr);\n\n fflush(stdout);\n}\n\nconst char* trim(const char* s)\n{\n while(s[0]==0x20)s++;\n\n return s;\n}\n\nvoid printHelp()\n{\n print(\"-q - quit\\n\");\n print(\"-h - help\\n\");\n print(\"-l - execute a script from file\\n\");\n print(\"