blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
4bf281792e3ca793b0d6219cd0de7ab528cd50c2
5f48a255bae33b09fdc35c56a09c175534f79ac0
/ExtentionSystem/Castable.h
de8e1e3ece4e4df5a18bf4a8347d26fbc1349f86
[]
no_license
reyoung/SimpleCppPluginSystem
5f8e0a12f223ca29088585b8817259aa96d66944
357ffbb7a9d3efc98b09b42a47d687451a2d3bb6
refs/heads/master
2016-09-06T01:26:20.412191
2011-07-02T14:20:33
2011-07-02T14:20:33
null
0
0
null
null
null
null
GB18030
C++
false
false
258
h
#pragma once #include "global.h" /** * \abstract 所有可转型类的基类,插件的基类。同时也是所有插件的基类 * \note */ class ExtentionSystem_DLL_API Castable { public: Castable(void); virtual ~Castable(void); };
[ [ [ 1, 13 ] ] ]
0ebdefa92b753f5cd31d012612dba9e7b9aaaa03
86c8c65dd5d7c07b46f134f6df76d5127e9428ff
/010.cpp
a0345ed2dc5a3f911862e870ace6e88afc115618
[]
no_license
kyokey/MIPT
2d2fc233475e414b33fe889594929be6af696b92
f0dcc64731deaf5d0f0949884865216c15c15dbe
refs/heads/master
2020-04-27T09:10:48.472859
2011-01-04T16:35:26
2011-01-04T16:35:26
1,219,926
0
0
null
null
null
null
UTF-8
C++
false
false
1,680
cpp
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <ctime> #include <queue> using namespace std; #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) #define sqr(a) ((a)*(a)) #define rep(i,a,b) for(i=(a);i<(b);i++) #define REP(i,n) rep(i,0,n) #define clr(a) memset((a),0,sizeof (a)); #define mabs(a) ((a)>0?(a):(-(a))) #define inf 1000000000 #define MAXE 15010 #define MAXN 1010 #define eps 1e-6 #define MOD 50261 int head[MAXN]; typedef struct node { int v; int next; }node; node E[MAXE]; int N,M,C; int ym[MAXN]; bool visited[MAXN]; int top=0; void adde(int u,int v) { E[top].v=v; E[top].next=head[u]; head[u]=top++; } bool dfs(int u) { int i; for (i=head[u];i!=-1;i=E[i].next) { int v=E[i].v; if(!visited[v]) { visited[v]=true; if(ym[v]==-1||dfs(ym[v])) { ym[v]=u; return true; } } } return false; } int main() { int i,j,k; scanf("%d%d%d",&N,&M,&C); top=0; REP(i,MAXN)head[i]=-1,ym[i]=-1; REP(i,C) { int u,v; scanf("%d%d",&u,&v); adde(u,v); } int ret=0; rep(i,1,N+1) { clr(visited); if(dfs(i)) ret++; } printf("%d\n",ret); REP(i,M+1) if(ym[i]!=-1) printf("%d %d\n",ym[i],i); return 0; }
[ "pq@pq-laptop.(none)" ]
[ [ [ 1, 92 ] ] ]
bf3765c446b2bbb340b44af052894fd0c45b8553
7ee1bcc17310b9f51c1a6be0ff324b6e297b6c8d
/AppData/Sources/VS 2005 WinCE WTL 8.0 SDI/Source/MainFrame.cpp
505c4d0edd5d99c79c596e53a737fcaa20748370
[]
no_license
SchweinDeBurg/afx-scratch
895585e98910f79127338bdca5b19c5e36921453
3181b779b4bb36ef431e5ce39e297cece1ca9cca
refs/heads/master
2021-01-19T04:50:48.770595
2011-06-18T05:14:22
2011-06-18T05:14:22
32,185,218
0
0
null
null
null
null
UTF-8
C++
false
false
1,642
cpp
// $PROJECT$ application. // Copyright (c) $YEAR$ by $AUTHOR$, // All rights reserved. // MainFrame.cpp - implementation of the CMainFrame class // initially generated by $GENERATOR$ on $DATE$ at $TIME$ // visit http://zarezky.spb.ru/projects/afx_scratch.html for more info ////////////////////////////////////////////////////////////////////////////////////////////// // PCH includes #include "stdafx.h" ////////////////////////////////////////////////////////////////////////////////////////////// // resource includes #include "Resource.h" ////////////////////////////////////////////////////////////////////////////////////////////// // other includes #include "MainFrame.h" ////////////////////////////////////////////////////////////////////////////////////////////// // construction/destruction CMainFrame::CMainFrame(void) { } CMainFrame::~CMainFrame(void) { } ////////////////////////////////////////////////////////////////////////////////////////////// // overridables BOOL CMainFrame::PreTranslateMessage(MSG* pMsg) { return (TBaseFrame::PreTranslateMessage(pMsg)); } ////////////////////////////////////////////////////////////////////////////////////////////// // message handlers LRESULT CMainFrame::OnCreate(CREATESTRUCT* /*lpCS*/) { WTL::AtlCreateEmptyMenuBar(m_hWnd); WTL::CMessageLoop* pMsgLoop = _Module.GetMessageLoop(); ATLASSERT(pMsgLoop != NULL); pMsgLoop->AddMessageFilter(this); return (0); } void CMainFrame::OnAppExit(UINT /*uCode*/, int /*nID*/, HWND /*hWndCtrl*/) { DestroyWindow(); SetMsgHandled(TRUE); } // end of file
[ "Elijah@9edebcd1-9b41-0410-8d36-53a5787adf6b", "Elijah Zarezky@9edebcd1-9b41-0410-8d36-53a5787adf6b" ]
[ [ [ 1, 9 ], [ 13, 14 ], [ 23, 24 ], [ 28, 35 ], [ 47, 64 ] ], [ [ 10, 12 ], [ 15, 22 ], [ 25, 27 ], [ 36, 46 ] ] ]
14b6b60822dd26da038ceb043449f58311908292
971b000b9e6c4bf91d28f3723923a678520f5bcf
/PaperSizeScroll/getmargin.cpp
1cfb511af4832cf65a2ad38a32394b7cea28fad3
[]
no_license
google-code-export/fop-miniscribus
14ce53d21893ce1821386a94d42485ee0465121f
966a9ca7097268c18e690aa0ea4b24b308475af9
refs/heads/master
2020-12-24T17:08:51.551987
2011-09-02T07:55:05
2011-09-02T07:55:05
32,133,292
2
0
null
null
null
null
UTF-8
C++
false
false
4,072
cpp
/******************************************************************************* * class GetMargin ******************************************************************************* * Copyright (C) 2007 by Peter Hohl * e-Mail: [email protected] * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *******************************************************************************/ #include "getmargin.h" // /* Save file as getmargin.cpp */ /* incomming class name GetMargin */ // #include <QCloseEvent> // GetMargin::GetMargin( QWidget* parent ) : QDialog( parent ) { setupUi( this ); Genable = false; unitas = setter.value("CurrentRunningUnit").toString(); if (unitas.size() < 1) { unitas = "pt"; comboBox->setCurrentIndex(3); } else { comboBox->setCurrentIndex(comboBox->findText(unitas)); UnitChange(unitas); } current = QRectF ( 0, 0, 0, 0 ); connect(comboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(UnitChange(QString))); ///////connect(doubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(UpdateVars())); /////connect(doubleSpinBox_2, SIGNAL(valueChanged(double)), this, SLOT(UpdateVars())); ////////connect(doubleSpinBox_3, SIGNAL(valueChanged(double)), this, SLOT(UpdateVars())); //////////////connect(doubleSpinBox_4, SIGNAL(valueChanged(double)), this, SLOT(UpdateVars())); connect(pushButton, SIGNAL(clicked()),this, SLOT(UpdateVars())); Genable = true; } void GetMargin::UnitChange(const QString unite ) { unitas = unite; setter.setValue("CurrentRunningUnit",unitas); doubleSpinBox->setSuffix(QString(" %1.").arg(unitas)); doubleSpinBox_2->setSuffix(QString(" %1.").arg(unitas)); doubleSpinBox_3->setSuffix(QString(" %1.").arg(unitas)); doubleSpinBox_4->setSuffix(QString(" %1.").arg(unitas)); doubleSpinBox_4->setValue ( Pointo(a1,unitas) ); /* top */ doubleSpinBox_2->setValue ( Pointo(a2,unitas) ); /* right*/ doubleSpinBox->setValue ( Pointo(a3,unitas) ); /* bottom */ doubleSpinBox_3->setValue ( Pointo(a4,unitas) ); /* left */ } void GetMargin::UpdateVars() { if (!Genable) { return; } const qreal TopBB = ToPoint(doubleSpinBox_4->value(),unitas); a1 = TopBB; const qreal RightBB = ToPoint(doubleSpinBox_2->value(),unitas); a2 = RightBB; const qreal BottomBB = ToPoint(doubleSpinBox->value(),unitas); a3 = BottomBB; const qreal LeftBB = ToPoint(doubleSpinBox_3->value(),unitas); a4 = LeftBB; current = QRectF ( TopBB, RightBB ,BottomBB , LeftBB ); /* css sequense */ /* doubleSpinBox_4->setValue ( current.x() ); top doubleSpinBox_2->setValue ( current.y() ); doubleSpinBox->setValue ( current.width() ); bottom doubleSpinBox_3->setValue ( current.height() ); left */ /* QRectF ( qreal x, qreal y, qreal width, qreal height ) */ } void GetMargin::closeEvent( QCloseEvent* e ) { UpdateVars(); e->accept(); } /* Q_ASSERT ( bool test ) */ /* QString one; toLower() toUpper() split(",") endsWith() startsWith() QByteArray QString::toAscii() */ /* int nummer; */ /* QStringList list; join(); */ /* QUrl url; */ /* QByteArray byteArray; */ /* bool having; */ /* QDomDocument doc;*/ /* QDomElement root;*/
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 112 ] ] ]
df0ebc370c9da9e379857d10673b8bd545ce43b3
073dfce42b384c9438734daa8ee2b575ff100cc9
/RCF/include/RCF/Token.hpp
32ecd155ff2c50698ac2f8699dfd78c211e30fe0
[]
no_license
r0ssar00/iTunesSpeechBridge
a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf
71a27a52e66f90ade339b2b8a7572b53577e2aaf
refs/heads/master
2020-12-24T17:45:17.838301
2009-08-24T22:04:48
2009-08-24T22:04:48
285,393
1
0
null
null
null
null
UTF-8
C++
false
false
2,265
hpp
//****************************************************************************** // RCF - Remote Call Framework // Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved. // Consult your license for conditions of use. // Version: 1.1 // Contact: jarl.lindrud <at> gmail.com //****************************************************************************** #ifndef INCLUDE_RCF_TOKEN_HPP #define INCLUDE_RCF_TOKEN_HPP #include <iosfwd> #include <vector> #include <boost/noncopyable.hpp> #include <RCF/Export.hpp> #include <RCF/SerializationDefs.hpp> #include <RCF/ThreadLibrary.hpp> #include <RCF/TypeTraits.hpp> namespace SF { class Archive; } namespace RCF { class RCF_EXPORT Token { public: Token(); Token(int id); int getId() const; friend bool operator<(const Token &lhs, const Token &rhs); friend bool operator==(const Token &lhs, const Token &rhs); friend bool operator!=(const Token &lhs, const Token &rhs); #ifdef RCF_USE_SF_SERIALIZATION void serialize(SF::Archive &ar, const unsigned int); #endif #ifdef RCF_USE_BOOST_SERIALIZATION template<typename Archive> void serialize(Archive &ar, const unsigned int) { ar & boost::serialization::make_nvp("Id", mId); } #endif friend RCF_EXPORT std::ostream &operator<<(std::ostream &os, const Token &token); private: int mId; }; class TokenFactory : boost::noncopyable { public: TokenFactory(int tokenCount); bool requestToken(Token &token); void returnToken(const Token &token); const std::vector<Token> & getTokenSpace(); std::size_t getAvailableTokenCount(); bool isAvailable(const Token & token); private: std::vector<Token> mTokenSpace; std::vector<Token> mAvailableTokens; ReadWriteMutex mMutex; }; } // namespace RCF RCF_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(RCF::Token) #endif // ! INCLUDE_RCF_TOKEN_HPP
[ [ [ 1, 84 ] ] ]
7ee725409a123c2b1eb4703aa02fe9cd54ab1fa2
89d2197ed4531892f005d7ee3804774202b1cb8d
/GWEN/src/Controls/Menu.cpp
8e7218235c7e7936a7f4792f703e186d2d83d41b
[ "MIT", "Zlib" ]
permissive
hpidcock/gbsfml
ef8172b6c62b1c17d71d59aec9a7ff2da0131d23
e3aa990dff8c6b95aef92bab3e94affb978409f2
refs/heads/master
2020-05-30T15:01:19.182234
2010-09-29T06:53:53
2010-09-29T06:53:53
35,650,825
0
0
null
null
null
null
UTF-8
C++
false
false
3,848
cpp
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #include "stdafx.h" #include "Gwen/Gwen.h" #include "Gwen/Controls/Menu.h" #include "Gwen/Skin.h" #include "Gwen/Utility.h" using namespace Gwen; using namespace Gwen::Controls; GWEN_CONTROL_CONSTRUCTOR( Menu ) { SetBounds( 0, 0, 10, 10 ); SetPadding( Padding( 2, 2, 2, 2 ) ); SetDisableIconMargin(false); SetAutoHideBars( true ); SetScroll( false, true ); } void Menu::Render( Skin::Base* skin ) { skin->DrawMenu( this, IconMarginDisabled() ); } void Menu::RenderUnder( Skin::Base* skin ) { BaseClass::RenderUnder( skin ); skin->DrawShadow( this ); } void Menu::Layout( Skin::Base* skin ) { int childrenHeight = 0; for ( Base::List::iterator it = m_InnerPanel->Children.begin(); it != m_InnerPanel->Children.end(); ++it ) { Base* pChild = dynamic_cast<Base*>(*it); if ( !pChild ) continue; childrenHeight += pChild->Height(); } if ( Y() + childrenHeight > GetCanvas()->Height() ) childrenHeight = GetCanvas()->Height() - Y(); SetSize( Width(), childrenHeight ); BaseClass::Layout( skin ); } MenuItem* Menu::AddItem( const Gwen::UnicodeString& strName, const UnicodeString& strIconName, Gwen::Event::Handler* pHandler, Gwen::Event::Function fn ) { MenuItem* pItem = new MenuItem( this ); pItem->SetText( strName ); pItem->SetImage( strIconName ); if ( fn && pHandler ) { pItem->onMenuItemSelected.Add( pHandler, fn ); } OnAddItem( pItem ); return pItem; } void Menu::OnAddItem( MenuItem* item ) { item->Dock( Pos::Top ); item->SetTextPadding( Padding( IconMarginDisabled() ? 0 : 24, 0, 16, 0 ) ); item->SetPadding( Padding( 4, 4, 4, 4 ) ); item->SizeToContents(); item->SetAlignment( Pos::CenterV | Pos::Left ); item->onHoverEnter.Add( this, &Menu::OnHoverItem ); // Do this here - after Top Docking these values mean nothing in layout int w = item->Width() + 10 + 32; if ( w < Width() ) w = Width(); SetSize( w, Height() ); } void Menu::ClearItems() { for ( Base::List::iterator it = m_InnerPanel->Children.begin(); it != m_InnerPanel->Children.end(); ++it ) { Base* pChild = *it; if ( !pChild ) continue; pChild->DelayedDelete(); } } MenuItem* Menu::AddItem( const Gwen::String& strName, const String& strIconName, Gwen::Event::Handler* pHandler, Gwen::Event::Function fn ) { return AddItem( Gwen::Utility::StringToUnicode( strName ), Gwen::Utility::StringToUnicode( strIconName ), pHandler, fn ); } void Menu::CloseAll() { for ( Base::List::iterator it = m_InnerPanel->Children.begin(); it != m_InnerPanel->Children.end(); ++it ) { Base* pChild = *it; MenuItem* pItem = dynamic_cast<MenuItem*>(pChild); if ( !pItem ) continue; pItem->CloseMenu(); } } bool Menu::IsMenuOpen() { for ( Base::List::iterator it = m_InnerPanel->Children.begin(); it != m_InnerPanel->Children.end(); ++it ) { Base* pChild = *it; MenuItem* pItem = dynamic_cast<MenuItem*>(pChild); if ( !pItem ) continue; if ( pItem->IsMenuOpen() ) return true; } return false; } void Menu::OnHoverItem( Gwen::Controls::Base* pControl ) { if ( !ShouldHoverOpenMenu() ) return; MenuItem* pItem = dynamic_cast<MenuItem*>(pControl); if (!pItem) return; if ( pItem->IsMenuOpen() ) return; CloseAll(); pItem->OpenMenu(); } void Menu::Close() { SetHidden( true ); } void Menu::CloseMenus() { BaseClass::CloseMenus(); CloseAll(); Close(); } void Menu::AddDivider() { MenuDivider* divider = new MenuDivider( this ); divider->Dock( Pos::Top ); divider->SetMargin( Margin( IconMarginDisabled() ? 0 : 24, 0, 4, 0 ) ); } void MenuDivider::Render( Gwen::Skin::Base* skin ) { skin->DrawMenuDivider( this ); }
[ "haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793" ]
[ [ [ 1, 173 ] ] ]
428921a9788aa3d74b3a4defa679088af78358f1
593b85562f3e570a5a6e75666d8cd1c535daf3b6
/Source/Wrappers/CSGD_Direct3D.h
d8c0c63a3cce334ca33ea5da8b94043ceacaae34
[]
no_license
rayjohannessen/songofalbion
fc62c317d829ceb7c215b805fed4276788a22154
83d7e87719bfb3ade14096d4969aa32c524c1902
refs/heads/master
2021-01-23T13:18:10.028635
2011-02-13T00:23:37
2011-02-13T00:23:37
32,121,693
1
0
null
null
null
null
UTF-8
C++
false
false
10,725
h
//////////////////////////////////////////////////////// // File : "CSGD_Direct3D.h" // // Author : Jensen Rivera (JR) // // Date Created : 5/25/2006 // // Purpose : Wrapper class for Direct3D. //////////////////////////////////////////////////////// /* Disclaimer: This source code was developed for and is the property of: Full Sail University Game Development Curriculum 2008-2009 and Full Sail Real World Education Game Design Curriculum 2000-2008 Full Sail students may not redistribute this code, but may use it in any project for educational purposes. */ #pragma once // The include files for Direct3D9 #include <d3d9.h> #include <d3dx9.h> // The library files for Direct3D9 #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") #pragma comment (lib, "dxguid.lib") // For macros #include "SGD_Util.h" // for SAFE_RELEASE and DXERROR class CSGD_Direct3D { private: // The Direct3D object. LPDIRECT3D9 m_lpDirect3DObject; // The Direct3D Device. LPDIRECT3DDEVICE9 m_lpDirect3DDevice; // The Direct3DX Sprite Interface. LPD3DXSPRITE m_lpSprite; // The Direct3DX Font Interface. LPD3DXFONT m_lpFont; // The Direct3DX Line Interface LPD3DXLINE m_lpLine; // The presentation parameters of the device. D3DPRESENT_PARAMETERS m_PresentParams; // The handle to the window Direct3D is initialized in. HWND m_hWnd; // The single static object of this class. static CSGD_Direct3D m_Instance; private: /////////////////////////////////////////////////////////////////// // Function: "CSGD_Direct3D(Constructor)" /////////////////////////////////////////////////////////////////// CSGD_Direct3D(void); CSGD_Direct3D(CSGD_Direct3D &ref); CSGD_Direct3D &operator=(CSGD_Direct3D &ref); public: /////////////////////////////////////////////////////////////////// // Function: "~CSGD_Direct3D(Destructor)" /////////////////////////////////////////////////////////////////// ~CSGD_Direct3D(void); /////////////////////////////////////////////////////////////////// // Function: "SetView" // // Last Modified: 5/25/2006 // // Input: void // // Return: void. // // Purpose: Set up the virtual "camera". /////////////////////////////////////////////////////////////////// void SetView(); /////////////////////////////////////////////////////////////////// // Function: "SetProjection" // // Last Modified: 5/25/2006 // // Input: void // // Return: void. // // Purpose: Set up the device's projection. /////////////////////////////////////////////////////////////////// void SetProjection(); /////////////////////////////////////////////////////////////////// // Function: "GetInstance" // // Last Modified: 5/25/2006 // // Input: void // // Return: An instance to this class. // // Purpose: Returns an instance to this class. /////////////////////////////////////////////////////////////////// static CSGD_Direct3D* GetInstance(void); /////////////////////////////////////////////////////////////////// // Function: "CSGD_Direct3D(Accessors)" // // Last Modified: 5/25/2006 // // Input: void // // Return: A pointer to a data member in this class. // // Purpose: Accesses data members in this class. /////////////////////////////////////////////////////////////////// LPDIRECT3D9 GetDirect3DObject(void); LPDIRECT3DDEVICE9 GetDirect3DDevice(void); LPD3DXSPRITE GetSprite(void); LPD3DXLINE GetLine(void); const D3DPRESENT_PARAMETERS*GetPresentParams(void); /////////////////////////////////////////////////////////////////// // Function: "InitDirect3D" // // Last Modified: 10/29/2008 // // Input: hWnd A handle to the window to initialize // Direct3D in. // nScreenWidth The width to initialize the device into. // nScreenHeight The height to initialize the device into. // bIsWindowed The screen mode to initialize the device into. // bVsync true to put the device into vsynced display mode. // // Return: true if successful. // // Purpose: Initializes Direct3D9. /////////////////////////////////////////////////////////////////// bool InitDirect3D(HWND hWnd, int nScreenWidth, int nScreenHeight, bool bIsWindowed = true, bool bVsync = true); /////////////////////////////////////////////////////////////////// // Function: "Shutdown" // // Last Modified: 5/25/2006 // // Input: void // // Return: void // // Purpose: Shuts down Direct3D9. /////////////////////////////////////////////////////////////////// void Shutdown(void); /////////////////////////////////////////////////////////////////// // Function: "Clear" // // Last Modified: 5/25/2006 // // Input: ucRed The amount of red to clear the screen with (0-255). // ucGreen The amount of green to clear the screen with (0-255). // ucBlue The amount of blue to clear the screen with (0-255). // // Return: void // // Purpose: Clears the screen to a given color. /////////////////////////////////////////////////////////////////// void Clear(unsigned char ucRed = 0, unsigned char ucGreen = 0, unsigned char ucBlue = 0); /////////////////////////////////////////////////////////////////// // Function: "DeviceBegin" // // Last Modified: 5/25/2006 // // Input: void // // Return: true if successful. // // Purpose: Begins the device for rendering. /////////////////////////////////////////////////////////////////// bool DeviceBegin(void); /////////////////////////////////////////////////////////////////// // Function: "SpriteBegin" // // Last Modified: 5/25/2006 // // Input: void // // Return: true if successful. // // Purpose: Begins the sprite for rendering. /////////////////////////////////////////////////////////////////// bool SpriteBegin(void); /////////////////////////////////////////////////////////////////// // Function: "LineBegin" // // Last Modified: 5/25/2006 // // Input: void // // Return: true if successful. // // Purpose: Begins the line for rendering. /////////////////////////////////////////////////////////////////// bool LineBegin(void); /////////////////////////////////////////////////////////////////// // Function: "DeviceEnd" // // Last Modified: 5/25/2006 // // Input: void // // Return: true if successful. // // Purpose: Ends the device for rendering. /////////////////////////////////////////////////////////////////// bool DeviceEnd(void); /////////////////////////////////////////////////////////////////// // Function: "SpriteEnd" // // Last Modified: 5/25/2006 // // Input: void // // Return: true if successful. // // Purpose: Ends the sprite for rendering. /////////////////////////////////////////////////////////////////// bool SpriteEnd(void); /////////////////////////////////////////////////////////////////// // Function: "LineEnd" // // Last Modified: 5/25/2006 // // Input: void // // Return: true if successful. // // Purpose: Ends the line for rendering. /////////////////////////////////////////////////////////////////// bool LineEnd(void); /////////////////////////////////////////////////////////////////// // Function: "Present" // // Last Modified: 5/25/2006 // // Input: void // // Return: void // // Purpose: Renders your back buffer to the screen. /////////////////////////////////////////////////////////////////// void Present(void); /////////////////////////////////////////////////////////////////// // Function: "ChangeDisplayParam" // // Last Modified: 5/25/2006 // // Input: nWidth The width to change the device to. // nHeight The height to change the device to. // bWindowed The mode to put the window in. // // Return: void // // Purpose: Changes the display parameters of the device. /////////////////////////////////////////////////////////////////// void ChangeDisplayParam(int nWidth, int nHeight, bool bWindowed); /////////////////////////////////////////////////////////////////// // Function: "DrawRect" // // Last Modified: 5/25/2006 // // Input: rRt The region of the screen to fill. // ucRed The amount of red to fill that region with (0-255). // ucGreen The amount of green to fill that region with (0-255). // ucBlue The amount of blue to fill that region with (0-255). // // Return: void // // Purpose: Draws a rectangle of a given color to the screen. /////////////////////////////////////////////////////////////////// void DrawRect(RECT rRt, unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue); /////////////////////////////////////////////////////////////////// // Function: "DrawLine" // // Last Modified: 5/25/2006 // // Input: nX1 The starting x of the line. // nY1 The starting y of the line. // nX2 The ending x of the line. // nY2 The ending y of the line. // ucRed The amount of red to draw the line with (0-255). // ucGreen The amount of green to draw the line with (0-255). // ucBlue The amount of blue to draw the line with (0-255). // // Return: void // // Purpose: Draws a rectangle of a given color to the screen. /////////////////////////////////////////////////////////////////// void DrawLine(int nX1, int nY1, int nX2, int nY2, unsigned char ucRed = 255, unsigned char ucGreen = 255, unsigned char ucBlue = 255); /////////////////////////////////////////////////////////////////// // Function: "DrawText" // // Last Modified: 5/25/2006 // // Input: lpzText The text to draw to the screen. // nX The x position to draw the text at. // nY The y position to draw the text at. // ucRed The amount of red to draw the text with (0-255). // ucGreen The amount of green to draw the text with (0-255). // ucBlue The amount of blue to draw the text with (0-255). // // Return: void // // Purpose: Draws text to the screen with a given color. /////////////////////////////////////////////////////////////////// void DrawText(char *lpzText, int nX, int nY, unsigned char ucRed = 255, unsigned char ucGreen = 255, unsigned char ucBlue = 255); };
[ "AllThingsCandid@cb80bfb0-ca38-a83e-6856-ee7c686669b9" ]
[ [ [ 1, 337 ] ] ]
dcf6a04ca311f03fc614551490c7947c02fb51fd
1e299bdc79bdc75fc5039f4c7498d58f246ed197
/stdobj/zProcess.h
6a9fab5f96e44e166bc4430633dad92469a13d83
[]
no_license
moosethemooche/Certificate-Server
5b066b5756fc44151b53841482b7fa603c26bf3e
887578cc2126bae04c09b2a9499b88cb8c7419d4
refs/heads/master
2021-01-17T06:24:52.178106
2011-07-13T13:27:09
2011-07-13T13:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,673
h
//-------------------------------------------------------------------------------- // // Copyright (c) 1999 MarkCare Solutions // // Programming by Rich Schonthal // //-------------------------------------------------------------------------------- // Process.h: interface for the CProcess class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PROCESS_H__FA9A9163_6B7B_11D3_AEE0_005004A1C5F3__INCLUDED_) #define AFX_PROCESS_H__FA9A9163_6B7B_11D3_AEE0_005004A1C5F3__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //-------------------------------------------------------------------------------- #include "Handle.h" #include "result.h" //-------------------------------------------------------------------------------- class CProcess : public CObject, public CResult { public: PROCESS_INFORMATION m_procInfo; CHandle m_openHandle; public: CProcess(); ~CProcess(); bool Create(LPCTSTR pName, LPTSTR pCmdLine = NULL, LPCTSTR pCurDir = NULL, DWORD dwCreationFlags = 0, bool bInheritHandles = false, LPSTARTUPINFO lpStartupInfo = NULL, LPSECURITY_ATTRIBUTES lpProcessAttributes = NULL, LPSECURITY_ATTRIBUTES lpThreadAttributes = NULL, LPVOID lpEnvironment = NULL ); }; //-------------------------------------------------------------------------------- class CProcessArray : public CTypedPtrArray<CObArray, CProcess*> { public: ~CProcessArray() { for(int i = GetUpperBound(); i >= 0; i--) delete GetAt(i); }; }; #endif // !defined(AFX_PROCESS_H__FA9A9163_6B7B_11D3_AEE0_005004A1C5F3__INCLUDED_)
[ [ [ 1, 56 ] ] ]
e116630c5ae4507093a30cd759b1e18278635f58
8fb9ccf49a324a586256bb08c22edc92e23affcf
/src/TalComponent.h
f6f04d68102b08cd50f7a40b7f606d5e931f9896
[]
no_license
eriser/tal-noisemak3r
76468c98db61dfa28315284b4a5b1acfeb9c1ff6
1043c8f237741ea7beb89b5bd26243f8891cb037
refs/heads/master
2021-01-18T18:29:56.446225
2010-08-05T20:51:35
2010-08-05T20:51:35
62,891,642
1
0
null
null
null
null
UTF-8
C++
false
false
7,575
h
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-7 by Raw Material Software ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License, as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with JUCE; if not, visit www.gnu.org/licenses or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ------------------------------------------------------------------------------ If you'd like to release a closed-source product which uses JUCE, commercial licenses are also available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #ifndef TALCOMPONENTEDITOR_H #define TALCOMPONENTEDITOR_H #include "TalCore.h" #include "FilmStripKnob.h" #include "ImageSlider.h" #include "ImageToggleButton.h" #include "./Engine/AudioUtils.h" //============================================================================== /** This is the Component that our filter will use as its UI. One or more of these is created by the DemoJuceFilter::createEditor() method, and they will be deleted at some later time by the wrapper code. To demonstrate the correct way of connecting a filter to its UI, this class is a ChangeListener, and our demo filter is a ChangeBroadcaster. The editor component registers with the filter when it's created and deregisters when it's destroyed. When the filter's parameters are changed, it broadcasts a message and this editor responds by updating its display. */ class TalComponent : public AudioProcessorEditor, public ChangeListener, public SliderListener, public ButtonListener, public ComboBoxListener { public: /** Constructor. When created, this will register itself with the filter for changes. It's safe to assume that the filter won't be deleted before this object is. */ TalComponent(TalCore* const ownerFilter); /** Destructor. */ ~TalComponent(); //============================================================================== /** Our demo filter is a ChangeBroadcaster, and will call us back when one of its parameters changes. */ void changeListenerCallback (void* source); void sliderValueChanged (Slider*); void buttonClicked (Button *); void comboBoxChanged (ComboBox*); //============================================================================== /** Standard Juce paint callback. */ void paint (Graphics& g); /** Standard Juce resize callback. */ //void resized(); static const char* bmp00128_png; static const int bmp00128_pngSize; static const char* bmp00129_png; static const int bmp00129_pngSize; static const char* bmp00130_png; static const int bmp00130_pngSize; static const char* bmp00131_png; static const int bmp00131_pngSize; static const char* bmp00132_png; static const int bmp00132_pngSize; static const char* bmp00133_png; static const int bmp00133_pngSize; static const char* bmp00134_png; static const int bmp00134_pngSize; static const char* bmp00135_png; static const int bmp00135_pngSize; private: //============================================================================== //const Image* internalCachedBackgroundImage; FilmStripKnob *volumeKnob; ComboBox *filtertypeComboBox; FilmStripKnob *cutoffKnob; FilmStripKnob *resonanceKnob; FilmStripKnob *filterContourKnob; FilmStripKnob *keyfollowKnob; FilmStripKnob *osc1VolumeKnob; FilmStripKnob *osc2VolumeKnob; FilmStripKnob *osc3VolumeKnob; FilmStripKnob *portamentoKnob; FilmStripKnob *osc1WaveformKnob; FilmStripKnob *osc2WaveformKnob; FilmStripKnob *oscMasterTuneKnob; FilmStripKnob *osc1TuneKnob; FilmStripKnob *osc2TuneKnob; FilmStripKnob *osc1FineTuneKnob; FilmStripKnob *osc2FineTuneKnob; ImageSlider *filterAttackKnob; ImageSlider *filterDecayKnob; ImageSlider *filterSustainKnob; ImageSlider *filterReleaseKnob; ImageSlider *ampAttackKnob; ImageSlider *ampDecayKnob; ImageSlider *ampSustainKnob; ImageSlider *ampReleaseKnob; ImageSlider *velocityVolumeKnob; ImageSlider *velocityContourKnob; ImageSlider *velocityCutoffKnob; ImageSlider *pitchwheelCutoffKnob; ImageSlider *pitchwheelPitchKnob; ImageSlider *highpassKnob; ImageSlider *detuneKnob; ImageToggleButton *oscSyncButton; ImageToggleButton *panicButton; ImageToggleButton *midiLearnButton; ImageToggleButton *chorus1Button; ImageToggleButton *chorus2Button; ComboBox *voicesComboBox; ComboBox *portamentoModeComboBox; FilmStripKnob *lfo1WaveformKnob; FilmStripKnob *lfo2WaveformKnob; FilmStripKnob *lfo1RateKnob; FilmStripKnob *lfo2RateKnob; FilmStripKnob *lfo1AmountKnob; FilmStripKnob *lfo2AmountKnob; ComboBox *lfo1DestinationComboBox; ComboBox *lfo2DestinationComboBox; FilmStripKnob *lfo1PhaseKnob; FilmStripKnob *lfo2PhaseKnob; FilmStripKnob *osc1PwKnob; FilmStripKnob *osc2FmKnob; FilmStripKnob *osc1PhaseKnob; FilmStripKnob *osc2PhaseKnob; FilmStripKnob *transposeKnob; FilmStripKnob *reverbWetKnob; FilmStripKnob *reverbDecayKnob; FilmStripKnob *reverbPreDelayKnob; FilmStripKnob *reverbHighCutKnob; FilmStripKnob *reverbLowCutKnob; FilmStripKnob *oscBitcrusherKnob; FilmStripKnob *ringmodulationKnob; FilmStripKnob *freeAdAttackKnob; FilmStripKnob *freeAdDecayKnob; FilmStripKnob *freeAdAmountKnob; ComboBox *freeAdDestinationComboBox; ImageToggleButton *lfo1SyncButton; ImageToggleButton *lfo1KeyTriggerButton; ImageToggleButton *lfo2SyncButton; ImageToggleButton *lfo2KeyTriggerButton; Label *versionLabel; Label *infoText; AudioUtils audioUtils; TooltipWindow tooltipWindow; HyperlinkButton *hyperlinkButtoon; void updateParametersFromFilter(); FilmStripKnob* addNormalKnob(int x, int y, TalCore* const ownerFilter, const Image knobImage, int numOfFrames, const int parameter); ImageToggleButton* addNormalButton(int x, int y, TalCore* const ownerFilter, const Image buttonImage, bool isKickButton, int parameter); ImageSlider* addSlider(int x, int y, TalCore* const ownerFilter, const Image sliderImage, int height, int parameter); ComboBox* addComboBox(int x, int y, int width, TalCore* const ownerFilter, int parameter); void updateInfo(Slider* caller); void setTooltip(Slider* slider); // handy wrapper method to avoid having to cast the filter to a DemoJuceFilter // every time we need it.. TalCore* getFilter() const throw() { return (TalCore*) getAudioProcessor(); } }; #endif
[ "patrickkunzch@1672e8fc-9579-4a43-9460-95afed9bdb0b" ]
[ [ [ 1, 232 ] ] ]
d33d8a1efd9d95fc8e451da577bbb9739af6ebe9
1585c7e187eec165138edbc5f1b5f01d3343232f
/СПиОС/PiChat/PiChat/PiChatClient/PiChatClient.h
e35f6ae8eb6ff5bef17552170902daf6a76ec242
[]
no_license
a-27m/vssdb
c8885f479a709dd59adbb888267a03fb3b0c3afb
d86944d4d93fd722e9c27cb134256da16842f279
refs/heads/master
2022-08-05T06:50:12.743300
2011-06-23T08:35:44
2011-06-23T08:35:44
82,612,001
1
0
null
2021-03-29T08:05:33
2017-02-20T23:07:03
C#
UTF-8
C++
false
false
524
h
// PiChatClient.h : main header file for the PROJECT_NAME application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CPiClientApp: // See PiChatClient.cpp for the implementation of this class // class CPiClientApp : public CWinApp { public: CPiClientApp(); // Overrides public: virtual BOOL InitInstance(); // Implementation DECLARE_MESSAGE_MAP() }; extern CPiClientApp theApp;
[ "Axell@bf672a44-3a04-1d4a-850b-c2a239875c8c" ]
[ [ [ 1, 31 ] ] ]
4ae99741a550c0c6a533b6a48e41fc0148dbe248
9b75c1c40dbeda4e9d393278d38a36a61484a5b6
/cpp files to be pasted in INCLUDE directory/FC.CPP
f6bee4a94cbc88a29b2c12d8a5936f3359a616fe
[]
no_license
yeskarthik/Project-Shark
b5fe9f14913618f0205c4a82003e466da52f7929
042869cd69b60e958c65de2a17b0bd34612e28dc
refs/heads/master
2020-05-22T13:49:42.317314
2011-04-06T06:35:21
2011-04-06T06:35:21
1,575,801
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
# include<fstream.h> void fc(char *target,char *source) { //char source[67],target[67]; //char ch; //cout<<endl<<"Enter source filename = "; //cin>>source; //cout<<endl<<"Enter target filename = "; //cin>>target; ifstream infile(source); ofstream outfile(target); outfile<<infile.rdbuf(); }
[ [ [ 1, 17 ] ] ]
96421a53f0ec55810a5ca668eb033202074db031
1de7bc93ba6d2e2000683eaf97277b35679ab873
/CryptoPP/utf8.cpp
e071e3aaeb674dfec2124184de3c346db072f579
[]
no_license
mohamadpk/secureimplugin
b184642095e24b623b618d02cc7c946fc9bed6bf
6ebfa5477b1aa8baaccea3f86f402f6d7f808de1
refs/heads/master
2021-03-12T23:50:12.141449
2010-04-28T06:54:37
2010-04-28T06:54:37
37,033,105
0
0
null
null
null
null
UTF-8
C++
false
false
2,989
cpp
#include "commonheaders.h" LPSTR szOut = NULL; LPWSTR wszOut = NULL; LPSTR __cdecl utf8encode(LPCWSTR str) { // LPSTR szOut; LPWSTR wszTemp, w; int len, i; if (str == NULL) return NULL; wszTemp = (LPWSTR)str; len = 0; for (w=wszTemp; *w; w++) { if (*w < 0x0080) len++; else if (*w < 0x0800) len += 2; else len += 3; } SAFE_FREE(szOut); if ((szOut = (LPSTR) malloc(len + 1)) == NULL) return NULL; i = 0; for (w=wszTemp; *w; w++) { if (*w < 0x0080) szOut[i++] = (BYTE) *w; else if (*w < 0x0800) { szOut[i++] = 0xc0 | (((*w) >> 6) &0x3f); szOut[i++] = 0x80 | ((*w) & 0x3f); } else { szOut[i++] = 0xe0 | ((*w) >> 12); szOut[i++] = 0x80 | (((*w) >> 6) & 0x3f); szOut[i++] = 0x80 | ((*w) & 0x3f); } } szOut[i] = '\0'; return szOut; } LPWSTR __cdecl utf8decode(LPCSTR str) { int i, len; LPSTR p; // LPWSTR wszOut; if (str == NULL) return NULL; len = strlen(str)+1; SAFE_FREE(wszOut); if ((wszOut = (LPWSTR) malloc(len*sizeof(WCHAR))) == NULL) return NULL; p = (LPSTR)str; i = 0; while (*p) { if ((p[0] & 0x80) == 0) { wszOut[i++] = *(p++); continue; } if ((p[0] & 0xe0) == 0xe0 && (p[1] & 0xc0) == 0x80 && (p[2] & 0xc0) == 0x80) { wszOut[i] = (*(p++) & 0x0f) << 12; wszOut[i] |= (*(p++) & 0x3f) << 6; wszOut[i++] |= (*(p++) & 0x3f); continue; } if ((p[0] & 0xe0) == 0xc0 && (p[1] & 0xc0) == 0x80) { wszOut[i] = (*(p++) & 0x1f) << 6; wszOut[i++] |= (*(p++) & 0x3f); continue; } wszOut[i++] = *p++; } wszOut[i] = '\0'; return wszOut; } // Returns true if the buffer only contains 7-bit characters. int __cdecl is_7bit_string(LPCSTR str) { while( *str ) { if ( *str & 0x80 ) { return FALSE; break; } str++; } return TRUE; } //Copyright (C) 2001, 2002 Peter Verthez //under GNU LGPL int __cdecl is_utf8_string(LPCSTR str) { int expect_bytes = 0; if (!str) return 0; while (*str) { if ((*str & 0x80) == 0) { /* Looks like an ASCII character */ if (expect_bytes) /* byte of UTF-8 character expected */ return 0; else { /* OK, ASCII character expected */ str++; } } else { /* Looks like byte of an UTF-8 character */ if (expect_bytes) { /* expect_bytes already set: first byte of UTF-8 char already seen */ if ((*str & 0xC0) == 0x80) { /* OK, next byte of UTF-8 character */ /* Decrement number of expected bytes */ expect_bytes--; str++; } else { /* again first byte ?!?! */ return 0; } } else { /* First byte of the UTF-8 character */ /* count initial one bits and set expect_bytes to 1 less */ char ch = *str; while (ch & 0x80) { expect_bytes++; ch = (ch & 0x7f) << 1; } expect_bytes--; str++; } } } return (expect_bytes == 0); } // EOF
[ "balookrd@d641cd86-4a32-0410-994c-055de1cff029" ]
[ [ [ 1, 149 ] ] ]
c2c62199f44a01fdccc9b50d771cca51a25caf5e
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/multi_index/test/test_set_ops.cpp
d86d93c8560fda2c36f91e2c57d6f3f88584dd61
[ "BSL-1.0" ]
permissive
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,457
cpp
/* Boost.MultiIndex test for standard set operations. * * Copyright 2003-2004 Joaquín M López Muñoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org/libs/multi_index for library home page. */ #include "test_set_ops.hpp" #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include <algorithm> #include <vector> #include "pre_multi_index.hpp" #include "employee.hpp" #include <boost/test/test_tools.hpp> using namespace boost::multi_index; void test_set_ops() { employee_set es; employee_set_by_name& i1=get<by_name>(es); const employee_set_by_age& i2=get<age>(es); es.insert(employee(0,"Joe",31)); es.insert(employee(1,"Robert",27)); es.insert(employee(2,"John",40)); es.insert(employee(3,"Albert",20)); es.insert(employee(4,"John",57)); BOOST_CHECK(i1.find("John")->name=="John"); BOOST_CHECK(i2.find(41)==i2.end()); BOOST_CHECK(i1.count("John")==2); BOOST_CHECK(es.count(employee(10,"",-1))==0); BOOST_CHECK(i1.lower_bound("John")->name=="John"); BOOST_CHECK( std::distance( i2.lower_bound(31), i2.upper_bound(60))==3); std::pair<employee_set_by_name::iterator,employee_set_by_name::iterator> p= i1.equal_range("John"); BOOST_CHECK(std::distance(p.first,p.second)==2); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 50 ] ] ]
5c0fca80e282133a0969f3eaad36a58e569a2487
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/disassembler/MUL_S.h
71d0192d7282738217f49650de65900b67515f75
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
363
h
/* MUL_S */ void AllegrexInstructionTemplate< 0x46000002, 0xffe0003f >::disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment) { using namespace Allegrex; ::strcpy(opcode_name, "mul.s"); ::sprintf(operands, "%s, %s, %s", fpr_name[fd(opcode)], fpr_name[fs(opcode)], fpr_name[ft(opcode)]); ::strcpy(comment, ""); }
[ [ [ 1, 9 ] ] ]
dc33ef33e1a04ce520761db7b9447ae51ec887ee
7476d2c710c9a48373ce77f8e0113cb6fcc4c93b
/RakNet/GetTime.cpp
5c091931550d8a9ba4f329e6ec6f26853b3e3294
[]
no_license
CmaThomas/Vault-Tec-Multiplayer-Mod
af23777ef39237df28545ee82aa852d687c75bc9
5c1294dad16edd00f796635edaf5348227c33933
refs/heads/master
2021-01-16T21:13:29.029937
2011-10-30T21:58:41
2011-10-30T22:00:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,644
cpp
/// \file /// /// This file is part of RakNet Copyright 2003 Jenkins Software LLC /// /// Usage of RakNet is subject to the appropriate license agreement. #if defined(_WIN32) #include "WindowsIncludes.h" // To call timeGetTime // on Code::Blocks, this needs to be libwinmm.a instead #pragma comment(lib, "Winmm.lib") #endif #include "GetTime.h" #if defined(_WIN32) DWORD mProcMask; DWORD mSysMask; HANDLE mThread; #else #include <sys/time.h> #include <unistd.h> RakNet::TimeUS initialTime; #endif static bool initialized=false; #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 #include "SimpleMutex.h" RakNet::TimeUS lastNormalizedReturnedValue=0; RakNet::TimeUS lastNormalizedInputValue=0; /// This constraints timer forward jumps to 1 second, and does not let it jump backwards /// See http://support.microsoft.com/kb/274323 where the timer can sometimes jump forward by hours or days /// This also has the effect where debugging a sending system won't treat the time spent halted past 1 second as elapsed network time RakNet::TimeUS NormalizeTime(RakNet::TimeUS timeIn) { RakNet::TimeUS diff, lastNormalizedReturnedValueCopy; static RakNet::SimpleMutex mutex; mutex.Lock(); if (timeIn>=lastNormalizedInputValue) { diff = timeIn-lastNormalizedInputValue; if (diff > GET_TIME_SPIKE_LIMIT) lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT; else lastNormalizedReturnedValue+=diff; } else lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT; lastNormalizedInputValue=timeIn; lastNormalizedReturnedValueCopy=lastNormalizedReturnedValue; mutex.Unlock(); return lastNormalizedReturnedValueCopy; } #endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 RakNet::Time RakNet::GetTime( void ) { return (RakNet::Time)(GetTimeUS()/1000); } RakNet::TimeMS RakNet::GetTimeMS( void ) { return (RakNet::TimeMS)(GetTimeUS()/1000); } #if defined(_WIN32) RakNet::TimeUS GetTimeUS_Windows( void ) { if ( initialized == false) { initialized = true; // Save the current process #if !defined(_WIN32_WCE) HANDLE mProc = GetCurrentProcess(); // Get the current Affinity #if _MSC_VER >= 1400 && defined (_M_X64) GetProcessAffinityMask(mProc, (PDWORD_PTR)&mProcMask, (PDWORD_PTR)&mSysMask); #else GetProcessAffinityMask(mProc, &mProcMask, &mSysMask); #endif mThread = GetCurrentThread(); #endif // _WIN32_WCE } // 9/26/2010 In China running LuDaShi, QueryPerformanceFrequency has to be called every time because CPU clock speeds can be different RakNet::TimeUS curTime; LARGE_INTEGER PerfVal; LARGE_INTEGER yo1; QueryPerformanceFrequency( &yo1 ); QueryPerformanceCounter( &PerfVal ); __int64 quotient, remainder; quotient=((PerfVal.QuadPart) / yo1.QuadPart); remainder=((PerfVal.QuadPart) % yo1.QuadPart); curTime = (RakNet::TimeUS) quotient*(RakNet::TimeUS)1000000 + (remainder*(RakNet::TimeUS)1000000 / yo1.QuadPart); #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 return NormalizeTime(curTime); #else return curTime; #endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 } #elif defined(__GNUC__) || defined(__GCCXML__) RakNet::TimeUS GetTimeUS_Linux( void ) { timeval tp; if ( initialized == false) { gettimeofday( &tp, 0 ); initialized=true; // I do this because otherwise RakNet::Time in milliseconds won't work as it will underflow when dividing by 1000 to do the conversion initialTime = ( tp.tv_sec ) * (RakNet::TimeUS) 1000000 + ( tp.tv_usec ); } // GCC RakNet::TimeUS curTime; gettimeofday( &tp, 0 ); curTime = ( tp.tv_sec ) * (RakNet::TimeUS) 1000000 + ( tp.tv_usec ); #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 return NormalizeTime(curTime - initialTime); #else return curTime - initialTime; #endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 } #endif RakNet::TimeUS RakNet::GetTimeUS( void ) { #if defined(_WIN32) return GetTimeUS_Windows(); #else return GetTimeUS_Linux(); #endif } bool RakNet::GreaterThan(RakNet::Time a, RakNet::Time b) { // a > b? const RakNet::Time halfSpan =(RakNet::Time) (((RakNet::Time)(const RakNet::Time)-1)/(RakNet::Time)2); return b!=a && b-a>halfSpan; } bool RakNet::LessThan(RakNet::Time a, RakNet::Time b) { // a < b? const RakNet::Time halfSpan = ((RakNet::Time)(const RakNet::Time)-1)/(RakNet::Time)2; return b!=a && b-a<halfSpan; }
[ [ [ 1, 220 ] ] ]
499d72781bcdc72a184b01b87c1a35481623aeec
8220ee892b48c97afedf5fb0709f819c451b6d51
/swarm.cpp
876f1d15db002f71f54d211fa80a55cde49960ab
[]
no_license
dwiel/swarm
5743c7d211b91f4e45e8cf9f33f87b3f43e0d431
b9940e1489e691fca87b7dd0250c428d52145152
refs/heads/master
2020-04-27T20:51:04.936432
2010-04-30T23:51:10
2010-04-30T23:51:10
242,755
2
0
null
null
null
null
UTF-8
C++
false
false
17,057
cpp
/* * This Code Was Created By Jeff Molofee 2000 * If You've Found This Code Useful, Please Let Me Know. * Visit My Site At nehe.gamedev.net * * this linux port by Ken Rockot ( read README ) */ #include <stdlib.h> #include <stdio.h> // Header File For Standard Input/Output #if defined(__APPLE_CPP__) || defined(__APPLE_CC__) || defined(__MACOS_CLASSIC__) #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> // Header File For The OpenGL #include <GL/glu.h> // Header File For The GLu #endif #include "SDL.h" #include <sys/time.h> #include <list> #include <vector> #include <iostream> #include <queue> #include <math.h> using namespace std; extern "C" { #include <lua.h> #include <lauxlib.h> #include <lualib.h> } #include "lo/lo.h" #include "vmath.h" #include "scene.hpp" #include "particle.hpp" #include "group.hpp" #include "swarm.hpp" #include <tolua++.h> #include "tolua_group.h" #include "tolua_swarm.h" #include "tolua_particle.h" #include "tolua_vmath.h" lua_State *L; bool active = true; // Window Active Flag Set To TRUE By Default bool fullscreen = true; // Fullscreen Flag Set To Fullscreen Mode By Default bool rainbow = true; // Rainbow Mode? bool sp; // Spacebar Pressed? bool rp; // Enter Key Pressed? int pause_movement = 0; float slowdown = 0.1f; // Slow Down Particles float xspeed; // Base X Speed (To Allow Keyboard Direction Of Tail) float yspeed; // Base Y Speed (To Allow Keyboard Direction Of Tail) float zoom = -40.0f; // Used To Zoom Out Scene scene; GLuint loop; // Misc Loop Variable GLuint col; // Current Color Selection GLuint delay; // Rainbow Effect Delay GLuint texture[1]; // Storage For Our Particle Texture bool keys[512]; // int window_width = 400; // int window_height = 300; int window_width = 1024; int window_height = 768; // int window_width = 800; // int window_height = 600; // TGA GLubyte *pixels; int shot_num; #define MAX_GROUPS 0 Group groups[MAX_GROUPS]; int HandleSDL ( SDL_Event *event ); // SDL event handler int LoadGLTextures() // Load Bitmap And Convert To A Texture { int Status; GLubyte *tex = new GLubyte[32 * 32 * 3]; FILE *tf; tf = fopen ( "data/particle.raw", "rb" ); size_t ret = fread ( tex, 1, 32 * 32 * 3, tf ); fclose ( tf ); if(ret) { // do stuff Status=1; // Set The Status To TRUE glGenTextures(1, &texture[0]); // Create One Texture glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, 3, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, tex); delete [] tex; return Status; // Return The Status } else { return 0; } } GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window { if (height==0) // Prevent A Divide By Zero By { height=1; // Making Height Equal One } glViewport(0,0,width,height); // Reset The Current Viewport glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,20000.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix } int InitGL(void) { if(!LoadGLTextures()) { // If Texture Didn't Load Return FALSE return 0; } glShadeModel(GL_SMOOTH); glClearColor(0.0f,0.0f,0.0f,0.0f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glDisable(GL_DEPTH_TEST); // Disable Depth Testing glEnable(GL_BLEND); // Enable Blending glBlendFunc(GL_SRC_ALPHA,GL_ONE); // Type Of Blending To Perform glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); // Really Nice Point Smoothing glEnable(GL_TEXTURE_2D); // Enable Texture Mapping glBindTexture(GL_TEXTURE_2D, texture[0]); // Select Our Texture for(set<Group*>::iterator iter = Group::groups.begin(); iter != Group::groups.end(); ++iter) { (*iter)->scene = &scene; (*iter)->controlled = true; } // saveTGA_init(); // Initialization Went OK return 1; } int DrawGLScene(double timediff) // Here's Where We Do All The Drawing { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer glLoadIdentity(); for(set<Group*>::iterator iter = Group::groups.begin(); iter != Group::groups.end(); ++iter) { (*iter)->Draw(); } SDL_GL_SwapBuffers (); // saveTGA(); return 1; // Everything Went OK } void print_debug() { // printf("number of 0s" } void saveTGA_init() { int nSize = window_width * window_height * 3; pixels = new GLubyte [nSize]; shot_num = 0; } void saveTGA_destroy() { delete [] pixels; } //this will save a TGA in the screenshots //folder under incrementally numbered files void saveTGA() { int nSize = window_width * window_height * 3; glPixelStorei(GL_PACK_ALIGNMENT,1); char cFileName[64]; FILE *fScreenshot; if (pixels == NULL) return; sprintf(cFileName,"screenshots/screenshot_%08d.tga",shot_num); fScreenshot = fopen(cFileName,"wb"); glReadPixels(0, 0, window_width, window_height, GL_RGB, GL_UNSIGNED_BYTE, pixels); //convert to BGR format unsigned char temp; int i = 0; while (i < nSize) { temp = pixels[i]; //grab blue pixels[i] = pixels[i+2];//assign red to blue pixels[i+2] = temp; //assign blue to red i += 3; //skip to next blue byte } unsigned char TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0}; unsigned char header[6] = {window_width%256,window_width/256, window_height%256,window_height/256,24,0}; fwrite(TGAheader, sizeof(unsigned char), 12, fScreenshot); fwrite(header, sizeof(unsigned char), 6, fScreenshot); fwrite(pixels, sizeof(GLubyte), nSize, fScreenshot); fclose(fScreenshot); shot_num++; } void check_keys (float timediff) { if(keys[SDLK_SPACE]) luaL_dofile(L, "foo.lua"); // maybe wait and do this in Lua or python ... // controls.push_back(Control(&scene.speed, "scene speed", Linear(SDLK_s, 0.1f)); // TODO: control amount velocity affects shape // TODO: control weight on nearest neighbors // TODO: control number of particles in swarm if (keys[SDLK_s] && keys[SDLK_UP]) { scene.speed += scene.speed * 0.1f * timediff; cout << "scene speed " << scene.speed << endl; } if (keys[SDLK_s] && keys[SDLK_DOWN]) { scene.speed -= scene.speed * 0.1f * timediff; cout << "scene speed " << scene.speed << endl; } if (keys[SDLK_s] && keys[SDLK_PAGEUP]) { scene.speed += scene.speed * 1.0f * timediff; cout << "scene speed " << scene.speed << endl; } if (keys[SDLK_s] && keys[SDLK_PAGEDOWN]) { scene.speed -= scene.speed * 1.0f * timediff; cout << "scene speed " << scene.speed << endl; } if (keys[SDLK_b] && keys[SDLK_x] && keys[SDLK_UP]) { groups[0].vel_render_scale_x += groups[0].vel_render_scale_x * 0.1f * timediff; cout << "vel_render_scale_x: " << groups[0].vel_render_scale_x << endl; } else if (keys[SDLK_b] && keys[SDLK_x] && keys[SDLK_DOWN]) { groups[0].vel_render_scale_x -= groups[0].vel_render_scale_x * 0.1f * timediff; cout << "vel_render_scale_x: " << groups[0].vel_render_scale_x << endl; } else if (keys[SDLK_b] && keys[SDLK_x] && keys[SDLK_PAGEUP]) { groups[0].vel_render_scale_x += groups[0].vel_render_scale_x * 1.0f * timediff; cout << "vel_render_scale_x: " << groups[0].vel_render_scale_x << endl; } else if (keys[SDLK_b] && keys[SDLK_x] && keys[SDLK_PAGEDOWN]) { groups[0].vel_render_scale_x -= groups[0].vel_render_scale_x * 1.0f * timediff; cout << "vel_render_scale_x: " << groups[0].vel_render_scale_x << endl; } if (keys[SDLK_b] && keys[SDLK_y] && keys[SDLK_UP]) { groups[0].vel_render_scale_y += groups[0].vel_render_scale_y * 0.1f * timediff; cout << "vel_render_scale_y: " << groups[0].vel_render_scale_y << endl; } else if (keys[SDLK_b] && keys[SDLK_y] && keys[SDLK_DOWN]) { groups[0].vel_render_scale_y -= groups[0].vel_render_scale_y * 0.1f * timediff; cout << "vel_render_scale_y: " << groups[0].vel_render_scale_y << endl; } else if (keys[SDLK_b] && keys[SDLK_y] && keys[SDLK_PAGEUP]) { groups[0].vel_render_scale_y += groups[0].vel_render_scale_y * 1.0f * timediff; cout << "vel_render_scale_y: " << groups[0].vel_render_scale_y << endl; } else if (keys[SDLK_b] && keys[SDLK_y] && keys[SDLK_PAGEDOWN]) { groups[0].vel_render_scale_y -= groups[0].vel_render_scale_y * 1.0f * timediff; cout << "vel_render_scale_y: " << groups[0].vel_render_scale_y << endl; } else if (keys[SDLK_b] && keys[SDLK_UP]) { groups[0].vel_render_scale_x += groups[0].vel_render_scale_x * 0.1f * timediff; groups[0].vel_render_scale_y += groups[0].vel_render_scale_y * 0.1f * timediff; cout << "vel_render_scale: " << groups[0].vel_render_scale_x << endl; } else if (keys[SDLK_b] && keys[SDLK_DOWN]) { groups[0].vel_render_scale_x -= groups[0].vel_render_scale_x * 0.1f * timediff; groups[0].vel_render_scale_y -= groups[0].vel_render_scale_y * 0.1f * timediff; cout << "vel_render_scale: " << groups[0].vel_render_scale_x << endl; } else if (keys[SDLK_b] && keys[SDLK_PAGEUP]) { groups[0].vel_render_scale_x += groups[0].vel_render_scale_x * 1.0f * timediff; groups[0].vel_render_scale_y += groups[0].vel_render_scale_y * 1.0f * timediff; cout << "vel_render_scale: " << groups[0].vel_render_scale_x << endl; } else if (keys[SDLK_b] && keys[SDLK_PAGEDOWN]) { groups[0].vel_render_scale_x -= groups[0].vel_render_scale_x * 1.0f * timediff; groups[0].vel_render_scale_y -= groups[0].vel_render_scale_y * 1.0f * timediff; cout << "vel_render_scale: " << groups[0].vel_render_scale_x << endl; } if (keys[SDLK_c] && keys[SDLK_UP]) { groups[0].color_off += 1.0f * timediff; cout << "color_off: " << groups[0].color_off << endl; } if (keys[SDLK_c] && keys[SDLK_DOWN]) { groups[0].color_off -= 1.0f * timediff; cout << "color_off: " << groups[0].color_off << endl; } if (keys[SDLK_c] && keys[SDLK_PAGEUP]) { groups[0].color_off += 10.0f * timediff; cout << "color_off: " << groups[0].color_off << endl; } if (keys[SDLK_c] && keys[SDLK_PAGEDOWN]) { groups[0].color_off -= 10.0f * timediff; cout << "color_off: " << groups[0].color_off << endl; } // if (keys[SDLK_z] && keys[SDLK_UP]) { // scene.zoom += 1.0f * timediff; // Zoom In // cout << "scene zoom: " << scene.zoom << endl; // } // if (keys[SDLK_z] && keys[SDLK_DOWN]) { // scene.zoom -= 1.0f * timediff; // Zoom Out // cout << "scene zoom: " << scene.zoom << endl; // } // if (keys[SDLK_z] && keys[SDLK_PAGEUP]) { // scene.zoom += 10.0f * timediff; // Zoom In // cout << "scene zoom: " << scene.zoom << endl; // } // if (keys[SDLK_z] && keys[SDLK_PAGEDOWN]) { // scene.zoom -= 10.0f * timediff; // Zoom Out // cout << "scene zoom: " << scene.zoom << endl; // } } int HandleSDL(SDL_Event *event) { int done = 0; switch(event->type) { case SDL_QUIT: done = 1; break; case SDL_KEYDOWN: if(event->key.keysym.sym == SDLK_ESCAPE) done = 1; keys[event->key.keysym.sym] = true; break; case SDL_KEYUP: keys[event->key.keysym.sym] = false; break; } return done; } void OSC_error(int num, const char *msg, const char *path) { printf("liblo server error %d in path %s: %s\n", num, path, msg); } // 100 - 600 int bass_handler(const char *path, const char *types, lo_arg **argv, int argc, void *data, void *user_data) { Group *group = (*Group::groups.begin()); group->vel_render_scale_x = (argv[0]->f / 1000.0f) - 1.0f; group->vel_render_scale_y = (argv[0]->f / 1000.0f) - 1.0f; cout << "bass:" << argv[0]->f << endl; return 0; } // - 1000 int mid_handler(const char *path, const char *types, lo_arg **argv, int argc, void *data, void *user_data) { Group *group = (*Group::groups.begin()); group->color_off = (argv[0]->f / 50.0f); cout << "mid:" << argv[0]->f << endl; return 0; } // - 1500 int high_handler(const char *path, const char *types, lo_arg **argv, int argc, void *data, void *user_data) { groups[0].scene->speed = pow(argv[0]->f, 2.0f) / 1500; return 0; } int lua_execute_handler(const char *path, const char *types, lo_arg **argv, int argc, void *data, void *user_data) { string str = ""; for(int i = 0; i < argc; ++i) { str += argv[i]->s; } luaL_dostring(L, str.c_str()); return 0; } int generic_handler(const char *path, const char *types, lo_arg **argv, int argc, void *data, void *user_data) { // int i; // // printf("path: <%s>\n", path); // for (i=0; i<argc; i++) { // printf("arg %d '%c' ", i, types[i]); // //lo_arg_pp(types[i], argv[i]); // printf("\n"); // } // printf("\n"); // fflush(stdout); // // return 1; lua_getfield(L, LUA_GLOBALSINDEX, "OSCevent"); lua_pushstring(L, path); if(types[0] == 'f' ) { lua_pushnumber(L, argv[0]->f); } else { lua_pushnumber(L, argv[0]->i); } if (lua_pcall(L, 2, 0, 0)) { cout << "error in OSCevent: " << lua_tostring(L, -1) << endl; lua_pop(L, 1); } return 1; } float gettime() { timeval now; gettimeofday(&now, NULL); return now.tv_sec + (now.tv_usec / 1000000.0f); } void setBackgroundColor(float r, float g, float b) { glClearColor(r, g, b, 0.0f); } void sendOSC(float data) { // lo_address t; // // t = lo_address_new("192.168.1.67", "57122"); // lo_send(t, "/fm/set", "i", (int)data); //cout << "/fm/set" << " " << data << endl; } int main(int argc, char **argv) { SDL_Init(SDL_INIT_VIDEO); lo_server s = lo_server_new("9001", OSC_error); // lo_server_add_method(s, "/notes/bass", "f", bass_handler, NULL); // lo_server_add_method(s, "/notes/mid", "f", mid_handler, NULL); //lo_server_add_method(s, "/notes/high", "f", high_handler, NULL); lo_server_add_method(s, "/lua/execute", NULL, lua_execute_handler, NULL); lo_server_add_method(s, NULL, NULL, generic_handler, NULL); // int flags = SDL_DOUBLEBUF | SDL_FULLSCREEN | SDL_OPENGL; // int flags = SDL_FULLSCREEN | SDL_OPENGL; int flags = SDL_OPENGL; SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_SetVideoMode(window_width, window_height, 16, flags); // SDL_SetVideoMode(640, 480, 16, flags); InitGL (); ReSizeGLScene ( window_width, window_height ); // ReSizeGLScene ( 640, 480 ); L = lua_open(); luaL_openlibs(L); tolua_group_open(L); tolua_swarm_open(L); tolua_vmath_open(L); tolua_particle_open(L); luaL_dofile(L, "foo.lua"); lua_getfield(L, LUA_GLOBALSINDEX, "init"); if (lua_pcall(L, 0, 0, 0)) { cout << "error in init: " << lua_tostring(L, -1) << endl; lua_pop(L, 1); } for(set<Group*>::iterator iter = Group::groups.begin(); iter != Group::groups.end(); ++iter) { (*iter)->scene = &scene; (*iter)->controlled = true; } timeval now, prev; double timediff; int done = 0; gettimeofday(&prev, NULL); // intialize the time while(!done) { gettimeofday(&now, NULL); timediff = (now.tv_sec - prev.tv_sec) + (now.tv_usec - prev.tv_usec)/1000000.0f; prev = now; printf("\rFPS: %f", 1.0f/timediff); for(set<Group*>::iterator iter = Group::groups.begin(); iter != Group::groups.end(); ++iter) { (*iter)->Move(timediff); } DrawGLScene(timediff); check_keys(timediff); lua_getfield(L, LUA_GLOBALSINDEX, "update"); if (lua_pcall(L, 0, 0, 0) != 0) { cout << "error in update: " << lua_tostring(L, -1) << endl; lua_pop(L, 1); } SDL_Event event; while(SDL_PollEvent(&event)) { done = HandleSDL(&event); } lo_server_recv_noblock(s, 0); } // saveTGA_destroy(); SDL_Quit(); lua_close(L); cout << endl; return 0; }
[ "dwiel@dwiel.(none)", "[email protected]", "[email protected]" ]
[ [ [ 1, 10 ], [ 21, 31 ], [ 38, 45 ], [ 55, 74 ], [ 90, 99 ], [ 102, 102 ], [ 108, 108 ], [ 114, 114 ], [ 116, 116 ], [ 121, 159 ], [ 163, 163 ], [ 166, 173 ], [ 175, 175 ], [ 179, 181 ], [ 184, 190 ], [ 243, 244 ], [ 247, 342 ], [ 359, 391 ], [ 397, 404 ], [ 407, 407 ], [ 411, 413 ], [ 415, 419 ], [ 461, 461 ], [ 479, 483 ], [ 491, 491 ], [ 493, 495 ], [ 498, 499 ], [ 523, 531 ], [ 534, 536 ], [ 543, 551 ], [ 554, 555 ], [ 557, 558 ], [ 561, 561 ] ], [ [ 11, 20 ], [ 48, 48 ], [ 426, 427 ], [ 559, 560 ] ], [ [ 32, 37 ], [ 46, 47 ], [ 49, 54 ], [ 75, 89 ], [ 100, 101 ], [ 103, 107 ], [ 109, 113 ], [ 115, 115 ], [ 117, 120 ], [ 160, 162 ], [ 164, 165 ], [ 174, 174 ], [ 176, 178 ], [ 182, 183 ], [ 191, 242 ], [ 245, 246 ], [ 343, 358 ], [ 392, 396 ], [ 405, 406 ], [ 408, 410 ], [ 414, 414 ], [ 420, 425 ], [ 428, 460 ], [ 462, 478 ], [ 484, 490 ], [ 492, 492 ], [ 496, 497 ], [ 500, 522 ], [ 532, 533 ], [ 537, 542 ], [ 552, 553 ], [ 556, 556 ] ] ]
8a7bc4c8316aa99d3fe9f03f098d03325e354e50
2982a765bb21c5396587c86ecef8ca5eb100811f
/util/wm5/LibMathematics/ComputationalGeometry/Wm5ConvexHull2.h
30e81f6c797eaacca1f1e9bf0df417fc40f64a33
[]
no_license
evanw/cs224final
1a68c6be4cf66a82c991c145bcf140d96af847aa
af2af32732535f2f58bf49ecb4615c80f141ea5b
refs/heads/master
2023-05-30T19:48:26.968407
2011-05-10T16:21:37
2011-05-10T16:21:37
1,653,696
27
9
null
null
null
null
UTF-8
C++
false
false
2,805
h
// Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.1 (2010/10/01) #ifndef WM5CONVEXHULL2_H #define WM5CONVEXHULL2_H #include "Wm5MathematicsLIB.h" #include "Wm5ConvexHull1.h" #include "Wm5Query2.h" namespace Wm5 { template <typename Real> class WM5_MATHEMATICS_ITEM ConvexHull2 : public ConvexHull<Real> { public: // The input to the constructor is the array of vertices whose convex hull // is required. If you want ConvexHull2 to delete the vertices during // destruction, set bOwner to 'true'. Otherwise, you own the vertices and // must delete them yourself. // // You have a choice of speed versus accuracy. The fastest choice is // Query::QT_INT64, but it gives up a lot of precision, scaling the points // to [0,2^{20}]^3. The choice Query::QT_INTEGER gives up less precision, // scaling the points to [0,2^{24}]^3. The choice Query::QT_RATIONAL uses // exact arithmetic, but is the slowest choice. The choice Query::QT_REAL // uses floating-point arithmetic, but is not robust in all cases. ConvexHull2 (int numVertices, Vector2<Real>* vertices, Real epsilon, bool owner, Query::Type queryType); virtual ~ConvexHull2 (); // If GetDimension() returns 1, then the points lie on a line. You must // create a ConvexHull1 object using the function provided. const Vector2<Real>& GetLineOrigin () const; const Vector2<Real>& GetLineDirection () const; ConvexHull1<Real>* GetConvexHull1 () const; private: using ConvexHull<Real>::mQueryType; using ConvexHull<Real>::mNumVertices; using ConvexHull<Real>::mDimension; using ConvexHull<Real>::mNumSimplices; using ConvexHull<Real>::mIndices; using ConvexHull<Real>::mEpsilon; using ConvexHull<Real>::mOwner; class Edge { public: Edge (int v0, int v1); int GetSign (int i, const Query2<Real>* query); void Insert (Edge* adj0, Edge* adj1); void DeleteSelf (); void DeleteAll (); void GetIndices (int& numIndices, int*& indices); int V[2]; Edge* E[2]; int Sign; int Time; }; bool Update (Edge*& hull, int i); // The input points. Vector2<Real>* mVertices; // Support for robust queries. Vector2<Real>* mSVertices; Query2<Real>* mQuery; // The line of containment if the dimension is 1. Vector2<Real> mLineOrigin, mLineDirection; }; typedef ConvexHull2<float> ConvexHull2f; typedef ConvexHull2<double> ConvexHull2d; } #endif
[ [ [ 1, 88 ] ] ]
85814d440e66f4722f85f63ed2c1fb119b0af242
f8c4a7b2ed9551c01613961860115aaf427d3839
/src/vlrSoundLayer.h
0d060d05f5d1054500a9564ecdd63952db3c6f3d
[]
no_license
ifgrup/mvj-grupo5
de145cd57d7c5ff2c140b807d2d7c5bbc57cc5a9
6ba63d89b739c6af650482d9c259809e5042a3aa
refs/heads/master
2020-04-19T15:17:15.490509
2011-12-19T17:40:19
2011-12-19T17:40:19
34,346,323
0
0
null
null
null
null
UTF-8
C++
false
false
860
h
#ifndef __SOUNDLAYER_H__ #define __SOUNDLAYER_H__ #pragma comment(lib,"fmodex_vc.lib") #include <windows.h> #include <fmod.hpp> #include <fmod_errors.h> #include "cCritter.h" #define STATE_MAIN 0 #define STATE_GAME 1 #define STATE_WIN 2 #define PASOS 0 #define DISPARO 1 #define ATAQUE 2 class vlrSoundLayer { public: vlrSoundLayer (); virtual ~vlrSoundLayer(); bool Init(); void ERRCHECK(FMOD_RESULT result); void vlrSoundLayer::LoadData(); bool PlaySound(int state); bool Playeffects(int state); bool SoundEffectsUnit(cCritter *Critter); void Finalize(); // private: FMOD::Sound *sound1, *sound2, *sound3,*sound4,*sound5; FMOD::Channel *channel ,*channel2,*channelef, *channelef1, *channelef2; FMOD_RESULT result; FMOD::System *system; }; #endif
[ "[email protected]@7a9e2121-179f-53cc-982f-8ee3039a786c", "[email protected]@7a9e2121-179f-53cc-982f-8ee3039a786c" ]
[ [ [ 1, 36 ], [ 41, 51 ] ], [ [ 37, 40 ] ] ]
d248b12b1d1989324d2fb7f1be0cb3b2dad03864
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/depends/ClanLib/src/Core/XML/xpath_evaluator.cpp
623788847e037e765c8809edcf2ceb657d257b54
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
3,771
cpp
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #include "precomp.h" #include "API/Core/XML/xpath_evaluator.h" #include "API/Core/XML/dom_node.h" #include "API/Core/Text/string_help.h" #include "xpath_evaluator_impl.h" #include "xpath_token.h" ///////////////////////////////////////////////////////////////////////////// // CL_XPathEvaluator Construction: CL_XPathEvaluator::CL_XPathEvaluator() : impl(new CL_XPathEvaluator_Impl) { } ///////////////////////////////////////////////////////////////////////////// // CL_XPathEvaluator Operations: CL_XPathObject CL_XPathEvaluator::evaluate(const CL_StringRef &expression, CL_DomNode context_node) { CL_XPathToken prev_token; CL_XPathEvaluateResult result = impl->evaluate(expression, context_node, prev_token); if (result.next_token.type != CL_XPathToken::type_none) throw CL_Exception("Syntax error in xpath expression"); return result.result; } /* std::vector<CL_DomNode> XPathEvaluator::evaluate( const CL_StringRef &expression, CL_DomNode context_node, int context_position, int context_size) { int tokenizer_pos = 0; CL_StringRef token = read_token(expression, tokenizer_pos); if (token == "/") { context_node = context_node.ownerDocument(); token = read_token(expression, tokenizer_pos); } if (token.empty()) { std::vector<CL_DomNode> nodes; nodes.push_back(context_node); return nodes; } CL_StringRef axis_name; CL_StringRef node_test; CL_StringRef next_token = peek_token(expression, tokenizer_pos); if (next_token == "::") { axis_name = token; node_test = read_token(expression, tokenzier_pos); } else { if (token[0] == '@') { axis_name = "attribute"; node_test = token.substr(1); } else { axis_name = "child"; node_test = token; } } std::vector<CL_DomNode> location_nodes = find_location_nodes(axis_name, node_test); next_token = peek_token(expression, tokenizer_pos); while (next_token == "[") { read_token(expression, tokenizer_pos); filter_location_nodes(location_nodes, expression, tokenizer_pos); } int tokenizer_pos = 0; CL_StringRef token = read_token(expression, tokenizer_pos); if (token.empty()) { return location_nodes; } else if (token == "/") { std::vector<CL_DomNode> union_nodes; std::vector<CL_DomNode>::size_type i = 0, size = location_nodes.size(); for (i = 0; i < size; i++) { std::vector<CL_DomNode> nodes = evaluate( expression.substr(tokenizer_pos), location_nodes[i], i, size); union_nodes.append(nodes); } return union_nodes; } else { throw Exception("XPath syntax error"); } } */
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 131 ] ] ]
5101de668d324240475d486c7c80757c8e5107c0
3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c
/zju.finished/2019.cpp
d18a29a15a1b01f3b9990b86df098018ac41f86b
[]
no_license
usherfu/zoj
4af6de9798bcb0ffa9dbb7f773b903f630e06617
8bb41d209b54292d6f596c5be55babd781610a52
refs/heads/master
2021-05-28T11:21:55.965737
2009-12-15T07:58:33
2009-12-15T07:58:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
985
cpp
#include<iostream> // 组合数学中的差分数列,相当于不断求导 using namespace std; enum { SIZ = 108, }; int num, pos, cnt; int dat[SIZ]; int dif[SIZ]; int iterate(){ int i; for(i=pos-2; i>=0; i--){ dif[i] += dif[i+1]; } return dif[0]; } void fun(){ int i; pos = 0; while(num > 0){ dif[pos++] = dat[num-1]; --num; for(i=0; i<num; i++){ dat[i] = dat[i+1] - dat[i]; } } while(pos > 1 && dif[pos-1] == 0){ pos--; } while(cnt > 0){ i = iterate(); printf("%d", i); if(--cnt) printf(" "); } printf("\n"); } int readIn(){ scanf("%d%d", &num, &cnt); for(int i=0; i<num; i++){ scanf("%d", &dat[i]); } return 1; } int main(){ int tst; scanf("%d", &tst); while(tst --){ readIn(); fun(); } return 0; }
[ [ [ 1, 57 ] ] ]
262ed97d5cb59296183ab22d543a9c1422a52642
3761dcce2ce81abcbe6d421d8729af568d158209
/src/cybergarage/http/HTTPResponse.cpp
14be4de0e056a17dbf02b60e0b26ff30e76625f2
[ "BSD-3-Clause" ]
permissive
claymeng/CyberLink4CC
af424e7ca8529b62e049db71733be91df94bf4e7
a1a830b7f4caaeafd5c2db44ad78fbb5b9f304b2
refs/heads/master
2021-01-17T07:51:48.231737
2011-04-08T15:10:49
2011-04-08T15:10:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,687
cpp
/****************************************************************** * * CyberHTTP for C++ * * Copyright (C) Satoshi Konno 2002-2003 * * File: HTTPResponse.cpp * * Revision; * * 03/27/03 * - first revision * 05/19/04 * - Changed the header include order for Cygwin. * 10/22/04 * - Added isSuccessful(). * ******************************************************************/ #include <cybergarage/http/HTML.h> #include <cybergarage/http/HTTPResponse.h> #include <cybergarage/http/HTTPServer.h> #if defined(BTRON) || defined(ITRON) || defined(TENGINE) #include <cybergarage/util/StringUtil.h> #endif #include <iostream> #include <sstream> using namespace std; using namespace CyberHTTP; #if defined(BTRON) || defined(ITRON) || defined(TENGINE) using namespace CyberUtil; #endif HTTPResponse::HTTPResponse() { string buf; setStatusCode(0); setContentType(TEXT_CONTENT_TYPE); setVersion(HTTP::VER_11); setServer(GetServerName(buf)); } HTTPResponse::HTTPResponse(HTTPResponse *httpRes) { setStatusCode(0); set(httpRes); } //////////////////////////////////////////////// // Status Line //////////////////////////////////////////////// const char *HTTPResponse::getStatusLineString(string &statusLineBuf) { #ifndef NO_USE_OSTRINGSTREAM ostringstream strBuf; strBuf << "HTTP/" << getVersion() << " " << getStatusCode() << " " << HTTP::StatusCode2String(statusCode) << HTTP::CRLF; statusLineBuf = strBuf.str(); #else string ibuf; statusLineBuf = "HTTP/"; statusLineBuf += getVersion(); statusLineBuf += " "; statusLineBuf += Integer2String(getStatusCode(), ibuf); statusLineBuf += " "; statusLineBuf += HTTP::StatusCode2String(statusCode); statusLineBuf += HTTP::CRLF; #endif return statusLineBuf.c_str(); } //////////////////////////////////////////////// // getHeader //////////////////////////////////////////////// const char *HTTPResponse::getHeader(string &headerBuf) { #ifndef NO_USE_OSTRINGSTREAM ostringstream strBuf; string statusLine; string header; strBuf << getStatusLineString(statusLine); strBuf << getHeaderString(header); headerBuf = strBuf.str(); #else string strBuf; getStatusLineString(headerBuf); headerBuf += getHeaderString(strBuf); #endif return headerBuf.c_str(); } //////////////////////////////////////////////// // toString //////////////////////////////////////////////// const char *HTTPResponse::toString(string &buf) { string header; buf = ""; buf.append(getHeader(header)); buf.append(HTTP::CRLF); buf.append(getContent()); return buf.c_str(); } void HTTPResponse::print() { std::string buf; #ifndef NO_USE_STD_COUT std::cout << toString(buf) << std::endl; #else printf("%s\n", toString(buf)); #endif }
[ "skonno@b944b01c-6696-4570-ab44-a0e08c11cb0e" ]
[ [ [ 1, 118 ] ] ]
82476e9849a829ad894869549bc60481ea948764
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/projects/PacketsGrasper/selectio/SocketPackets.cpp
064a7456e67029a45d83a3125fac91c4459969dc
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
GB18030
C++
false
false
5,638
cpp
#include "StdAfx.h" #include ".\socketpackets.h" #include ".\handlequeue.h" #include ".\bufferresult.h" //================================================= // class SocketPackets; // 查看是否存在已经完成的包 bool SocketPackets::isAnyCompleteSOCKET() { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); return completed_packets_.size() != 0; } void SocketPackets::removeSocketRel(const SOCKET s, BufferResult * result) { assert (NULL != result); using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); {// 删除所有完成的包 COMPLETED_PACKETS::iterator iter = completed_packets_.find(s); while (completed_packets_.end() != iter) { result->removeBufferResult(iter->second); delete iter->second; completed_packets_.erase(iter); // 获取下一个 iter = completed_packets_.find(s); } } {// 删除所有未完成的包 SOCK_DATA_MAP::iterator iter = _sockets_map_.find(s); while (_sockets_map_.end() != iter) { delete iter->second; _sockets_map_.erase(iter); // 获取下一个 iter = _sockets_map_.begin(); } } } // 将所有已经有完成包的socket存放在fd_set当中 // 此函数一般会在preselect中调用 void SocketPackets::getAllCompleteSOCKET(fd_set *readfds, HandleQueue * handler) { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); int handle_result; COMPLETED_PACKETS::const_iterator iter = completed_packets_.begin(); while ( iter != completed_packets_.end()) { // 不只包完整, 且数据需要处理完全 if (handler->getResult(iter->second, &handle_result)) { FD_SET(iter->first, readfds); iter = completed_packets_.upper_bound(iter->first); } } } // 将与SOCKET对应HTTPPacket的包添加到完成队列当中 int SocketPackets::addCompletedPacket(const SOCKET s, HTTPPacket *p) { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); completed_packets_.insert(std::make_pair(s, p)); return 0; } // 获取与SOCKET对应第一个已经完成的包 HTTPPacket * SocketPackets::getCompletedPacket(const SOCKET s) { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); COMPLETED_PACKETS::iterator iter = completed_packets_.find(s); if (completed_packets_.end() == iter) { return NULL; } else { return iter->second; } } int SocketPackets::removeCompletedPacket(const SOCKET s, HTTPPacket *p) { using namespace yanglei_utility; //SingleLock<CAutoCreateCS> lock(&cs_); // OutputDebugString("remove complete socket"); COMPLETED_PACKETS::iterator iter = completed_packets_.begin(); COMPLETED_PACKETS::const_iterator iterEnd = completed_packets_.end(); for (; iter != iterEnd; ++iter) { if (iter->second->getCode() == p->getCode()) { delete p; // **** 把这个忘了,导致内存泄漏 completed_packets_.erase(iter); return 1; } } return 0; } void SocketPackets::freeAllCompletedPacket() { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); COMPLETED_PACKETS::const_iterator iter = completed_packets_.begin(); for (; iter != completed_packets_.end(); ++iter) { if (iter->second != NULL) { delete iter->second; } } completed_packets_.clear(); } // 删除掉所有保存的临时包 void SocketPackets::clearAllPackets() { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); // char buffer[1024]; SOCK_DATA_MAP::iterator iter = _sockets_map_.begin(); for (; iter != _sockets_map_.end(); ++iter) { if (iter->second != NULL) { delete iter->second; } } _sockets_map_.clear(); } bool SocketPackets::isThereUncompletePacket(const SOCKET s) { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); return _sockets_map_.find(s) != _sockets_map_.end(); } // 获取与SOCKET相关的未完成的包 HTTPPacket * SocketPackets::getSOCKETPacket(const SOCKET s) { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); SOCK_DATA_MAP::iterator iter = _sockets_map_.lower_bound(s); SOCK_DATA_MAP::iterator iterEnd = _sockets_map_.upper_bound(s); for (; iter != iterEnd; ++iter) { // 这里为什么会出现完成的包呢 ?? assert (iter->second->isComplete() == false); return iter->second; } HTTPPacket *packet = new HTTPPacket; _sockets_map_.insert(std::make_pair(s, packet)); return packet; } //int socketpackets::replacepacket(socket s, httppacket *p, httppacket * new_packet) { // using namespace yanglei_utility; // singlelock<cautocreatecs> lock(&cs_); // // sock_data_map::iterator iter = _sockets_map_.lower_bound(s); // sock_data_map::const_iterator iterend = _sockets_map_.upper_bound(s); // for (; iter != iterend; ++iter) { // if (iter->second->getcode() == p->getcode()) { // assert(s == iter->first); // iter->second = new_packet; // return 1; // } // } // // return 0; //} int SocketPackets::removePacket(const SOCKET s, HTTPPacket *p) { using namespace yanglei_utility; SingleLock<CAutoCreateCS> lock(&cs_); SOCK_DATA_MAP::iterator iter = _sockets_map_.lower_bound(s); SOCK_DATA_MAP::const_iterator iterEnd = _sockets_map_.upper_bound(s); for (; iter != iterEnd; ++iter) { if (iter->second->getCode() == p->getCode()) { //char buffer[1024]; //sprintf(buffer, "== remove socket : %d, code : %d", s, p->getCode()); //OutputDebugString(buffer); assert(s == iter->first); _sockets_map_.erase(iter); return 1; } } assert(false); return 0; }
[ [ [ 1, 190 ] ] ]
32b493480ff75bb7d9836c47d9c7301f4bacca24
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/HovercraftUniverse/CheckPointRepresentation.h
19101cc46267e0bc7f88186d2c352a3bd6d95c47
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
732
h
#ifndef CHECKPOINTREPRESENTATION_H_ #define CHECKPOINTREPRESENTATION_H_ #include "EntityRepresentation.h" #include <vector> namespace HovUni { class CheckPoint; /** * Representation of a checkpoint entity. * * @author Kristof Overdulve */ class CheckPointRepresentation : public EntityRepresentation { public: /** * Constructor. */ CheckPointRepresentation(CheckPoint * entity, Ogre::SceneManager * sceneMgr, Ogre::String meshFile, Ogre::String resourceGroupName, bool visible, bool castShadows, Ogre::Real renderingDistance, Ogre::String materialFile, std::vector<Ogre::String> subMaterials); /** * Destructor. */ ~CheckPointRepresentation(); }; } #endif
[ "kristof.overdulve@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c", "pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c" ]
[ [ [ 1, 8 ], [ 11, 33 ] ], [ [ 9, 10 ] ] ]
d2ced70037d5fc5dddcb8d4205100e530617ed19
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/dialog/src/AimlNode.cpp
64543f42c76e529214b5869290058201d508e31e
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,370
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "AimlNode.h" namespace rl { AimlNode::AimlNode(AimlNode* parent) : mParent(parent) { if(mParent) { mIndex = mParent->getCurrentChildIndex(); } } AimlNode::~AimlNode() { } unsigned int AimlNode::getCurrentChildIndex() { return mChildNodes.size(); } AimlNode* AimlNode::getFirstChild() { return mChildNodes[0]; } AimlNode* AimlNode::getNextSibling() { // std::find(mChildNodes.begin(), mChildNodes.end(), mParent ); return mParent->getNode(mIndex+1); } AimlNode* AimlNode::getNode(unsigned int index) { return mChildNodes[index]; } } // Namespace rl end
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 57 ] ] ]
f2e4dbd78d3612c2a281533861000be2630fc7ca
942b88e59417352fbbb1a37d266fdb3f0f839d27
/src/fileio.cxx
605448ff1cfe8306fb916dd9fb6a3f6ee55683ae
[ "BSD-2-Clause" ]
permissive
take-cheeze/ARGSS...
2c1595d924c24730cc714d017edb375cfdbae9ef
2f2830e8cc7e9c4a5f21f7649287cb6a4924573f
refs/heads/master
2016-09-05T15:27:26.319404
2010-12-13T09:07:24
2010-12-13T09:07:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,690
cxx
#include <boost/ptr_container/ptr_vector.hpp> #include <fstream> #include "fileio.hxx" #include "rgssad.hxx" namespace FileIO { std::string toSlash(std::string const& str) { std::string ret = str; for(std::string::iterator it = ret.begin(); it != ret.end(); ++it) if(*it == '\\') *it = '/'; return ret; } std::string toYen(std::string const& str) { std::string ret = str; for(std::string::iterator it = ret.begin(); it != ret.end(); ++it) if(*it == '/') *it = '\\'; return ret; } namespace { typedef boost::ptr_vector<RgssAdExtracter> ArchiveVector; ArchiveVector archives_; std::map< std::string, std::vector< uint8_t > > files_; char const* DEFAULT_ARCHIVE = "./Game.rgssad"; } // namespace bool exists(std::string const& filename) { std::string yen = toYen(filename); // in a "rgssad" the separator is YEN sign for(ArchiveVector::const_iterator it = archives_.begin(); it < archives_.end(); ++it) { if( it->exists(yen) ) return true; } /* * TODO: to absolute file path */ std::string slash = toSlash(filename); if( files_.find(slash) != files_.end() ) return true; std::ifstream file( slash.c_str() ); return file.is_open(); } std::vector< uint8_t > const& get(std::string const& name) { std::string slash = toSlash(name); // most filsystem uses slash as a separator assert( exists(slash) ); // the file mush exist std::string yen = toYen(name); // in a "rgssad" the separator is YEN sign for(ArchiveVector::iterator it = archives_.begin(); it < archives_.end(); ++it) { if( it->exists(yen) ) return it->get(yen); } if( files_.find(slash) == files_.end() ) { std::FILE* fp = std::fopen( slash.c_str(), "rb" ); assert(fp); int res; res = std::fseek(fp, 0, SEEK_END); assert(res == 0); unsigned int size = ftell(fp); res = std::fseek(fp, 0, SEEK_SET); assert(res == 0); files_[slash] = std::vector< uint8_t >(size); size_t ret = std::fread( &(files_[slash][0]), sizeof(uint8_t), size, fp ); assert(ret == size); } return files_.find(slash)->second; } void init() { if( exists(DEFAULT_ARCHIVE) ) { archives_.push_back( std::auto_ptr<RgssAdExtracter>( new RgssAdExtracter(DEFAULT_ARCHIVE) ) ); } } std::vector<std::string> getRgssAdList() { std::vector< std::string > ret; for(ArchiveVector::iterator it = archives_.begin(); it < archives_.end(); ++it) { for(std::multimap< std::string, RgssAdExtracter::Entry >::const_iterator it2 = it->entry().begin(); it2 != it->entry().end(); ++it2) { ret.push_back(it2->first); } } return ret; } } // namespace FileIO
[ [ [ 1, 88 ] ] ]
9195228247289d16168c875e35ee5b151c2c7425
dab945db8541c30011771caf8ddb63ec8c683618
/templates/FrameAppCCProject/app_classname.cpp
a2bbc7caba667182b4d871ed27334b0eb5f488ae
[]
no_license
romanm11/bada-SDK-1.0.0-com.osp.ide
feb25cd9727e5f746cf618c752f933ca4a4ab61c
cd051d031310457a90eb558212b6c93b62b4dbf0
refs/heads/master
2020-04-06T04:20:24.837952
2010-10-27T18:46:27
2010-10-27T18:46:27
1,132,307
0
0
null
null
null
null
UTF-8
C++
false
false
2,792
cpp
/** * Name : $(baseName) * Version : $(version) * Vendor : $(vendor) * Description : $(description) */ #include "$(baseName).h" using namespace Osp::App; using namespace Osp::Base; using namespace Osp::System; using namespace Osp::Graphics; $(baseName)::$(baseName)() { } $(baseName)::~$(baseName)() { } Application* $(baseName)::CreateInstance(void) { // Create the instance through the constructor. return new $(baseName)(); } bool $(baseName)::OnAppInitializing(AppRegistry& appRegistry) { // TODO: // Initialize UI resources and application specific data. // The application's permanent data and context can be obtained from the appRegistry. // // If this method is successful, return true; otherwise, return false. // If this method returns false, the application will be terminated. // Uncomment the following statement to listen to the screen on/off events. //PowerManager::SetScreenEventListener(*this); return true; } bool $(baseName)::OnAppTerminating(AppRegistry& appRegistry, bool forcedTermination) { // TODO: // Deallocate resources allocated by this application for termination. // The application's permanent data and context can be saved via appRegistry. return true; } void $(baseName)::OnForeground(void) { // TODO: // Start or resume drawing when the application is moved to the foreground. Canvas* pCanvas = GetAppFrame()->GetCanvasN(); Font font; font.Construct(FONT_STYLE_PLAIN | FONT_STYLE_BOLD, 50); pCanvas->SetFont(font); pCanvas->DrawText(Point(30, 30), GetAppName()); pCanvas->Show(); delete pCanvas; } void $(baseName)::OnBackground(void) { // TODO: // Stop drawing when the application is moved to the background. } void $(baseName)::OnLowMemory(void) { // TODO: // Free unused resources or close the application. } void $(baseName)::OnBatteryLevelChanged(BatteryLevel batteryLevel) { // TODO: // Handle any changes in battery level here. // Stop using multimedia features(camera, mp3 etc.) if the battery level is CRITICAL. } void $(baseName)::OnScreenOn (void) { // TODO: // Get the released resources or resume the operations that were paused or stopped in OnScreenOff(). } void $(baseName)::OnScreenOff (void) { // TODO: // Unless there is a strong reason to do otherwise, release resources (such as 3D, media, and sensors) to allow the device to enter the sleep mode to save the battery. // Invoking a lengthy asynchronous method within this listener method can be risky, because it is not guaranteed to invoke a callback before the device enters the sleep mode. // Similarly, do not perform lengthy operations in this listener method. Any operation must be a quick one. }
[ "rom@garay.(none)" ]
[ [ [ 1, 107 ] ] ]
13bbd0efba4e6fd7bde63b44e9f6e782f7548eef
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/framework/movie/movieplayer2.cpp
ca38551aac05bcedbb0cd382630cd419320475c7
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
5,403
cpp
//#define LOCAL_PROFILE #include"movieplayer.h" #include"../../auxiliary/mathematics.h" #include"../../auxiliary/debug/warning.h" #include"../../auxiliary/debug/profile.h" #include"../../auxiliary/debug/assert.h" #include"core/xiph/oggdecodermanagersingle.h" #include"core/xiph/oggfile.h" #include"core/storagereadermultithread.h" namespace Maid { // ここの実装はデコードスレッドが使う関数を書いておきます // ゲーム側が使う関数は 1.cpp を参照 unt MoviePlayer::ThreadFunction( volatile ThreadController::BRIGEDATA& brige ) { while( true ) { if( brige.IsExit ) { break; } switch( m_State ) { case STATE_INITIALIZING: { Init(brige); }break; case STATE_SEEKING: { Seek(brige); }break; case STATE_WORKING: { Work(brige); }break; case STATE_END: { ThreadController::Sleep(5); }break; } } m_State = STATE_EMPTY; return 0; } void MoviePlayer::Init(volatile ThreadController::BRIGEDATA& state) { { Movie::SPSTORAGEREADER pSingle( new Movie::Xiph::OggFile(m_FileName) ); m_pStorage.reset( new Movie::StorageReaderMultiThread(pSingle, 50) ); m_pManager.reset( new Movie::Xiph::OggDecoderManagerSingle() ); } m_pStorage->Initialize(); m_pManager->Initialize(); while( true ) { if( state.IsExit ) { break; } ThreadController::Sleep(1); if( m_pStorage->IsEnd() ) { break; } if( m_pManager->Setuped() ) { break; } Movie::SPSTORAGESAMPLE pSample; m_pStorage->Read( pSample ); if( pSample.get()==NULL ) { continue; } m_pManager->AddSource( pSample ); } { { Movie::SPSAMPLEFORMAT pFormat; m_pManager->GetFormat( DECODERID_FRAME1, pFormat ); if( pFormat.get()!=NULL ) { const Movie::SampleFormatFrame& fmt = *boost::shared_static_cast<Movie::SampleFormatFrame>(pFormat); m_FileInfo.IsImage = true; m_FileInfo.Image.EncodedSize = fmt.EncodedSize; m_FileInfo.Image.DisplaySize = fmt.DisplaySize; m_FileInfo.Image.DisplayOffset = fmt.DisplayOffset; m_FileInfo.Image.FpsNumerator = fmt.FpsNumerator; m_FileInfo.Image.FpsDenominator = fmt.FpsDenominator; m_FileInfo.Image.AspectNumerator= fmt.AspectNumerator; m_FileInfo.Image.AspectDenominator = fmt.AspectDenominator; m_FileInfo.Image.PixelFormat = (FILEINFO::FRAME::PIXELFORMAT)fmt.PixelFormat; } } { Movie::SPSAMPLEFORMAT pFormat; m_pManager->GetFormat( DECODERID_PCM1, pFormat ); if( pFormat.get()!=NULL ) { const Movie::SampleFormatPCM& fmt = *boost::shared_static_cast<Movie::SampleFormatPCM>(pFormat); m_FileInfo.IsPCM = true; m_FileInfo.Pcm.Format = fmt.Format; } } } // 初期化が終了したらシークへ m_State = STATE_SEEKING; } void MoviePlayer::Seek(volatile ThreadController::BRIGEDATA& state) { // 名前はシークですが、バッファリングも行う const double time = m_Timer.Get(); if( 0<time ) { m_pManager->BeginSkipMode( time ); } // サンプルが埋まるまで入れ続ける while( true ) { if( state.IsExit ) { break; } if( m_pStorage->IsEnd() ) { break; } if( m_pManager->IsSampleFull() ) { break; } Update(); } // デコード前が埋まるまで入れ続ける while( true ) { if( state.IsExit ) { break; } if( m_pStorage->IsEnd() ) { break; } if( m_pManager->IsSourceFull() ) { break; } Update(); } // ストレージが埋まるまで待つ while( true ) { if( state.IsExit ) { break; } if( m_pStorage->IsEnd() ) { break; } if( m_pStorage->IsCacheFull() ) { break; } ThreadController::Sleep(1); } m_State = STATE_WORKING; } void MoviePlayer::Work(volatile ThreadController::BRIGEDATA& state) { while( true ) { if( state.IsExit ) { break; } { // 再生が遅れていたら、スキップ const double now = m_Timer.Get(); const double dec = m_pManager->GetTime(); if( dec < now ) { m_pManager->BeginSkipMode( now ); } } if( m_pStorage->IsEnd() ) { if( m_pManager->IsDecodeEnd() ) { break; } ThreadController::Sleep(1); } Update(); } m_State = STATE_END; } void MoviePlayer::Update() { const bool IsSourceFull = m_pManager->IsSourceFull(); // サンプルがいっぱい? const bool IsSampleFull = m_pManager->IsSampleFull(); // キャッシュが全部いっぱい? ThreadController::Sleep(0); if( IsSourceFull && IsSampleFull ) { // 待ち ThreadController::Sleep(1); }else { if( IsSourceFull ) { ThreadController::Sleep(1); }else { /*サンプル追加*/ Movie::SPSTORAGESAMPLE pSample; m_pStorage->Read( pSample ); if( pSample.get()!=NULL ) { m_pManager->AddSource( pSample ); } } if( IsSampleFull ) { ThreadController::Sleep(1); }else { /*デコード*/ Movie::Xiph::OggDecoderManagerSingle& manage = static_cast<Movie::Xiph::OggDecoderManagerSingle&>(*m_pManager); manage.Update(); } } } }
[ "[email protected]", "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 12 ], [ 14, 212 ] ], [ [ 13, 13 ] ] ]
835ab137068d72e31f971ba5e6ebe9b4029f90d6
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/DOMWriterFilter.hpp
6bafaff4f5c01a3c1a5fc62b00183f65930ef772
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
5,830
hpp
#ifndef DOMWriterFilter_HEADER_GUARD_ #define DOMWriterFilter_HEADER_GUARD_ /* * Copyright 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMWriterFilter.hpp,v 1.10 2004/09/08 13:55:39 peiyongz Exp $ * $Log: DOMWriterFilter.hpp,v $ * Revision 1.10 2004/09/08 13:55:39 peiyongz * Apache License Version 2.0 * * Revision 1.9 2003/03/07 19:59:09 tng * [Bug 11692] Unimplement the hidden constructors and assignment operator to remove warnings from gcc. * * Revision 1.8 2002/11/04 15:09:25 tng * C++ Namespace Support. * * Revision 1.7 2002/08/22 15:04:57 tng * Remove unused parameter variables in inline functions. * * Revision 1.6 2002/06/06 20:53:07 tng * Documentation Fix: Update the API Documentation for DOM headers * * Revision 1.5 2002/06/04 14:24:04 peiyongz * Make DOMWriterFilter pure abstract class w/o implementing any method * and data * * Revision 1.4 2002/06/03 22:34:53 peiyongz * DOMWriterFilter: setter provided, and allows any SHOW setting * * Revision 1.3 2002/05/31 20:59:40 peiyongz * Add "introduced in DOM3" * * Revision 1.2 2002/05/30 16:25:33 tng * Fix doxygen warning message. * * Revision 1.1 2002/05/28 22:38:55 peiyongz * DOM3 Save Interface: DOMWriter/DOMWriterFilter * */ /** * * DOMWriterFilter.hpp: interface for the DOMWriterFilter class. * * DOMWriterFilter provide applications the ability to examine nodes * as they are being serialized. * * DOMWriterFilter lets the application decide what nodes should be * serialized or not. * * The DOMDocument, DOMDocumentType, DOMNotation, and DOMEntity nodes are not passed * to the filter. * * @since DOM Level 3 */ #include <xercesc/dom/DOMNodeFilter.hpp> XERCES_CPP_NAMESPACE_BEGIN class CDOM_EXPORT DOMWriterFilter : public DOMNodeFilter { protected: // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Hidden constructors */ //@{ DOMWriterFilter() {}; //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- /** @name Unimplemented constructors and operators */ //@{ DOMWriterFilter(const DOMWriterFilter &); DOMWriterFilter & operator = (const DOMWriterFilter &); //@} public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~DOMWriterFilter() {}; //@} // ----------------------------------------------------------------------- // Virtual DOMWriterFilter interface // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 3 */ //@{ /** * Interface from <code>DOMNodeFilter</code>, * to be implemented by implementation (derived class) */ virtual short acceptNode(const DOMNode* node) const = 0; /** * Tells the DOMWriter what types of nodes to show to the filter. * See <code>DOMNodeFilter</code> for definition of the constants. * The constant SHOW_ATTRIBUTE is meaningless here, attribute nodes will * never be passed to a DOMWriterFilter. * * <p><b>"Experimental - subject to change"</b></p> * * @return The constants of what types of nodes to show. * @see setWhatToShow * @since DOM Level 3 */ virtual unsigned long getWhatToShow() const =0; /** * Set what types of nodes are to be presented. * See <code>DOMNodeFilter</code> for definition of the constants. * * <p><b>"Experimental - subject to change"</b></p> * * @param toShow The constants of what types of nodes to show. * @see getWhatToShow * @since DOM Level 3 */ virtual void setWhatToShow(unsigned long toShow) =0; //@} private: // ----------------------------------------------------------------------- // Private data members // // fWhatToShow // // The whatToShow mask. // Tells the DOMWriter what types of nodes to show to the filter. // See NodeFilter for definition of the constants. // The constants // SHOW_ATTRIBUTE, // SHOW_DOCUMENT, // SHOW_DOCUMENT_TYPE, // SHOW_NOTATION, and // SHOW_DOCUMENT_FRAGMENT are meaningless here, // Entity nodes are not passed to the filter. // // Those nodes will never be passed to a DOMWriterFilter. // // Derived class shall add this data member: // // unsigned long fWhatToShow; // ----------------------------------------------------------------------- }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 179 ] ] ]
f6f3a636555f1b9d94d8fe5306f182de618bfc04
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/has_2arg_use_facet_fail.cpp
707c711d29032e36971a864b70b2a0f2b64a118c
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,213
cpp
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004, // by libs/config/tools/generate // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_HAS_TWO_ARG_USE_FACET // This file should not compile, if it does then // BOOST_HAS_TWO_ARG_USE_FACET may be defined. // see boost_has_2arg_use_facet.ipp for more details // Do not edit this file, it was generated automatically by // ../tools/generate from boost_has_2arg_use_facet.ipp on // Sun Jul 25 11:47:49 GMTDT 2004 // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifndef BOOST_HAS_TWO_ARG_USE_FACET #include "boost_has_2arg_use_facet.ipp" #else #error "this file should not compile" #endif int main( int, char *[] ) { return boost_has_two_arg_use_facet::test(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 39 ] ] ]
3ffe999c5498e8645f55e63aa5c87d48c6382c9d
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/serialization/test/test_demo_fast_archive.cpp
e4e85ee64893f4c215a726c6d6a957fbb9771536
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // test_demo_fast_binary_archive.cpp // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/test/test_tools.hpp> #define main test_main #include "../example/demo_fast_archive.cpp"
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 13 ] ] ]
26c749a83cd69ac974353483102899a348bffff5
fa318c29963c7a594c8de6f1b3f3369e154fad7e
/C++/TopCoder/SRM498DIV2/250.cpp
8bcb6de8e9602362b3f6b48ba31cdf0417f6fd50
[]
no_license
cnsuhao/xadillax-personal
1732c251828c549f57b675f36608f1e51f56b626
2a2394ac2ebc64bc349551b46225231e07a63ba2
refs/heads/master
2021-05-29T03:00:28.064794
2011-03-26T06:36:46
2011-03-26T06:36:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,826
cpp
/** * @brief AdditionGame * A problem of TopCoder. * * @author XadillaX */ #include <iostream> #include <cstdio> #include <string> #include <cmath> #include <list> #include <map> #include <string.h> #include <time.h> #include <cstdlib> #include <stack> #include <algorithm> #include <queue> #include <vector> using namespace std; #define INF 0x3f3f3f3f #define clr(x) memset((x), 0, sizeof(x)) #define inf(x) memset((x), 0x7f, sizeof(x)) #define MAX(a, b) (a > b ? a : b) #define MIN(a, b) (a < b ? a : b) const int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; class AdditionGame { public: int getMaximumPoints(int, int, int, int); int a, b, c; int calc() { int r = 0; if(a >= b && a >= c) { //cout << a << endl; r = a; a--; if(a < 0) a = 0; } else if(b >= a && b >= c) { r = b; b--; if(b < 0) b = 0; } else if(c >= a && c >= b) { r = c; c--; if(c < 0) c = 0; } return r; } }; int AdditionGame::getMaximumPoints(int A, int B, int C, int N) { int ans = 0; a = A, b = B, c = C; for(int i = 0; i < N; i++) { ans += calc(); } return ans; } // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof bool KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, int p3, bool hasAnswer, int p4) { cout << "Test " << testNum << ": [" << p0 << "," << p1 << "," << p2 << "," << p3; cout << "]" << endl; AdditionGame *obj; int answer; obj = new AdditionGame(); clock_t startTime = clock(); answer = obj->getMaximumPoints(p0, p1, p2, p3); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << p4 << endl; } cout << "Your answer:" << endl; cout << "\t" << answer << endl; if (hasAnswer) { res = answer == p4; } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; int p0; int p1; int p2; int p3; int p4; { // ----- test 0 ----- p0 = 3; p1 = 4; p2 = 5; p3 = 3; p4 = 13; all_right = KawigiEdit_RunTest(0, p0, p1, p2, p3, true, p4) && all_right; // ------------------ } { // ----- test 1 ----- p0 = 1; p1 = 1; p2 = 1; p3 = 8; p4 = 3; all_right = KawigiEdit_RunTest(1, p0, p1, p2, p3, true, p4) && all_right; // ------------------ } { // ----- test 2 ----- p0 = 3; p1 = 5; p2 = 48; p3 = 40; p4 = 1140; all_right = KawigiEdit_RunTest(2, p0, p1, p2, p3, true, p4) && all_right; // ------------------ } { // ----- test 3 ----- p0 = 36; p1 = 36; p2 = 36; p3 = 13; p4 = 446; all_right = KawigiEdit_RunTest(3, p0, p1, p2, p3, true, p4) && all_right; // ------------------ } { // ----- test 4 ----- p0 = 8; p1 = 2; p2 = 6; p3 = 13; p4 = 57; all_right = KawigiEdit_RunTest(4, p0, p1, p2, p3, true, p4) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
[ "[email protected]@633dafb3-0c77-9a0a-df9f-af5249c8126a" ]
[ [ [ 1, 187 ] ] ]
d1f4c01b76efed7efe702e04d8ad669c7eaf11f6
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/validators/DTD/DTDScanner.cpp
9386d6b57d2a60a2e5ed96b2190d7e71f6393624
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
131,429
cpp
/* * Copyright 1999-2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DTDScanner.cpp 191054 2005-06-17 02:56:35Z jberry $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/BinMemInputStream.hpp> #include <xercesc/util/FlagJanitor.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/UnexpectedEOFException.hpp> #include <xercesc/sax/InputSource.hpp> #include <xercesc/framework/XMLDocumentHandler.hpp> #include <xercesc/framework/XMLEntityHandler.hpp> #include <xercesc/framework/XMLValidator.hpp> #include <xercesc/internal/EndOfEntityException.hpp> #include <xercesc/internal/XMLScanner.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/common/MixedContentModel.hpp> #include <xercesc/validators/DTD/DTDEntityDecl.hpp> #include <xercesc/validators/DTD/DocTypeHandler.hpp> #include <xercesc/validators/DTD/DTDScanner.hpp> #include <xercesc/util/OutOfMemoryException.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local methods // --------------------------------------------------------------------------- // // This method automates the grunt work of looking at a char and see if its // a repetition suffix. If so, it creates a new correct rep node and wraps // the pass node in it. Otherwise, it returns the previous node. // static ContentSpecNode* makeRepNode(const XMLCh testCh, ContentSpecNode* const prevNode, MemoryManager* const manager) { if (testCh == chQuestion) { return new (manager) ContentSpecNode ( ContentSpecNode::ZeroOrOne , prevNode , 0 , true , true , manager ); } else if (testCh == chPlus) { return new (manager) ContentSpecNode ( ContentSpecNode::OneOrMore , prevNode , 0 , true , true , manager ); } else if (testCh == chAsterisk) { return new (manager) ContentSpecNode ( ContentSpecNode::ZeroOrMore , prevNode , 0 , true , true , manager ); } // Just return the incoming node return prevNode; } // --------------------------------------------------------------------------- // DTDValidator: Constructors and Destructor // --------------------------------------------------------------------------- DTDScanner::DTDScanner( DTDGrammar* dtdGrammar , DocTypeHandler* const docTypeHandler , MemoryManager* const grammarPoolMemoryManager , MemoryManager* const manager) : fMemoryManager(manager) , fGrammarPoolMemoryManager(grammarPoolMemoryManager) , fDocTypeHandler(docTypeHandler) , fDumAttDef(0) , fDumElemDecl(0) , fDumEntityDecl(0) , fInternalSubset(false) , fNextAttrId(1) , fDTDGrammar(dtdGrammar) , fBufMgr(0) , fReaderMgr(0) , fScanner(0) , fPEntityDeclPool(0) , fEmptyNamespaceId(0) , fDocTypeReaderId(0) { fPEntityDeclPool = new (fMemoryManager) NameIdPool<DTDEntityDecl>(109, 128, fMemoryManager); } DTDScanner::~DTDScanner() { delete fDumAttDef; delete fDumElemDecl; delete fDumEntityDecl; delete fPEntityDeclPool; } // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- void DTDScanner::setScannerInfo(XMLScanner* const owningScanner , ReaderMgr* const readerMgr , XMLBufferMgr* const bufMgr) { // We don't own any of these, we just reference them fScanner = owningScanner; fReaderMgr = readerMgr; fBufMgr = bufMgr; if (fScanner->getDoNamespaces()) fEmptyNamespaceId = fScanner->getEmptyNamespaceId(); else fEmptyNamespaceId = 0; fDocTypeReaderId = fReaderMgr->getCurrentReaderNum(); } // --------------------------------------------------------------------------- // DTDScanner: Private scanning methods // --------------------------------------------------------------------------- bool DTDScanner::checkForPERef( const bool inLiteral , const bool inMarkup) { bool gotSpace = false; // // See if we have any spaces up front. If so, then skip them and set // the gotSpaces flag. // if (fReaderMgr->skippedSpace()) { fReaderMgr->skipPastSpaces(); gotSpace = true; } // If the next char is a percent, then expand the PERef if (!fReaderMgr->skippedChar(chPercent)) return gotSpace; while (true) { if (!expandPERef(false, inLiteral, inMarkup, false)) fScanner->emitError(XMLErrs::ExpectedEntityRefName); // And skip any more spaces in the expanded value if (fReaderMgr->skippedSpace()) { fReaderMgr->skipPastSpaces(); gotSpace = true; } if (!fReaderMgr->skippedChar(chPercent)) break; } return gotSpace; } bool DTDScanner::expandPERef( const bool scanExternal , const bool inLiteral , const bool inMarkup , const bool throwEndOfExt) { fScanner->setHasNoDTD(false); XMLBufBid bbName(fBufMgr); // // If we are in the internal subset and in markup, then this is // an error but we go ahead and do it anyway. // if (fInternalSubset && inMarkup) fScanner->emitError(XMLErrs::PERefInMarkupInIntSubset); if (!fReaderMgr->getName(bbName.getBuffer())) { fScanner->emitError(XMLErrs::ExpectedPEName); // Skip the semicolon if that's what we ended up on fReaderMgr->skippedChar(chSemiColon); return false; } // If no terminating semicolon, emit an error but try to keep going if (!fReaderMgr->skippedChar(chSemiColon)) fScanner->emitError(XMLErrs::UnterminatedEntityRef, bbName.getRawBuffer()); // // Look it up in the PE decl pool and see if it exists. If not, just // emit an error and continue. // XMLEntityDecl* decl = fPEntityDeclPool->getByKey(bbName.getRawBuffer()); if (!decl) { // XML 1.0 Section 4.1 if (fScanner->getStandalone()) { // no need to check fScanner->fHasNoDTD which is for sure false // since we are in expandPERef already fScanner->emitError(XMLErrs::EntityNotFound, bbName.getRawBuffer()); } else { if (fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::VC_EntityNotFound, bbName.getRawBuffer()); } return false; } // // XML 1.0 Section 2.9 // If we are a standalone document, then it has to have been declared // in the internal subset. Keep going though. // if (fScanner->getDoValidation() && fScanner->getStandalone() && !decl->getDeclaredInIntSubset()) fScanner->getValidator()->emitError(XMLValid::VC_IllegalRefInStandalone, bbName.getRawBuffer()); // // Okee dokee, we found it. So create either a memory stream with // the entity value contents, or a file stream if its an external // entity. // if (decl->isExternal()) { // And now create a reader to read this entity InputSource* srcUsed; XMLReader* reader = fReaderMgr->createReader ( decl->getBaseURI() , decl->getSystemId() , decl->getPublicId() , false , inLiteral ? XMLReader::RefFrom_Literal : XMLReader::RefFrom_NonLiteral , XMLReader::Type_PE , XMLReader::Source_External , srcUsed , fScanner->getCalculateSrcOfs() , fScanner->getDisableDefaultEntityResolution() ); // Put a janitor on the source so its cleaned up on exit Janitor<InputSource> janSrc(srcUsed); // If the creation failed then throw an exception if (!reader) ThrowXMLwithMemMgr1(RuntimeException, XMLExcepts::Gen_CouldNotOpenExtEntity, srcUsed ? srcUsed->getSystemId() : decl->getSystemId(), fMemoryManager); // Set the 'throw at end' flag, to the one we were given reader->setThrowAtEnd(throwEndOfExt); // // Push the reader. If its a recursive expansion, then emit an error // and return an failure. // if (!fReaderMgr->pushReader(reader, decl)) { fScanner->emitError(XMLErrs::RecursiveEntity, decl->getName()); return false; } // // If the caller wants us to scan the external entity, then lets // do that now. // if (scanExternal) { XMLEntityHandler* entHandler = fScanner->getEntityHandler(); // If we have an entity handler, tell it we are starting this entity if (entHandler) entHandler->startInputSource(*srcUsed); // // Scan the external entity now. The parameter tells it that // it is not in an include section. Get the current reader // level so we can catch partial markup errors and be sure // to get back to here if we get an exception out of the // ext subset scan. // const unsigned int readerNum = fReaderMgr->getCurrentReaderNum(); try { scanExtSubsetDecl(false, false); } catch(const OutOfMemoryException&) { throw; } catch(...) { // Pop the reader back to the original level fReaderMgr->cleanStackBackTo(readerNum); // End the input source, even though its not happy if (entHandler) entHandler->endInputSource(*srcUsed); throw; } // If we have an entity handler, tell it we are ending this entity if (entHandler) entHandler->endInputSource(*srcUsed); } else { // If it starts with the XML string, then parse a text decl if (fScanner->checkXMLDecl(true)) scanTextDecl(); } } else { // Create a reader over a memory stream over the entity value XMLReader* valueReader = fReaderMgr->createIntEntReader ( decl->getName() , inLiteral ? XMLReader::RefFrom_Literal : XMLReader::RefFrom_NonLiteral , XMLReader::Type_PE , decl->getValue() , decl->getValueLen() , false ); // // Trt to push the entity reader onto the reader manager stack, // where it will become the subsequent input. If it fails, that // means the entity is recursive, so issue an error. The reader // will have just been discarded, but we just keep going. // if (!fReaderMgr->pushReader(valueReader, decl)) fScanner->emitError(XMLErrs::RecursiveEntity, decl->getName()); } return true; } bool DTDScanner::getQuotedString(XMLBuffer& toFill) { // Reset the target buffer toFill.reset(); // Get the next char which must be a single or double quote XMLCh quoteCh; if (!fReaderMgr->skipIfQuote(quoteCh)) return false; while (true) { // Get another char const XMLCh nextCh = fReaderMgr->getNextChar(); // See if it matches the starting quote char if (nextCh == quoteCh) break; // // We should never get either an end of file null char here. If we // do, just fail. It will be handled more gracefully in the higher // level code that called us. // if (!nextCh) return false; // Else add it to the buffer toFill.append(nextCh); } return true; } XMLAttDef* DTDScanner::scanAttDef(DTDElementDecl& parentElem, XMLBuffer& bufToUse) { // Check for PE ref or optional whitespace checkForPERef(false, true); // Get the name of the attribute if (!fReaderMgr->getName(bufToUse)) { fScanner->emitError(XMLErrs::ExpectedAttrName); return 0; } // // Look up this attribute in the parent element's attribute list. If // it already exists, then use the dummy. // DTDAttDef* decl = parentElem.getAttDef(bufToUse.getRawBuffer()); if (decl) { // It already exists, so put out a warning fScanner->emitError ( XMLErrs::AttListAlreadyExists , bufToUse.getRawBuffer() , parentElem.getFullName() ); // Use the dummy decl to parse into and set its name to the name we got if (!fDumAttDef) { fDumAttDef = new (fMemoryManager) DTDAttDef(fMemoryManager); fDumAttDef->setId(fNextAttrId++); } fDumAttDef->setName(bufToUse.getRawBuffer()); decl = fDumAttDef; } else { // // It does not already exist so create a new one, give it the next // available unique id, and add it // decl = new (fGrammarPoolMemoryManager) DTDAttDef ( bufToUse.getRawBuffer() , XMLAttDef::CData , XMLAttDef::Implied , fGrammarPoolMemoryManager ); decl->setId(fNextAttrId++); decl->setExternalAttDeclaration(isReadingExternalEntity()); parentElem.addAttDef(decl); } // Set a flag to indicate whether we are doing a dummy parse const bool isIgnored = (decl == fDumAttDef); // Space is required here, so check for PE ref, and require space if (!checkForPERef(false, true)) fScanner->emitError(XMLErrs::ExpectedWhitespace); // // Next has to be one of the attribute type strings. This tells us what // is to follow. // if (fReaderMgr->skippedString(XMLUni::fgCDATAString)) { decl->setType(XMLAttDef::CData); } else if (fReaderMgr->skippedString(XMLUni::fgIDString)) { if (!fReaderMgr->skippedString(XMLUni::fgRefString)) decl->setType(XMLAttDef::ID); else if (!fReaderMgr->skippedChar(chLatin_S)) decl->setType(XMLAttDef::IDRef); else decl->setType(XMLAttDef::IDRefs); } else if (fReaderMgr->skippedString(XMLUni::fgEntitString)) { if (fReaderMgr->skippedChar(chLatin_Y)) { decl->setType(XMLAttDef::Entity); } else if (fReaderMgr->skippedString(XMLUni::fgIESString)) { decl->setType(XMLAttDef::Entities); } else { fScanner->emitError ( XMLErrs::ExpectedAttributeType , decl->getFullName() , parentElem.getFullName() ); return 0; } } else if (fReaderMgr->skippedString(XMLUni::fgNmTokenString)) { if (fReaderMgr->skippedChar(chLatin_S)) decl->setType(XMLAttDef::NmTokens); else decl->setType(XMLAttDef::NmToken); } else if (fReaderMgr->skippedString(XMLUni::fgNotationString)) { // Check for PE ref and require space if (!checkForPERef(false, true)) fScanner->emitError(XMLErrs::ExpectedWhitespace); decl->setType(XMLAttDef::Notation); if (!scanEnumeration(*decl, bufToUse, true)) return 0; // Set the value as the enumeration for this decl decl->setEnumeration(bufToUse.getRawBuffer()); } else if (fReaderMgr->skippedChar(chOpenParen)) { decl->setType(XMLAttDef::Enumeration); if (!scanEnumeration(*decl, bufToUse, false)) return 0; // Set the value as the enumeration for this decl decl->setEnumeration(bufToUse.getRawBuffer()); } else { fScanner->emitError ( XMLErrs::ExpectedAttributeType , decl->getFullName() , parentElem.getFullName() ); return 0; } // Space is required here, so check for PE ref, and require space if (!checkForPERef(false, true)) fScanner->emitError(XMLErrs::ExpectedWhitespace); // And then scan for the optional default value declaration scanDefaultDecl(*decl); // If validating, then do a couple of validation constraints if (fScanner->getDoValidation()) { if (decl->getType() == XMLAttDef::ID) { if ((decl->getDefaultType() != XMLAttDef::Implied) && (decl->getDefaultType() != XMLAttDef::Required)) { fScanner->getValidator()->emitError(XMLValid::BadIDAttrDefType, decl->getFullName()); } } // if attdef is xml:space, check correct enumeration (default|preserve) const XMLCh fgXMLSpace[] = { chLatin_x, chLatin_m, chLatin_l, chColon, chLatin_s, chLatin_p, chLatin_a, chLatin_c, chLatin_e, chNull }; if (XMLString::equals(decl->getFullName(),fgXMLSpace)) { const XMLCh fgPreserve[] = { chLatin_p, chLatin_r, chLatin_e, chLatin_s, chLatin_e, chLatin_r, chLatin_v, chLatin_e, chNull }; const XMLCh fgDefault[] = { chLatin_d, chLatin_e, chLatin_f, chLatin_a, chLatin_u, chLatin_l, chLatin_t, chNull }; bool ok = false; if (decl->getType() == XMLAttDef::Enumeration) { BaseRefVectorOf<XMLCh>* enumVector = XMLString::tokenizeString(decl->getEnumeration(), fMemoryManager); int size = enumVector->size(); ok = (size == 1 && (XMLString::equals(enumVector->elementAt(0), fgDefault) || XMLString::equals(enumVector->elementAt(0), fgPreserve))) || (size == 2 && (XMLString::equals(enumVector->elementAt(0), fgDefault) && XMLString::equals(enumVector->elementAt(1), fgPreserve))) || (size == 2 && (XMLString::equals(enumVector->elementAt(1), fgDefault) && XMLString::equals(enumVector->elementAt(0), fgPreserve))); delete enumVector; } if (!ok) fScanner->getValidator()->emitError(XMLValid::IllegalXMLSpace); } } // If we have a doc type handler, tell it about this attdef. if (fDocTypeHandler) fDocTypeHandler->attDef(parentElem, *decl, isIgnored); return decl; } void DTDScanner::scanAttListDecl() { // Space is required here, so check for a PE ref if (!checkForPERef(false, true)) { fScanner->emitError(XMLErrs::ExpectedWhitespace); fReaderMgr->skipPastChar(chCloseAngle); return; } // // Next should be the name of the element it belongs to, so get a buffer // and get the name into it. // XMLBufBid bbName(fBufMgr); if (!fReaderMgr->getName(bbName.getBuffer())) { fScanner->emitError(XMLErrs::ExpectedElementName); fReaderMgr->skipPastChar(chCloseAngle); return; } // // Find this element's declaration. If it has not been declared yet, // we will force one into the list, but not mark it as declared. // DTDElementDecl* elemDecl = (DTDElementDecl*) fDTDGrammar->getElemDecl(fEmptyNamespaceId, 0, bbName.getRawBuffer(), Grammar::TOP_LEVEL_SCOPE); if (!elemDecl) { // // Lets fault in a declaration and add it to the pool. We mark // it having been created because of an attlist. Later, if its // declared, this will be updated. // elemDecl = new (fGrammarPoolMemoryManager) DTDElementDecl ( bbName.getRawBuffer() , fEmptyNamespaceId , DTDElementDecl::Any , fGrammarPoolMemoryManager ); elemDecl->setCreateReason(XMLElementDecl::AttList); elemDecl->setExternalElemDeclaration(isReadingExternalEntity()); fDTDGrammar->putElemDecl((XMLElementDecl*) elemDecl); } // If we have a doc type handler, tell it the att list is starting if (fDocTypeHandler) fDocTypeHandler->startAttList(*elemDecl); // // Now we loop until we are done with all of the attributes in this // list. We need a buffer to use for local processing. // XMLBufBid bbTmp(fBufMgr); XMLBuffer& tmpBuf = bbTmp.getBuffer(); bool seenAnId = false; while (true) { // Get the next char out and see what it tells us to do const XMLCh nextCh = fReaderMgr->peekNextChar(); // Watch for EOF if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); if (nextCh == chCloseAngle) { // We are done with this attribute list fReaderMgr->getNextChar(); break; } else if (fReaderMgr->getCurrentReader()->isWhitespace(nextCh)) { // // If advanced callbacks are enabled and we have a doc // type handler, then gather up the white space and call // back on the doctype handler. Otherwise, just skip // whitespace. // if (fDocTypeHandler) { fReaderMgr->getSpaces(tmpBuf); fDocTypeHandler->doctypeWhitespace ( tmpBuf.getRawBuffer() , tmpBuf.getLen() ); } else { fReaderMgr->skipPastSpaces(); } } else if (nextCh == chPercent) { // Eat the percent and expand the ref fReaderMgr->getNextChar(); expandPERef(false, false, true); } else { // // It must be an attribute name, so scan it. We let // it use our local buffer for its name scanning. // XMLAttDef* attDef = scanAttDef(*elemDecl, tmpBuf); if (!attDef) { fReaderMgr->skipPastChar(chCloseAngle); break; } // // If we are validating and its an ID type, then we have to // make sure that we have not seen an id attribute yet. Set // the flag to say that we've seen one now also. // if (fScanner->getDoValidation()) { if (attDef->getType() == XMLAttDef::ID) { if (seenAnId) fScanner->getValidator()->emitError(XMLValid::MultipleIdAttrs, elemDecl->getFullName()); seenAnId = true; } } } } // If we have a doc type handler, tell it the att list is ending if (fDocTypeHandler) fDocTypeHandler->endAttList(*elemDecl); } // // This method is called to scan the value of an attribute in content. This // involves some normalization and replacement of general entity and // character references. // // End of entity's must be dealt with here. During DTD scan, they can come // from external entities. During content, they can come from any entity. // We just eat the end of entity and continue with our scan until we come // to the closing quote. If an unterminated value causes us to go through // subsequent entities, that will cause errors back in the calling code, // but there's little we can do about it here. // bool DTDScanner::scanAttValue(const XMLCh* const attrName , XMLBuffer& toFill , const XMLAttDef::AttTypes type) { enum States { InWhitespace , InContent }; // Reset the target buffer toFill.reset(); // Get the next char which must be a single or double quote XMLCh quoteCh; if (!fReaderMgr->skipIfQuote(quoteCh)) return false; // // We have to get the current reader because we have to ignore closing // quotes until we hit the same reader again. // const unsigned int curReader = fReaderMgr->getCurrentReaderNum(); // // Loop until we get the attribute value. Note that we use a double // loop here to avoid the setup/teardown overhead of the exception // handler on every round. // XMLCh nextCh; XMLCh secondCh = 0; States curState = InContent; bool firstNonWS = false; bool gotLeadingSurrogate = false; bool escaped; while (true) { try { while(true) { nextCh = fReaderMgr->getNextChar(); if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); // Check for our ending quote in the same entity if (nextCh == quoteCh) { if (curReader == fReaderMgr->getCurrentReaderNum()) return true; // Watch for spillover into a previous entity if (curReader > fReaderMgr->getCurrentReaderNum()) { fScanner->emitError(XMLErrs::PartialMarkupInEntity); return false; } } // // Check for an entity ref now, before we let it affect our // whitespace normalization logic below. We ignore the empty flag // in this one. // escaped = false; if (nextCh == chAmpersand) { if (scanEntityRef(nextCh, secondCh, escaped) != EntityExp_Returned) { gotLeadingSurrogate = false; continue; } } else if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { // Check for correct surrogate pairs if (gotLeadingSurrogate) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { if (gotLeadingSurrogate) { if ((nextCh < 0xDC00) || (nextCh > 0xDFFF)) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr->getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); fScanner->emitError ( XMLErrs::InvalidCharacterInAttrValue , attrName , tmpBuf ); } gotLeadingSurrogate = false; } // // If its not escaped, then make sure its not a < character, which // is not allowed in attribute values. // if (!escaped && (nextCh == chOpenAngle)) fScanner->emitError(XMLErrs::BracketInAttrValue, attrName); // // If the attribute is a CDATA type we do simple replacement of // tabs and new lines with spaces, if the character is not escaped // by way of a char ref. // // Otherwise, we do the standard non-CDATA normalization of // compressing whitespace to single spaces and getting rid of // leading and trailing whitespace. // if (type == XMLAttDef::CData) { if (!escaped) { if ((nextCh == 0x09) || (nextCh == 0x0A) || (nextCh == 0x0D)) nextCh = chSpace; } } else { if (curState == InWhitespace) { if (!fReaderMgr->getCurrentReader()->isWhitespace(nextCh)) { if (firstNonWS) toFill.append(chSpace); curState = InContent; firstNonWS = true; } else { continue; } } else if (curState == InContent) { if (fReaderMgr->getCurrentReader()->isWhitespace(nextCh)) { curState = InWhitespace; continue; } firstNonWS = true; } } // Else add it to the buffer toFill.append(nextCh); if (secondCh) { toFill.append(secondCh); secondCh=0; } } } catch(const EndOfEntityException&) { // Just eat it and continue. gotLeadingSurrogate = false; escaped = false; } } return true; } bool DTDScanner::scanCharRef(XMLCh& first, XMLCh& second) { bool gotOne = false; unsigned int value = 0; // // Set the radix. Its supposed to be a lower case x if hex. But, in // order to recover well, we check for an upper and put out an error // for that. // unsigned int radix = 10; if (fReaderMgr->skippedChar(chLatin_x)) { radix = 16; } else if (fReaderMgr->skippedChar(chLatin_X)) { fScanner->emitError(XMLErrs::HexRadixMustBeLowerCase); radix = 16; } while (true) { const XMLCh nextCh = fReaderMgr->peekNextChar(); // Watch for EOF if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); // Break out on the terminating semicolon if (nextCh == chSemiColon) { fReaderMgr->getNextChar(); break; } // // Convert this char to a binary value, or bail out if its not // one. // unsigned int nextVal; if ((nextCh >= chDigit_0) && (nextCh <= chDigit_9)) nextVal = (unsigned int)(nextCh - chDigit_0); else if ((nextCh >= chLatin_A) && (nextCh <= chLatin_F)) nextVal= (unsigned int)(10 + (nextCh - chLatin_A)); else if ((nextCh >= chLatin_a) && (nextCh <= chLatin_f)) nextVal = (unsigned int)(10 + (nextCh - chLatin_a)); else { // // If we got at least a sigit, then do an unterminated ref // error. Else, do an expected a numerical ref thing. // if (gotOne) fScanner->emitError(XMLErrs::UnterminatedCharRef); else fScanner->emitError(XMLErrs::ExpectedNumericalCharRef); return false; } // // Make sure its valid for the radix. If not, then just eat the // digit and go on after issueing an error. Else, update the // running value with this new digit. // if (nextVal >= radix) { XMLCh tmpStr[2]; tmpStr[0] = nextCh; tmpStr[1] = chNull; fScanner->emitError(XMLErrs::BadDigitForRadix, tmpStr); } else { value = (value * radix) + nextVal; } // Indicate that we got at least one good digit gotOne = true; // Eat the char we just processed fReaderMgr->getNextChar(); } // Return the char (or chars) // And check if the character expanded is valid or not if (value >= 0x10000 && value <= 0x10FFFF) { value -= 0x10000; first = XMLCh((value >> 10) + 0xD800); second = XMLCh((value & 0x3FF) + 0xDC00); } else if (value <= 0xFFFD) { first = XMLCh(value); second = 0; if (!fReaderMgr->getCurrentReader()->isXMLChar(first) && !fReaderMgr->getCurrentReader()->isControlChar(first)) { // Character reference was not in the valid range fScanner->emitError(XMLErrs::InvalidCharacterRef); return false; } } else { // Character reference was not in the valid range fScanner->emitError(XMLErrs::InvalidCharacterRef); return false; } return true; } ContentSpecNode* DTDScanner::scanChildren(const DTDElementDecl& elemDecl, XMLBuffer& bufToUse) { // Check for a PE ref here, but don't require spaces checkForPERef(false, true); // We have to check entity nesting here unsigned int curReader; // // We know that the caller just saw an opening parenthesis, so we need // to parse until we hit the end of it, recursing for other nested // parentheses we see. // // We have to check for one up front, since it could be something like // (((a)*)) etc... // ContentSpecNode* curNode = 0; if (fReaderMgr->skippedChar(chOpenParen)) { curReader = fReaderMgr->getCurrentReaderNum(); // Lets call ourself and get back the resulting node curNode = scanChildren(elemDecl, bufToUse); // If that failed, no need to go further, return failure if (!curNode) return 0; if (curReader != fReaderMgr->getCurrentReaderNum() && fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::PartialMarkupInPE); } else { // Not a nested paren, so it must be a leaf node if (!fReaderMgr->getName(bufToUse)) { fScanner->emitError(XMLErrs::ExpectedElementName); return 0; } // // Create a leaf node for it. If we can find the element id for // this element, then use it. Else, we have to fault in an element // decl, marked as created because of being in a content model. // XMLElementDecl* decl = fDTDGrammar->getElemDecl(fEmptyNamespaceId, 0, bufToUse.getRawBuffer(), Grammar::TOP_LEVEL_SCOPE); if (!decl) { decl = new (fGrammarPoolMemoryManager) DTDElementDecl ( bufToUse.getRawBuffer() , fEmptyNamespaceId , DTDElementDecl::Any , fGrammarPoolMemoryManager ); decl->setCreateReason(XMLElementDecl::InContentModel); decl->setExternalElemDeclaration(isReadingExternalEntity()); fDTDGrammar->putElemDecl(decl); } curNode = new (fGrammarPoolMemoryManager) ContentSpecNode ( decl->getElementName() , fGrammarPoolMemoryManager ); // Check for a PE ref here, but don't require spaces const bool gotSpaces = checkForPERef(false, true); // Check for a repetition character after the leaf const XMLCh repCh = fReaderMgr->peekNextChar(); ContentSpecNode* tmpNode = makeRepNode(repCh, curNode, fGrammarPoolMemoryManager); if (tmpNode != curNode) { if (gotSpaces) { if (fScanner->emitErrorWillThrowException(XMLErrs::UnexpectedWhitespace)) { delete tmpNode; } fScanner->emitError(XMLErrs::UnexpectedWhitespace); } fReaderMgr->getNextChar(); curNode = tmpNode; } } // Check for a PE ref here, but don't require spaces checkForPERef(false, true); // // Ok, the next character tells us what kind of content this particular // model this particular parentesized section is. Its either a choice if // we see ',', a sequence if we see '|', or a single leaf node if we see // a closing paren. // const XMLCh opCh = fReaderMgr->peekNextChar(); if ((opCh != chComma) && (opCh != chPipe) && (opCh != chCloseParen)) { // Not a legal char, so delete our node and return failure delete curNode; fScanner->emitError(XMLErrs::ExpectedSeqChoiceLeaf); return 0; } // // Create the head node of the correct type. We need this to remember // the top of the local tree. If it was a single subexpr, then just // set the head node to the current node. For the others, we'll build // the tree off the second child as we move across. // ContentSpecNode* headNode = 0; ContentSpecNode::NodeTypes curType = ContentSpecNode::UnknownType; if (opCh == chComma) { curType = ContentSpecNode::Sequence; headNode = new (fGrammarPoolMemoryManager) ContentSpecNode ( curType , curNode , 0 , true , true , fGrammarPoolMemoryManager ); curNode = headNode; } else if (opCh == chPipe) { curType = ContentSpecNode::Choice; headNode = new (fGrammarPoolMemoryManager) ContentSpecNode ( curType , curNode , 0 , true , true , fGrammarPoolMemoryManager ); curNode = headNode; } else { headNode = curNode; fReaderMgr->getNextChar(); } // // If it was a sequence or choice, we just loop until we get to the // end of our section, adding each new leaf or sub expression to the // right child of the current node, and making that new node the current // node. // if ((opCh == chComma) || (opCh == chPipe)) { ContentSpecNode* lastNode = 0; while (true) { // // The next thing must either be another | or , character followed // by another leaf or subexpression, or a closing parenthesis, or a // PE ref. // if (fReaderMgr->lookingAtChar(chPercent)) { checkForPERef(false, true); } else if (fReaderMgr->skippedSpace()) { // Just skip whitespace fReaderMgr->skipPastSpaces(); } else if (fReaderMgr->skippedChar(chCloseParen)) { // // We've hit the end of this section, so break out. But, we // need to see if we left a partial sequence of choice node // without a second node. If so, we have to undo that and // put its left child into the right node of the previous // node. // if ((curNode->getType() == ContentSpecNode::Choice) || (curNode->getType() == ContentSpecNode::Sequence)) { if (!curNode->getSecond()) { ContentSpecNode* saveFirst = curNode->orphanFirst(); lastNode->setSecond(saveFirst); curNode = lastNode; } } break; } else if (fReaderMgr->skippedChar(opCh)) { // Check for a PE ref here, but don't require spaces checkForPERef(false, true); if (fReaderMgr->skippedChar(chOpenParen)) { curReader = fReaderMgr->getCurrentReaderNum(); // Recurse to handle this new guy ContentSpecNode* subNode; try { subNode = scanChildren(elemDecl, bufToUse); } catch (const XMLErrs::Codes) { delete headNode; throw; } // If it failed, we are done, clean up here and return failure if (!subNode) { delete headNode; return 0; } if (curReader != fReaderMgr->getCurrentReaderNum() && fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::PartialMarkupInPE); // Else patch it in and make it the new current ContentSpecNode* newCur = new (fGrammarPoolMemoryManager) ContentSpecNode ( curType , subNode , 0 , true , true , fGrammarPoolMemoryManager ); curNode->setSecond(newCur); lastNode = curNode; curNode = newCur; } else { // // Got to be a leaf node, so get a name. If we cannot get // one, then clean up and get outa here. // if (!fReaderMgr->getName(bufToUse)) { delete headNode; fScanner->emitError(XMLErrs::ExpectedElementName); return 0; } // // Create a leaf node for it. If we can find the element // id for this element, then use it. Else, we have to // fault in an element decl, marked as created because // of being in a content model. // XMLElementDecl* decl = fDTDGrammar->getElemDecl(fEmptyNamespaceId, 0, bufToUse.getRawBuffer(), Grammar::TOP_LEVEL_SCOPE); if (!decl) { decl = new (fGrammarPoolMemoryManager) DTDElementDecl ( bufToUse.getRawBuffer() , fEmptyNamespaceId , DTDElementDecl::Any , fGrammarPoolMemoryManager ); decl->setCreateReason(XMLElementDecl::InContentModel); decl->setExternalElemDeclaration(isReadingExternalEntity()); fDTDGrammar->putElemDecl(decl); } ContentSpecNode* tmpLeaf = new (fGrammarPoolMemoryManager) ContentSpecNode ( decl->getElementName() , fGrammarPoolMemoryManager ); // Check for a repetition character after the leaf const XMLCh repCh = fReaderMgr->peekNextChar(); ContentSpecNode* tmpLeaf2 = makeRepNode(repCh, tmpLeaf, fGrammarPoolMemoryManager); if (tmpLeaf != tmpLeaf2) fReaderMgr->getNextChar(); // // Create a new sequence or choice node, with the leaf // (or rep surrounding it) we just got as its first node. // Make the new node the second node of the current node, // and then make it the current node. // ContentSpecNode* newCur = new (fGrammarPoolMemoryManager) ContentSpecNode ( curType , tmpLeaf2 , 0 , true , true , fGrammarPoolMemoryManager ); curNode->setSecond(newCur); lastNode = curNode; curNode = newCur; } } else { // Cannot be valid delete headNode; // emitError may do a throw so need to clean-up first if (opCh == chComma) { fScanner->emitError(XMLErrs::ExpectedChoiceOrCloseParen); } else { fScanner->emitError ( XMLErrs::ExpectedSeqOrCloseParen , elemDecl.getFullName() ); } return 0; } } } // // We saw the terminating parenthesis so lets check for any repetition // character, and create a node for that, making the head node the child // of it. // XMLCh repCh = fReaderMgr->peekNextChar(); ContentSpecNode* retNode = makeRepNode(repCh, headNode, fGrammarPoolMemoryManager); if (retNode != headNode) fReaderMgr->getNextChar(); return retNode; } // // We get here after the '<!--' part of the comment. We scan past the // terminating '-->' It will calls the appropriate handler with the comment // text, if one is provided. A comment can be in either the document or // the DTD, so the fInDocument flag is used to know which handler to send // it to. // void DTDScanner::scanComment() { enum States { InText , OneDash , TwoDashes }; // Get a buffer for this XMLBufBid bbComment(fBufMgr); // // Get the comment text into a temp buffer. Be sure to use temp buffer // two here, since its to be used for stuff that is potentially longer // than just a name. // bool gotLeadingSurrogate = false; States curState = InText; while (true) { // Get the next character const XMLCh nextCh = fReaderMgr->getNextChar(); // Watch for an end of file if (!nextCh) { fScanner->emitError(XMLErrs::UnterminatedComment); ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); } // Check for correct surrogate pairs if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { if (gotLeadingSurrogate) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { if (gotLeadingSurrogate) { if ((nextCh < 0xDC00) || (nextCh > 0xDFFF)) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr->getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); fScanner->emitError(XMLErrs::InvalidCharacter, tmpBuf); } gotLeadingSurrogate = false; } if (curState == InText) { // If its a dash, go to OneDash state. Otherwise take as text if (nextCh == chDash) curState = OneDash; else bbComment.append(nextCh); } else if (curState == OneDash) { // // If its another dash, then we change to the two dashes states. // Otherwise, we have to put in the deficit dash and the new // character and go back to InText. // if (nextCh == chDash) { curState = TwoDashes; } else { bbComment.append(chDash); bbComment.append(nextCh); curState = InText; } } else if (curState == TwoDashes) { // The next character must be the closing bracket if (nextCh != chCloseAngle) { fScanner->emitError(XMLErrs::IllegalSequenceInComment); fReaderMgr->skipPastChar(chCloseAngle); return; } break; } } // If there is a doc type handler, then pass on the comment stuff if (fDocTypeHandler) fDocTypeHandler->doctypeComment(bbComment.getRawBuffer()); } bool DTDScanner::scanContentSpec(DTDElementDecl& toFill) { // // Check for for a couple of the predefined content type strings. If // its not one of these, its got to be a parenthesized reg ex type // expression. // if (fReaderMgr->skippedString(XMLUni::fgEmptyString)) { toFill.setModelType(DTDElementDecl::Empty); return true; } if (fReaderMgr->skippedString(XMLUni::fgAnyString)) { toFill.setModelType(DTDElementDecl::Any); return true; } // Its got to be a parenthesized regular expression if (!fReaderMgr->skippedChar(chOpenParen)) { fScanner->emitError ( XMLErrs::ExpectedContentSpecExpr , toFill.getFullName() ); return false; } // Get the current reader id, so we can test for partial markup const unsigned int curReader = fReaderMgr->getCurrentReaderNum(); // We could have a PE ref here, but don't require space checkForPERef(false, true); // // Now we look for a PCDATA string. If its PCDATA, then it must be a // MIXED model. Otherwise, it must be a regular list of children in // a regular expression perhaps. // bool status; if (fReaderMgr->skippedString(XMLUni::fgPCDATAString)) { // Set the model to mixed toFill.setModelType(DTDElementDecl::Mixed_Simple); status = scanMixed(toFill); // // If we are validating we have to check that there are no multiple // uses of any child elements. // if (fScanner->getDoValidation()) { if (((const MixedContentModel*)toFill.getContentModel())->hasDups()) fScanner->getValidator()->emitError(XMLValid::RepElemInMixed); } } else { // // We have to do a recursive scan of the content model. Create a // buffer for it to use, for efficiency. It returns the top ofthe // content spec node tree, which we set if successful. // toFill.setModelType(DTDElementDecl::Children); XMLBufBid bbTmp(fBufMgr); ContentSpecNode* resNode = scanChildren(toFill, bbTmp.getBuffer()); status = (resNode != 0); if (status) toFill.setContentSpec(resNode); } // Make sure we are on the same reader as where we started if (curReader != fReaderMgr->getCurrentReaderNum() && fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::PartialMarkupInPE); return status; } void DTDScanner::scanDefaultDecl(DTDAttDef& toFill) { if (fReaderMgr->skippedString(XMLUni::fgRequiredString)) { toFill.setDefaultType(XMLAttDef::Required); return; } if (fReaderMgr->skippedString(XMLUni::fgImpliedString)) { toFill.setDefaultType(XMLAttDef::Implied); return; } if (fReaderMgr->skippedString(XMLUni::fgFixedString)) { // // There must be space before the fixed value. If there is not, then // emit an error but keep going. // if (!fReaderMgr->skippedSpace()) fScanner->emitError(XMLErrs::ExpectedWhitespace); else fReaderMgr->skipPastSpaces(); toFill.setDefaultType(XMLAttDef::Fixed); } else { toFill.setDefaultType(XMLAttDef::Default); } // // If we got here, its fixed or default, so we need to get a value. // If we don't, then emit an error but just set the default value to // an empty string and try to keep going. // // Check for PE ref or optional whitespace checkForPERef(false, true); XMLBufBid bbValue(fBufMgr); if (!scanAttValue(toFill.getFullName(), bbValue.getBuffer(), toFill.getType())) fScanner->emitError(XMLErrs::ExpectedDefAttrDecl); toFill.setValue(bbValue.getRawBuffer()); } // // This is called after seeing '<!ELEMENT' which indicates that an element // markup is starting. This guy scans the rest of it and adds it to the // element decl pool if it has not already been declared. // void DTDScanner::scanElementDecl() { // // Space is legal (required actually) here so check for a PE ref. If // we don't get our whitespace, then issue and error, but try to keep // going. // if (!checkForPERef(false, true)) fScanner->emitError(XMLErrs::ExpectedWhitespace); // Get a buffer for the element name and scan in the name XMLBufBid bbName(fBufMgr); if (!fReaderMgr->getName(bbName.getBuffer())) { fScanner->emitError(XMLErrs::ExpectedElementName); fReaderMgr->skipPastChar(chCloseAngle); return; } // Look this guy up in the element decl pool DTDElementDecl* decl = (DTDElementDecl*) fDTDGrammar->getElemDecl(fEmptyNamespaceId, 0, bbName.getRawBuffer(), Grammar::TOP_LEVEL_SCOPE); // // If it does not exist, then we need to create it. If it does and // its marked as declared, then that's an error, but we still need to // scan over the content model so use the dummy declaration that the // parsing code can fill in. // if (decl) { if (decl->isDeclared()) { if (fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::ElementAlreadyExists, bbName.getRawBuffer()); if (!fDumElemDecl) fDumElemDecl = new (fMemoryManager) DTDElementDecl ( bbName.getRawBuffer() , fEmptyNamespaceId , DTDElementDecl::Any , fMemoryManager ); else fDumElemDecl->setElementName(bbName.getRawBuffer(),fEmptyNamespaceId); } } else { // // Create the new empty declaration to fill in and put it into // the decl pool. // decl = new (fGrammarPoolMemoryManager) DTDElementDecl ( bbName.getRawBuffer() , fEmptyNamespaceId , DTDElementDecl::Any , fGrammarPoolMemoryManager ); fDTDGrammar->putElemDecl(decl); } // Set a flag for whether we will ignore this one const bool isIgnored = (decl == fDumElemDecl); // Mark this one if being externally declared decl->setExternalElemDeclaration(isReadingExternalEntity()); // Mark this one as being declared decl->setCreateReason(XMLElementDecl::Declared); // Another check for a PE ref, with at least required whitespace if (!checkForPERef(false, true)) fScanner->emitError(XMLErrs::ExpectedWhitespace); // And now scan the content model for this guy. if (!scanContentSpec(*decl)) { fReaderMgr->skipPastChar(chCloseAngle); return; } // Another check for a PE ref, but we don't require whitespace here checkForPERef(false, true); // And we should have the ending angle bracket if (!fReaderMgr->skippedChar(chCloseAngle)) { fScanner->emitError(XMLErrs::UnterminatedElementDecl, bbName.getRawBuffer()); fReaderMgr->skipPastChar(chCloseAngle); } // // If we have a DTD handler tell it about the new element decl. We // tell it if its one that can be ignored, cause its an override of a // previously existing decl. If it is being ignored, only call back // if advanced callbacks are enabled. // if (fDocTypeHandler) fDocTypeHandler->elementDecl(*decl, isIgnored); } // // This method will process a general or parameter entity reference. The // entity name and entity text will be stored in the entity pool. The value // of the entity will be scanned for any other parameter entity or char // references which will be expanded. So the stored value can only have // general entity references when done. // void DTDScanner::scanEntityDecl() { // // Space is required here, but we cannot check for a PE Ref since // there could be a legal (no-ref) percent sign here. Since any // entity that ended here would be illegal, we just skip spaces // and then check for a percent. // if (!fReaderMgr->lookingAtSpace()) fScanner->emitError(XMLErrs::ExpectedWhitespace); else fReaderMgr->skipPastSpaces(); const bool isPEDecl = fReaderMgr->skippedChar(chPercent); // // If a PE decl, then eat the percent and check for spaces or a // PE ref on the other side of it. At least spaces are required. // if (isPEDecl) { if (!checkForPERef(false, true)) fScanner->emitError(XMLErrs::ExpectedWhitespace); } // // Now lets get a name, which should be the name of the entity. We // have to get a buffer for this. // XMLBufBid bbName(fBufMgr); if (!fReaderMgr->getName(bbName.getBuffer())) { fScanner->emitError(XMLErrs::ExpectedPEName); fReaderMgr->skipPastChar(chCloseAngle); return; } // If namespaces are enabled, then no colons allowed if (fScanner->getDoNamespaces()) { if (XMLString::indexOf(bbName.getRawBuffer(), chColon) != -1) fScanner->emitError(XMLErrs::ColonNotLegalWithNS); } // // See if this entity already exists. If so, then the existing one // takes precendence. So we use the local dummy decl to parse into // and just ignore the results. // DTDEntityDecl* entityDecl; if (isPEDecl) entityDecl = fPEntityDeclPool->getByKey(bbName.getRawBuffer()); else entityDecl = fDTDGrammar->getEntityDecl(bbName.getRawBuffer()); if (entityDecl) { if (!fDumEntityDecl) fDumEntityDecl = new (fMemoryManager) DTDEntityDecl(fMemoryManager); fDumEntityDecl->setName(bbName.getRawBuffer()); entityDecl = fDumEntityDecl; } else { // Its not in existence already, then create an entity decl for it entityDecl = new (fGrammarPoolMemoryManager) DTDEntityDecl(bbName.getRawBuffer(), false, fGrammarPoolMemoryManager); // // Set the declaration location. The parameter indicates whether its // declared in the content/internal subset, so we know whether or not // its in the external subset. // entityDecl->setDeclaredInIntSubset(fInternalSubset); // Add it to the appropriate entity decl pool if (isPEDecl) fPEntityDeclPool->put(entityDecl); else fDTDGrammar->putEntityDecl(entityDecl); } // Set a flag that indicates whether we are ignoring this one const bool isIgnored = (entityDecl == fDumEntityDecl); // Set the PE flag on it entityDecl->setIsParameter(isPEDecl); // // Space is legal (required actually) here so check for a PE ref. If // we don't get our whitespace, then issue an error, but try to keep // going. // if (!checkForPERef(false, true)) fScanner->emitError(XMLErrs::ExpectedWhitespace); // save the hasNoDTD status for Entity Constraint Checking bool hasNoDTD = fScanner->getHasNoDTD(); if (hasNoDTD && isPEDecl) fScanner->setHasNoDTD(false); // According to the type call the value scanning method if (!scanEntityDef(*entityDecl, isPEDecl)) { fReaderMgr->skipPastChar(chCloseAngle); fScanner->setHasNoDTD(true); fScanner->emitError(XMLErrs::ExpectedEntityValue); return; } if (hasNoDTD) fScanner->setHasNoDTD(true); // Space is legal (but not required) here so check for a PE ref checkForPERef(false, true); // And then we have to have the closing angle bracket if (!fReaderMgr->skippedChar(chCloseAngle)) { fScanner->emitError(XMLErrs::UnterminatedEntityDecl, entityDecl->getName()); fReaderMgr->skipPastChar(chCloseAngle); } // // If we have a doc type handler, then call it. But only call it for // ignored elements if advanced callbacks are enabled. // if (fDocTypeHandler) fDocTypeHandler->entityDecl(*entityDecl, isPEDecl, isIgnored); } // // This method will scan a general/character entity ref. It will either // expand a char ref and return the value directly, or it will expand // a general entity and a reader for it onto the reader stack. // // The return value indicates whether the value was returned directly or // pushed as a reader or it failed. // // The escaped flag tells the caller whether the returnd parameter resulted // from a character reference, which escapes the character in some cases. It // only makes any difference if the return indicates the value was returned // directly. // // NOTE: This is only called when scanning attribute values, so we always // expand general entities. // DTDScanner::EntityExpRes DTDScanner::scanEntityRef(XMLCh& firstCh, XMLCh& secondCh, bool& escaped) { // Assume no escape and no second char escaped = false; secondCh = 0; // We have to insure its all done in a single entity const unsigned int curReader = fReaderMgr->getCurrentReaderNum(); // // If the next char is a pound, then its a character reference and we // need to expand it always. // if (fReaderMgr->skippedChar(chPound)) { // // Its a character reference, so scan it and get back the numeric // value it represents. If it fails, just return immediately. // if (!scanCharRef(firstCh, secondCh)) return EntityExp_Failed; if (curReader != fReaderMgr->getCurrentReaderNum()) fScanner->emitError(XMLErrs::PartialMarkupInEntity); // Its now escaped since it was a char ref escaped = true; return EntityExp_Returned; } // Get the name of the general entity XMLBufBid bbName(fBufMgr); if (!fReaderMgr->getName(bbName.getBuffer())) { fScanner->emitError(XMLErrs::ExpectedEntityRefName); return EntityExp_Failed; } // // Next char must be a semi-colon. But if its not, just emit // an error and try to continue. // if (!fReaderMgr->skippedChar(chSemiColon)) fScanner->emitError(XMLErrs::UnterminatedEntityRef, bbName.getRawBuffer()); // Make sure it was all in one entity reader if (curReader != fReaderMgr->getCurrentReaderNum()) fScanner->emitError(XMLErrs::PartialMarkupInEntity); // Look it up the name the general entity pool XMLEntityDecl* decl = fDTDGrammar->getEntityDecl(bbName.getRawBuffer()); // If it does not exist, then obviously an error if (!decl) { // XML 1.0 Section 4.1 if (fScanner->getStandalone() || fScanner->getHasNoDTD()) { fScanner->emitError(XMLErrs::EntityNotFound, bbName.getRawBuffer()); } else { if (fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::VC_EntityNotFound, bbName.getRawBuffer()); } return EntityExp_Failed; } // // XML 1.0 Section 4.1 // If we are a standalone document, then it has to have been declared // in the internal subset. // if (fScanner->getStandalone() && !decl->getDeclaredInIntSubset()) fScanner->emitError(XMLErrs::IllegalRefInStandalone, bbName.getRawBuffer()); // // If its a special char reference, then its escaped and we can return // it directly. // if (decl->getIsSpecialChar()) { firstCh = decl->getValue()[0]; escaped = true; return EntityExp_Returned; } if (decl->isExternal()) { // If its unparsed, then its not valid here // XML 1.0 Section 4.4.4 the appearance of a reference to an unparsed entity is forbidden. if (decl->isUnparsed()) { fScanner->emitError(XMLErrs::NoUnparsedEntityRefs, bbName.getRawBuffer()); return EntityExp_Failed; } // We are in an attribute value, so not valid. // XML 1.0 Section 4.4.4 a reference to an external entity in an attribute value is forbidden. fScanner->emitError(XMLErrs::NoExtRefsInAttValue); // And now create a reader to read this entity InputSource* srcUsed; XMLReader* reader = fReaderMgr->createReader ( decl->getBaseURI() , decl->getSystemId() , decl->getPublicId() , false , XMLReader::RefFrom_NonLiteral , XMLReader::Type_General , XMLReader::Source_External , srcUsed , fScanner->getCalculateSrcOfs() , fScanner->getDisableDefaultEntityResolution() ); // Put a janitor on the source so it gets cleaned up on exit Janitor<InputSource> janSrc(srcUsed); // // If the creation failed then throw an exception // if (!reader) ThrowXMLwithMemMgr1(RuntimeException, XMLExcepts::Gen_CouldNotOpenExtEntity, srcUsed ? srcUsed->getSystemId() : decl->getSystemId(), fMemoryManager); // // Push the reader. If its a recursive expansion, then emit an error // and return an failure. // if (!fReaderMgr->pushReader(reader, decl)) { fScanner->emitError(XMLErrs::RecursiveEntity, decl->getName()); return EntityExp_Failed; } // If it starts with the XML string, then parse a text decl if (fScanner->checkXMLDecl(true)) scanTextDecl(); } else { // // Create a reader over a memory stream over the entity value // We force it to assume UTF-16 by passing in an encoding // string. This way it won't both trying to predecode the // first line, looking for an XML/TextDecl. // XMLReader* valueReader = fReaderMgr->createIntEntReader ( decl->getName() , XMLReader::RefFrom_NonLiteral , XMLReader::Type_General , decl->getValue() , decl->getValueLen() , false ); // // Trt to push the entity reader onto the reader manager stack, // where it will become the subsequent input. If it fails, that // means the entity is recursive, so issue an error. The reader // will have just been discarded, but we just keep going. // if (!fReaderMgr->pushReader(valueReader, decl)) fScanner->emitError(XMLErrs::RecursiveEntity, decl->getName()); } return EntityExp_Pushed; } // // This method will scan a quoted literal of an entity value. It has to // deal with replacement of PE references; however, since this is a DTD // scanner, all such entity literals are in entity decls and therefore // general entities are not expanded. // bool DTDScanner::scanEntityLiteral(XMLBuffer& toFill) { toFill.reset(); // Get the next char which must be a single or double quote XMLCh quoteCh; if (!fReaderMgr->skipIfQuote(quoteCh)) return false; // Get a buffer for pulling in entity names when we see GE refs XMLBufBid bbName(fBufMgr); XMLBuffer& nameBuf = bbName.getBuffer(); // Remember the current reader const unsigned int orgReader = fReaderMgr->getCurrentReaderNum(); // // Loop until we see the ending quote character, handling any references // in the process. // XMLCh nextCh; XMLCh secondCh = 0; bool gotLeadingSurrogate = false; while (true) { nextCh = fReaderMgr->getNextChar(); // // Watch specifically for EOF and issue a more meaningful error // if that occurs (since an unterminated quoted char can cause // this easily.) // if (!nextCh) { fScanner->emitError(XMLErrs::UnterminatedEntityLiteral); ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); } // // Break out on our terminating quote char when we are back in the // same reader. Otherwise, we might trigger on a nested quote char // in an expanded entity. // if ((nextCh == quoteCh) && (fReaderMgr->getCurrentReaderNum() == orgReader)) { break; } if (nextCh == chPercent) { // // Put the PE's value on the reader stack and then jump back // to the top to start processing it. The parameter indicates // that it should not scan the reference's content as an external // subset. // expandPERef(false, true, true); continue; } // // Ok, now that all the other special stuff is checked, we can // look for a general entity. In here, we cannot have a naked & // and will only expand numerical char refs or the intrinsic char // refs. Others will be left alone. // if (nextCh == chAmpersand) { // // Here, we only expand numeric char refs, but not any general // entities. However, the stupid XML spec requires that we check // and make sure it does refer to a general entity if its not // a char ref (i.e. no naked '&' chars.) // if (fReaderMgr->skippedChar(chPound)) { // If it failed, then just jump back to the top and try to pick up if (!scanCharRef(nextCh, secondCh)) { gotLeadingSurrogate = false; continue; } } else { if (!fReaderMgr->getName(nameBuf)) { fScanner->emitError(XMLErrs::ExpectedEntityRefName); } else { // // Since we are not expanding any of this, we have to // put the amp and name into the target buffer as data. // toFill.append(chAmpersand); toFill.append(nameBuf.getRawBuffer()); // Make sure we skipped a trailing semicolon if (!fReaderMgr->skippedChar(chSemiColon)) { fScanner->emitError ( XMLErrs::UnterminatedEntityRef , nameBuf.getRawBuffer() ); } // And make the new character the semicolon nextCh = chSemiColon; } // Either way here we reset the surrogate flag gotLeadingSurrogate = false; } } else if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { if (gotLeadingSurrogate) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { if (gotLeadingSurrogate) { if ((nextCh < 0xDC00) || (nextCh > 0xDFFF)) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); } else if (!fReaderMgr->getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); fScanner->emitError(XMLErrs::InvalidCharacter, tmpBuf); fReaderMgr->skipPastChar(quoteCh); return false; } gotLeadingSurrogate = false; } // Looks ok, so add it to the literal toFill.append(nextCh); if (secondCh) { toFill.append(secondCh); secondCh=0; } } // // If we got here and did not get back to the original reader level, // then we propogated some entity out of the literal, so issue an // error, but don't fail. // if (fReaderMgr->getCurrentReaderNum() != orgReader && fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::PartialMarkupInPE); return true; } // // This method is called after the entity name has been scanned, and any // PE referenced following the name is handled. The passed decl will be // filled in with the info scanned. // bool DTDScanner::scanEntityDef(DTDEntityDecl& decl, const bool isPEDecl) { // Its got to be an entity literal if (fReaderMgr->lookingAtChar(chSingleQuote) || fReaderMgr->lookingAtChar(chDoubleQuote)) { // Get a buffer for the literal XMLBufBid bbValue(fBufMgr); if (!scanEntityLiteral(bbValue.getBuffer())) return false; // Set it on the entity decl decl.setValue(bbValue.getRawBuffer()); return true; } // // Its got to be an external entity, so there must be an external id. // Get buffers for them and scan an external id into them. // XMLBufBid bbPubId(fBufMgr); XMLBufBid bbSysId(fBufMgr); if (!scanId(bbPubId.getBuffer(), bbSysId.getBuffer(), IDType_External)) return false; ReaderMgr::LastExtEntityInfo lastInfo; fReaderMgr->getLastExtEntityInfo(lastInfo); // Fill in the id fields of the decl with the info we got const XMLCh* publicId = bbPubId.getRawBuffer(); const XMLCh* systemId = bbSysId.getRawBuffer(); decl.setPublicId((publicId && *publicId) ? publicId : 0); decl.setSystemId((systemId && *systemId) ? systemId : 0); decl.setBaseURI((lastInfo.systemId && *lastInfo.systemId) ? lastInfo.systemId : 0); // If its a PE decl, we are done bool gotSpaces = checkForPERef(false, true); if (isPEDecl) { // // Check for a common error here. NDATA is not allowed for PEs // so check for the NDATA string. If found give a nice meaningful // error and continue parsing to eat the NDATA text. // if (gotSpaces) { if (fReaderMgr->skippedString(XMLUni::fgNDATAString)) fScanner->emitError(XMLErrs::NDATANotValidForPE); } else { return true; } } // If looking at close angle now, we are done if (fReaderMgr->lookingAtChar(chCloseAngle)) return true; // Else we had to have seem the whitespace if (!gotSpaces) fScanner->emitError(XMLErrs::ExpectedWhitespace); // We now have to see a notation data string if (!fReaderMgr->skippedString(XMLUni::fgNDATAString)) fScanner->emitError(XMLErrs::ExpectedNDATA); // Space is required here, but try to go on if not if (!checkForPERef(false, true)) fScanner->emitError(XMLErrs::ExpectedWhitespace); // Get a name XMLBufBid bbName(fBufMgr); if (!fReaderMgr->getName(bbName.getBuffer())) { fScanner->emitError(XMLErrs::ExpectedNotationName); return false; } // Set the decl's notation name decl.setNotationName(bbName.getRawBuffer()); return true; } // // This method is called after an attribute decl name or a notation decl has // been scanned and then an opening parenthesis was see, indicating the list // of values. It scans the enumeration values and creates a single string // which has a single space between each value. // // The terminating close paren ends this scan. // bool DTDScanner::scanEnumeration( const DTDAttDef& attDef , XMLBuffer& toFill , const bool notation) { // Reset the passed buffer toFill.reset(); // Check for PE ref but don't require space checkForPERef(false, true); // If this is a notation, we need an opening paren if (notation) { if (!fReaderMgr->skippedChar(chOpenParen)) fScanner->emitError(XMLErrs::ExpectedOpenParen); } // We need a local buffer to use as well XMLBufBid bbTmp(fBufMgr); while (true) { // Space is allowed here for either type so check for PE ref checkForPERef(false, true); // And then get either a name or a name token bool success; if (notation) success = fReaderMgr->getName(bbTmp.getBuffer()); else success = fReaderMgr->getNameToken(bbTmp.getBuffer()); if (!success) { fScanner->emitError ( XMLErrs::ExpectedEnumValue , attDef.getFullName() ); return false; } // Append this value to the target value toFill.append(bbTmp.getRawBuffer(), bbTmp.getLen()); // Space is allowed here for either type so check for PE ref checkForPERef(false, true); // Check for the terminating paren if (fReaderMgr->skippedChar(chCloseParen)) break; // And append a space separator toFill.append(chSpace); // Check for the pipe character separator if (!fReaderMgr->skippedChar(chPipe)) { fScanner->emitError(XMLErrs::ExpectedEnumSepOrParen); return false; } } return true; } bool DTDScanner::scanEq() { fReaderMgr->skipPastSpaces(); if (fReaderMgr->skippedChar(chEqual)) { fReaderMgr->skipPastSpaces(); return true; } return false; } // // This method is called when an external entity reference is seen in the // DTD or an external DTD subset is encountered, and their contents pushed // onto the reader stack. This method will scan that contents. // void DTDScanner::scanExtSubsetDecl(const bool inIncludeSect, const bool isDTD) { // Indicate we are in the external subset now FlagJanitor<bool> janContentFlag(&fInternalSubset, false); bool bAcceptDecl = !inIncludeSect; // Get a buffer for whitespace XMLBufBid bbSpace(fBufMgr); // // If we have a doc type handler and we are not being called recursively // to handle an include section, tell it the ext subset starts // if (fDocTypeHandler && !inIncludeSect) fDocTypeHandler->startExtSubset(); // // We have to play a trick here if the current entity we are parsing // is a PE. Because the spooling code will put out a whitespace before // and after an expanded PE if its being scanned outside the context of // a literal entity, this will confuse this external subset code. // // So, we see if that is what is happening and, if so, eat the single // space, a check for the <?xml string. If we find it, we parse that // markup right now and put the space back. // if (fReaderMgr->isScanningPERefOutOfLiteral()) { if (fReaderMgr->skippedSpace()) { if (fScanner->checkXMLDecl(true)) { scanTextDecl(); bAcceptDecl = false; // <TBD> Figure out how to do this // fReaderMgr->unGet(chSpace); } } } // Get the current reader number const unsigned int orgReader = fReaderMgr->getCurrentReaderNum(); // // Loop until we hit the end of the external subset entity. Note that // we use a double loop here in order to avoid the overhead of doing // the exception setup/teardown work on every loop. // bool inMarkup = false; bool inCharData = false; while (true) { bool bDoBreak=false; // workaround for Borland bug with 'break' in 'catch' try { while (true) { const XMLCh nextCh = fReaderMgr->peekNextChar(); if (nextCh == chOpenAngle) { // Get the reader we started this on // XML 1.0 P28a Well-formedness constraint: PE Between Declarations const unsigned int orgReader = fReaderMgr->getCurrentReaderNum(); bool wasInPE = (fReaderMgr->getCurrentReader()->getType() == XMLReader::Type_PE); // // Now scan the markup. Set the flag so that we will know that // we were in markup if an end of entity exception occurs. // fReaderMgr->getNextChar(); inMarkup = true; scanMarkupDecl(bAcceptDecl); inMarkup = false; // // And see if we got back to the same level. If not, then its // a partial markup error. // if (fReaderMgr->getCurrentReaderNum() != orgReader){ if (wasInPE) fScanner->emitError(XMLErrs::PEBetweenDecl); else if (fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::PartialMarkupInPE); } } else if (fReaderMgr->getCurrentReader()->isWhitespace(nextCh)) { // // If we have a doc type handler, and advanced callbacks are // enabled, then gather up whitespace and call back. Otherwise // just skip whitespaces. // if (fDocTypeHandler) { inCharData = true; fReaderMgr->getSpaces(bbSpace.getBuffer()); inCharData = false; fDocTypeHandler->doctypeWhitespace ( bbSpace.getRawBuffer() , bbSpace.getLen() ); } else { // // If we hit an end of entity in the middle of white // space, that's fine. We'll just come back in here // again on the next round and skip some more. // fReaderMgr->skipPastSpaces(); } } else if (nextCh == chPercent) { // // Expand (and scan if external) the reference value. Tell // it to throw an end of entity exception at the end of the // entity. // fReaderMgr->getNextChar(); expandPERef(true, false, false, true); } else if (inIncludeSect && (nextCh == chCloseSquare)) { // // Its the end of a conditional include section. So scan it and // decrement the include depth counter. // fReaderMgr->getNextChar(); if (!fReaderMgr->skippedChar(chCloseSquare)) { fScanner->emitError(XMLErrs::ExpectedEndOfConditional); fReaderMgr->skipPastChar(chCloseAngle); } else if (!fReaderMgr->skippedChar(chCloseAngle)) { fScanner->emitError(XMLErrs::ExpectedEndOfConditional); fReaderMgr->skipPastChar(chCloseAngle); } return; } else if (!nextCh) { return; // nothing left } else { fReaderMgr->getNextChar(); if (!fReaderMgr->getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); fScanner->emitError(XMLErrs::InvalidCharacter, tmpBuf); } else { fScanner->emitError(XMLErrs::InvalidDocumentStructure); } // Try to get realigned static const XMLCh toSkip[] = { chPercent, chCloseSquare, chOpenAngle, chNull }; fReaderMgr->skipUntilInOrWS(toSkip); } bAcceptDecl = false; } } catch(const EndOfEntityException& toCatch) { // // If the external entity ended while we were in markup, then that's // a partial markup error. // if (inMarkup) { fScanner->emitError(XMLErrs::PartialMarkupInEntity); inMarkup = false; } // If we were in char data, then send what we got if (inCharData) { // Send what we got, then rethrow if (fDocTypeHandler) { fDocTypeHandler->doctypeWhitespace ( bbSpace.getRawBuffer() , bbSpace.getLen() ); } inCharData = false; } // // If the entity that just ended was the entity that we started // on, then this is the end of the external subset. // if (orgReader == toCatch.getReaderNum()) bDoBreak=true; } if(bDoBreak) break; } // If we have a doc type handler, tell it the ext subset ends if (fDocTypeHandler && isDTD) fDocTypeHandler->endExtSubset(); } // // This method will scan for an id, either public or external. // // // [75] ExternalID ::= 'SYSTEM' S SystemLiteral // | 'PUBLIC' S PubidLiteral S SystemLiteral // [83] PublicID ::= 'PUBLIC' S PubidLiteral // bool DTDScanner::scanId( XMLBuffer& pubIdToFill , XMLBuffer& sysIdToFill , const IDTypes whatKind) { // Clean out both return buffers pubIdToFill.reset(); sysIdToFill.reset(); // // Check first for the system id first. If we find it, and system id // is one of the legal values, then lets try to scan it. // // 'SYSTEM' S SystemLiteral if (fReaderMgr->skippedString(XMLUni::fgSysIDString)) { // If they were looking for a public id, then we failed if (whatKind == IDType_Public) { fScanner->emitError(XMLErrs::ExpectedPublicId); return false; } // We must skip spaces if (!fReaderMgr->skipPastSpaces()) { fScanner->emitError(XMLErrs::ExpectedWhitespace); return false; } // Get the system literal value return scanSystemLiteral(sysIdToFill); } // Now scan for public id // 'PUBLIC' S PubidLiteral S SystemLiteral // or // 'PUBLIC' S PubidLiteral // If we don't have any public id string => Error if (!fReaderMgr->skippedString(XMLUni::fgPubIDString)) { fScanner->emitError(XMLErrs::ExpectedSystemOrPublicId); return false; } // // So following this we must have whitespace, a public literal, whitespace, // and a system literal. // if (!fReaderMgr->skipPastSpaces()) { fScanner->emitError(XMLErrs::ExpectedWhitespace); // // Just in case, if they just forgot the whitespace but the next char // is a single or double quote, then keep going. // const XMLCh chPeek = fReaderMgr->peekNextChar(); if ((chPeek != chDoubleQuote) && (chPeek != chSingleQuote)) return false; } if (!scanPublicLiteral(pubIdToFill)) return false; // If they wanted a public id, then this is all if (whatKind == IDType_Public) return true; // check if there is any space follows bool hasSpace = fReaderMgr->skipPastSpaces(); // // In order to recover best here we need to see if // the next thing is a quote or not // const XMLCh chPeek = fReaderMgr->peekNextChar(); const bool bIsQuote = ((chPeek == chDoubleQuote) || (chPeek == chSingleQuote)); if (!hasSpace) { if (whatKind == IDType_External) { // // If its an external Id, then we need to see the system id. // So, emit the error. But, if the next char is a quote, don't // give up since its probably going to work. The user just // missed the separating space. Otherwise, fail. // fScanner->emitError(XMLErrs::ExpectedWhitespace); if (!bIsQuote) return false; } else { // // We can legally return here. But, if the next char is a quote, // then that's probably not what was desired, since its probably // just that space was forgotten and there really is a system // id to follow. // // So treat it like missing whitespace if so and keep going. // Else, just return success. // if (bIsQuote) fScanner->emitError(XMLErrs::ExpectedWhitespace); else return true; } } if (bIsQuote) { // there is a quote coming, scan the system literal if (!scanSystemLiteral(sysIdToFill)) return false; } else { // no quote, if expecting exteral id, this is an error if (whatKind == IDType_External) fScanner->emitError(XMLErrs::ExpectedQuotedString); } return true; } // // This method will scan the contents of an ignored section. It assumes that // we already are in the body, i.e. we've seen <![IGNORE[ at this point. So // we have to just scan until we see a matching ]]> closing markup. // void DTDScanner::scanIgnoredSection() { // // Depth starts at one because we are already in one section and want // to parse until we hit its end. // unsigned long depth = 1; bool gotLeadingSurrogate = false; while (true) { const XMLCh nextCh = fReaderMgr->getNextChar(); if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); if (nextCh == chOpenAngle) { if (fReaderMgr->skippedChar(chBang) && fReaderMgr->skippedChar(chOpenSquare)) { depth++; } } else if (nextCh == chCloseSquare) { if (fReaderMgr->skippedChar(chCloseSquare)) { while (fReaderMgr->skippedChar(chCloseSquare)) { // Do nothing, just skip them } if (fReaderMgr->skippedChar(chCloseAngle)) { depth--; if (!depth) break; } } } // Deal with surrogate pairs else if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { // Its a leading surrogate. If we already got one, then // issue an error, else set leading flag to make sure that // we look for a trailing next time. if (gotLeadingSurrogate) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { // If its a trailing surrogate, make sure that we are // prepared for that. Else, its just a regular char so make // sure that we were not expected a trailing surrogate. if ((nextCh >= 0xDC00) && (nextCh <= 0xDFFF)) { // Its trailing, so make sure we were expecting it if (!gotLeadingSurrogate) fScanner->emitError(XMLErrs::Unexpected2ndSurrogateChar); } else { // Its just a char, so make sure we were not expecting a // trailing surrogate. if (gotLeadingSurrogate) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); // Its got to at least be a valid XML character else if (!fReaderMgr->getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); fScanner->emitError(XMLErrs::InvalidCharacter, tmpBuf); } } gotLeadingSurrogate = false; } } } // // This method scans the entire internal subset. All we can have here is // decl markup, and PE references. The expanded PE references must contain // whole markup, so we don't have to worry about their content at this // level. We just scan them, expand them, push them, and parse their content // right there, via the expandERef() method. // bool DTDScanner::scanInternalSubset() { // Indicate we are in the internal subset now FlagJanitor<bool> janContentFlag(&fInternalSubset, true); // If we have a doc type handler, tell it the internal subset starts if (fDocTypeHandler) fDocTypeHandler->startIntSubset(); // Get a buffer for whitespace XMLBufBid bbSpace(fBufMgr); bool noErrors = true; while (true) { const XMLCh nextCh = fReaderMgr->peekNextChar(); // // If we get an end of file marker, just unget it and return a // failure status. The caller will then see the end of file and // faill out correctly. // if (!nextCh) return false; // Watch for the end of internal subset marker if (nextCh == chCloseSquare) { fReaderMgr->getNextChar(); break; } if (nextCh == chPercent) { // // Expand (and scan if external) the reference value. Tell // it to set the reader to cause an end of entity exception // when this reader dies, which is what the scanExtSubset // method wants (who is called to scan this.) // fReaderMgr->getNextChar(); expandPERef(true, false, false, true); } else if (nextCh == chOpenAngle) { // Remember this reader before we start the scan, for checking // XML 1.0 P28a Well-formedness constraint: PE Between Declarations const unsigned int orgReader = fReaderMgr->getCurrentReaderNum(); bool wasInPE = (fReaderMgr->getCurrentReader()->getType() == XMLReader::Type_PE); // And scan this markup fReaderMgr->getNextChar(); scanMarkupDecl(false); // If we did not get back to entry level, then partial markup if (fReaderMgr->getCurrentReaderNum() != orgReader) { if (wasInPE) fScanner->emitError(XMLErrs::PEBetweenDecl); else if (fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::PartialMarkupInPE); } } else if (fReaderMgr->getCurrentReader()->isWhitespace(nextCh)) { // // IF we are doing advanced callbacks and have a doc type // handler, then get the whitespace and call the doc type // handler with it. Otherwise, just skip whitespace. // if (fDocTypeHandler) { fReaderMgr->getSpaces(bbSpace.getBuffer()); fDocTypeHandler->doctypeWhitespace ( bbSpace.getRawBuffer() , bbSpace.getLen() ); } else { fReaderMgr->skipPastSpaces(); } } else { // Not valid, so emit an error XMLCh tmpBuf[9]; XMLString::binToText ( fReaderMgr->getNextChar() , tmpBuf , 8 , 16 , fMemoryManager ); fScanner->emitError ( XMLErrs::InvalidCharacterInIntSubset , tmpBuf ); // // If an '>', then probably an abnormally terminated // internal subset so just return. // if (nextCh == chCloseAngle) { noErrors = false; break; } // // Otherwise, try to sync back up by scanning forward for // a reasonable start character. // static const XMLCh toSkip[] = { chPercent, chCloseSquare, chOpenAngle, chNull }; fReaderMgr->skipUntilInOrWS(toSkip); } } // If we have a doc type handler, tell it the internal subset ends if (fDocTypeHandler) fDocTypeHandler->endIntSubset(); return noErrors; } // // This method is called once we see a < in the input of an int/ext subset, // which indicates the start of some sort of markup. // void DTDScanner::scanMarkupDecl(const bool parseTextDecl) { // // We only have two valid first characters here. One is a ! which opens // some markup decl. The other is a ?, which could begin either a PI // or a text decl. If parseTextDecl is false, we cannot accept a text // decl. // const XMLCh nextCh = fReaderMgr->getNextChar(); if (nextCh == chBang) { if (fReaderMgr->skippedChar(chDash)) { if (fReaderMgr->skippedChar(chDash)) { scanComment(); } else { fScanner->emitError(XMLErrs::CommentsMustStartWith); fReaderMgr->skipPastChar(chCloseAngle); } } else if (fReaderMgr->skippedChar(chOpenSquare)) { // // Its a conditional section. This is only valid in the external // subset, so issue an error if we aren't there. // if (fInternalSubset) { fScanner->emitError(XMLErrs::ConditionalSectInIntSubset); fReaderMgr->skipPastChar(chCloseAngle); return; } // A PE ref can happen here, but space is not required checkForPERef(false, true); if (fReaderMgr->skippedString(XMLUni::fgIncludeString)) { checkForPERef(false, true); // Check for the following open square bracket if (!fReaderMgr->skippedChar(chOpenSquare)) fScanner->emitError(XMLErrs::ExpectedINCLUDEBracket); // Get the reader we started this on const unsigned int orgReader = fReaderMgr->getCurrentReaderNum(); checkForPERef(false, true); // // Recurse back to the ext subset call again, telling it its // in an include section. // scanExtSubsetDecl(true, false); // // And see if we got back to the same level. If not, then its // a partial markup error. // if (fReaderMgr->getCurrentReaderNum() != orgReader && fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::PartialMarkupInPE); } else if (fReaderMgr->skippedString(XMLUni::fgIgnoreString)) { checkForPERef(false, true); // Check for the following open square bracket if (!fReaderMgr->skippedChar(chOpenSquare)) fScanner->emitError(XMLErrs::ExpectedINCLUDEBracket); // Get the reader we started this on const unsigned int orgReader = fReaderMgr->getCurrentReaderNum(); // And scan over the ignored part scanIgnoredSection(); // // And see if we got back to the same level. If not, then its // a partial markup error. // if (fReaderMgr->getCurrentReaderNum() != orgReader && fScanner->getDoValidation()) fScanner->getValidator()->emitError(XMLValid::PartialMarkupInPE); } else { fScanner->emitError(XMLErrs::ExpectedIncOrIgn); fReaderMgr->skipPastChar(chCloseAngle); } } else if (fReaderMgr->skippedString(XMLUni::fgAttListString)) { scanAttListDecl(); } else if (fReaderMgr->skippedString(XMLUni::fgElemString)) { scanElementDecl(); } else if (fReaderMgr->skippedString(XMLUni::fgEntityString)) { scanEntityDecl(); } else if (fReaderMgr->skippedString(XMLUni::fgNotationString)) { scanNotationDecl(); } else { fScanner->emitError(XMLErrs::ExpectedMarkupDecl); fReaderMgr->skipPastChar(chCloseAngle); } } else if (nextCh == chQuestion) { // It could be a PI or the XML declaration. Check for Decl if (fScanner->checkXMLDecl(false)) { // If we are not accepting text decls, its an error if (parseTextDecl) { scanTextDecl(); } else { // Emit the error and skip past this markup fScanner->emitError(XMLErrs::TextDeclNotLegalHere); fReaderMgr->skipPastChar(chCloseAngle); } } else { // It has to be a PI scanPI(); } } else { // Can't be valid so emit error and try to skip past end of this decl fScanner->emitError(XMLErrs::ExpectedMarkupDecl); fReaderMgr->skipPastChar(chCloseAngle); } } // // This method is called for a mixed model element's content mode. We've // already scanned past the '(PCDATA' part by the time we get here. So // everything else is element names separated by | characters until we // hit the end. The passed element decl's content model is filled in with // the information found. // bool DTDScanner::scanMixed(DTDElementDecl& toFill) { // // The terminating star is only required if there is something more // than (PCDATA). // bool starRequired = false; // Get a buffer to be used below to get element names XMLBufBid bbName(fBufMgr); XMLBuffer& nameBuf = bbName.getBuffer(); // // Create an initial content spec node. Its just a leaf node with a // PCDATA element id. This current node pointer will be pushed down the // tree as we go. // ContentSpecNode* curNode = new (fGrammarPoolMemoryManager) ContentSpecNode ( new (fGrammarPoolMemoryManager) QName ( XMLUni::fgZeroLenString , XMLUni::fgZeroLenString , XMLElementDecl::fgPCDataElemId , fGrammarPoolMemoryManager ) , false , fGrammarPoolMemoryManager ); // // Set the initial leaf as the temporary head. If we hit the first choice // node, it will be set up here. When done, this is the node that's set // as the content spec for the element. // ContentSpecNode* headNode = curNode; // Remember the original node so we can sense the first choice node ContentSpecNode* orgNode = curNode; // // We just loop around, getting the | character at the top and then // looking for the next element name. We keep up with the last node // and add each new one to its right node. // while (true) { // // First of all we check for some grunt work details of skipping // whitespace, expand PE refs, and catching invalid reps. // if (fReaderMgr->lookingAtChar(chPercent)) { // Expand it and continue checkForPERef(false, true); } else if (fReaderMgr->skippedChar(chAsterisk)) { // // Tell them they can't have reps in mixed model, but eat // it and keep going if we are allowed to. // if (fScanner->emitErrorWillThrowException(XMLErrs::NoRepInMixed)) { delete headNode; } fScanner->emitError(XMLErrs::NoRepInMixed); } else if (fReaderMgr->skippedSpace()) { // Spaces are ok at this point, just eat them and continue fReaderMgr->skipPastSpaces(); } else { if (!fReaderMgr->skippedChar(chPipe)) { // Has to be the closing paren now. if (!fReaderMgr->skippedChar(chCloseParen)) { delete headNode; fScanner->emitError(XMLErrs::UnterminatedContentModel, toFill.getElementName()->getLocalPart()); return false; } bool starSkipped = true; if (!fReaderMgr->skippedChar(chAsterisk)) { starSkipped = false; if (starRequired) { if (fScanner->emitErrorWillThrowException(XMLErrs::ExpectedAsterisk)) { delete headNode; } fScanner->emitError(XMLErrs::ExpectedAsterisk); } } // // Create a zero or more node and make the original head // node its first child. // if (starRequired || starSkipped) { headNode = new (fGrammarPoolMemoryManager) ContentSpecNode ( ContentSpecNode::ZeroOrMore , headNode , 0 , true , true , fGrammarPoolMemoryManager ); } // Store the head node as the content spec of the element. toFill.setContentSpec(headNode); break; } // Its more than just a PCDATA, so an ending star will be required now starRequired = true; // Space is legal here so check for a PE ref, but don't require space checkForPERef(false, true); // Get a name token if (!fReaderMgr->getName(nameBuf)) { delete headNode; fScanner->emitError(XMLErrs::ExpectedElementName); return false; } // // Create a leaf node for it. If we can find the element id for // this element, then use it. Else, we have to fault in an element // decl, marked as created because of being in a content model. // XMLElementDecl* decl = fDTDGrammar->getElemDecl(fEmptyNamespaceId, 0, nameBuf.getRawBuffer(), Grammar::TOP_LEVEL_SCOPE); if (!decl) { decl = new (fGrammarPoolMemoryManager) DTDElementDecl ( nameBuf.getRawBuffer() , fEmptyNamespaceId , DTDElementDecl::Any , fGrammarPoolMemoryManager ); decl->setCreateReason(XMLElementDecl::InContentModel); decl->setExternalElemDeclaration(isReadingExternalEntity()); fDTDGrammar->putElemDecl(decl); } // // If the current node is the original node, this is the first choice // node, so create an initial choice node with the current node and // the new element id. Store this as the head node. // // Otherwise, we have to steal the right node of the previous choice // and weave in another choice node there, which has the old choice // as its left and the new leaf as its right. // if (curNode == orgNode) { curNode = new (fGrammarPoolMemoryManager) ContentSpecNode ( ContentSpecNode::Choice , curNode , new (fGrammarPoolMemoryManager) ContentSpecNode ( decl->getElementName() , fGrammarPoolMemoryManager ) , true , true , fGrammarPoolMemoryManager ); // Remember the top node headNode = curNode; } else { ContentSpecNode* oldRight = curNode->orphanSecond(); curNode->setSecond ( new (fGrammarPoolMemoryManager) ContentSpecNode ( ContentSpecNode::Choice , oldRight , new (fGrammarPoolMemoryManager) ContentSpecNode ( decl->getElementName() , fGrammarPoolMemoryManager ) , true , true , fGrammarPoolMemoryManager ) ); // Make the new right node the current node curNode = curNode->getSecond(); } } } return true; } // // This method is called when we see a '<!NOTATION' string while scanning // markup decl. It parses out the notation and its id and stores a new // notation decl object in the notation decl pool. // void DTDScanner::scanNotationDecl() { // Space is required here so check for a PE ref, and require space if (!checkForPERef(false, true)) { fScanner->emitError(XMLErrs::ExpectedWhitespace); fReaderMgr->skipPastChar(chCloseAngle); return; } // // And now we get a name, which is the name of the notation. Get a // buffer for the name. // XMLBufBid bbName(fBufMgr); if (!fReaderMgr->getName(bbName.getBuffer())) { fScanner->emitError(XMLErrs::ExpectedNotationName); fReaderMgr->skipPastChar(chCloseAngle); return; } // If namespaces are enabled, then no colons allowed if (fScanner->getDoNamespaces()) { if (XMLString::indexOf(bbName.getRawBuffer(), chColon) != -1) fScanner->emitError(XMLErrs::ColonNotLegalWithNS); } // Space is required here so check for a PE ref, and require space if (!checkForPERef(false, true)) { fScanner->emitError(XMLErrs::ExpectedWhitespace); fReaderMgr->skipPastChar(chCloseAngle); return; } // // And scan an external or public id. We need buffers to use for both // of these. // XMLBufBid bbPubId(fBufMgr); XMLBufBid bbSysId(fBufMgr); if (!scanId(bbPubId.getBuffer(), bbSysId.getBuffer(), IDType_Either)) { fReaderMgr->skipPastChar(chCloseAngle); return; } // We can have an optional space or PE ref here checkForPERef(false, true); // // See if it already exists. If so, add it to the notatino decl pool. // Otherwise, if advanced callbacks are on, create a temp one and // call out for that one. // XMLNotationDecl* decl = fDTDGrammar->getNotationDecl(bbName.getRawBuffer()); bool isIgnoring = (decl != 0); if (isIgnoring) { fScanner->emitError(XMLErrs::NotationAlreadyExists, bbName.getRawBuffer()); } else { // Fill in a new notation declaration and add it to the pool const XMLCh* publicId = bbPubId.getRawBuffer(); const XMLCh* systemId = bbSysId.getRawBuffer(); ReaderMgr::LastExtEntityInfo lastInfo; fReaderMgr->getLastExtEntityInfo(lastInfo); decl = new (fGrammarPoolMemoryManager) XMLNotationDecl ( bbName.getRawBuffer() , (publicId && *publicId) ? publicId : 0 , (systemId && *systemId) ? systemId : 0 , (lastInfo.systemId && *lastInfo.systemId) ? lastInfo.systemId : 0 , fGrammarPoolMemoryManager ); fDTDGrammar->putNotationDecl(decl); } // // If we have a document type handler, then tell it about this. If we // are ignoring it, only call out if advanced callbacks are enabled. // if (fDocTypeHandler) { fDocTypeHandler->notationDecl ( *decl , isIgnoring ); } // And one more optional space or PE ref checkForPERef(false, true); // And skip the terminating bracket if (!fReaderMgr->skippedChar(chCloseAngle)) fScanner->emitError(XMLErrs::UnterminatedNotationDecl); } // // Scans a PI and calls the appropriate callbacks. A PI can happen in either // the document or the DTD, so it calls the appropriate handler according // to the fInDocument flag. // // At entry we have just scanned the <? part, and need to now start on the // PI target name. // void DTDScanner::scanPI() { const XMLCh* namePtr = 0; const XMLCh* targetPtr = 0; // // If there are any spaces here, then warn about it. If we aren't in // 'first error' mode, then we'll come back and can easily pick up // again by just skipping them. // if (fReaderMgr->lookingAtSpace()) { fScanner->emitError(XMLErrs::PINameExpected); fReaderMgr->skipPastSpaces(); } // Get a buffer for the PI name and scan it in XMLBufBid bbName(fBufMgr); if (!fReaderMgr->getName(bbName.getBuffer())) { fScanner->emitError(XMLErrs::PINameExpected); fReaderMgr->skipPastChar(chCloseAngle); return; } // Point the name pointer at the raw data namePtr = bbName.getRawBuffer(); // See if it issome form of 'xml' and emit a warning //if (!XMLString::compareIString(namePtr, XMLUni::fgXMLString)) if (bbName.getLen() == 3 && (((namePtr[0] == chLatin_x) || (namePtr[0] == chLatin_X)) && ((namePtr[1] == chLatin_m) || (namePtr[1] == chLatin_M)) && ((namePtr[2] == chLatin_l) || (namePtr[2] == chLatin_L)))) fScanner->emitError(XMLErrs::NoPIStartsWithXML); // If namespaces are enabled, then no colons allowed if (fScanner->getDoNamespaces()) { if (XMLString::indexOf(namePtr, chColon) != -1) fScanner->emitError(XMLErrs::ColonNotLegalWithNS); } // // If we don't hit a space next, then the PI has no target. If we do // then get out the target. Get a buffer for it as well // XMLBufBid bbTarget(fBufMgr); if (fReaderMgr->skippedSpace()) { // Skip any leading spaces fReaderMgr->skipPastSpaces(); bool gotLeadingSurrogate = false; // It does have a target, so lets move on to deal with that. while (1) { const XMLCh nextCh = fReaderMgr->getNextChar(); // Watch for an end of file, which is always bad here if (!nextCh) { fScanner->emitError(XMLErrs::UnterminatedPI); ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); } // Watch for potential terminating character if (nextCh == chQuestion) { // It must be followed by '>' to be a termination of the target if (fReaderMgr->skippedChar(chCloseAngle)) break; } // Check for correct surrogate pairs if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { if (gotLeadingSurrogate) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { if (gotLeadingSurrogate) { if ((nextCh < 0xDC00) || (nextCh > 0xDFFF)) fScanner->emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr->getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); fScanner->emitError(XMLErrs::InvalidCharacter, tmpBuf); } gotLeadingSurrogate = false; } bbTarget.append(nextCh); } } else { // No target, but make sure its terminated ok if (!fReaderMgr->skippedChar(chQuestion)) { fScanner->emitError(XMLErrs::UnterminatedPI); fReaderMgr->skipPastChar(chCloseAngle); return; } if (!fReaderMgr->skippedChar(chCloseAngle)) { fScanner->emitError(XMLErrs::UnterminatedPI); fReaderMgr->skipPastChar(chCloseAngle); return; } } // Point the target pointer at the raw data targetPtr = bbTarget.getRawBuffer(); // // If we have a handler, then call it. // if (fDocTypeHandler) { fDocTypeHandler->doctypePI ( namePtr , targetPtr ); } } // // This method scans a public literal. It must be quoted and all of its // characters must be valid public id characters. The quotes are discarded // and the results are returned. // bool DTDScanner::scanPublicLiteral(XMLBuffer& toFill) { toFill.reset(); // Get the next char which must be a single or double quote XMLCh quoteCh; if (!fReaderMgr->skipIfQuote(quoteCh)) { fScanner->emitError(XMLErrs::ExpectedQuotedString); return false; } while (true) { const XMLCh nextCh = fReaderMgr->getNextChar(); // Watch for EOF if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); if (nextCh == quoteCh) break; // // If its not a valid public id char, then report it but keep going // since that's the best recovery scheme. // if (!fReaderMgr->getCurrentReader()->isPublicIdChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); fScanner->emitError(XMLErrs::InvalidPublicIdChar, tmpBuf); } toFill.append(nextCh); } return true; } // // This method handles scanning in a quoted system literal. It expects to // start on the open quote and returns after eating the ending quote. There // are not really any restrictions on the contents of system literals. // bool DTDScanner::scanSystemLiteral(XMLBuffer& toFill) { toFill.reset(); // Get the next char which must be a single or double quote XMLCh quoteCh; if (!fReaderMgr->skipIfQuote(quoteCh)) { fScanner->emitError(XMLErrs::ExpectedQuotedString); return false; } while (true) { const XMLCh nextCh = fReaderMgr->getNextChar(); // Watch for EOF if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); // Break out on terminating quote if (nextCh == quoteCh) break; toFill.append(nextCh); } return true; } // // This method is called to scan a text decl line, which can be the first // line in an external entity or external subset. // // On entry the <? has been scanned, and next should be 'xml' followed by // some whitespace, version string, etc... // [77] TextDecl::= '<?xml' VersionInfo? EncodingDecl S? '?>' // void DTDScanner::scanTextDecl() { // Skip any subsequent whitespace before the version string fReaderMgr->skipPastSpaces(); // Next should be the version string XMLBufBid bbVersion(fBufMgr); if (fReaderMgr->skippedString(XMLUni::fgVersionString)) { if (!scanEq()) { fScanner->emitError(XMLErrs::ExpectedEqSign); fReaderMgr->skipPastChar(chCloseAngle); return; } // // Followed by a single or double quoted version. Get a buffer for // the string. // if (!getQuotedString(bbVersion.getBuffer())) { fScanner->emitError(XMLErrs::BadXMLVersion); fReaderMgr->skipPastChar(chCloseAngle); return; } // If its not our supported version, issue an error but continue if (XMLString::equals(bbVersion.getRawBuffer(), XMLUni::fgVersion1_1)) { if (fScanner->getXMLVersion() != XMLReader::XMLV1_1) fScanner->emitError(XMLErrs::UnsupportedXMLVersion, bbVersion.getRawBuffer()); } else if (!XMLString::equals(bbVersion.getRawBuffer(), XMLUni::fgVersion1_0)) fScanner->emitError(XMLErrs::UnsupportedXMLVersion, bbVersion.getRawBuffer()); } // Ok, now we must have an encoding string XMLBufBid bbEncoding(fBufMgr); fReaderMgr->skipPastSpaces(); bool gotEncoding = false; if (fReaderMgr->skippedString(XMLUni::fgEncodingString)) { // There must be a equal sign next if (!scanEq()) { fScanner->emitError(XMLErrs::ExpectedEqSign); fReaderMgr->skipPastChar(chCloseAngle); return; } // Followed by a single or double quoted version string getQuotedString(bbEncoding.getBuffer()); if (bbEncoding.isEmpty() || !XMLString::isValidEncName(bbEncoding.getRawBuffer())) { fScanner->emitError(XMLErrs::BadXMLEncoding, bbEncoding.getRawBuffer()); fReaderMgr->skipPastChar(chCloseAngle); return; } // Indicate that we got an encoding gotEncoding = true; } // // Encoding declarations are required in the external entity // if there is a text declaration present // if (!gotEncoding) { fScanner->emitError(XMLErrs::EncodingRequired); fReaderMgr->skipPastChar(chCloseAngle); return; } fReaderMgr->skipPastSpaces(); if (!fReaderMgr->skippedChar(chQuestion)) { fScanner->emitError(XMLErrs::UnterminatedXMLDecl); fReaderMgr->skipPastChar(chCloseAngle); } else if (!fReaderMgr->skippedChar(chCloseAngle)) { fScanner->emitError(XMLErrs::UnterminatedXMLDecl); fReaderMgr->skipPastChar(chCloseAngle); } // // If we have a document type handler and advanced callbacks are on, // then call the TextDecl callback // if (fDocTypeHandler) { fDocTypeHandler->TextDecl ( bbVersion.getRawBuffer() , bbEncoding.getRawBuffer() ); } // // If we got an encoding string, then we have to call back on the reader // to tell it what the encoding is. // if (!bbEncoding.isEmpty()) { if (!fReaderMgr->getCurrentReader()->setEncoding(bbEncoding.getRawBuffer())) fScanner->emitError(XMLErrs::ContradictoryEncoding, bbEncoding.getRawBuffer()); } } XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 3856 ] ] ]
c81e20bdc46bc8640c2fed1c5d93ba7fcb69e3d5
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/TagLib/mpeg/id3v2/id3v2framefactory.h
b852a3395c5d0f806205784a69dd37b6ec85db3f
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
7,242
h
/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : [email protected] ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #ifndef TAGLIB_ID3V2FRAMEFACTORY_H #define TAGLIB_ID3V2FRAMEFACTORY_H #include "taglib_export.h" #include "tbytevector.h" #include "id3v2frame.h" #include "id3v2header.h" namespace TagLib { namespace ID3v2 { class TAGLIB_EXPORT TextIdentificationFrame; //! A factory for creating ID3v2 frames during parsing /*! * This factory abstracts away the frame creation process and instantiates * the appropriate ID3v2::Frame subclasses based on the contents of the * data. * * Reimplementing this factory is the key to adding support for frame types * not directly supported by TagLib to your application. To do so you would * subclass this factory reimplement createFrame(). Then by setting your * factory to be the default factory in ID3v2::Tag constructor or with * MPEG::File::setID3v2FrameFactory() you can implement behavior that will * allow for new ID3v2::Frame subclasses (also provided by you) to be used. * * This implements both <i>abstract factory</i> and <i>singleton</i> patterns * of which more information is available on the web and in software design * textbooks (Notably <i>Design Patters</i>). * * \note You do not need to use this factory to create new frames to add to * an ID3v2::Tag. You can instantiate frame subclasses directly (with new) * and add them to a tag using ID3v2::Tag::addFrame() * * \see ID3v2::Tag::addFrame() */ class TAGLIB_EXPORT FrameFactory { public: static FrameFactory *instance(); /*! * Create a frame based on \a data. \a synchSafeInts should only be set * false if we are parsing an old tag (v2.3 or older) that does not support * synchsafe ints. * * \deprecated Please use the method below that accepts a ID3v2::Header * instance in new code. */ Frame *createFrame(const ByteVector &data, bool synchSafeInts) const; /*! * Create a frame based on \a data. \a version should indicate the ID3v2 * version of the tag. As ID3v2.4 is the most current version of the * standard 4 is the default. * * \deprecated Please use the method below that accepts a ID3v2::Header * instance in new code. */ Frame *createFrame(const ByteVector &data, uint version = 4) const; /*! * Create a frame based on \a data. \a tagHeader should be a valid * ID3v2::Header instance. */ // BIC: make virtual Frame *createFrame(const ByteVector &data, Header *tagHeader) const; /*! * Returns the default text encoding for text frames. If setTextEncoding() * has not been explicitly called this will only be used for new text * frames. However, if this value has been set explicitly all frames will be * converted to this type (unless it's explitly set differently for the * individual frame) when being rendered. * * \see setDefaultTextEncoding() */ String::Type defaultTextEncoding() const; /*! * Set the default text encoding for all text frames that are created to * \a encoding. If no value is set the frames with either default to the * encoding type that was parsed and new frames default to Latin1. * * Valid string types for ID3v2 tags are Latin1, UTF8, UTF16 and UTF16BE. * * \see defaultTextEncoding() */ void setDefaultTextEncoding(String::Type encoding); public: //=== Alex. Remove the leak static void ClearInstance() { delete factory; factory = 0; } //=== Alex. Remove the leak === END protected: /*! * Constructs a frame factory. Because this is a singleton this method is * protected, but may be used for subclasses. */ FrameFactory(); /*! * Destroys the frame factory. In most cases this will never be called (as * is typical of singletons). */ virtual ~FrameFactory(); /*! * This method checks for compliance to the current ID3v2 standard (2.4) * and does nothing in the common case. However if a frame is found that * is not compatible with the current standard, this method either updates * the frame or indicates that it should be discarded. * * This method with return true (with or without changes to the frame) if * this frame should be kept or false if it should be discarded. * * See the id3v2.4.0-changes.txt document for further information. */ virtual bool updateFrame(Frame::Header *header) const; private: FrameFactory(const FrameFactory &); FrameFactory &operator=(const FrameFactory &); /*! * This method is used internally to convert a frame from ID \a from to ID * \a to. If the frame matches the \a from pattern and converts the frame * ID in the \a header or simply does nothing if the frame ID does not match. */ void convertFrame(const char *from, const char *to, Frame::Header *header) const; void updateGenre(TextIdentificationFrame *frame) const; static FrameFactory *factory; class FrameFactoryPrivate; FrameFactoryPrivate *d; }; } } #endif
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 174 ] ] ]
e8e6578a026e7079ff9f6205fdcda46c4d119dfd
611fc0940b78862ca89de79a8bbeab991f5f471a
/src/Teki/Boss/Majo/RollingApple.cpp
48ec501bc681378ae43ccf59fba5c3ef6661c5d8
[]
no_license
LakeIshikawa/splstage2
df1d8f59319a4e8d9375b9d3379c3548bc520f44
b4bf7caadf940773a977edd0de8edc610cd2f736
refs/heads/master
2021-01-10T21:16:45.430981
2010-01-29T08:57:34
2010-01-29T08:57:34
37,068,575
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,173
cpp
#include "RollingApple.h" #include "..\\..\\..\\Management\\GameControl.h" RollingApple::RollingApple(int rXPx, int rYPx, int rType) : Apple( rXPx, rYPx ) { APPLE_RLSP = GF("APPLE_RLSP"); APPLE_KTSP = GF("APPLE_KTSP"); mStatus = FALL; mType = rType; } RollingApple::~RollingApple() {} /* メイン処理 */ void RollingApple::Move() { RollIfHitGround(); Kaiten(); Apple::Move(); } /* 地面とあたった瞬間に転がり始める */ void RollingApple::RollIfHitGround() { if( mStatus == FALL && IsHittingGround() ){ mStatus = ROLL; mAngle = 0; if( mType == 2) mType = 2 + (rand()%2?-1:1); switch( mType ){ case 3: { mSpX = -APPLE_RLSP; mAngSp = -APPLE_KTSP; } break; case 1: { mSpX = APPLE_RLSP; mAngSp = APPLE_KTSP; } break; } } } /* 回転して転がる */ void RollingApple::Kaiten() { mAngle += mAngSp; if( mAngle >= D3DX_PI*2 ) mAngle = 0; } /* 描画 */ void RollingApple::Draw() { if( mStatus == ROLL ){ DX_SCROLL_ROT_DRAW("graphics\\item\\Apple_Death.png", mX, mY, mNo*APPLESZX, 0, (APPLESZX)*(mNo+1), APPLESZY, mAngle); } else{ Apple::Draw(); } }
[ "lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b" ]
[ [ [ 1, 65 ] ] ]
0380d5e1a76c25e3e559ff55a059cc98fb6f87c5
3187b0dd0d7a7b83b33c62357efa0092b3943110
/src/dlib/svm/function_abstract.h
6b302a45980de73c15205721721a0310003591f3
[ "BSL-1.0" ]
permissive
exi/gravisim
8a4dad954f68960d42f1d7da14ff1ca7a20e92f2
361e70e40f58c9f5e2c2f574c9e7446751629807
refs/heads/master
2021-01-19T17:45:04.106839
2010-10-22T09:11:24
2010-10-22T09:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,787
h
// Copyright (C) 2007 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_SVm_FUNCTION_ABSTRACT_ #ifdef DLIB_SVm_FUNCTION_ABSTRACT_ #include <cmath> #include <limits> #include <sstream> #include "../matrix/matrix_abstract.h" #include "../algs.h" #include "../serialize.h" namespace dlib { // ---------------------------------------------------------------------------------------- template < typename K > struct decision_function { /*! REQUIREMENTS ON K K must be a kernel function object type as defined at the top of this document. WHAT THIS OBJECT REPRESENTS This object represents a decision or regression function that was learned by a kernel based learning algorithm. !*/ typedef typename K::scalar_type scalar_type; typedef typename K::sample_type sample_type; typedef typename K::mem_manager_type mem_manager_type; typedef matrix<scalar_type,0,1,mem_manager_type> scalar_vector_type; typedef matrix<sample_type,0,1,mem_manager_type> sample_vector_type; const scalar_vector_type alpha; const scalar_type b; const K kernel_function; const sample_vector_type support_vectors; decision_function ( ); /*! ensures - #b == 0 - #alpha.nr() == 0 - #support_vectors.nr() == 0 !*/ decision_function ( const decision_function& f ); /*! ensures - #*this is a copy of f !*/ decision_function ( const scalar_vector_type& alpha_, const scalar_type& b_, const K& kernel_function_, const sample_vector_type& support_vectors_ ) : alpha(alpha_), b(b_), kernel_function(kernel_function_), support_vectors(support_vectors_) {} /*! ensures - populates the decision function with the given support vectors, weights(i.e. alphas), b term, and kernel function. !*/ decision_function& operator= ( const decision_function& d ); /*! ensures - #*this is identical to d - returns *this !*/ scalar_type operator() ( const sample_type& x ) const /*! ensures - evalutes this sample according to the decision function contained in this object. !*/ { scalar_type temp = 0; for (long i = 0; i < alpha.nr(); ++i) temp += alpha(i) * kernel_function(x,support_vectors(i)); returns temp - b; } }; template < typename K > void serialize ( const decision_function<K>& item, std::ostream& out ); /*! provides serialization support for decision_function !*/ template < typename K > void deserialize ( decision_function<K>& item, std::istream& in ); /*! provides serialization support for decision_function !*/ // ---------------------------------------------------------------------------------------- template < typename K > struct probabilistic_decision_function { /*! REQUIREMENTS ON K K must be a kernel function object type as defined at the top of this document. WHAT THIS OBJECT REPRESENTS This object represents a binary decision function that returns an estimate of the probability that a given sample is in the +1 class. !*/ typedef typename K::scalar_type scalar_type; typedef typename K::sample_type sample_type; typedef typename K::mem_manager_type mem_manager_type; const scalar_type a; const scalar_type b; const decision_function<K> decision_funct; probabilistic_decision_function ( ); /*! ensures - #a == 0 - #b == 0 - #decision_function has its initial value !*/ probabilistic_decision_function ( const probabilistic_decision_function& f ); /*! ensures - #*this is a copy of f !*/ probabilistic_decision_function ( const scalar_type a_, const scalar_type b_, const decision_function<K>& decision_funct_ ) : a(a_), b(b_), decision_funct(decision_funct_) {} /*! ensures - populates the probabilistic decision function with the given a, b, and decision_function. !*/ probabilistic_decision_function& operator= ( const probabilistic_decision_function& d ); /*! ensures - #*this is identical to d - returns *this !*/ scalar_type operator() ( const sample_type& x ) const /*! ensures - returns a number P such that: - 0 <= P <= 1 - P represents the probability that sample x is from the class +1 !*/ { // Evaluate the normal SVM decision function scalar_type f = decision_funct(x); // Now basically normalize the output so that it is a properly // conditioned probability of x being in the +1 class given // the output of the SVM. return 1/(1 + std::exp(a*f + b)); } }; template < typename K > void serialize ( const probabilistic_decision_function<K>& item, std::ostream& out ); /*! provides serialization support for probabilistic_decision_function !*/ template < typename K > void deserialize ( probabilistic_decision_function<K>& item, std::istream& in ); /*! provides serialization support for probabilistic_decision_function !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_SVm_FUNCTION_ABSTRACT_
[ [ [ 1, 233 ] ] ]
360dcd6c1d16478564043b1d6e0e962fc0baeffe
8be41f8425a39f7edc92efb3b73b6a8ca91150f3
/Qt/project-build-desktop/ui_mainwindow.h
e5b37a96b6dddd7b210f25e0713c2903b999b40c
[]
no_license
SysMa/msq-summer-project
b497a061feef25cac1c892fe4dd19ebb30ae9a56
0ef171aa62ad584259913377eabded14f9f09e4b
refs/heads/master
2021-01-23T09:28:34.696908
2011-09-16T06:39:52
2011-09-16T06:39:52
34,208,886
0
1
null
null
null
null
UTF-8
C++
false
false
20,783
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created: Wed Sep 14 23:26:49 2011 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QComboBox> #include <QtGui/QDateEdit> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QMainWindow> #include <QtGui/QMenu> #include <QtGui/QMenuBar> #include <QtGui/QPushButton> #include <QtGui/QStatusBar> #include <QtGui/QToolBar> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> #include <palnetwidget.h> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QAction *actionToogle_Mercury; QAction *actionVenus; QAction *actionEarth; QAction *actionMoon; QAction *actionMars; QAction *actionJupiter; QAction *actionNeptune; QAction *actionSaturn; QAction *actionUranus; QAction *actionMercury; QAction *actionVenus_2; QAction *actionEarth_2; QAction *actionMoon_2; QAction *actionMars_2; QAction *actionJupiter_2; QAction *actionSaturn_2; QAction *actionNeptune_2; QAction *actionUranus_2; QAction *actionAbout; QAction *actionHelp; QAction *actionHot_Key_List; QAction *actionSolar; QAction *actionSun_Earth_Moon; QAction *actionEclipse; QAction *actionPlanetary_Alignments; QAction *actionNext_Notice; QWidget *centralWidget; QVBoxLayout *verticalLayout; palnetWidget *widget_2; QWidget *widget; QLabel *label; QDateEdit *dateEdit; QPushButton *pushButton_3; QLabel *label_2; QComboBox *comboBox; QPushButton *pushButton_4; QLabel *label_3; QLabel *label_4; QComboBox *comboBox_2; QComboBox *comboBox_3; QPushButton *pushButton; QPushButton *pushButton_2; QPushButton *pushButton_5; QMenuBar *menuBar; QMenu *menuPalnet; QMenu *menuCircles; QMenu *menuHelp; QMenu *menuChange_Mode; QMenu *menuNotice; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QString::fromUtf8("MainWindow")); MainWindow->resize(803, 476); actionToogle_Mercury = new QAction(MainWindow); actionToogle_Mercury->setObjectName(QString::fromUtf8("actionToogle_Mercury")); actionToogle_Mercury->setCheckable(true); actionVenus = new QAction(MainWindow); actionVenus->setObjectName(QString::fromUtf8("actionVenus")); actionVenus->setCheckable(true); actionEarth = new QAction(MainWindow); actionEarth->setObjectName(QString::fromUtf8("actionEarth")); actionEarth->setCheckable(true); actionMoon = new QAction(MainWindow); actionMoon->setObjectName(QString::fromUtf8("actionMoon")); actionMoon->setCheckable(true); actionMars = new QAction(MainWindow); actionMars->setObjectName(QString::fromUtf8("actionMars")); actionMars->setCheckable(true); actionJupiter = new QAction(MainWindow); actionJupiter->setObjectName(QString::fromUtf8("actionJupiter")); actionJupiter->setCheckable(true); actionNeptune = new QAction(MainWindow); actionNeptune->setObjectName(QString::fromUtf8("actionNeptune")); actionNeptune->setCheckable(true); actionSaturn = new QAction(MainWindow); actionSaturn->setObjectName(QString::fromUtf8("actionSaturn")); actionSaturn->setCheckable(true); actionUranus = new QAction(MainWindow); actionUranus->setObjectName(QString::fromUtf8("actionUranus")); actionUranus->setCheckable(true); actionMercury = new QAction(MainWindow); actionMercury->setObjectName(QString::fromUtf8("actionMercury")); actionMercury->setCheckable(true); actionVenus_2 = new QAction(MainWindow); actionVenus_2->setObjectName(QString::fromUtf8("actionVenus_2")); actionVenus_2->setCheckable(true); actionEarth_2 = new QAction(MainWindow); actionEarth_2->setObjectName(QString::fromUtf8("actionEarth_2")); actionEarth_2->setCheckable(true); actionMoon_2 = new QAction(MainWindow); actionMoon_2->setObjectName(QString::fromUtf8("actionMoon_2")); actionMoon_2->setCheckable(true); actionMars_2 = new QAction(MainWindow); actionMars_2->setObjectName(QString::fromUtf8("actionMars_2")); actionMars_2->setCheckable(true); actionJupiter_2 = new QAction(MainWindow); actionJupiter_2->setObjectName(QString::fromUtf8("actionJupiter_2")); actionJupiter_2->setCheckable(true); actionSaturn_2 = new QAction(MainWindow); actionSaturn_2->setObjectName(QString::fromUtf8("actionSaturn_2")); actionSaturn_2->setCheckable(true); actionNeptune_2 = new QAction(MainWindow); actionNeptune_2->setObjectName(QString::fromUtf8("actionNeptune_2")); actionNeptune_2->setCheckable(true); actionUranus_2 = new QAction(MainWindow); actionUranus_2->setObjectName(QString::fromUtf8("actionUranus_2")); actionUranus_2->setCheckable(true); actionAbout = new QAction(MainWindow); actionAbout->setObjectName(QString::fromUtf8("actionAbout")); actionHelp = new QAction(MainWindow); actionHelp->setObjectName(QString::fromUtf8("actionHelp")); actionHot_Key_List = new QAction(MainWindow); actionHot_Key_List->setObjectName(QString::fromUtf8("actionHot_Key_List")); actionSolar = new QAction(MainWindow); actionSolar->setObjectName(QString::fromUtf8("actionSolar")); actionSun_Earth_Moon = new QAction(MainWindow); actionSun_Earth_Moon->setObjectName(QString::fromUtf8("actionSun_Earth_Moon")); actionEclipse = new QAction(MainWindow); actionEclipse->setObjectName(QString::fromUtf8("actionEclipse")); actionPlanetary_Alignments = new QAction(MainWindow); actionPlanetary_Alignments->setObjectName(QString::fromUtf8("actionPlanetary_Alignments")); actionNext_Notice = new QAction(MainWindow); actionNext_Notice->setObjectName(QString::fromUtf8("actionNext_Notice")); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QString::fromUtf8("centralWidget")); verticalLayout = new QVBoxLayout(centralWidget); verticalLayout->setSpacing(6); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); widget_2 = new palnetWidget(centralWidget); widget_2->setObjectName(QString::fromUtf8("widget_2")); widget_2->setMaximumSize(QSize(16777215, 16777215)); verticalLayout->addWidget(widget_2); widget = new QWidget(centralWidget); widget->setObjectName(QString::fromUtf8("widget")); widget->setMaximumSize(QSize(16777215, 80)); label = new QLabel(widget); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(10, 10, 31, 16)); dateEdit = new QDateEdit(widget); dateEdit->setObjectName(QString::fromUtf8("dateEdit")); dateEdit->setGeometry(QRect(50, 10, 91, 22)); pushButton_3 = new QPushButton(widget); pushButton_3->setObjectName(QString::fromUtf8("pushButton_3")); pushButton_3->setGeometry(QRect(170, 10, 75, 23)); label_2 = new QLabel(widget); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(10, 50, 111, 20)); comboBox = new QComboBox(widget); comboBox->setObjectName(QString::fromUtf8("comboBox")); comboBox->setGeometry(QRect(120, 50, 121, 22)); pushButton_4 = new QPushButton(widget); pushButton_4->setObjectName(QString::fromUtf8("pushButton_4")); pushButton_4->setGeometry(QRect(680, 10, 91, 23)); label_3 = new QLabel(widget); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setGeometry(QRect(280, 10, 61, 16)); label_4 = new QLabel(widget); label_4->setObjectName(QString::fromUtf8("label_4")); label_4->setGeometry(QRect(280, 50, 54, 12)); comboBox_2 = new QComboBox(widget); comboBox_2->setObjectName(QString::fromUtf8("comboBox_2")); comboBox_2->setGeometry(QRect(350, 10, 131, 22)); comboBox_3 = new QComboBox(widget); comboBox_3->setObjectName(QString::fromUtf8("comboBox_3")); comboBox_3->setGeometry(QRect(350, 50, 131, 22)); pushButton = new QPushButton(widget); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setGeometry(QRect(680, 50, 91, 23)); pushButton_2 = new QPushButton(widget); pushButton_2->setObjectName(QString::fromUtf8("pushButton_2")); pushButton_2->setGeometry(QRect(500, 10, 151, 23)); pushButton_5 = new QPushButton(widget); pushButton_5->setObjectName(QString::fromUtf8("pushButton_5")); pushButton_5->setGeometry(QRect(500, 50, 151, 23)); verticalLayout->addWidget(widget); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QString::fromUtf8("menuBar")); menuBar->setGeometry(QRect(0, 0, 803, 19)); menuPalnet = new QMenu(menuBar); menuPalnet->setObjectName(QString::fromUtf8("menuPalnet")); menuCircles = new QMenu(menuBar); menuCircles->setObjectName(QString::fromUtf8("menuCircles")); menuHelp = new QMenu(menuBar); menuHelp->setObjectName(QString::fromUtf8("menuHelp")); menuChange_Mode = new QMenu(menuBar); menuChange_Mode->setObjectName(QString::fromUtf8("menuChange_Mode")); menuNotice = new QMenu(menuBar); menuNotice->setObjectName(QString::fromUtf8("menuNotice")); MainWindow->setMenuBar(menuBar); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QString::fromUtf8("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QString::fromUtf8("statusBar")); MainWindow->setStatusBar(statusBar); menuBar->addAction(menuChange_Mode->menuAction()); menuBar->addAction(menuNotice->menuAction()); menuBar->addAction(menuPalnet->menuAction()); menuBar->addAction(menuCircles->menuAction()); menuBar->addAction(menuHelp->menuAction()); menuPalnet->addAction(actionToogle_Mercury); menuPalnet->addAction(actionVenus); menuPalnet->addAction(actionEarth); menuPalnet->addAction(actionMoon); menuPalnet->addAction(actionMars); menuPalnet->addAction(actionJupiter); menuPalnet->addAction(actionNeptune); menuPalnet->addAction(actionSaturn); menuPalnet->addAction(actionUranus); menuCircles->addAction(actionMercury); menuCircles->addAction(actionVenus_2); menuCircles->addAction(actionEarth_2); menuCircles->addAction(actionMoon_2); menuCircles->addAction(actionMars_2); menuCircles->addAction(actionJupiter_2); menuCircles->addAction(actionSaturn_2); menuCircles->addAction(actionNeptune_2); menuCircles->addAction(actionUranus_2); menuHelp->addAction(actionAbout); menuHelp->addSeparator(); menuHelp->addAction(actionHelp); menuHelp->addAction(actionHot_Key_List); menuChange_Mode->addAction(actionSolar); menuChange_Mode->addAction(actionSun_Earth_Moon); menuNotice->addAction(actionEclipse); menuNotice->addAction(actionPlanetary_Alignments); menuNotice->addAction(actionNext_Notice); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8)); actionToogle_Mercury->setText(QApplication::translate("MainWindow", "Hide Mercury", 0, QApplication::UnicodeUTF8)); actionVenus->setText(QApplication::translate("MainWindow", "Hide Venus", 0, QApplication::UnicodeUTF8)); actionEarth->setText(QApplication::translate("MainWindow", "Hide Earth", 0, QApplication::UnicodeUTF8)); actionMoon->setText(QApplication::translate("MainWindow", "Hide Moon", 0, QApplication::UnicodeUTF8)); actionMars->setText(QApplication::translate("MainWindow", "Hide Mars", 0, QApplication::UnicodeUTF8)); actionJupiter->setText(QApplication::translate("MainWindow", "Hide Jupiter", 0, QApplication::UnicodeUTF8)); actionNeptune->setText(QApplication::translate("MainWindow", "Hide Neptune", 0, QApplication::UnicodeUTF8)); actionSaturn->setText(QApplication::translate("MainWindow", "Hide Saturn", 0, QApplication::UnicodeUTF8)); actionUranus->setText(QApplication::translate("MainWindow", "Hide Uranus", 0, QApplication::UnicodeUTF8)); actionMercury->setText(QApplication::translate("MainWindow", "Hide Mercury Line", 0, QApplication::UnicodeUTF8)); actionVenus_2->setText(QApplication::translate("MainWindow", "Hide Venus Line", 0, QApplication::UnicodeUTF8)); actionEarth_2->setText(QApplication::translate("MainWindow", "Hide Earth Line", 0, QApplication::UnicodeUTF8)); actionMoon_2->setText(QApplication::translate("MainWindow", "Hide Moon Line", 0, QApplication::UnicodeUTF8)); actionMars_2->setText(QApplication::translate("MainWindow", "Hide Mars Line", 0, QApplication::UnicodeUTF8)); actionJupiter_2->setText(QApplication::translate("MainWindow", "Hide Jupiter Line", 0, QApplication::UnicodeUTF8)); actionSaturn_2->setText(QApplication::translate("MainWindow", "Hide Saturn Line", 0, QApplication::UnicodeUTF8)); actionNeptune_2->setText(QApplication::translate("MainWindow", "Hide Neptune Line", 0, QApplication::UnicodeUTF8)); actionUranus_2->setText(QApplication::translate("MainWindow", "Hide Uranus Line", 0, QApplication::UnicodeUTF8)); actionAbout->setText(QApplication::translate("MainWindow", "About", 0, QApplication::UnicodeUTF8)); actionHelp->setText(QApplication::translate("MainWindow", "Advice", 0, QApplication::UnicodeUTF8)); actionHot_Key_List->setText(QApplication::translate("MainWindow", "Hot Key List", 0, QApplication::UnicodeUTF8)); actionSolar->setText(QApplication::translate("MainWindow", "Solar", 0, QApplication::UnicodeUTF8)); actionSun_Earth_Moon->setText(QApplication::translate("MainWindow", "Sun-Earth-Moon", 0, QApplication::UnicodeUTF8)); actionEclipse->setText(QApplication::translate("MainWindow", "Eclipse", 0, QApplication::UnicodeUTF8)); actionPlanetary_Alignments->setText(QApplication::translate("MainWindow", "Planetary Alignments", 0, QApplication::UnicodeUTF8)); actionNext_Notice->setText(QApplication::translate("MainWindow", "Next Notice", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("MainWindow", "\346\227\245\346\234\237\357\274\232", 0, QApplication::UnicodeUTF8)); pushButton_3->setText(QApplication::translate("MainWindow", "Set", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("MainWindow", "\351\200\211\346\213\251\350\246\201\350\247\202\345\257\237\347\232\204\350\241\214\346\230\237\357\274\232", 0, QApplication::UnicodeUTF8)); comboBox->clear(); comboBox->insertItems(0, QStringList() << QApplication::translate("MainWindow", "None", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Mercury", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Venus", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Earth", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Mars", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Jupiter", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Saturn", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Uranus", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Neptune", 0, QApplication::UnicodeUTF8) ); pushButton_4->setText(QApplication::translate("MainWindow", "Hot Key List", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("MainWindow", "Look From:", 0, QApplication::UnicodeUTF8)); label_4->setText(QApplication::translate("MainWindow", "Look To :", 0, QApplication::UnicodeUTF8)); comboBox_2->clear(); comboBox_2->insertItems(0, QStringList() << QApplication::translate("MainWindow", "Default", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Center", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 1", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 2", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 3", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 4", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 5", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 6", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 7", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 8", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Distance 9", 0, QApplication::UnicodeUTF8) ); comboBox_3->clear(); comboBox_3->insertItems(0, QStringList() << QApplication::translate("MainWindow", "Default( the Sun)", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Moon", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Mercury", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Venus", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Earth", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Mars", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Jupiter", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Saturn", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Uranus", 0, QApplication::UnicodeUTF8) << QApplication::translate("MainWindow", "Neptune", 0, QApplication::UnicodeUTF8) ); pushButton->setText(QApplication::translate("MainWindow", "About", 0, QApplication::UnicodeUTF8)); pushButton_2->setText(QApplication::translate("MainWindow", "Planetary Alignments", 0, QApplication::UnicodeUTF8)); pushButton_5->setText(QApplication::translate("MainWindow", "Help", 0, QApplication::UnicodeUTF8)); menuPalnet->setTitle(QApplication::translate("MainWindow", "Hide Palnet", 0, QApplication::UnicodeUTF8)); menuCircles->setTitle(QApplication::translate("MainWindow", "Hide Circles", 0, QApplication::UnicodeUTF8)); menuHelp->setTitle(QApplication::translate("MainWindow", "Help", 0, QApplication::UnicodeUTF8)); menuChange_Mode->setTitle(QApplication::translate("MainWindow", "Change Mode", 0, QApplication::UnicodeUTF8)); menuNotice->setTitle(QApplication::translate("MainWindow", "Notice", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
[ "[email protected]@551f4f89-5e81-c284-84fc-d916aa359411" ]
[ [ [ 1, 372 ] ] ]
7d7381fb57269d13dff954ad5cdf86775b20b89f
e69b70003384635b23d90e2ae866e764a0f62a4c
/THISEditor/src/THISExporter.cpp
16259e8823af977d04eefc4cc30a3ab7c23e3003
[]
no_license
obviousjim/THISEditor
20021cfaf7fe8f78f33307204e34a42b6b2d6a39
e4c31cdcdc30432f977c3da94080878aff93995a
refs/heads/master
2021-01-10T18:53:42.763859
2011-09-18T14:21:15
2011-09-18T14:21:15
2,406,361
0
0
null
null
null
null
UTF-8
C++
false
false
1,868
cpp
/* * THISExporter.cpp * THIS_Editor * * Created by Jim on 6/26/11. * Copyright 2011 FlightPhase. All rights reserved. * */ #include "THISExporter.h" #include "THISTimeline.h" #include "ofFileUtils.h" THISExporter::THISExporter() { inputTimeline = NULL; outputTimeline = NULL; currentFrame = 0; exporting = false; shouldCancelExport = false; } bool THISExporter::isExporting() { return exporting; } float THISExporter::getPercentDone() { return ofMap(currentFrame, startFrame, endFrame, 0, 1.0, true); } void THISExporter::cancelExport() { shouldCancelExport = true; } void THISExporter::threadedFunction() { if(inputTimeline == NULL){ ofLog(OF_LOG_ERROR, "THISExporter -- no input timeline"); return; } if(outputTimeline == NULL){ ofLog(OF_LOG_ERROR, "THISExporter -- no output timeline"); return; } currentFrame = startFrame; if(!ofDirectory::doesDirectoryExist(pathPrefix+"/output/", false)){ if(!ofDirectory::createDirectory(pathPrefix+"/output/")){ ofLog(OF_LOG_ERROR, "THISExporter -- couldn't make output directory: " + pathPrefix+"/output/"); return; } } exporting = true; shouldCancelExport = false; char filename[1024]; while(isThreadRunning() && !shouldCancelExport){ outputTimeline->outputFrame = currentFrame; ofImage* outputFrame = outputTimeline->renderOutputFrame(false); if(outputFrame != NULL){ sprintf(filename, "%s/output/output_%05d.png", pathPrefix.c_str(), currentFrame); outputFrame->saveImage(string(filename)); } else{ ofLog(OF_LOG_ERROR, "Couldn't export frame %d ", currentFrame); } inputTimeline->purgeMemoryForExport(); currentFrame++; if(currentFrame > endFrame){ break; } ofSleepMillis(5); } shouldCancelExport = false; exporting = false; }
[ [ [ 1, 85 ] ] ]
6d24d2fcbeb759fab14e5bafc2042ab5c58d4ce4
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/DSDK/include/mrsid_readers/MG3CompositeImageReader.h
8dc1c7dffdd3285bba311a77d42912761bdaf814
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,165
h
/* $Id: MG3CompositeImageReader.h 5124 2006-10-27 11:40:40Z lubia $ */ /* ////////////////////////////////////////////////////////////////////////// // // // This code is Copyright (c) 2004 LizardTech, Inc, 1008 Western Avenue, // // Suite 200, Seattle, WA 98104. Unauthorized use or distribution // // prohibited. Access to and use of this code is permitted only under // // license from LizardTech, Inc. Portions of the code are protected by // // US and foreign patents and other filings. All Rights Reserved. // // // ////////////////////////////////////////////////////////////////////////// */ /* PUBLIC */ #ifndef MG3COMPOSITEIMAGEREADER_H #define MG3COMPOSITEIMAGEREADER_H // lt_lib_mrsid_mrsidReaders #include "MrSIDImageReaderBase.h" // lt_lib_mrsid_core #include "lti_imageStageManager.h" LT_BEGIN_NAMESPACE(LizardTech) #if defined(LT_COMPILER_MS) #pragma warning(push,4) #endif class MG3Container; class MG3SingleImageReader; class MG2ImageReader; /** * reader for MrSID/MG3 images * * This class supports reading MrSID/MG3 images. * * @note MrSID/MG2 images are not supported with this class. */ class MG3CompositeImageReader : public MrSIDImageReaderBase, public LTIImageStageManager { public: /** * constructor * * Create an MG3 reader from the given file. * * The \a imageNumber array allows for control over * which tiles in the image should be opened to form * the composite (mosaic) image. If NULL is passed, * all tiles will be used. * * To determine the tiles available in the image, * you can use the static getCompositeImageInfo() * member function. * * @param fileSpec file containing MrSID image * @param imageNumber array of image tile numbers * @param numImages size of \a imageNumber array * @param useWorldFile incorporate world file data when reading image * @param memoryUsage control memory resource usage * @param streamUsage control stream resource usage */ MG3CompositeImageReader(const LTFileSpec& fileSpec, const lt_uint32* imageNumber, lt_uint32 numImages, bool useWorldFile, MrSIDMemoryUsage memoryUsage, MrSIDStreamUsage streamUsage); /** * constructor * * Construct an MG3 image from a stream. (See file-based * constructor for details.) * * @param stream stream containing MrSID image (may not be NULL) * @param imageNumber array of image tile numbers * @param numImages size of \a imageNumber array * @param worldFileStream stream containing world file data (may be NULL) * @param memoryUsage control memory resource usage * @param streamUsage control stream resource usage */ MG3CompositeImageReader(LTIOStreamInf* stream, const lt_uint32* imageNumber, lt_uint32 numImages, LTIOStreamInf* worldFileStream, MrSIDMemoryUsage memoryUsage, MrSIDStreamUsage streamUsage); MG3CompositeImageReader(MG3Container* container, const lt_uint32* imageNumber, lt_uint32 numImages, LTIOStreamInf* worldFileStream, MrSIDMemoryUsage memoryUsage, MrSIDStreamUsage streamUsage); virtual ~MG3CompositeImageReader(); LT_STATUS initialize(); LT_STATUS setStripHeight(lt_uint32 stripHeight); lt_uint32 getStripHeight() const; lt_uint8 getNumLevels() const; bool isLocked() const; void getVersion(lt_uint8& major, lt_uint8& minor, lt_uint8& tweak, char& letter) const; /** * query if is optimizable * * Returns true if and only if the image can be further compressed. * * @return true, if and only if the image may be compressed */ bool isOptimizable() const; /** * tile type queries * * This function are used to determine whether any of the tiles * in the image are MG2. */ /*@{*/ bool hasMG2Data() const; /*@}*/ lt_uint32 getMinBlockSize() const; lt_uint32 getMaxBlockSize() const; void setInterruptDelegate(LTIInterruptDelegate* delegate); lt_int64 getPhysicalFileSize() const; /** * file format type of image tile */ enum CompositeImageType { COMPOSITETYPE_MG2 = 1, COMPOSITETYPE_MG3 = 2 }; /** * structure representing tiled image */ struct CompositeImageInfo { /** image tile number */ lt_uint32 imageId; /** x-position of tile in the mosaic */ double xPos; /** y-position of tile in the mosaic */ double yPos; /** type of image tile */ CompositeImageType imageType; }; /** * query tile information * * This function is used to collect information about the tiles in the * image. * * The caller takes ownership of the returned \a tileInfo array. * * @param tileInfo array of tile information structures to be set * @param numTiles number of tiles * @return status code indicating success or failure */ LT_STATUS getTileInfo(CompositeImageInfo *&tileInfo, lt_uint32 &numTiles) const; /** * query tile information * * This function is used to collect information about the tiles in * the image contained in the given file. * * The caller takes ownership of the returned \a info array. * * @param fileSpec name of image to query * @param tileInfo array of tile information structures to be set * @param numTiles number of tiles * @return status code indicating success or failure */ static LT_STATUS getCompositeImageInfo(const LTFileSpec &fileSpec, CompositeImageInfo *&tileInfo, lt_uint32 &numTiles); /** * query tile information * * This function is used to collect information about the tiles in * the image contained in the given stream. * * The caller takes ownership of the returned \a info array. * * @param stream stream containing image to query * @param tileInfo array of tile information structures to be set * @param numTiles number of tiles * @return status code indicating success or failure */ static LT_STATUS getCompositeImageInfo(LTIOStreamInf &stream, CompositeImageInfo *&tileInfo, lt_uint32 &numTiles); static LT_STATUS getCompositeImageInfo(const MG3Container &container, CompositeImageInfo *&tileInfo, lt_uint32 &numTiles); bool getReaderScene(lt_uint32 imageIndex, const LTIScene &scene, LTIScene &mosaicScene, LTIScene &readerScene) const; LT_STATUS projectPointAtMag(double upperLeft, double mag, double& newUpperLeft) const; LT_STATUS projectDimAtMag(double dim, double mag, double& newDim) const; LT_STATUS getDimsAtMag(double mag, lt_uint32& width, lt_uint32& height) const; protected: LT_STATUS decodeBegin(const LTIScene& scene); LT_STATUS decodeStrip(LTISceneBuffer& stripBuffer, const LTIScene& stripScene); LT_STATUS decodeEnd(); LT_STATUS init(void); virtual LT_STATUS createMG2Reader(lt_uint32 imageNumber, MG2ImageReader *&mg2Reader); virtual LT_STATUS createMG3Reader(lt_uint32 imageNumber, MG3SingleImageReader *&mg3Reader); virtual LT_STATUS updateMemoryModel(); LT_STATUS createImageStage(lt_uint32 imageNumber, LTIImageStage *&imageStage); LT_STATUS deleteImageStage(lt_uint32 imageNumber, LTIImageStage *imageStage); struct Data; Data *m_dat; private: typedef MrSIDImageReaderBase Super; // nope MG3CompositeImageReader(const MG3CompositeImageReader&); MG3CompositeImageReader& operator=(const MG3CompositeImageReader&); }; LT_END_NAMESPACE(LizardTech) #if defined(LT_COMPILER_MS) #pragma warning(pop) #endif #endif // MG3COMPOSITEIMAGEREADER_H
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 272 ] ] ]
e0b8d00a8d2430f9c0722ab9c94e7f6af458b2b2
829192b59a3c7a8451aad6d3079dd2a4b99f4aeb
/codigo/elemento.h
6b20f370d432198bdfd5ea8e41ba1fd85fd2a8dc
[]
no_license
ctkawa/edexplorer
fcafe7111374e3a6c2f65d91f949672b9d1bf31c
7ff76cd4139b0b7dd127dd48a5c9cc7ee7cab66a
refs/heads/master
2021-01-10T12:44:37.012917
2011-06-07T21:00:03
2011-06-07T21:00:03
43,203,499
1
1
null
null
null
null
UTF-8
C++
false
false
580
h
#ifndef ELEMENTO_H #define ELEMENTO_H #include <iostream> /* Sobrecarregar operacoes ==,... */ using namespace std; class elemento { friend ostream &operator<<(ostream &, elemento); private: int valor; public: elemento(); elemento(int); elemento(const elemento&); virtual ~elemento(); void setValor(int); int getValor() const; bool operator==(elemento const &); bool operator!=(elemento const &); elemento& operator=(int); bool operator<(elemento const &); bool operator>(elemento const &); }; #endif // ELEMENTO_H
[ "[email protected]", "ctkawa@04c4bf83-96d4-3932-496e-5ed035fafcdf", "[email protected]", "[email protected]" ]
[ [ [ 1, 4 ], [ 6, 10 ], [ 26, 30 ] ], [ [ 5, 5 ] ], [ [ 11, 21 ], [ 23, 25 ] ], [ [ 22, 22 ] ] ]
809ac69d1a406f715403c2489a89183b5565b236
ce28ec891a0d502e7461fd121b4d96a308c9dab7
/sql/SQLConnectionDescription.h
5d2e25be137783493b557cdad92ebae563988879
[]
no_license
aktau/Tangerine
fe84f6578ce918d1fa151138c0cc5780161b3b8f
179ac9901513f90b17c5cd4add35608a7101055b
refs/heads/master
2020-06-08T17:07:53.860642
2011-08-14T09:41:41
2011-08-14T09:41:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,323
h
#ifndef SQLCONNECTIONDESCRIPTION_H_ #define SQLCONNECTIONDESCRIPTION_H_ #include <QString> #include <QFile> #include <QDomDocument> #include <QDebug> #define DBD_DOCTYPE "thera-database" #define DBD_ROOTTAG "connect" #define DBD_LASTVERSION "1.0" #define DBD_TYPE "type" #define DBD_HOST "host" #define DBD_PORT "port" #define DBD_DBNAME "dbname" #define DBD_USER "user" #define DBD_PASS "password" class SQLConnectionDescription { public: typedef enum { MYSQL, SQLITE, POSTGRESQL, NUM_DB_TYPES } DbType; public: SQLConnectionDescription(const QString& file); SQLConnectionDescription(SQLConnectionDescription::DbType _type, const QString& _host, int _port, const QString& _dbname, const QString& _user, const QString& _password); SQLConnectionDescription(SQLConnectionDescription::DbType _type, const QString& sqliteFile); // this is for an SQLite, specifying any other DbType will result in an isValid() being false static QString dbTypeToString(SQLConnectionDescription::DbType type); static SQLConnectionDescription::DbType dbStringToType(const QString& type); bool save(const QString& file) const; bool load(const QString& file); bool isValid() const { return mValid; } SQLConnectionDescription::DbType getType() const { return type; } QString getHost() const { return host; } int getPort() const { return port; } QString getDbname() const { return dbname; } QString getUser() const { return user; } QString getPassword() const { return password; } QString getConnectionName() const { return (type == SQLITE) ? dbname : (host + ":" + QString::number(port) + "/" + dbname); } private: DbType type; QString host; int port; QString dbname; QString user; QString password; bool mValid; }; SQLConnectionDescription::SQLConnectionDescription(const QString& file) : mValid(false) { load(file); } SQLConnectionDescription::SQLConnectionDescription(SQLConnectionDescription::DbType _type, const QString& _host, int _port, const QString& _dbname, const QString& _user, const QString& _password) : type(_type), host(_host), port(_port), dbname(_dbname), user(_user), password(_password), mValid(true) { } SQLConnectionDescription::SQLConnectionDescription(SQLConnectionDescription::DbType _type, const QString& sqliteFile) : type(_type), dbname(sqliteFile), mValid(false) { if (type == SQLITE) mValid = true; } QString SQLConnectionDescription::dbTypeToString(SQLConnectionDescription::DbType type) { switch (type) { case MYSQL: return "MySQL"; case POSTGRESQL: return "PostgreSQL"; default: return "UNKNOWN_DB_TYPE"; } } SQLConnectionDescription::DbType SQLConnectionDescription::dbStringToType(const QString& type) { QString uType = type.toUpper(); if (uType == "MYSQL") { return MYSQL; } else if (uType == "POSTGRESQL") { return POSTGRESQL; } else { return NUM_DB_TYPES; } } bool SQLConnectionDescription::save(const QString& filename) const { assert(type != SQLITE); QFile file(filename); if (file.exists()) { qDebug() << "SQLConnectionDescription::save: Overwriting" << filename; } if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QTextStream out(&file); QDomDocument doc(DBD_DOCTYPE); QDomElement options = doc.createElement(DBD_ROOTTAG); options.setAttribute("version", DBD_LASTVERSION); { QDomElement option(doc.createElement(DBD_TYPE)); option.appendChild(doc.createTextNode(dbTypeToString(type))); options.appendChild(option); } { QDomElement option(doc.createElement(DBD_HOST)); option.appendChild(doc.createTextNode(host)); options.appendChild(option); } { QDomElement option(doc.createElement(DBD_PORT)); option.appendChild(doc.createTextNode(QString::number(port))); options.appendChild(option); } { QDomElement option(doc.createElement(DBD_DBNAME)); option.appendChild(doc.createTextNode(dbname)); options.appendChild(option); } { QDomElement option(doc.createElement(DBD_USER)); option.appendChild(doc.createTextNode(user)); options.appendChild(option); } { QDomElement option(doc.createElement(DBD_PASS)); option.appendChild(doc.createTextNode(password)); options.appendChild(option); } doc.appendChild(options); doc.save(out, 1); file.close(); } else { qDebug() << "SQLConnectionDescription::save: Could not open" << filename; return false; } return true; } bool SQLConnectionDescription::load(const QString& filename) { QFile file(filename); QFileInfo fileinfo(file); if (fileinfo.suffix() == "db") { // SQLite databases have the .db suffix, they are not XML files and the database name is // taken as equal to the filename (Qt convention) // it's not imporant whether the file exists or not, since it will be created if it doesn't // in the QSqlDatabase::open() call type = SQLITE; dbname = filename; return mValid = true; } if (!file.exists()) { qDebug("SQLConnectionDescription::load: file %s did not exist", qPrintable(filename)); return mValid = false; } // open the file in read-only mode if (file.open(QIODevice::ReadOnly)) { QDomDocument doc; bool succes = doc.setContent(&file); file.close(); if (succes) { QDomElement root(doc.documentElement()); for (QDomElement option = root.firstChildElement(); !option.isNull(); option = option.nextSiblingElement()) { if (option.tagName() == DBD_TYPE) type = dbStringToType(option.text()); if (option.tagName() == DBD_HOST) host = option.text(); if (option.tagName() == DBD_PORT) port = option.text().toInt(); if (option.tagName() == DBD_DBNAME) dbname = option.text(); if (option.tagName() == DBD_USER) user = option.text(); if (option.tagName() == DBD_PASS) password = option.text(); } } else { qDebug() << "SQLConnectionDescription::load: Reading XML file" << filename << "failed"; return mValid = false; } } else { qDebug() << "SQLConnectionDescription::load: Could not open" << filename; return mValid = false; } return mValid = true; } #endif /* SQLCONNECTIONDESCRIPTION_H_ */
[ [ [ 1, 224 ] ] ]
67b206e2f1b1eace539009cf9b62ccf8bf54420a
559770fbf0654bc0aecc0f8eb33843cbfb5834d9
/haina/codes/beluga/client/symbian/SQLite60/group/sqlitetest.uid.cpp
005096b36b621bcdc88298c28763b469053ccaa8
[]
no_license
CMGeorge/haina
21126c70c8c143ca78b576e1ddf352c3d73ad525
c68565d4bf43415c4542963cfcbd58922157c51a
refs/heads/master
2021-01-11T07:07:16.089036
2010-08-18T09:25:07
2010-08-18T09:25:07
49,005,284
1
0
null
null
null
null
UTF-8
C++
false
false
189
cpp
#include <e32cmn.h> #pragma data_seg(".SYMBIAN") __EMULATOR_IMAGE_HEADER2(0x1000007a,0x100039ce,0xa000029f,EPriorityForeground,0xBF030u,0x00000000u,0xA000029F,0,0,0) #pragma data_seg()
[ "shaochuan.yang@6c45ac76-16e4-11de-9d52-39b120432c5d" ]
[ [ [ 1, 4 ] ] ]
46045ddc76bfb40964f3fed0aba341e610162e3e
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaProtocol/ResponseMessageFactory.hpp
a1c3f86c2655f176d1731208bd4ec5f7583fe6e0
[]
no_license
pazuzu156/Enigma
9a0aaf0cd426607bb981eb46f5baa7f05b66c21f
b8a4dfbd0df206e48072259dbbfcc85845caad76
refs/heads/master
2020-06-06T07:33:46.385396
2011-12-19T03:14:15
2011-12-19T03:14:15
3,023,618
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,478
hpp
#ifndef RESPONSEMESSAGEFACTORY_HPP_INCLUDED #define RESPONSEMESSAGEFACTORY_HPP_INCLUDED /* Copyright © 2009 Christopher Joseph Dean Schaefer (disks86) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "Message.hpp" #include "Messages/MessageContainer.hpp" namespace Enigma { class DllExport ResponseMessageFactory { private: static const size_t MESSAGE_TYPE=0; static const size_t MESSAGE_LENGTH=1; protected: public: ResponseMessageFactory(); ~ResponseMessageFactory(); MessageContainer* CreateMessage(Message& message); }; }; #endif // RESPONSEMESSAGEFACTORY_HPP_INCLUDED
[ [ [ 1, 39 ] ] ]
fc83e211bd4b709bd94b8666b0761a4a2f782fdf
bfe8eca44c0fca696a0031a98037f19a9938dd26
/DDEPrint/MFCDDE.H
66051bd54821caca76117117a913a2c08a634e18
[]
no_license
luge/foolject
a190006bc0ed693f685f3a8287ea15b1fe631744
2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c
refs/heads/master
2021-01-10T07:41:06.726526
2011-01-21T10:25:22
2011-01-21T10:25:22
36,303,977
0
0
null
null
null
null
UTF-8
C++
false
false
4,008
h
/* * File: mfcdde.h * Purpose: MFC DDE classes * Author: Julian Smart */ #ifndef MFCDDEH #define MFCDDEH #include <ddeml.h> /* * Mini-DDE implementation Most transactions involve a topic name and an item name (choose these as befits your application). A client can: - ask the server to execute commands (data) associated with a topic - request data from server by topic and item - poke data into the server - ask the server to start an advice loop on topic/item - ask the server to stop an advice loop A server can: - respond to execute, request, poke and advice start/stop - send advise data to client Note that this limits the server in the ways it can send data to the client, i.e. it can't send unsolicited information. * */ class CDDEServer; class CDDEClient; class CDDEConnection: public CObject { public: char *buf_ptr; CString topic_name; int buf_size; CDDEServer *server; CDDEClient *client; HCONV hConv; char *sending_data; int data_size; int data_type; CDDEConnection(char *buffer, int size); CDDEConnection(void); ~CDDEConnection(void); // Calls that CLIENT can make virtual BOOL Execute(char *data, int size = -1, int format = CF_TEXT); virtual BOOL Execute(const CString& str) { return Execute((char *)(const char *)str, -1, CF_TEXT); } virtual char *Request(const CString& item, int *size = NULL, int format = CF_TEXT); virtual BOOL Poke(const CString& item, char *data, int size = -1, int format = CF_TEXT); virtual BOOL StartAdvise(const CString& item); virtual BOOL StopAdvise(const CString& item); // Calls that SERVER can make virtual BOOL Advise(const CString& item, char *data, int size = -1, int format = CF_TEXT); // Calls that both can make virtual BOOL Disconnect(void); virtual void Notify(BOOL notify); // Internal use only // Callbacks to SERVER - override at will virtual BOOL OnExecute(const CString& topic, char *data, int size, int format) { return FALSE; }; virtual char *OnRequest(const CString& topic, const CString& item, int *size, int format) { return NULL; }; virtual BOOL OnPoke(const CString& topic, const CString& item, char *data, int size, int format) { return FALSE; }; virtual BOOL OnStartAdvise(const CString& topic, const CString& item) { return FALSE; }; virtual BOOL OnStopAdvise(const CString& topic, const CString& item) { return FALSE; }; // Callbacks to CLIENT - override at will virtual BOOL OnAdvise(const CString& topic, const CString& item, char *data, int size, int format) { return FALSE; }; // Callbacks to BOTH // Default behaviour is to delete connection and return TRUE virtual BOOL OnDisconnect(void); }; class CDDEObject: public CObject { public: int lastError; CString service_name; // Server only CObList connections; CDDEObject(void); ~CDDEObject(void); // Find/delete CDDEConnection corresponding to the HCONV CDDEConnection *FindConnection(HCONV conv); BOOL DeleteConnection(HCONV conv); }; class CDDEServer: public CDDEObject { public: CDDEServer(void); ~CDDEServer(void); BOOL Create(const CString& server_name); // Returns FALSE if can't create server (e.g. port // number is already in use) virtual CDDEConnection *OnAcceptConnection(const CString& topic); }; class CDDEClient: public CDDEObject { public: CDDEClient(void); ~CDDEClient(void); BOOL ValidHost(const CString& host); virtual CDDEConnection *MakeConnection(const CString& host, const CString& server, const CString& topic); // Call this to make a connection. // Returns NULL if cannot. virtual CDDEConnection *OnMakeConnection(void); // Tailor this to return own connection. }; void DDEInitialize(); void DDECleanUp(); #endif
[ "greatfoolbear@756bb6b0-a119-0410-8338-473b6f1ccd30" ]
[ [ [ 1, 130 ] ] ]
b33ab9738a56011c47932a9adad2c4e0d50ff212
a7985fd90271731c73cab45029ee9a9903c8e1a2
/client/westley.hennigh_cs260/westley.hennigh_cs260/udp.h
c7108f5fd5fd45589a6af4c1dca654bae32c97b9
[]
no_license
WestleyArgentum/cs260-networking
129039f7ad2a89b9350ddcac0cc50a17c6f74bf7
36d2d34400ad93906e2b4839278e4b33de28ae8b
refs/heads/master
2021-01-01T05:47:12.910324
2010-04-07T07:01:40
2010-04-07T07:01:40
32,187,121
0
0
null
null
null
null
UTF-8
C++
false
false
217
h
#ifndef UDP_H #define UDP_H class UDP // Universal Digipen Public drive { public: UDP(char* file_): file(file_){}; void write(void); void read(void); private: char* file; }; #endif
[ "knuxjr@1f2afcba-5144-80f4-e828-afee2f9acc6f" ]
[ [ [ 1, 14 ] ] ]
31d90f467a53798cbe677b29c1714f979b024dcf
465943c5ffac075cd5a617c47fd25adfe496b8b4
/DESTINAT.CPP
1afdaef1bb9a783c4c5b77674f2835a693c05e09
[]
no_license
paulanthonywilson/airtrafficcontrol
7467f9eb577b24b77306709d7b2bad77f1b231b7
6c579362f30ed5f81cabda27033f06e219796427
refs/heads/master
2016-08-08T00:43:32.006519
2009-04-09T21:33:22
2009-04-09T21:33:22
172,292
1
0
null
null
null
null
UTF-8
C++
false
false
545
cpp
/* function definitions for Destination class Paul Wilson 3/4/96 4/4/96 */ # include "Destinat.h" /**************************************************************************/ Destination::Destination ( Position GrndPos_i, int ID_i, const Heading &Dir_i ) : Landmark (GrndPos_i, ID_i), Dir_c (Dir_i) { assert (GrndPos_i.NextMove(Dir_c).inField()); } /**************************************************************************/ Heading Destination::Dir() { return Dir_c; }
[ [ [ 1, 33 ] ] ]
60606b757e9b5d5fb2e50965960a1d89dd070cf0
71d018f8dbcf49cfb07511de5d58d6ad7df816f7
/scistudio/trunk/VIEWANI.H
dc467929623e0de0c77f3142b626bcfeae25019f
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
qq431169079/SciStudio
48225261386402530156fc2fc14ff0cad62174e8
a1fccbdcb423c045078b927e7c275b9d1bcae6b3
refs/heads/master
2020-05-29T13:01:50.800903
2010-09-14T07:10:07
2010-09-14T07:10:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,703
h
//--------------------------------------------------------------------------- #ifndef viewaniH #define viewaniH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ComCtrls.hpp> #include <ExtCtrls.hpp> #include <ToolWin.hpp> #include <ImgList.hpp> //--------------------------------------------------------------------------- class TDlgViewAni : public TForm { __published: // IDE-managed Components TLabel *Label1; TTrackBar *TrackBar1; TPanel *Panel1; TLabel *Label2; TToolBar *ToolBar1; TToolButton *ToolButton1; TToolButton *ToolButton2; TToolButton *ToolButton3; TToolButton *ToolButton4; TTrackBar *TrackBar2; TTimer *Timer1; TImageList *ImageList1; TScrollBox *scbView; TImage *imgView; TShape *shpView; void __fastcall Timer1Timer(TObject *Sender); void __fastcall ToolButton1Click(TObject *Sender); void __fastcall ToolButton2Click(TObject *Sender); void __fastcall ToolButton3Click(TObject *Sender); void __fastcall TrackBar2Change(TObject *Sender); void __fastcall TrackBar1Change(TObject *Sender); void __fastcall FormClose(TObject *Sender, TCloseAction &Action); private: // User declarations public: // User declarations __fastcall TDlgViewAni(TComponent* Owner); sciVIEW *view; sciVIEWLOOP *loop,*realLoop; int Cel,W,H; TWndGfxEdit *ViewEditWin; tPAL *pal; }; //--------------------------------------------------------------------------- extern PACKAGE TDlgViewAni *DlgViewAni; //--------------------------------------------------------------------------- #endif
[ "mageofmarr@d0e240c1-a1d3-4535-ae25-191325aad40e" ]
[ [ [ 1, 52 ] ] ]
bd8217424f19d6af791f97919302ad1bf6bc95e5
5ed707de9f3de6044543886ea91bde39879bfae6
/ASFantasy/ASFIsapi/Source/ASFantasyHtmlServer.cpp
a4d27d909f9cb2515c52069895bb85d033574c46
[]
no_license
grtvd/asifantasysports
9e472632bedeec0f2d734aa798b7ff00148e7f19
76df32c77c76a76078152c77e582faa097f127a8
refs/heads/master
2020-03-19T02:25:23.901618
1999-12-31T16:00:00
2018-05-31T19:48:19
135,627,290
0
0
null
null
null
null
UTF-8
C++
false
false
13,687
cpp
/* ASFantasyHtmlServer.cpp */ /******************************************************************************/ /******************************************************************************/ #include "CBldVCL.h" #pragma hdrstop #include "CommType.h" #include "CommDB.h" #include "PasswordEncode.h" #include "ASMemberDB.h" #include "ASFantasyAppOptions.h" #include "ASFantasyType.h" #include "ASFantasyHtmlServer.h" #include "ASFantasySignupIntroPage.h" #include "ASFantasySignupWhichPage.h" #include "ASFantasyNewMemberSignupPage.h" #include "ASFantasyNewParticSignupPage.h" #if 0 //BOB #include "ParticUpgradePage.h" #include "ParticPremiumTrialPage.h" #endif #include "ASFantasyPickParticPage.h" #include "ASFantasyHubPage.h" #include "ASFantasyCustomPage.h" #include "ASFantasyLeagueSignupPage.h" #include "ASFantasyTeamsPage.h" #include "ASFantasyDraftRankingsPage.h" #include "ASFantasyDraftResultsPage.h" #include "ASFantasySchedulePage.h" #include "ASFantasyLineupPage.h" #include "ASFantasyGameResultsPage.h" #include "ASFantasyStandingsPage.h" #include "ASFantasyFreeAgentPage.h" #include "ASFantasyTradePage.h" #include "ASFantasyPlayoffPage.h" using namespace asmember; namespace asfantasy { /******************************************************************************/ const char* gInvalidPageMsg = "Oops! The page you are requesting is no " "longer valid."; /******************************************************************************/ /******************************************************************************/ ASFantasyHtmlServer::~ASFantasyHtmlServer() { //BOB CloseDatabase(fDatabase); } /******************************************************************************/ void ASFantasyHtmlServer::buildPage(const char* pageName) { THtmlPageOptions& pageOptions = getPageOptions(); THTMLWriter htmlWriter(fContent.get()); TMemberID memberID; ASFantasyBasePageHtmlViewPtr pageHtmlViewPtr; int htmlPageID; if(InSystemMaintMode()) { CStrVar msg; msg.copy("Sorry, "); msg.concat(pageOptions.getAppNameAbbr()); msg.concat(" is currently in system maintenance mode and, as a " "result, your request cannot be fulfilled.\r\n\r\nThe system " "should be back up again shortly.\r\n\r\nThank you."); pageHtmlViewPtr = createMessagePage(pageOptions,htmlWriter,false,msg); pageHtmlViewPtr->process(); return; } OpenDatabase(MemberDatabaseName()); OpenDatabase(MemberMiscDatabaseName()); OpenDatabase(PrimaryDatabaseName()); try { setUpPageOptions(); fContent->Position = 0; if(getQuery().len() == 0) { pageHtmlViewPtr = createMessagePage(pageOptions,htmlWriter,true, "Unknown Request."); pageHtmlViewPtr->process(); } else { try { htmlPageID = pageOptions.getPageLinkInfoEnum(pageName); } catch(...) { CommErrMsg(cel_Warning,"ASFantasyHtmlServer::buildPage: " "Invalid Page(%s)",pageName); pageHtmlViewPtr = createMessagePage(pageOptions,htmlWriter, true,gInvalidPageMsg); pageHtmlViewPtr->process(); return; } // If Partic is already set, make sure it is current if(pageOptions.isRqstParticSet()) if(!determineRqstParticActive(htmlWriter)) return; // If Hub page was selected without a User, determine who User should be. if((htmlPageID == htmlHubPage) && !pageOptions.isRqstParticSet()) if(!determineRqstPartic(htmlWriter)) return; determineGameView(); { const THTMLPageLinkInfo& pageLinkInfo = pageOptions.getPageLinkInfo(htmlPageID); if(pageLinkInfo.IsMemberNeeded()) { if(!pageOptions.isRqstMemberSet()) throw ASIException("ASFantasyHtmlServer::buildPage: attempting to access a secured page"); } if(pageLinkInfo.IsParticNeeded()) { if(!pageOptions.isRqstParticSet()) throw ASIException("ASFantasyHtmlServer::buildPage: user required to access page"); if(!determineRqstParticActive(htmlWriter)) return; } } pageHtmlViewPtr = createNewPage(htmlPageID,pageOptions,htmlWriter); pageHtmlViewPtr->process(); } return; } catch(MemberParticMismatchException&) { } buildMemberParticMismatchPage(htmlWriter); } /******************************************************************************/ ASFantasyBasePageHtmlViewPtr ASFantasyHtmlServer::createMessagePage( THtmlPageOptions& pageOptions,THTMLWriter& htmlWriter,const bool isError, const char* message) { if(isError) return(ASFantasyBasePageHtmlViewPtr(new TErrorPageHtmlView(*this, pageOptions,htmlWriter,message))); return(ASFantasyBasePageHtmlViewPtr(new TMessagePageHtmlView(*this, pageOptions,htmlWriter,message))); } /******************************************************************************/ ASFantasyBasePageHtmlViewPtr ASFantasyHtmlServer::createNewPage(int htmlPage, THtmlPageOptions& pageOptions,THTMLWriter& htmlWriter) { if(htmlPage == htmlSignupIntroGetPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasySignupIntroGetPage( *this,pageOptions,htmlWriter))); if(htmlPage == htmlSignupWhichGetPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasySignupWhichGetPage( *this,pageOptions,htmlWriter))); if(htmlPage == htmlNewMemberSignupPremiumGetPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyNewMemberSignupPremiumGetPage( *this,pageOptions,htmlWriter))); if(htmlPage == htmlNewMemberSignupPostPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyNewMemberSignupPostPage( *this,pageOptions,htmlWriter))); if(htmlPage == htmlNewParticSignupPremiumGetPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyNewParticSignupPremiumGetPage( *this,pageOptions,htmlWriter))); if(htmlPage == htmlNewParticSignupPostPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyNewParticSignupPostPage( *this,pageOptions,htmlWriter))); if(htmlPage == htmlHubPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyHubPageHtmlView(*this, pageOptions,htmlWriter))); if(htmlPage == htmlCustomPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyCustomPageHtmlView(*this, pageOptions,htmlWriter))); if(htmlPage == htmlLeagueSignupPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyLeagueSignupPageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlTeamsPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyTeamsPageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlDraftRankingsPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyDraftRankingsPageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlDraftResultsPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyDraftResultsPageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlSchedulePage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasySchedulePageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlLineupPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyLineupPageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlGameResultsPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyGameResultsPageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlStandingsPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyStandingsPageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlFreeAgentPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyFreeAgentPageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlTradePage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyTradePageHtmlView( *this,pageOptions,htmlWriter))); if(htmlPage == htmlPlayoffPage) return(ASFantasyBasePageHtmlViewPtr(new ASFantasyPlayoffPageHtmlView( *this,pageOptions,htmlWriter))); CommErrMsg(cel_Error,"ASFantasyHtmlServer::createNewPage: unknown page(%d)", htmlPage); return(createMessagePage(pageOptions,htmlWriter,true,gInvalidPageMsg)); } /******************************************************************************/ void ASFantasyHtmlServer::setUpPageOptions() { THtmlPageOptions& pageOptions = getPageOptions(); TMemberID memberID; TParticID particID; TPassword password; TEncodedParticID user; CStrVar tempStr; tempStr = getStringField("Backdoor",cam_MayNotExist); if(tempStr.hasLen()) pageOptions.setBackdoorAccess(TBooleanType(tempStr)); memberID = getEnvVar(EnvVarRemoteUser).c_str(); if(!memberID.isUndefined()) pageOptions.setRqstMemberID(memberID); user = getStringField(gURLUserFieldStr,cam_MayNotExist).c_str(); if(user.Len() > 0) { TPartic::decodeParticID(user, particID, password); pageOptions.setRqstPartic(particID,password); } } /******************************************************************************/ void ASFantasyHtmlServer::determineGameView() { THtmlPageOptions& pageOptions = getPageOptions(); // Determine Season or Draft View if(pageOptions.isRqstLeagueSet()) { TLeaguePtr leaguePtr = pageOptions.getRqstLeague(); TGamePhase gamePhase = leaguePtr->getGamePhase(); if((gamePhase != gmph_Enrollment) && (gamePhase != gmph_PreDraft) && (gamePhase != gmph_Draft)) pageOptions.setSeasonView(true); } } /******************************************************************************/ /* Fetched all Partics for Member. If one is found then, RqstPartic is set. If multiple are found, the PickParticPage is built. Returning false means page has already been built and caller should not build a page. */ bool ASFantasyHtmlServer::determineRqstPartic(THTMLWriter& htmlWriter) { THtmlPageOptions& pageOptions = getPageOptions(); ASFantasyBasePageHtmlViewPtr pageHtmlViewPtr; TMemberID memberID; TParticVector particVector; if(!pageOptions.isRqstMemberSet()) throw ASIException("ASFantasyHtmlServer::determineRqstPartic: attempting to access a secured page"); memberID = pageOptions.getRqstMemberID(); LoadParticVectorByMemberIDGameID(memberID,CurrentGameID(),particVector); if(particVector.size() == 1) { TParticPtr particPtr = *particVector.begin(); pageOptions.setRqstPartic(particPtr->getParticID(),particPtr->getPassword()); } else { pageHtmlViewPtr = ASFantasyBasePageHtmlViewPtr( new ASFantasyPickParticPageHtmlView(*this,pageOptions,htmlWriter, particVector)); pageHtmlViewPtr->process(); return(false); } return(true); } /******************************************************************************/ bool ASFantasyHtmlServer::determineRqstParticActive(THTMLWriter& htmlWriter) { THtmlPageOptions& pageOptions = getPageOptions(); TParticPtr particPtr = pageOptions.getRqstPartic(); ASFantasyBasePageHtmlViewPtr pageHtmlViewPtr; CStrVar msg; bool isError = false; if((particPtr->getStatus() == pts_Disabled) || (particPtr->getStatus() == pts_GameOver) || (particPtr->getGameID() != CurrentGameID())) { if(particPtr->getGameID() != CurrentGameID()) { CommErrMsg(cel_Warning,"ASFantasyHtmlServer::determineRqstParticActive: " "Accessing old ParticID(%s)",particPtr->getParticID().c_str()); msg.copyVarg(gInvalidPageMsg); isError = true; } else if(particPtr->getStatus() == pts_Disabled) { msg.copyVarg("ALERT! Your %s account has been disabled.", pageOptions.getAppNameAbbr().c_str()); isError = true; } else { msg.copyVarg("The %s season is complete and access to your team " "is no longer available.\r\n\r\nThanks for playing. See you " "next year.",pageOptions.getAppNameAbbr().c_str()); } pageHtmlViewPtr = createMessagePage(pageOptions,htmlWriter,isError,msg); pageHtmlViewPtr->process(); return(false); } return(true); } /******************************************************************************/ void ASFantasyHtmlServer::buildMemberParticMismatchPage(THTMLWriter& htmlWriter) { THtmlPageOptions& pageOptions = getPageOptions(); ASFantasyBasePageHtmlViewPtr pageHtmlViewPtr; TMemberID loggedInMemberID; TMemberID particMemberID; TEncodedParticID user; TParticPtr particPtr; CStrVar msg; loggedInMemberID = getEnvVar(EnvVarRemoteUser).c_str(); if(loggedInMemberID.isUndefined()) throw ASIException("ASFantasyHtmlServer::buildMemberParticMismatchPage: loggedInMemberID.isUndefined()"); loggedInMemberID.ToUpper(); user = getStringField(gURLUserFieldStr,cam_MayNotExist).c_str(); if(user.Len() > 0) particPtr = TPartic::createGetByEncoded(user,cam_MustExist); else throw ASIException("ASFantasyHtmlServer::buildMemberParticMismatchPage: user.Len() == 0"); particMemberID = particPtr->getMemberID(); particMemberID.ToUpper(); msg.copy("Error: You are attempting to access information for User \""); msg.concat(particMemberID.c_str()); msg.concat("\" but you are logged in as User \""); msg.concat(loggedInMemberID.c_str()); msg.concat("\".\r\n\r\n"); msg.concat("You must restart your browser and re-login as User \""); msg.concat(particMemberID.c_str()); msg.concat("\"."); pageHtmlViewPtr = createMessagePage(pageOptions,htmlWriter,true,msg); pageHtmlViewPtr->process(); } /******************************************************************************/ }; //namespace asfantasy /******************************************************************************/ /******************************************************************************/
[ [ [ 1, 435 ] ] ]
2541e787acc9ce0eccec1187c9bda54585b512fc
822ab63b75d4d4e2925f97b9360a1b718b5321bc
/KSegmentView/ksegmentview.cpp
72e5d55242f20531a75f09bf55c8f6d70eddd62a
[]
no_license
sriks/decii
71e4becff5c30e77da8f87a56383e02d48b78b28
02c58fbaea69c2448249710d13f2e774762da2c3
refs/heads/master
2020-05-17T23:03:27.822905
2011-12-16T07:29:38
2011-12-16T07:29:38
32,251,281
0
0
null
null
null
null
UTF-8
C++
false
false
3,544
cpp
/* * Author: Srikanth Sombhatla * Copyright 2010 Konylabs. All rights reserved. * */ #include <QGraphicsScene> #include <QGraphicsSceneMouseEvent> #include <QGraphicsLinearLayout> #include <QGraphicsWidget> #include <QGestureEvent> #include <QPanGesture> #include <QDebug> #include "ksegment.h" #include "ksegmentwidget.h" #include "ksegmentview.h" /*! \class KSegmentView \brief A QGraphicsView derived class which encapsulates a container with a layout to hold segments. \ref KSegment, KSegmentWidget or any QGraphicsWidget can be added to this view. Internally this view has a container which is a \ref KSegment. Hence a \ref KSegment or \ref KSegmentWidget can be added directly into this view, which inturn arranges the items in the order in which they are added. \section usage Usage \code KSegment* labelSegment = new KSegment(Qt::Vertical); labelSegment->layout()->setSpacing(0); labelSegment->addItem(new QGraphicsTextItem("Title")); labelSegment->addItem(new QGraphicsTextItem("Subtitle")); KSegment* buttonSegment = new KSegment(Qt::Vertical); buttonSegment->layout()->setSpacing(10); buttonSegment->addItem(new QPushButton("Upload")); QPushButton* removeButton = new QPushButton("Remove"); buttonSegment->addItem(removeButton); // Now add all segments to a segment widget. // KSegmentWidget* segmentWidget = new KSegmentWidget(Qt::Horizontal); // Segments apppear in the order in which they are added. segmentWidget->addItem(labelSegment); segmentWidget->addItem(buttonSegment); KSegmentView segmentView = new KSegmentView(Qt::Vertical); segmentView->addSegmentWidget(segmentWidget); \endcode \sa QGraphicsView QGraphicsWidget KSegment KSegmentWidget **/ KSegmentView::KSegmentView(Qt::Orientation aOrientation,QWidget *aParent) : QGraphicsView(aParent) { QGraphicsScene* s = new QGraphicsScene; setScene(s); mContainer = new KSegment(aOrientation); mContainer->setObjectName("container"); mContainer->setPos(0,0); scene()->addItem(mContainer); // ownership is transferred to scene setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } /*! Adds a \ref KSegmentWidget to this view. Ownership is transferred. Since \ref KSegmentWidget has a visual appearance, once it is added the size policy is set so that it can grow horizontally, but fixed vertically. This is required for vertical layout since removing an item makes other items to grow vertically. \sa addSegment **/ void KSegmentView::addSegmentWidget(KSegmentWidget* aSegmentWidget) { aSegmentWidget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); aSegmentWidget->setParentContainer(mContainer->layout()); mContainer->addItem(aSegmentWidget); } /*! Adds a \ref KSegment to this view. Ownership is transferred. Use this method to add a \ref KSegmentWidget with a defined sizepolicy. It is always a good practice to define the sizepolicy of items so that they are resized when other items in the layout are removed. By default, a layout tries to resize the items to fit the layout area. \sa addSegmentWidget **/ void KSegmentView::addSegment(KSegment* aSegment) { mContainer->addItem(aSegment); } void KSegmentView::resizeEvent(QResizeEvent *event) { qDebug()<<__PRETTY_FUNCTION__; } // eof
[ "srikanthsombhatla@016151e7-202e-141d-2e90-f2560e693586" ]
[ [ [ 1, 98 ] ] ]
57e0ded7fdc3b96247bfeab9a2dff98355d1f548
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/preprocessed/src/apply_wrap.cpp
9a2c46733e7538eb52edd3789ce9ce957445ffe2
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
// Copyright Aleksey Gurtovoy 2002-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/boost/boost/libs/mpl/preprocessed/src/apply_wrap.cpp,v $ // $Date: 2006/06/12 05:11:54 $ // $Revision: 1.3.8.1 $ #define BOOST_MPL_PREPROCESSING_MODE #include <boost/config.hpp> #include <boost/mpl/apply_wrap.hpp>
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 16 ] ] ]
d9ffc4075bb411632dc2e5a8b11ceaffb2bd3f0d
edc1580926ff41a9c4e1eb1862bbdd7ce7fa46f9
/IMesh/IMesh.UI/stdafx.cpp
c6a6773f84be4c52b6bf09db3ec239f2f07158bb
[]
no_license
bolitt/imesh-thu
40209b89393981fa6bd6ed3c7f5cc367829bd913
477204edee0f387e92eec5e92283fb4233cbdcb3
refs/heads/master
2021-01-01T05:31:36.652001
2010-12-26T14:35:28
2010-12-26T14:35:28
32,119,789
0
0
null
null
null
null
GB18030
C++
false
false
168
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // IMesh.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "bolitt@13b8c736-bc73-099a-6f45-29f97c997e63" ]
[ [ [ 1, 8 ] ] ]
d5b52aa28648f0ef44f2fd13cf5ce476c8495f51
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/src/sao/Scheduler.h
9b4f130c5f4cc740946c3cd6f27784a20e9cfd68
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UHC
C++
false
false
1,426
h
#ifndef NSRPC_SAO_SCHEDULER_H #define NSRPC_SAO_SCHEDULER_H #ifdef _MSC_VER # pragma once #endif #pragma warning ( push ) #pragma warning ( disable: 4251 4800 4996 ) #include <ace/Task.h> #pragma warning ( pop ) #include <queue> #include <ctime> namespace nsrpc { namespace sao { class MethodRequest; class ProcessorCallback; /** * @class Scheduler * * 클라이언트의 요청을 처리하기 위한 Task */ class Scheduler : private ACE_Task_Base { typedef std::queue<MethodRequest*> RpcMethodQueue; public: Scheduler(ProcessorCallback* callback) : callback_(callback), stop_(false), available_(lock_), lastLogTime_(time(0)), prevQueueSize_(0) {} virtual ~Scheduler(); bool start(); void stop(); /// Method queue를 비운다 void flush(); void schedule(MethodRequest* request); private: MethodRequest* getRpcMethod(); MethodRequest* getRpcMethod_i(); int getRequestQueueSize(); private: // = ACE_Task_Base overring virtual int svc(); private: ProcessorCallback* callback_; RpcMethodQueue requestQueue_; volatile bool stop_; ACE_Thread_Mutex lock_; ACE_Condition_Thread_Mutex available_; time_t lastLogTime_; size_t prevQueueSize_; }; } // namespace sao } // namespace nsrpc #endif // NSRPC_SAO_SCHEDULER_H
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 74 ] ] ]
f106cebb8bc23e7d96507859be39844b749515f8
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/src/p2p/P2pPacketCoder.h
12c637d2153beb52fcf62fa294411a16da415652
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,583
h
#ifndef NSRPC_P2PPACKETCODER_H #define NSRPC_P2PPACKETCODER_H #ifdef _MSC_VER # pragma once #endif #include <nsrpc/p2p/P2pConfig.h> #include <nsrpc/detail/PacketCoder.h> #include <nsrpc/p2p/detail/P2pProtocol.h> namespace nsrpc { /** @addtogroup protocol * @{ */ /** * @class P2pPacketCoder * P2P Àü¿ë PacketCoder */ class P2pPacketCoder : public PacketCoder { enum { defaultPacketSize = (P2pConfig::defaultMtu * 2), defaultPacketPoolSize = 10 }; public: virtual ~P2pPacketCoder() {} virtual void reset() {} virtual void setEncryptSeed(const Seed& /*seed*/) {} virtual void setDecryptSeed(const Seed& /*seed*/) {} virtual void generateCipherSeed(Seed& encryptSeed, Seed& decryptSeed) const { encryptSeed.clear(); decryptSeed.clear(); } virtual void extendCipherKeyTimeLimit() {} virtual size_t getHeaderSize() const { return P2pPacketHeader::getHeaderSize(); } virtual size_t getDefaultPacketSize() const { return defaultPacketSize; } virtual size_t getMaxPacketSize() const { return defaultPacketSize; } virtual size_t getDefaultPacketPoolSize() const { return defaultPacketPoolSize; } virtual bool shouldExchangeCipherSeed() const { return false; } virtual bool isCipherKeyExpired() const { return false; } }; /** @} */ // addtogroup protocol } // namespace nsrpc #endif // !defined(NSRPC_P2PPACKETCODER_H)
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 75 ] ] ]
45441f12035360ee0d9aa952308ccedec8da7146
9749359952275ab38253e98171139457717018bd
/src/NufFitsHeadRecord.cpp
a926b33831a4fbec4a071e697a98e08390b9a500
[]
no_license
DancingOnWater/NuFits
bcfe511a709bf7aac8a8410bdee8398dbdfa6fb5
769b5ee73bee600f2c412480ca01f1f9573358a3
refs/heads/master
2021-01-01T06:44:57.272348
2011-09-20T10:39:35
2014-12-31T11:02:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,352
cpp
#include "NufFitsHeadRecord.h" #include <iostream> namespace NufFitsHeadRecordPriavte { void eraseWhiteSpace(std::string *recordPart) { int i; for(i =0; i!= recordPart->length() && recordPart->at(i) == ' '; ++i); recordPart->erase(0, i); for(i = recordPart->length()-1; i!= -1 && recordPart->at(i) == ' '; --i); recordPart->erase(i+1, recordPart->length()-1); } } NufFitsHeadRecord::NufFitsHeadRecord() { } NufFitsHeadRecord::NufFitsHeadRecord(const NufFitsHeadRecord &other) { keyword = other.keyword; value = other.value; comment = other.comment; } NufFitsHeadRecord::NufFitsHeadRecord(const std::string &field) { fromString(field); } NufFitsHeadRecord NufFitsHeadRecord::operator =(const NufFitsHeadRecord &other) { keyword = other.keyword; value = other.value; comment = other.comment; } std::string NufFitsHeadRecord::toString() const { std::string str(NufFitsHeadRecord::StringSize, ' '); str.replace(0, keyword.size(),keyword); int lastnumber = MaxNameSize; if(value.size() != 0){ str[MaxNameSize]='='; str.replace(MaxNameSize+2, value.size(), value); lastnumber += 2+value.size(); } if(comment.size() >0){ str[lastnumber]='/'; str.replace(lastnumber+1, comment.size(), comment); } return str; } bool NufFitsHeadRecord::fromString(const std::string &field) { if (field.size() < NufFitsHeadRecord::MaxNameSize) return false; keyword = field.substr(0, MaxNameSize); NufFitsHeadRecordPriavte::eraseWhiteSpace(&keyword); if(field.length() <= MaxNameSize + 2){ value.clear(); comment.clear(); return true; } int endNumber=MaxNameSize-1; if((field.at(MaxNameSize)=='=') && (field.at(MaxNameSize+1)==' ')) { endNumber = field.find('/', MaxNameSize+2); value = field.substr(MaxNameSize+2, endNumber-MaxNameSize-2); NufFitsHeadRecordPriavte::eraseWhiteSpace(&value); } else keyword.clear(); if(endNumber < field.length()-1){ comment = field.substr(endNumber+1); NufFitsHeadRecordPriavte::eraseWhiteSpace(&comment); } else comment.clear(); return true; }
[ [ [ 1, 89 ] ] ]
17ebd36c4be01bab88534373e8b334eb3d460001
7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3
/src/option/AddressBarPropertyPage.h
d9eb8987271a34522b6d63d6d4c678316029efe5
[]
no_license
plus7/DonutG
b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6
2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b
refs/heads/master
2020-06-01T15:30:31.747022
2010-08-21T18:51:01
2010-08-21T18:51:01
767,753
1
2
null
null
null
null
SHIFT_JIS
C++
false
false
9,081
h
/** * @file AddressBarPropertyPage.h * @brief アドレスバーのオプション設定. * @note * +++ AddressBar.hより分離 */ #pragma once class CDonutAddressBar; class CDonutSearchBar; class CDonutAddressBarPropertyPage : public CPropertyPageImpl < CDonutAddressBarPropertyPage > , public CWinDataExchange < CDonutAddressBarPropertyPage > { public: // Constants enum { IDD = IDD_PROPPAGE_ADDRESSBAR }; private: // Data members int m_nAutoComplete; int m_nNewWin; int m_nNoActivate; int m_nLoadTypedUrls; int m_nGoBtnVisible; CDonutAddressBar& m_AddressBar; CDonutSearchBar & m_SearchBar; //minit // UH CString m_strEnterCtrl; //*+++ 未使用かも? CString m_strEnterShift; //*+++ 未使用かも? int m_nUseEnterCtrl; int m_nUseEnterShift; int m_nTextVisible; //minit int m_nReplaceSpace; BOOL m_bInit; BOOL m_bAddCtrl; BOOL m_bAddShift; //+++ CString m_strIeExePath; CEdit m_edit; //+++ public: // DDX map BEGIN_DDX_MAP( CDonutAddressBarPropertyPage ) DDX_CHECK( IDC_CHECK_ABR_AUTOCOMPLETE, m_nAutoComplete ) DDX_CHECK( IDC_CHECK_ABR_NEWWIN, m_nNewWin ) DDX_CHECK( IDC_CHECK_ADB_NOACTIVATE, m_nNoActivate ) DDX_CHECK( IDC_CHECK_ABR_LOADTYPEDURLS, m_nLoadTypedUrls) DDX_CHECK( IDC_CHECK_ABR_GOBTNVISIBLE, m_nGoBtnVisible ) DDX_CHECK( IDC_CHECK_ABR_TEXTVISIBLE, m_nTextVisible ) // UH //DDX_TEXT( IDC_EDIT_CTRL_ENTER, m_strEnterCtrl ) //DDX_TEXT( IDC_EDIT_SHIFT_ENTER, m_strEnterShift ) DDX_CHECK( IDC_CHECK_CTRL_ENTER, m_nUseEnterCtrl ) DDX_CHECK( IDC_CHECK_SHIFT_ENTER, m_nUseEnterShift) //minit DDX_CHECK( IDC_CHECK_REPLACE, m_nReplaceSpace ) //+++ DDX_TEXT ( IDC_ADDRESS_BAR_ICON_EXE, m_strIeExePath ) END_DDX_MAP() //+++ BEGIN_MSG_MAP( CDonutAddressBarPropertyPage ) COMMAND_ID_HANDLER_EX( IDC_BTN_ADDRESS_BAR_EXE, OnButton ) CHAIN_MSG_MAP(CPropertyPageImpl<CDonutAddressBarPropertyPage>) END_MSG_MAP() // Constructor CDonutAddressBarPropertyPage(CDonutAddressBar &adBar, CDonutSearchBar &searchBar) : m_AddressBar(adBar) , m_SearchBar(searchBar) , m_bInit(FALSE) , m_bAddCtrl(FALSE) , m_bAddShift(FALSE) #if 1 //+++ , m_nAutoComplete(0) , m_nNewWin(0) , m_nNoActivate(0) , m_nLoadTypedUrls(0) , m_nGoBtnVisible(0) , m_nUseEnterCtrl(0) , m_nUseEnterShift(0) , m_nTextVisible(0) , m_nReplaceSpace(0) #endif { _SetData(); } public: // Overrides BOOL OnSetActive() { if (!m_bInit) { InitComboBox(); m_bInit = TRUE; } #if 1 //+++ if (m_edit.m_hWnd == NULL) { m_edit.Attach( GetDlgItem(IDC_ADDRESS_BAR_ICON_EXE) ); m_edit.SetWindowText(m_strIeExePath); } #endif SetModified(TRUE); return DoDataExchange(FALSE); } BOOL OnKillActive() { return DoDataExchange(TRUE); } BOOL OnApply() { if ( DoDataExchange(TRUE) ) { _GetData(); return TRUE; } else return FALSE; } // Implementation private: void _GetData() { // update flags DWORD dwFlags = 0; if (m_nAutoComplete ) { dwFlags |= ABR_EX_AUTOCOMPLETE; } if (m_nNewWin ) { dwFlags |= ABR_EX_OPENNEWWIN; } if (m_nNoActivate ) { dwFlags |= ABR_EX_NOACTIVATE; } if (m_nNewWin ) { dwFlags |= ABR_EX_OPENNEWWIN; } if (m_nLoadTypedUrls) { dwFlags |= ABR_EX_LOADTYPEDURLS; } if (m_nGoBtnVisible ) { dwFlags |= ABR_EX_GOBTNVISIBLE; } // U.H if (m_nTextVisible ) { dwFlags |= ABR_EX_TEXTVISIBLE; } if (m_nUseEnterCtrl ) { dwFlags |= ABR_EX_ENTER_CTRL; } if (m_nUseEnterShift) { dwFlags |= ABR_EX_ENTER_SHIFT; } if (m_nReplaceSpace ) { dwFlags |= ABR_EX_SEARCH_REPLACE; } m_AddressBar.SetAddressBarExtendedStyle(dwFlags); //x CIniFileO pr( g_szIniFileName, STR_ADDRESS_BAR ); //pr.SetValue(m_strEnterCtrl, _T("EnterCtrl")); //pr.SetValue(m_strEnterShift, _T("EnterShift")); CComboBox cmbCtrl = GetDlgItem(IDC_COMBO_CTRL_ENTER); CComboBox cmbShift = GetDlgItem(IDC_COMBO_SHIFT_ENTER); CString strBufCtrl, strBufShift; int idx; idx = cmbCtrl.GetCurSel(); if (idx != CB_ERR) cmbCtrl.GetLBText(idx, strBufCtrl); CIniFileO pr( g_szIniFileName, STR_ADDRESS_BAR ); if (strBufCtrl.Find( _T("※") ) != 0) { if (m_bAddCtrl) idx = idx - 1; pr.SetValue ( idx, _T("EnterCtrlIndex") ); pr.SetStringUW( strBufCtrl, _T("EnterCtrlEngin") ); pr.SetStringUW( CDonutSearchBar::GetSearchIniPath(), _T("EnterCtrlPath") ); } idx = cmbShift.GetCurSel(); if (idx != CB_ERR) cmbShift.GetLBText(idx, strBufShift); if (strBufShift.Find( _T("※") ) != 0) { if (m_bAddShift) idx = idx - 1; pr.SetValue( idx, _T("EnterShiftIndex") ); pr.SetStringUW( strBufShift, _T("EnterShiftEngin") ); pr.SetStringUW( CDonutSearchBar::GetSearchIniPath(), _T("EnterShiftPath") ); } #if 0 //+++ //m_edit.GetWindowText(m_strIeExePath, MAX_PATH); #endif pr.SetStringUW( m_strIeExePath, _T("IeExePath") ); //+++ } void _SetData() { DWORD dwFlags = m_AddressBar.GetAddressBarExtendedStyle(); m_nAutoComplete = _check_flag(ABR_EX_AUTOCOMPLETE, dwFlags); //+++ ? 1 : 0; m_nNewWin = _check_flag(ABR_EX_OPENNEWWIN, dwFlags); //+++ ? 1 : 0; m_nNoActivate = _check_flag(ABR_EX_NOACTIVATE, dwFlags); //+++ ? 1 : 0; m_nLoadTypedUrls = _check_flag(ABR_EX_LOADTYPEDURLS, dwFlags); //+++ ? 1 : 0; m_nGoBtnVisible = _check_flag(ABR_EX_GOBTNVISIBLE, dwFlags); //+++ ? 1 : 0; // vvv UH vvv m_nTextVisible = _check_flag(ABR_EX_TEXTVISIBLE, dwFlags); //+++ ? 1 : 0; m_nUseEnterCtrl = _check_flag(ABR_EX_ENTER_CTRL, dwFlags); //+++ ? 1 : 0; m_nUseEnterShift = _check_flag(ABR_EX_ENTER_SHIFT, dwFlags); //+++ ? 1 : 0; //minit m_nReplaceSpace = _check_flag(ABR_EX_SEARCH_REPLACE, dwFlags); //+++ ? 1 : 0; } void InitComboBox() { CComboBox cmbCtrl = GetDlgItem(IDC_COMBO_CTRL_ENTER); CComboBox cmbShift = GetDlgItem(IDC_COMBO_SHIFT_ENTER); CString strBuf; #if 1 //+++ m_SearchBar.InitComboBox_for_AddressBarPropertyPage(cmbCtrl, cmbShift); #else int nCount = m_SearchBar.m_cmbEngine.GetCount(); for (int i = 0; i < nCount; i++) { m_SearchBar.m_cmbEngine.GetLBText(i, strBuf); cmbCtrl.AddString(strBuf); cmbShift.AddString(strBuf); } #endif CIniFileI pr( g_szIniFileName , STR_ADDRESS_BAR ); DWORD idxCtrl = pr.GetValue ( _T("EnterCtrlIndex") , 0 ); DWORD idxShift = pr.GetValue ( _T("EnterShiftIndex"), 0 ); CString strPathCtrl = pr.GetStringUW( _T("EnterCtrlPath") ); CString strPathShift = pr.GetStringUW( _T("EnterShiftPath" ) ); CString strEnginCtrl = pr.GetStringUW( _T("EnterCtrlEngin" ) ); CString strEnginShift= pr.GetStringUW( _T("EnterShiftEngin") ); m_strIeExePath = pr.GetStringUW( _T("IeExePath") ); //+++ pr.Close(); //まず旧仕様の場合(Search.iniオンリー) if ( strPathCtrl.IsEmpty() ) { //検索ファイルが変更されていたら以前の登録エンジンには※をつける if ( CDonutSearchBar::GetSearchIniPath() != _GetFilePath( _T("Search.ini") ) ) { CString strText = _T("※") + strEnginCtrl; cmbCtrl.InsertString(0, strText); strText = _T("※") + strEnginShift; cmbShift.InsertString(0, strText); cmbCtrl.SetCurSel(0); cmbShift.SetCurSel(0); m_bAddCtrl = m_bAddShift = TRUE; } else { //完全に旧仕様通りに動作 cmbCtrl.SetCurSel(idxCtrl); cmbShift.SetCurSel(idxShift); } } else { //設定時の検索ファイルと今のファイルが異なる場合は以前のエンジンに※をつけて追加 if (CDonutSearchBar::GetSearchIniPath() != strPathCtrl) { CString strText = _T("※") + strEnginCtrl; cmbCtrl.InsertString(0, strText); cmbCtrl.SetCurSel(0); m_bAddCtrl = TRUE; } else { cmbCtrl.SetCurSel(idxCtrl); } if (CDonutSearchBar::GetSearchIniPath() != strPathShift) { CString strText = _T("※") + strEnginShift; cmbShift.InsertString(0, strText); cmbShift.SetCurSel(0); m_bAddShift = TRUE; } else { cmbShift.SetCurSel(idxShift); } } } #if 1 //+++ void OnButton(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/) { //TCHAR szOldPath[MAX_PATH]; //szOldPath[0] = 0; //::GetCurrentDirectory(MAX_PATH, szOldPath); //::SetCurrentDirectory( Misc::GetExeDirectory() ); static const TCHAR szFilter[] = _T("全ファイル(*.*)\0*.*\0\0"); CFileDialog fileDlg(TRUE, NULL, NULL, OFN_HIDEREADONLY, szFilter); fileDlg.m_ofn.lpstrTitle = _T("アドレスバー・アイコンで起動するアプリ"); if (fileDlg.DoModal() == IDOK) { m_edit.SetWindowText(fileDlg.m_szFileName); //m_strIeExePath = fileDlg.m_szFileName; } // // restore current directory //::SetCurrentDirectory(szOldPath); } #endif };
[ [ [ 1, 311 ] ] ]
1b0a55ca5957504b174fe9a6e7422a6a32c9b8db
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-01-06/pcbnew/files.cpp
daebbe15d32e87ad7661a291f753094096a96392
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
8,369
cpp
/***************************************************/ /* Files.cpp: Lecture / Sauvegarde des fichiers PCB */ /***************************************************/ #include "fctsys.h" #include "common.h" #include "pcbnew.h" #include "protos.h" #include "id.h" /****************************************************/ void WinEDA_PcbFrame::Files_io(wxCommandEvent& event) /****************************************************/ /* Gestion generale des commandes de lecture de fichiers */ { int id = event.GetId(); wxClientDC dc(DrawPanel); wxString msg; DrawPanel->PrepareGraphicContext(&dc); // Arret des commandes en cours if( GetScreen()->ManageCurseur && GetScreen()->ForceCloseManageCurseur ) { GetScreen()->ForceCloseManageCurseur(this, &dc); } SetToolID(0, wxCURSOR_ARROW,wxEmptyString); switch (id) { case ID_MENU_LOAD_FILE: case ID_LOAD_FILE: Clear_Pcb(&dc, TRUE); LoadOnePcbFile(wxEmptyString, &dc, FALSE); ReCreateAuxiliaryToolbar(); break; case ID_MENU_READ_LAST_SAVED_VERSION_BOARD: case ID_MENU_RECOVER_BOARD: { wxString filename, oldfilename = GetScreen()->m_FileName; if ( id == ID_MENU_RECOVER_BOARD) { filename = g_SaveFileName + PcbExtBuffer; } else { filename = oldfilename; ChangeFileNameExt(filename, wxT(".000")); } if ( ! wxFileExists(filename) ) { msg = _("Recovery file ") + filename + _(" not found"); DisplayInfo(this, msg); break; } else { msg = _("Ok to load Recovery file ") + filename; if ( ! IsOK (this, msg) ) break; } Clear_Pcb(&dc, TRUE); LoadOnePcbFile(filename, &dc, FALSE); GetScreen()->m_FileName = oldfilename; SetTitle(GetScreen()->m_FileName); ReCreateAuxiliaryToolbar(); } break; case ID_MENU_APPEND_FILE: case ID_APPEND_FILE: LoadOnePcbFile(wxEmptyString, &dc, TRUE); break; case ID_MENU_NEW_BOARD: case ID_NEW_BOARD: Clear_Pcb(&dc, TRUE); GetScreen()->m_FileName.Printf( wxT("%s%cnoname%s"), wxGetCwd().GetData(), DIR_SEP, PcbExtBuffer.GetData()); SetTitle(GetScreen()->m_FileName); break; case ID_LOAD_FILE_1: case ID_LOAD_FILE_2: case ID_LOAD_FILE_3: case ID_LOAD_FILE_4: case ID_LOAD_FILE_5: case ID_LOAD_FILE_6: case ID_LOAD_FILE_7: case ID_LOAD_FILE_8: case ID_LOAD_FILE_9: case ID_LOAD_FILE_10: Clear_Pcb(&dc, TRUE); wxSetWorkingDirectory(wxPathOnly(GetLastProject(id - ID_LOAD_FILE_1))); LoadOnePcbFile( GetLastProject(id - ID_LOAD_FILE_1).GetData(), &dc, FALSE); ReCreateAuxiliaryToolbar(); break; case ID_SAVE_BOARD: case ID_MENU_SAVE_BOARD: SavePcbFile(GetScreen()->m_FileName); break; case ID_MENU_SAVE_BOARD_AS: SavePcbFile(wxEmptyString); break; case ID_PCB_GEN_CMP_FILE: RecreateCmpFileFromBoard(); break; default: DisplayError(this, wxT("File_io Internal Error") ); break; } } /*****************************************************************************************/ int WinEDA_PcbFrame::LoadOnePcbFile(const wxString & FullFileName, wxDC * DC, bool Append) /******************************************************************************************/ /* Lecture d'un fichier PCB, le nom etant dans PcbNameBuffer.s retourne: 0 si fichier non lu ( annulation de commande ... ) 1 si OK */ { int ii; FILE * source; wxString msg; ActiveScreen = GetScreen(); if( GetScreen()->IsModify() && !Append ) { if( !IsOK(this, _("Board Modified: Continue ?")) ) return(0); } m_SelTrackWidthBox_Changed = TRUE; m_SelViaSizeBox_Changed = TRUE; if( Append ) { GetScreen()->m_FileName = wxEmptyString; GetScreen()->SetModify(); m_Pcb->m_Status_Pcb = 0; } if( FullFileName == wxEmptyString) { msg = wxT("*") + PcbExtBuffer; wxString FileName = EDA_FileSelector(_("Board files:"), wxEmptyString, /* Chemin par defaut */ GetScreen()->m_FileName, /* nom fichier par defaut */ PcbExtBuffer, /* extension par defaut */ msg, /* Masque d'affichage */ this, wxOPEN, FALSE ); if ( FileName == wxEmptyString ) return FALSE; GetScreen()->m_FileName = FileName; } else GetScreen()->m_FileName = FullFileName; ///////////////////////// /* Lecture Fichier PCB */ ///////////////////////// source = wxFopen(GetScreen()->m_FileName,wxT("rt")); if (source == NULL) { msg.Printf(_("File <%s> not found"),GetScreen()->m_FileName.GetData()) ; DisplayError(this, msg) ; return(0); } /* Lecture de l'entete et TEST si PCB format ASCII */ GetLine(source, cbuf, &ii ); if( strncmp( cbuf, "PCBNEW-BOARD",12) != 0) { fclose(source); DisplayError(this, wxT("Unknown file type")); return(0); } SetTitle(GetScreen()->m_FileName); SetLastProject(GetScreen()->m_FileName); // Rechargement de la configuration: wxSetWorkingDirectory( wxPathOnly(GetScreen()->m_FileName) ); if( Append ) ReadPcbFile(DC, source, TRUE); else { Read_Config(GetScreen()->m_FileName); // Mise a jour du toolbar d'options m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill; m_DisplayModText = DisplayOpt.DisplayModText ; m_DisplayModEdge = DisplayOpt.DisplayModEdge; m_DisplayPadFill = DisplayOpt.DisplayPadFill; ReadPcbFile(DC, source, FALSE); } fclose(source); GetScreen()->ClrModify(); if( Append ) { GetScreen()->SetModify(); GetScreen()->m_FileName.Printf( wxT("%s%cnoname%s"), wxGetCwd().GetData(), DIR_SEP, PcbExtBuffer.GetData()); } /* liste des pads recalculee avec Affichage des messages d'erreur */ build_liste_pads(); Affiche_Infos_Status_Pcb(this); g_SaveTime = time(NULL); return(1); } /***********************************************************/ bool WinEDA_PcbFrame::SavePcbFile(const wxString & FileName) /************************************************************/ /* Sauvegarde du fichier PCB en format ASCII */ { wxString old_name, FullFileName, msg; bool saveok = TRUE; FILE * dest; if( FileName == wxEmptyString ) { msg = wxT("*") + PcbExtBuffer; FullFileName = EDA_FileSelector(_("Board files:"), wxEmptyString, /* Chemin par defaut */ GetScreen()->m_FileName, /* nom fichier par defaut */ PcbExtBuffer, /* extension par defaut */ msg, /* Masque d'affichage */ this, wxSAVE, FALSE ); if ( FullFileName == wxEmptyString ) return FALSE; GetScreen()->m_FileName = FullFileName; } else GetScreen()->m_FileName = FileName; /* mise a jour date si modifications */ if ( GetScreen()->IsModify() ) { GetScreen()->m_Date = GenDate(); } /* Calcul du nom du fichier a creer */ FullFileName = MakeFileName(wxEmptyString, GetScreen()->m_FileName, PcbExtBuffer); /* Calcul du nom du fichier de sauvegarde */ old_name = FullFileName; ChangeFileNameExt(old_name,wxT(".000")); /* Changement du nom de l'ancien fichier s'il existe */ if ( wxFileExists(FullFileName) ) { /* conversion en *.000 de l'ancien fichier */ wxRemoveFile(old_name); /* S'il y a une ancienne sauvegarde */ if( ! wxRenameFile(FullFileName,old_name) ) { msg = _("Warning: unable to create bakfile ") + old_name; DisplayError(this, msg, 15) ; saveok = FALSE; } } else { old_name = wxEmptyString; saveok = FALSE; } /* Sauvegarde de l'ancien fichier */ dest = wxFopen(FullFileName, wxT("wt")); if (dest == 0) { msg = _("Unable to create ") + FullFileName; DisplayError(this, msg) ; saveok = FALSE; } if( dest ) { GetScreen()->m_FileName = FullFileName; SetTitle(GetScreen()->m_FileName); SavePcbFormatAscii(dest); fclose(dest) ; } /* Affichage des fichiers crees: */ MsgPanel->EraseMsgBox(); if( saveok ) { msg = _("Backup file: ") + old_name; Affiche_1_Parametre(this, 1,msg, wxEmptyString, CYAN); } if ( dest ) msg = _("Write Board file: "); else msg = _("Failed to create "); msg += FullFileName; Affiche_1_Parametre(this, 1,wxEmptyString,msg, CYAN); g_SaveTime = time(NULL); /* Reset delai pour sauvegarde automatique */ GetScreen()->ClrModify(); return TRUE; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 331 ] ] ]
399049faf02ce0ec5c9386924e1a2a6360d1da18
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/impl/DOMConfigurationImpl.cpp
7aaaf8b9ff986a9de1085ce738666f8a7c377013
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
15,415
cpp
/* * Copyright 2003,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DOMConfigurationImpl.hpp" #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/dom/DOMException.hpp> #include <xercesc/util/Janitor.hpp> XERCES_CPP_NAMESPACE_BEGIN const bool DOMConfigurationImpl::fFalse = false; const bool DOMConfigurationImpl::fTrue = true; /* canonical-form */ const XMLCh DOMConfigurationImpl::fgCANONICAL_FORM[] = { chLatin_c, chLatin_a, chLatin_n, chLatin_o, chLatin_n, chLatin_i, chLatin_c, chLatin_a, chLatin_l, chDash, chLatin_f, chLatin_o, chLatin_r, chLatin_m, chNull }; /* cdata-sections */ const XMLCh DOMConfigurationImpl::fgCDATA_SECTIONS[] = { chLatin_c, chLatin_d, chLatin_a, chLatin_t, chLatin_a, chDash, chLatin_s, chLatin_e, chLatin_c, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chLatin_s, chNull }; /* comments */ const XMLCh DOMConfigurationImpl::fgCOMMENTS[] = { chLatin_c, chLatin_o, chLatin_m, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chLatin_s, chNull }; /* datatype-normalization */ const XMLCh DOMConfigurationImpl::fgDATATYPE_NORMALIZATION[] = { chLatin_d, chLatin_a, chLatin_t, chLatin_a, chLatin_t, chLatin_y, chLatin_p, chLatin_e, chDash, chLatin_n, chLatin_o, chLatin_r, chLatin_m, chLatin_a, chLatin_l, chLatin_i, chLatin_z, chLatin_a, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chNull }; /* discard-default-content */ const XMLCh DOMConfigurationImpl::fgDISCARD_DEFAULT_CONTENT[] = { chLatin_d, chLatin_i, chLatin_s, chLatin_c, chLatin_a, chLatin_r, chLatin_d, chDash, chLatin_d, chLatin_e, chLatin_f, chLatin_a, chLatin_u, chLatin_l, chLatin_t, chDash, chLatin_c, chLatin_o, chLatin_n, chLatin_t, chLatin_e, chLatin_n, chLatin_t, chNull }; /* entities */ const XMLCh DOMConfigurationImpl::fgENTITIES[] = { chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_i, chLatin_e, chLatin_s, chNull }; /* infoset */ const XMLCh DOMConfigurationImpl::fgINFOSET[] = { chLatin_i, chLatin_n, chLatin_f, chLatin_o, chLatin_s, chLatin_e, chLatin_t, chNull }; /* namespaces */ const XMLCh DOMConfigurationImpl::fgNAMESPACES[] = { chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chLatin_p, chLatin_a, chLatin_c, chLatin_e, chLatin_s, chNull }; /* namespace-declarations */ const XMLCh DOMConfigurationImpl::fgNAMESPACE_DECLARATIONS[] = { chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chLatin_p, chLatin_a, chLatin_c, chLatin_e, chDash, chLatin_d, chLatin_e, chLatin_c, chLatin_l, chLatin_a, chLatin_r, chLatin_a, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chLatin_s, chNull }; /* normalize-characters */ const XMLCh DOMConfigurationImpl::fgNORMALIZE_CHARACTERS[] = { chLatin_n, chLatin_o, chLatin_r, chLatin_m, chLatin_a, chLatin_l, chLatin_i, chLatin_z, chLatin_e, chDash, chLatin_c, chLatin_h, chLatin_a, chLatin_r, chLatin_a, chLatin_c, chLatin_t, chLatin_e, chLatin_r, chLatin_s, chNull }; /* split-cdata-sections */ const XMLCh DOMConfigurationImpl::fgSPLIT_CDATA_SECTIONS[] = { chLatin_s, chLatin_p, chLatin_l, chLatin_i, chLatin_t, chDash, chLatin_c, chLatin_d, chLatin_a, chLatin_t, chLatin_a, chDash, chLatin_s, chLatin_e, chLatin_c, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chLatin_s, chNull }; /* validate */ const XMLCh DOMConfigurationImpl::fgVALIDATE[] = { chLatin_v, chLatin_a, chLatin_l, chLatin_i, chLatin_d, chLatin_a, chLatin_t, chLatin_e, chNull }; /* validate-if-schema */ const XMLCh DOMConfigurationImpl::fgVALIDATE_IF_SCHEMA[] = { chLatin_v, chLatin_a, chLatin_l, chLatin_i, chLatin_d, chLatin_a, chLatin_t, chLatin_e, chDash, chLatin_i, chLatin_f, chDash, chLatin_s, chLatin_c, chLatin_h, chLatin_e, chLatin_m, chLatin_a, chNull }; /* whitespace-in-element-content */ const XMLCh DOMConfigurationImpl::fgWHITESPACE_IN_ELEMENT_CONTENT[] = { chLatin_w, chLatin_h, chLatin_i, chLatin_t, chLatin_e, chLatin_s, chLatin_p, chLatin_a, chLatin_c, chLatin_e, chDash, chLatin_i, chLatin_n, chDash, chLatin_e, chLatin_l, chLatin_e, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chDash, chLatin_c, chLatin_o, chLatin_n, chLatin_t, chLatin_e, chLatin_n, chLatin_t, chNull }; /* error-handler */ const XMLCh DOMConfigurationImpl::fgERROR_HANDLER[] = { chLatin_e, chLatin_r, chLatin_r, chLatin_o, chLatin_r, chDash, chLatin_h, chLatin_a, chLatin_n, chLatin_d, chLatin_l, chLatin_e, chLatin_r, chNull }; /* schema-type */ const XMLCh DOMConfigurationImpl::fgSCHEMA_TYPE[] = { chLatin_s, chLatin_c, chLatin_h, chLatin_e, chLatin_m, chLatin_a, chDash, chLatin_t, chLatin_y, chLatin_p, chLatin_e, chNull }; /* schema-location */ const XMLCh DOMConfigurationImpl::fgSCHEMA_LOCATION[] = { chLatin_s, chLatin_c, chLatin_h, chLatin_e, chLatin_m, chLatin_a, chDash, chLatin_l, chLatin_o, chLatin_c, chLatin_a, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chNull }; const unsigned short DOMConfigurationImpl::fDEFAULT_VALUES = 0x2596; DOMConfigurationImpl::DOMConfigurationImpl(MemoryManager* const manager): featureValues(fDEFAULT_VALUES), fErrorHandler(0), fSchemaType(0), fSchemaLocation(0) , fMemoryManager(manager) { } DOMConfigurationImpl::~DOMConfigurationImpl() { } void DOMConfigurationImpl::setParameter(const XMLCh* name, const void* value) { XMLCh* lowerCaseName = XMLString::replicate(name, fMemoryManager); ArrayJanitor<XMLCh> janName(lowerCaseName, fMemoryManager); XMLString::lowerCase(lowerCaseName); if(!canSetParameter(lowerCaseName, value)) { throw DOMException(DOMException::NOT_SUPPORTED_ERR, 0, fMemoryManager); } bool isBooleanParameter = true; DOMConfigurationFeature whichFlag; try { whichFlag = getFeatureFlag(lowerCaseName); } catch(DOMException e) { // must not be a boolean parameter isBooleanParameter = false; } if(isBooleanParameter) { if(*((bool*)value)) { featureValues |= whichFlag; } else { featureValues &= ~whichFlag; } } else { if(XMLString::equals(lowerCaseName, fgERROR_HANDLER)) { fErrorHandler = (DOMErrorHandler*)value; } else if (XMLString::equals(lowerCaseName, fgSCHEMA_TYPE)) { fSchemaType = (XMLCh*)value; } else if (XMLString::equals(lowerCaseName, fgSCHEMA_LOCATION)) { fSchemaLocation = (XMLCh*)value; } else { // canSetParameter above should take care of this case throw DOMException(DOMException::NOT_FOUND_ERR, 0, fMemoryManager); } } } // -------------------------------------- // Getter Methods // -------------------------------------- const void* DOMConfigurationImpl::getParameter(const XMLCh* name) const { XMLCh* lowerCaseName = XMLString::replicate(name, fMemoryManager); ArrayJanitor<XMLCh> janName(lowerCaseName, fMemoryManager); XMLString::lowerCase(lowerCaseName); bool isBooleanParameter = true; DOMConfigurationFeature whichFlag; try { whichFlag = getFeatureFlag(lowerCaseName); } catch (DOMException e) { // must not be a boolean parameter isBooleanParameter = false; } if(isBooleanParameter){ if(featureValues & whichFlag) { return &fTrue; } else { return &fFalse; } } else { if(XMLString::equals(lowerCaseName, fgERROR_HANDLER)) { return fErrorHandler; } else if (XMLString::equals(lowerCaseName, fgSCHEMA_TYPE)) { return fSchemaType; } else if (XMLString::equals(lowerCaseName, fgSCHEMA_LOCATION)) { return fSchemaLocation; } else { throw DOMException(DOMException::NOT_FOUND_ERR, 0, fMemoryManager); } } } // ----------------------------------------- // Query Methods // ----------------------------------------- bool DOMConfigurationImpl::canSetParameter(const XMLCh* name, const void* value) const { /** * canSetParameter(name, value) returns false in two conditions: * 1) if a [required] feature has no supporting code, then return false in * both the true and false outcomes (This is in order to be either fully * spec compliant, or not at all) * 2) if an [optional] feature has no supporting code, then return false **/ // if value is null, return true if(value == 0) return true; XMLCh* lowerCaseName = XMLString::replicate(name, fMemoryManager); ArrayJanitor<XMLCh> janName(lowerCaseName, fMemoryManager); XMLString::lowerCase(lowerCaseName); bool isBooleanParameter = true; bool booleanValue = false; DOMConfigurationFeature whichFlag; try { whichFlag = getFeatureFlag(lowerCaseName); booleanValue = *((bool*)value); } catch (DOMException e) { // must not be a boolean parameter isBooleanParameter = false; } if(isBooleanParameter) { switch (whichFlag) { case FEATURE_CANONICAL_FORM: if(booleanValue) return false; // optional // else return true; // required // case FEATURE_CDATA_SECTIONS: return true; case FEATURE_COMMENTS: return true; case FEATURE_DATATYPE_NORMALIZATION: if(booleanValue) return false; // required // else return true; // required // case FEATURE_DISCARD_DEFAULT_CONTENT: if(booleanValue) return false; // required // else return true; // required // case FEATURE_ENTITIES: if(booleanValue) return true; // required // else return true; // required // case FEATURE_INFOSET: if(booleanValue) return false; // required // else return true; // no effect// case FEATURE_NAMESPACES: return true; case FEATURE_NAMESPACE_DECLARATIONS: if(booleanValue) return true; // optional // else return false; // required // case FEATURE_NORMALIZE_CHARACTERS: if(booleanValue) return false; // optional // else return true; // required // case FEATURE_SPLIT_CDATA_SECTIONS: //we dont report an error in the false case so we cant claim we do it if(booleanValue) return false; // required // else return false; // required // case FEATURE_VALIDATE: if(booleanValue) return false; // optional // else return true; // required // case FEATURE_VALIDATE_IF_SCHEMA: if(booleanValue) return false; // optional // else return true; // required // case FEATURE_WHITESPACE_IN_ELEMENT_CONTENT: if(booleanValue) return true; // required // else return false; // optional // default: return false; // should never be here } } else { if(XMLString::equals(lowerCaseName, fgERROR_HANDLER)) { return true; // required // } else if (XMLString::equals(lowerCaseName, fgSCHEMA_TYPE)) { return false; // optional // } else if (XMLString::equals(lowerCaseName, fgSCHEMA_LOCATION)) { return false; // optional // } } return false; } // ------------------------------------------- // Impl methods // ------------------------------------------- DOMConfigurationImpl::DOMConfigurationFeature DOMConfigurationImpl::getFeatureFlag(const XMLCh* name) const { XMLCh* lowerCaseName = XMLString::replicate(name, fMemoryManager); ArrayJanitor<XMLCh> janName(lowerCaseName, fMemoryManager); XMLString::lowerCase(lowerCaseName); if(XMLString::equals(lowerCaseName, fgCANONICAL_FORM)) { return FEATURE_CANONICAL_FORM; } else if (XMLString::equals(lowerCaseName, fgCDATA_SECTIONS )) { return FEATURE_CDATA_SECTIONS; } else if (XMLString::equals(lowerCaseName, fgCOMMENTS)) { return FEATURE_COMMENTS; } else if (XMLString::equals(lowerCaseName, fgDATATYPE_NORMALIZATION)) { return FEATURE_DATATYPE_NORMALIZATION; } else if (XMLString::equals(lowerCaseName, fgDISCARD_DEFAULT_CONTENT)) { return FEATURE_DISCARD_DEFAULT_CONTENT; } else if (XMLString::equals(lowerCaseName, fgENTITIES)) { return FEATURE_ENTITIES; } else if (XMLString::equals(lowerCaseName, fgINFOSET)) { return FEATURE_INFOSET; } else if (XMLString::equals(lowerCaseName, fgNAMESPACES)) { return FEATURE_NAMESPACES; } else if (XMLString::equals(lowerCaseName, fgNAMESPACE_DECLARATIONS)) { return FEATURE_NAMESPACE_DECLARATIONS; } else if (XMLString::equals(lowerCaseName, fgNORMALIZE_CHARACTERS)) { return FEATURE_NORMALIZE_CHARACTERS; } else if (XMLString::equals(lowerCaseName, fgSPLIT_CDATA_SECTIONS)) { return FEATURE_SPLIT_CDATA_SECTIONS; } else if (XMLString::equals(lowerCaseName, fgVALIDATE)) { return FEATURE_VALIDATE; } else if (XMLString::equals(lowerCaseName, fgVALIDATE_IF_SCHEMA)) { return FEATURE_VALIDATE_IF_SCHEMA; } else if (XMLString::equals(lowerCaseName, fgWHITESPACE_IN_ELEMENT_CONTENT)) { return FEATURE_WHITESPACE_IN_ELEMENT_CONTENT; } else { throw DOMException(DOMException::NOT_FOUND_ERR, 0, fMemoryManager); } } DOMErrorHandler* DOMConfigurationImpl::getErrorHandler() const { return fErrorHandler; } const XMLCh* DOMConfigurationImpl::getSchemaType() const { return fSchemaType; } const XMLCh* DOMConfigurationImpl::getSchemaLocation() const { return fSchemaLocation; } void DOMConfigurationImpl::setErrorHandler(DOMErrorHandler *erHandler) { fErrorHandler = erHandler; } void DOMConfigurationImpl::setSchemaType(const XMLCh* st) { fSchemaType = st; } void DOMConfigurationImpl::setSchemaLocation(const XMLCh* sl) { fSchemaLocation = sl; } XERCES_CPP_NAMESPACE_END /** * End of file DOMConfigurationImpl.cpp */
[ [ [ 1, 335 ] ] ]
944bf25d937a40240cdf339c7f66475549226779
ea2786bfb29ab1522074aa865524600f719b5d60
/MultimodalSpaceShooter/src/scenes/GameOverScene.h
a7bf3f6b6daa8103dd76e25b85e06a73b27d7cab
[]
no_license
jeremysingy/multimodal-space-shooter
90ffda254246d0e3a1e25558aae5a15fed39137f
ca6e28944cdda97285a2caf90e635a73c9e4e5cd
refs/heads/master
2021-01-19T08:52:52.393679
2011-04-12T08:37:03
2011-04-12T08:37:03
1,467,691
0
1
null
null
null
null
UTF-8
C++
false
false
926
h
#ifndef GAMEOVERSCENE_H #define GAMEOVERSCENE_H #include "scenes/IScene.h" #include "input/EventListener.h" #include "input/MultimodalListener.h" #include "gui/Menu.h" #include "gui/ButtonListener.h" #include <SFML/Graphics/Text.hpp> ////////////////////////////////////////////////// /// Game over scene when the game is missed ////////////////////////////////////////////////// class GameOverScene : public IScene, public ButtonListener { public: GameOverScene(SceneManager& sceneManager); virtual void update(float frameTime); virtual void draw(sf::RenderTarget& window) const; virtual void onEvent(const sf::Event& event); virtual void onMultimodalEvent(Multimodal::Event event); virtual void onButtonPress(const std::string& buttonId); private: sf::Sprite myCursor; Menu myMenu; }; #endif // GAMEOVERSCENE_H
[ [ [ 1, 31 ] ] ]
09bb18f6f9e5c89aa638f75ecfdf02529d45a441
5e61787e7adba6ed1c2b5e40d38098ebdf9bdee8
/sans/models/c_models/sphere.cpp
417b1ef32a71a83d95043a8d114a6e8d411e7e14
[]
no_license
mcvine/sansmodels
4dcba43d18c930488b0e69e8afb04139e89e7b21
618928810ee7ae58ec35bbb839eba2a0117c4611
refs/heads/master
2021-01-22T13:12:22.721492
2011-09-30T14:01:06
2011-09-30T14:01:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,629
cpp
/** This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. If you use DANSE applications to do scientific research that leads to publication, we ask that you acknowledge the use of the software with the following sentence: "This work benefited from DANSE software developed under NSF award DMR-0520547." copyright 2008, University of Tennessee */ /** * Scattering model classes * The classes use the IGOR library found in * sansmodels/src/libigor * */ #include <math.h> #include "models.hh" #include "parameters.hh" #include <stdio.h> using namespace std; extern "C" { #include "libSphere.h" #include "sphere.h" } SphereModel :: SphereModel() { scale = Parameter(1.0); radius = Parameter(20.0, true); radius.set_min(0.0); sldSph = Parameter(4.0e-6); sldSolv = Parameter(1.0e-6); background = Parameter(0.0); } /** * Function to evaluate 1D scattering function * The NIST IGOR library is used for the actual calculation. * @param q: q-value * @return: function value */ double SphereModel :: operator()(double q) { double dp[5]; // Fill parameter array for IGOR library // Add the background after averaging dp[0] = scale(); dp[1] = radius(); dp[2] = sldSph(); dp[3] = sldSolv(); dp[4] = 0.0; // Get the dispersion points for the radius vector<WeightPoint> weights_rad; radius.get_weights(weights_rad); // Perform the computation, with all weight points double sum = 0.0; double norm = 0.0; double vol = 0.0; // Loop over radius weight points for(int i=0; i<weights_rad.size(); i++) { dp[1] = weights_rad[i].value; //Un-normalize SphereForm by volume sum += weights_rad[i].weight * SphereForm(dp, q) * pow(weights_rad[i].value,3); //Find average volume vol += weights_rad[i].weight * pow(weights_rad[i].value,3); norm += weights_rad[i].weight; } if (vol != 0.0 && norm != 0.0) { //Re-normalize by avg volume sum = sum/(vol/norm);} return sum/norm + background(); } /** * Function to evaluate 2D scattering function * @param q_x: value of Q along x * @param q_y: value of Q along y * @return: function value */ double SphereModel :: operator()(double qx, double qy) { double q = sqrt(qx*qx + qy*qy); return (*this).operator()(q); } /** * Function to evaluate 2D scattering function * @param pars: parameters of the sphere * @param q: q-value * @param phi: angle phi * @return: function value */ double SphereModel :: evaluate_rphi(double q, double phi) { return (*this).operator()(q); } /** * Function to calculate effective radius * @return: effective radius value */ double SphereModel :: calculate_ER() { SphereParameters dp; dp.scale = scale(); dp.radius = radius(); dp.sldSph = sldSph(); dp.sldSolv = sldSolv(); dp.background = background(); double rad_out = 0.0; // Perform the computation, with all weight points double sum = 0.0; double norm = 0.0; // Get the dispersion points for the radius vector<WeightPoint> weights_rad; radius.get_weights(weights_rad); // Loop over radius weight points to average the radius value for(int i=0; i<weights_rad.size(); i++) { sum += weights_rad[i].weight * weights_rad[i].value; norm += weights_rad[i].weight; } if (norm != 0){ //return the averaged value rad_out = sum/norm;} else{ //return normal value rad_out = radius();} return rad_out; }
[ [ [ 1, 19 ], [ 21, 29 ], [ 31, 36 ], [ 39, 48 ], [ 50, 54 ], [ 58, 65 ], [ 67, 71 ], [ 73, 73 ], [ 79, 80 ], [ 85, 108 ] ], [ [ 20, 20 ] ], [ [ 30, 30 ], [ 37, 38 ], [ 49, 49 ], [ 55, 57 ], [ 66, 66 ], [ 72, 72 ], [ 74, 78 ], [ 81, 84 ], [ 109, 144 ] ] ]
8fb77cc3e697b2ba10dfa2862d60f8c807be9012
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Scada/SysCADMarshal/SlotConnect.cpp
5af718d16321f5fddcfea94d380a9c1ca4ae74be
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,227
cpp
// SlotConnect.cpp: implementation of the CSlotConnect class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "SysCADMarshal.h" #include "Slot.h" #include "SlotConnect.h" #include "slotmngr.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif // ======================================================================= // // // // ======================================================================= CSlotConnPrf::CSlotConnPrf() { m_Mode=eNULL; }; // ----------------------------------------------------------------------- long CSlotConnPrf::Parse(LPCSTR File) { if (!FileExists((LPTSTR)File)) return 1; //m_sTag.FnName((LPTSTR)File); m_bYReversed=false; long RetCode=0; Strng Ext; Ext.FnExt((LPTSTR)File); if (Ext.XStrICmp(".txt")==0 || Ext.XStrICmp(".csv")==0) { FILE *h=fopen(File, "rt"); if (h) { char Buff[4096]; CSVColArray c; int Quote; int nFlds = 0; Buff[0]=0; while (strlen(Buff)==0 && fgets(Buff, sizeof(Buff), h)) XStrLTrim(Buff, " \t\n"); nFlds = ParseCSVTokens(Buff, c, Quote); if (nFlds>0) { if (_stricmp(Buff, "ABS")==0) m_Mode=eABS; else if (_stricmp(Buff, "SCL")==0) m_Mode=eSCL; else if (_stricmp(Buff, "SCL%")==0) m_Mode=eSCLPERC; else if (_stricmp(Buff, "CONTRONIC")==0) m_Mode=eCONTRONIC; else { return 4; goto Leave; } if (m_Mode==eCONTRONIC) { while (fgets(Buff, sizeof(Buff), h)) { int nFlds = ParseTokenList(Buff, c, "=:"); if (nFlds>=3) { CSlotConnPrfPt Pt; Pt.X=(float)SafeAtoF(c[1]); Pt.Y=(float)SafeAtoF(c[2]); m_Points.Add(Pt); } else if (m_Points.GetSize()>0) break; } } else { while (fgets(Buff, sizeof(Buff), h)) { int nFlds = ParseCSVTokens(Buff, c, Quote); if (nFlds>=2) { CSlotConnPrfPt Pt; Pt.X=(float)SafeAtoF(c[0]); Pt.Y=(float)SafeAtoF(c[1]); m_Points.Add(Pt); } else if (m_Points.GetSize()>0) break; } } if (m_Points.GetSize()<2) { RetCode=5; goto Leave; } m_bYReversed=m_Points[0].Y> m_Points[m_Points.GetUpperBound()].Y; fclose(h); } else RetCode=4; } else RetCode=2; Leave: if (h) fclose(h); return RetCode; } else return 3; }; // CONTRONIC FORMAT //NO. 1= .0 %: .0 I/P VALUE : //NO. 2= 6.2 %: 123.6 I/P VALUE : //NO. 3= 12.5 %: 221.1 I/P VALUE : //NO. 4= 18.7 %: 308.1 I/P VALUE : // ----------------------------------------------------------------------- LPCTSTR CSlotConnPrf::ErrorString(long RetCode) { switch (RetCode) { case 0: return "No Error"; case 1: return "File missing"; case 2: return "File not opened"; case 3: return "Must be txt or csv"; case 4: return "First Line must contain ABS,SCL SCL% or CONTRONIC"; case 5: return "Must have 2 or more points"; default: return "Unknown error"; } }; // ----------------------------------------------------------------------- double CSlotConnPrf::X2Y(double X) { double Y=0; long i0, i1, inc; i0=0; i1=m_Points.GetUpperBound()-1; inc=1; for (int i=i0; i<i1; i+=inc) if (X<=m_Points[i].X) break; CSlotConnPrfPt & Pt0=m_Points[i]; CSlotConnPrfPt & Pt1=m_Points[i+1]; Y=Pt0.Y+(Pt1.Y-Pt0.Y)*(X-Pt0.X)/(Pt1.X-Pt0.X); return Y; }; // ----------------------------------------------------------------------- double CSlotConnPrf::Y2X(double Y) { double X=0; long i0, i1, inc; if (m_bYReversed) { i0=m_Points.GetUpperBound(); i1=0+1; inc=-1; } else { i0=0; i1=m_Points.GetUpperBound()-1; inc=1; } for (int i=i0; i!=i1; i+=inc) if (Y<=m_Points[i].Y) break; CSlotConnPrfPt & Pt0=m_Points[i]; CSlotConnPrfPt & Pt1=m_Points[i+inc]; X=Pt0.X+(Pt1.X-Pt0.X)*(Y-Pt0.Y)/NZ(Pt1.Y-Pt0.Y); return X; }; // ======================================================================= // // // // ======================================================================= CSlotConnect::CSlotConnect(LPCSTR pTag, /*LPCSTR pCnvTxt,*/ bool IsSet, bool Inv) { m_sTag = pTag; m_bIsSet = IsSet; m_bIsGet = !IsSet; m_bInvert = Inv; m_bValid=false; m_eSrc=eCSD_Null; m_eDst=eCSD_Null; m_lSrcIndex=-1; m_lDstIndex=-1; m_bConnect1Done=false; m_pCdBlk = NULL; m_pCdBlkVar = NULL; m_lCdBlk=-1; m_pCdBlk=NULL; m_pCdBlkVar=NULL; m_bCdBlkVarFlt=false; } CSlotConnect::~CSlotConnect() { for (int i=0; i<m_Ops.GetSize(); i++) delete m_Ops[i]; }; // -------------------------------------------------------------------------- void CSlotConnect::SetDelayTimes(DWORD DelayTimeRise, DWORD DelayTimeFall) { m_Delay.m_UseValues = false; m_Delay.m_OnRise.SetSize(1); m_Delay.m_OnRise[0].m_dwTime=DelayTimeRise; m_Delay.m_OnFall.SetSize(1); m_Delay.m_OnFall[0].m_dwTime=DelayTimeFall; } // -------------------------------------------------------------------------- bool CSlotConnect::AddRiseValue(COleVariant v1, DWORD t1) { m_Delay.m_UseValues = true; int iLast=m_Delay.m_OnRise.GetSize(); m_Delay.m_OnRise.SetSize(iLast+1); m_Delay.m_OnRise[iLast].m_dwTime=t1; HRESULT hr=::VariantChangeType(&m_Delay.m_OnRise[iLast].m_Value, &v1, 0, VT_R8); return !FAILED(hr); }; // -------------------------------------------------------------------------- bool CSlotConnect::AddFallValue(COleVariant v1, DWORD t1) { m_Delay.m_UseValues = true; int iLast=m_Delay.m_OnFall.GetSize(); m_Delay.m_OnFall.SetSize(iLast+1); m_Delay.m_OnFall[iLast].m_dwTime=t1; HRESULT hr=::VariantChangeType(&m_Delay.m_OnFall[iLast].m_Value, &v1, 0, VT_R8); return !FAILED(hr); }; // -------------------------------------------------------------------------- void CSlotConnect::Initialise() { m_bValid=false; m_eSrc=eCSD_Null; m_eDst=eCSD_Null; m_lSrcIndex=-1; m_lDstIndex=-1; m_pCdBlk = NULL; m_pCdBlkVar = NULL; m_lCdBlk=-1; m_pCdBlk=NULL; m_pCdBlkVar=NULL; m_bCdBlkVarFlt=false; } // ----------------------------------------------------------------------- bool CSlotConnect::Connect(CSlot * pSlot) { long iDot; long iSpc; bool MustBeLink=false; Strng RootTag,WrkCnvTxt; m_sTag.TrimLeft(" "); m_sTag.TrimRight(" "); if ((iSpc=m_sTag.Find(' '))>0) { TaggedObject::SplitTagCnv((LPSTR)(LPCSTR)m_sTag, RootTag, WrkCnvTxt); TaggedObject::ValidateTag(RootTag); if (RootTag.Length()>0) { MustBeLink=true; } } else { // may be a link or something else RootTag=m_sTag; } //m_lLink=-1; m_lCdBlk=-1; m_eSrc=eCSD_Slot; m_lSrcIndex=pSlot->m_lSlot; m_lDstIndex=-1; m_bValid=false; m_pCdBlk=NULL; m_pCdBlkVar=NULL; if (!MustBeLink) { long iSlot=gs_SlotMngr.FindSlot(m_sTag); if (iSlot>=0) { m_eDst=eCSD_Slot; m_lDstIndex=iSlot; if (m_bIsGet) { Exchange(m_eSrc, m_eDst); Exchange(m_lSrcIndex, m_lDstIndex); gs_SlotMngr.m_Slots[m_lSrcIndex]->m_ReflectedGets.Add(this); } m_bValid=true; goto Done; } //Split Tag & Variable iDot=m_sTag.Find('.'); if (iDot>0) { CString CdTag=m_sTag.Left(iDot); CString Variable=m_sTag.Mid(iDot+1); if ((m_lCdBlk=gs_SlotMngr.FindCdBlk(CdTag))>=0) { //CString CdTag=Tag; //CString Variable=Var; m_eDst=eCSD_CdBlk; m_pCdBlk=gs_SlotMngr.m_CdBlks[m_lCdBlk]; m_pCdBlkVar=m_pCdBlk->m_Code.m_pVarList->FindTag((LPSTR)(LPCSTR)Variable); if (!m_pCdBlkVar) { pSlot->SetError(SErr_CdBlkTagMissing, "CodeBlock Tag '%s' not Found", Variable); return (m_bValid=false); goto Done; } switch (m_pCdBlkVar->WhatAmI()) { case VarDouble: m_bCdBlkVarFlt=true; break; case VarLong : case VarByte : case VarBit : m_bCdBlkVarFlt=false; break; default : pSlot->SetError(SErr_CdBlkTagBadType, "CodeBlock Tag '%s' Bad Type", Variable); m_bValid=false; goto Done; break; } if (m_bIsGet) { Exchange(m_eSrc, m_eDst); Exchange(m_lSrcIndex, m_lDstIndex); gs_SlotMngr.m_CdBlks[m_lCdBlk]->m_ReflectedGets.Add(this); } m_bValid=true; goto Done; } } } m_bValid=true; m_eDst=eCSD_Link; if (1) { CString LinkTag; if (0) { LinkTag=RootTag(); long i; while ((i=LinkTag.FindOneOf("."))>=0) LinkTag.SetAt(i, '_'); } else LinkTag = pSlot->m_sTag; m_lDstIndex=gs_SlotMngr.AddLink(pSlot, LinkTag, RootTag(), WrkCnvTxt(), pSlot->Type(), m_bIsGet, m_bIsSet); if (m_lDstIndex>=0) { if (m_bIsGet) { Exchange(m_eSrc, m_eDst); Exchange(m_lSrcIndex, m_lDstIndex); //EXCHANGE(eConnSrcDst, m_eSrc, m_eDst); //EXCHANGE(long, m_lSrcIndex, m_lDstIndex); gs_SlotMngr.m_Links[m_lSrcIndex]->m_ReflectedGets.Add(this); if (m_eSrc==eCSD_Link) { CLink &L=*gs_SlotMngr.m_Links[m_lSrcIndex]; CSlotConnArray &RGs=L.m_ReflectedGets; for (int rg=0; rg<RGs.GetSize(); rg++) { CSlotConnOpArray &Ops=RGs[rg]->m_Ops; for (int op=0; op<Ops.GetSize(); op++) { if (Ops[op]->IsConditioning()) { L.m_CondBlk.m_On = true; L.m_CondBlk.m_BaseValueValid = false; } } } } } else { } } } Done: //Dump(" "); return m_bValid; } // ----------------------------------------------------------------------- void CSlotConnect::CorrectConnects(CLongArray & NewNos) { if (m_eSrc==eCSD_Link) m_lSrcIndex=NewNos[m_lSrcIndex]; if (m_eDst==eCSD_Link) m_lDstIndex=NewNos[m_lDstIndex]; }; // ----------------------------------------------------------------------- void CSlotConnect::Dump(LPCSTR Hd) { dbgp("%sConn %s %s %s %10s %4i %10s ",//%4i Cd:%4i %08x %08x %s", Hd, m_bValid?"OK":" ", m_bIsGet?"Get":" ", m_bIsSet?"Set":" ", SrcDstString(m_eSrc), m_lSrcIndex, SrcDstString(m_eDst)); if (m_eDst==eCSD_CdBlk) dbgpln("Cd:%4i %08x %08x %s", m_lCdBlk, m_pCdBlk, m_pCdBlkVar, m_sTag); else dbgpln("%4i%22s%s", m_lDstIndex, "", m_sTag); for (int i=0; i<m_Delay.m_OnRise.GetCount(); i++) dbgpln(" Rise Delay %8.2f @ %5i msecs", m_Delay.m_OnRise[i].m_Value.dblVal, m_Delay.m_OnRise[i].m_dwTime); for (int i=0; i<m_Delay.m_OnFall.GetCount(); i++) dbgpln(" Fall Delay %8.2f @ %5i msecs", m_Delay.m_OnFall[i].m_Value.dblVal, m_Delay.m_OnFall[i].m_dwTime); } // ----------------------------------------------------------------------- void CSlotConnect::ApplyRangeLink2Slot(CSlot & S, COleVariant &V) { // Apply Range COMING into Link if (S.m_Range.m_bValid) { // Apply Range before going to Link if (IsFloatDataVT(V.vt)) { HRESULT hr=VariantChangeType(&V, &V, 0, VT_R8); if (FAILED(hr)) S.SetError(SErr_ApplyRangeLink2Slot, hr, ""); V.dblVal=(V.dblVal-S.m_Range.m_dMin)/(S.m_Range.m_dMax-S.m_Range.m_dMin); } else if (IsSignedDataVT(V.vt)) { HRESULT hr=VariantChangeType(&V, &V, 0, VT_I4); if (FAILED(hr)) S.SetError(SErr_ApplyRangeLink2Slot, hr, ""); V.lVal=(V.lVal-(long)S.m_Range.m_dMin)/(long)(S.m_Range.m_dMax-S.m_Range.m_dMin); } else if (IsUnsignedDataVT(V.vt)) { HRESULT hr=VariantChangeType(&V, &V, 0, VT_UI4); if (FAILED(hr)) S.SetError(SErr_ApplyRangeLink2Slot, hr, ""); V.ulVal=(V.ulVal-(unsigned long)S.m_Range.m_dMin)/(unsigned long)(S.m_Range.m_dMax-S.m_Range.m_dMin); } } } // ----------------------------------------------------------------------- void CSlotConnect::ApplyRangeSlot2Link(CSlot & S, COleVariant &V) { if (S.m_Range.m_bValid) { // Apply Range GOING to Link if (IsFloatDataVT(S.Type())) { V.ChangeType(VT_R8); V.dblVal=S.m_Range.m_dMin+V.dblVal*(S.m_Range.m_dMax-S.m_Range.m_dMin); } else if (IsSignedDataVT(S.Type())) { V.ChangeType(VT_I4); V.lVal=(long)S.m_Range.m_dMin+V.lVal*(long)(S.m_Range.m_dMax-S.m_Range.m_dMin); } else if (IsUnsignedDataVT(S.Type())) { V.ChangeType(VT_UI4); V.ulVal=(unsigned long)S.m_Range.m_dMin+V.ulVal*(unsigned long)(S.m_Range.m_dMax-S.m_Range.m_dMin); } } } // ----------------------------------------------------------------------- void CSlotConnect::Process(eConnSrcDst eSrc, long SrcI, eConnSrcDst eDst, long SrcDstI, CFullValue & SrcValue, int Direction) { // Always Executed as a SET - Hence the use of the ReflectedGets if (!m_bValid) return; if (eDst==eCSD_Default) eDst = m_eDst; switch (eDst) { case eCSD_Slot: { CFullValue V=SrcValue; ProcessOps(V); if (m_eSrc==eCSD_Link) ApplyRangeLink2Slot(*Slots[m_lDstIndex], V); gs_SlotMngr.AppendChange(eSrc, SrcI, eCSD_Slot, m_lDstIndex, -1, V, &m_Delay, false, !m_bConnect1Done); break; } case eCSD_CdBlk: { if (m_Delay.Configured()) { CFullValue V=SrcValue; gs_SlotMngr.AppendChange(eSrc, SrcI, eCSD_SlotConn, SrcDstI, -1, V, &m_Delay, false, !m_bConnect1Done); break; } // FALL THROUGH } case eCSD_SlotConn: { CFullValue V=SrcValue; ProcessOps(V); if (m_bCdBlkVarFlt) { V.ChangeType(VT_R8); m_pCdBlkVar->set(V.m_vValue.dblVal); } else { V.ChangeType(VT_I4); m_pCdBlkVar->set(V.m_vValue.lVal); } // Execute pgm CGExecContext ECtx(NULL); m_pCdBlk->m_Code.Execute(ECtx); // Update Destination Tags for (int i=0; i<m_pCdBlk->m_ReflectedGets.GetSize(); i++) { CSlotConnect &C=(*m_pCdBlk->m_ReflectedGets[i]); if (C.m_bCdBlkVarFlt) { CFullValue D=V; D.m_vValue=C.m_pCdBlkVar->getD(); C.ProcessOps(D); gs_SlotMngr.AppendChange(eCSD_CdBlk, C.m_lSrcIndex, C.m_eDst, C.m_lDstIndex, -1, D, &C.m_Delay, false, !m_bConnect1Done); } else { CFullValue L=V; L.m_vValue=C.m_pCdBlkVar->getL(); C.ProcessOps(L); gs_SlotMngr.AppendChange(eCSD_CdBlk, C.m_lSrcIndex, C.m_eDst, C.m_lDstIndex, -1, L, &C.m_Delay, false, !m_bConnect1Done); } } break; } case eCSD_Link: { CFullValue V=SrcValue; if (m_eSrc==eCSD_Slot) ApplyRangeSlot2Link(*Slots[m_lSrcIndex], V); ProcessOps(V); gs_SlotMngr.AppendChange(eSrc, m_lSrcIndex, eDst, m_lDstIndex, -1, V, &m_Delay, false, !m_bConnect1Done); break; } default: ReportError("CSlotConnect::Process", 0, "Invalid Destination %s ", SrcDstString(eDst)); } m_bConnect1Done=true; } // ----------------------------------------------------------------------- void CSlotConnect::ProcessOps(VARIANT &V) { if (m_Ops.GetSize() || m_bInvert) { COleVariant T; T.ChangeType(VT_R8, &V); if (m_bInvert && m_bIsGet) T.dblVal = (T.dblVal!=0? 0.0 : 1.0); for (int i=0; i<m_Ops.GetSize(); i++) T.dblVal=m_Ops[i]->Exec(T.dblVal, 0); if (m_bInvert && m_bIsSet) T.dblVal = (T.dblVal!=0? 0.0 : 1.0); VariantChangeType(&V, &T, 0, V.vt); } }; // ======================================================================= // // // // ======================================================================= long CSlotConnect::getSlotCount() const { return gs_SlotMngr.m_Slots.GetSize(); }; CSlot * CSlotConnect::getSlot(long Index) const { return gs_SlotMngr.m_Slots[Index]; }; void CSlotConnect::putSlot(long Index, CSlot * pSlot) { gs_SlotMngr.m_Slots[Index] = pSlot; }; long CSlotConnect::getLinkCount() const { return gs_SlotMngr.m_Links.GetSize(); }; CLink * CSlotConnect::getLink(long Index) const { return gs_SlotMngr.m_Links[Index]; }; void CSlotConnect::putLink(long Index, CLink * pLink) { gs_SlotMngr.m_Links[Index] = pLink; }; long CSlotConnect::getDeviceCount() const { return gs_SlotMngr.m_Devices.GetSize(); }; CDevice * CSlotConnect::getDevice(long Index) const { return gs_SlotMngr.m_Devices[Index]; }; void CSlotConnect::putDevice(long Index, CDevice * pDevice) { gs_SlotMngr.m_Devices[Index] = pDevice; }; // ======================================================================= // // // // =======================================================================
[ [ [ 1, 57 ], [ 59, 59 ], [ 61, 61 ], [ 63, 63 ], [ 65, 154 ], [ 156, 157 ], [ 160, 188 ], [ 190, 217 ], [ 219, 235 ], [ 237, 237 ], [ 243, 246 ], [ 271, 455 ], [ 468, 528 ], [ 530, 535 ], [ 540, 546 ], [ 548, 551 ], [ 562, 586 ], [ 588, 593 ], [ 595, 599 ], [ 601, 604 ], [ 606, 606 ], [ 610, 610 ], [ 612, 653 ] ], [ [ 58, 58 ], [ 60, 60 ], [ 62, 62 ], [ 64, 64 ], [ 155, 155 ], [ 158, 159 ], [ 189, 189 ], [ 218, 218 ], [ 236, 236 ], [ 238, 242 ], [ 247, 270 ], [ 456, 467 ], [ 529, 529 ], [ 536, 539 ], [ 547, 547 ], [ 552, 561 ], [ 587, 587 ], [ 594, 594 ], [ 600, 600 ], [ 605, 605 ], [ 607, 609 ], [ 611, 611 ] ] ]
dfb4346f8fb3ce276e2f55e8a7f4c71f675f0335
064195ded8860567e6d9e5cfad00bdb13d2d701d
/Directions.cpp
6d58bc8ce04022f340c4f81aa3e26121c7b9030b
[]
no_license
ryanbahneman/botsbcc
6aa8324d386c91f71946cd14384f0f47bbf13135
9f9a9b3fb4ce94b6c5fbdcb23176adcf0b8fa926
refs/heads/master
2021-01-15T18:50:56.961002
2009-04-02T20:59:32
2009-04-02T20:59:32
32,125,981
0
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
#include "Directions.h" Directions::Directions() { setNorth(false); setSouth(false); setEast(false); setWest(false); } Directions::Directions(bool north,bool south,bool east,bool west) { setNorth(north); setSouth(south); setEast(east); setWest(west); } /************************************************************ Getters & Setters for Directions **************************************************************/ bool Directions::getNorth(void) { return NORTH; } void Directions::setNorth(bool north) { NORTH=north; } bool Directions::getSouth(void) { return SOUTH; } void Directions::setSouth(bool south) { SOUTH=south; } bool Directions::getEast(void) { return EAST; } void Directions::setEast(bool east) { EAST=east; } bool Directions::getWest(void) { return WEST; } void Directions::setWest(bool west) { WEST = west; }
[ "[email protected]@545e0bd2-1449-11de-9d52-39b120432c5d" ]
[ [ [ 1, 59 ] ] ]
d6e15f64a6d02a14f0fb2b4a4f0e835845a0964b
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Agent/ConvexAgent/BoxBox/hkpBoxBoxManifold.h
f39265552b28a711dc39c82e73c59f49a53de55d
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,556
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_COLLIDE2_FEATURE_MANIFOLD_H #define HK_COLLIDE2_FEATURE_MANIFOLD_H #include <Physics/Collide/Agent/ConvexAgent/BoxBox/hkpBoxBoxContactPoint.h> class hkpCdBody; struct hkpProcessCollisionOutput; struct hkpCollisionInput; #define HK_BOXBOX_MANIFOLD_MAX_POINTS 8 class hkpBoxBoxManifold { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_CDINFO, hkpBoxBoxManifold ); hkpBoxBoxManifold(); // for 2.0 bridge int addPoint( const hkpCdBody& bodyA, const hkpCdBody& bodyB, hkpFeatureContactPoint& fcp ); void removePoint( int index ); inline int getNumPoints(); inline hkpFeatureContactPoint& operator[]( int index ); inline hkBool findInManifold( const hkpFeatureContactPoint& fcp ); inline hkBool isComplete(); inline void setComplete( hkBool complete ); inline hkBool hasNoPointsLeft(); public: hkpFeatureContactPoint m_contactPoints[HK_BOXBOX_MANIFOLD_MAX_POINTS]; hkUchar m_faceVertexFeatureCount; hkUchar m_numPoints; hkBool m_isComplete; // a complete manifold is one where no new points can be added via small rotations. hkBool m_manifoldNormalInitialized; hkUint32 m_manifoldNormalB; hkVector4 m_manifoldNormalA; }; #include <Physics/Collide/Agent/ConvexAgent/BoxBox/hkpBoxBoxManifold.inl> #endif // HK_COLLIDE2_FEATURE_MANIFOLD_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 80 ] ] ]
2bbde1d0c9c0269af3d3a17fe50e2d7a2295a6c5
1d6dcdeddc2066f451338361dc25196157b8b45c
/tp2/Escenario/Arbol.h
c0cc125694a0ebaea06971688c1846ccbb91d4e2
[]
no_license
nicohen/ssgg2009
1c105811837f82aaa3dd1f55987acaf8f62f16bb
467e4f475ef04d59740fa162ac10ee51f1f95f83
refs/heads/master
2020-12-24T08:16:36.476182
2009-08-15T00:43:57
2009-08-15T00:43:57
34,405,608
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
h
#ifndef ARBOL_H_INCLUDED #define ARBOL_H_INCLUDED #include "../Geometria/Curva.h" #include "Rama.h" class Arbol : public Dibujable{ public: /** Constructor: Construye una rama de orientacion aleatoria con hojas de orientacion aleatoria * @param modeladoHoja Es el modelo de hoja para las hojas de la rama * @param niveles Cantidad de ramas del arbol **/ Arbol(Curva* modeladoHoja, const unsigned short int niveles, Coordenadas* p); virtual ~Arbol(); /** * Dibuja el arbol en forma recursiva */ void dibujar(); /** Devuelve la ubicacion del arbol */ Coordenadas* getPosicion() { return this->posicion; } private: int nivelIzq; int nivelCtr; int nivelDer; Rama* raiz; unsigned short int niveles; Coordenadas* posicion; // crea el arbol void crearArbol(Rama* raiz); //Dibuja el arbol el forma recursiva a partir de la raiz pasada por parametro void dibujarRecursivo(Rama* raiz, int tipo); }; #endif // ARBOL_H_INCLUDED
[ "rodvar@6da81292-15a5-11de-a4db-e31d5fa7c4f0", "nicohen@6da81292-15a5-11de-a4db-e31d5fa7c4f0" ]
[ [ [ 1, 12 ], [ 14, 19 ], [ 25, 29 ], [ 32, 41 ] ], [ [ 13, 13 ], [ 20, 24 ], [ 30, 31 ] ] ]
746af01f7b8e93397b2b8d03b4386af38905eada
4b116281b895732989336f45dc65e95deb69917b
/Code Base/GSP410-Project2/Station.h
d203ca7df9e90d1cf744909ed99afccc2b94617b
[]
no_license
Pavani565/gsp410-spaceshooter
1f192ca16b41e8afdcc25645f950508a6f9a92c6
c299b03d285e676874f72aa062d76b186918b146
refs/heads/master
2021-01-10T00:59:18.499288
2011-12-12T16:59:51
2011-12-12T16:59:51
33,170,205
0
0
null
null
null
null
UTF-8
C++
false
false
143
h
#pragma once #include "Unit.h" #include "Definitions.h" class CStation : public CUnit { public: CStation(void); ~CStation(void); };
[ "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7" ]
[ [ [ 1, 10 ] ] ]
a090f9b444d8e3119cd57473867f32290a0d11fb
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Core/InGameMenuState.cpp
8a9fe4ad3e0cc61aaeb4398d4f670b11a3eead88
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
2,897
cpp
#include "OUAN_Precompiled.h" #include "InGameMenuState.h" #include "../Application.h" #include "../Graphics/RenderSubsystem.h" #include "../Audio/AudioSubsystem.h" #include "../GUI/GUISubsystem.h" #include "../GUI/GUIInGame.h" #include "GameStateManager.h" #include "MainMenuState.h" #include "GameOptionsState.h" #include "GameRunningState.h" using namespace OUAN; /// Default constructor InGameMenuState::InGameMenuState() :GameState() ,mClickChannel(-1) { } /// Destructor InGameMenuState::~InGameMenuState() { } /// init main menu's resources void InGameMenuState::init(ApplicationPtr app) { Logger::getInstance()->log("IN GAME MENU INIT"); GameState::init(app); mGUI=BOOST_PTR_CAST(GUIInGame,mApp->getGUISubsystem()->createGUI(GUI_LAYOUT_INGAMEMENU)); mGUI->initGUI(shared_from_this()); if (!mApp->getAudioSubsystem()->isLoaded("CLICK")) { mApp->getAudioSubsystem()->load("CLICK",AUDIO_RESOURCES_GROUP_NAME); } mApp->getGUISubsystem()->showCursor(); } /// Clean up main menu's resources void InGameMenuState::cleanUp() { GameState::cleanUp(); mGUI->destroy(); mApp->getGUISubsystem()->destroyGUI(); mApp->getGUISubsystem()->hideCursor(); } /// pause state void InGameMenuState::pause() { mGUI->destroy(); mApp->getGUISubsystem()->destroyGUI(); } /// resume state void InGameMenuState::resume() { mGUI=BOOST_PTR_CAST(GUIInGame,mApp->getGUISubsystem()->createGUI(GUI_LAYOUT_INGAMEMENU)); mGUI->initGUI(shared_from_this()); if (!mApp->getAudioSubsystem()->isLoaded("CLICK")) mApp->getAudioSubsystem()->load("CLICK",AUDIO_RESOURCES_GROUP_NAME); } /// process input events /// @param app the parent application void InGameMenuState::handleEvents() { int pad; int key; if (mApp->isPressedMenu(&pad,&key)) { mApp->getGameStateManager()->popState(); } } /// Update game according to the current state /// @param app the parent app void InGameMenuState::update(long elapsedTime) { GameState::update(elapsedTime); } void InGameMenuState::backToGame() { mApp->getAudioSubsystem()->playSound("CLICK",mClickChannel); mApp->getGameStateManager()->popState(); } void InGameMenuState::goToOptions() { mApp->getAudioSubsystem()->playSound("CLICK",mClickChannel); GameStatePtr nextState(new GameOptionsState()); //mApp->getGameStateManager()->changeState(nextState,mApp); mApp->getGameStateManager()->pushState(nextState,mApp); } void InGameMenuState::backToMenu() { mApp->getAudioSubsystem()->playSound("CLICK",mClickChannel); // if (openYesNoDialog("Are you sure you want to quit?")) mApp->mBackToMenu=true; mApp->getGameStateManager()->popState(); } void InGameMenuState::quit() { mApp->getAudioSubsystem()->playSound("CLICK",mClickChannel); // if (openYesNoDialog("Are you sure you want to quit?")) mApp->mExitRequested=true; }
[ "ithiliel@1610d384-d83c-11de-a027-019ae363d039", "wyern1@1610d384-d83c-11de-a027-019ae363d039", "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 33 ], [ 37, 38 ], [ 40, 40 ], [ 42, 42 ], [ 45, 50 ], [ 53, 76 ], [ 81, 81 ], [ 83, 89 ], [ 91, 97 ], [ 99, 118 ] ], [ [ 34, 34 ], [ 82, 82 ] ], [ [ 35, 36 ], [ 39, 39 ], [ 41, 41 ], [ 43, 44 ], [ 51, 52 ], [ 77, 80 ], [ 90, 90 ], [ 98, 98 ] ] ]
b14c827d07e571e65b8f3675969ac6e117f08e60
03d1f3dd8c9284b93890648d65a1589276ef505f
/VisualSPH/Render11/Render11.cpp
2134e21d0c158478447a17664e34ac526aade4e0
[]
no_license
shadercoder/photonray
18271358ca7f20a3c4a6326164d292774bfc3f53
e0bbad33bc9c03e094036748f965100023aa0287
refs/heads/master
2021-01-10T04:20:14.592834
2011-05-07T21:09:43
2011-05-07T21:09:43
45,577,179
0
0
null
null
null
null
UTF-8
C++
false
false
26,054
cpp
//-------------------------------------------------------------------------------------- // File: Render11.cpp // // This sample shows an simple implementation of the DirectX 11 Hardware Tessellator // for rendering a Bezier Patch. // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTgui.h" #include "DXUTsettingsDlg.h" #include "SDKmisc.h" #include "resource.h" #include <time.h> #include "Axis.h" #include "gMetaballs.h" #include "gParticlesRender.h" #include "ParticlesContainer.h" #include "Settings.h" #define DEG2RAD( a ) ( a * D3DX_PI / 180.f ) //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CModelViewerCamera g_Camera; // A model viewing camera CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // manages the 3D CDXUTDialog g_SampleUI; // dialog for sample specific controls // Resources CDXUTTextHelper* g_pTxtHelper = NULL; D3DXMATRIX g_World; float g_fScale = 0.0f; float g_fMetaballsSize = 0.0f; bool g_bSpinning = false; bool g_Capture = false; ParticlesContainer particlesContainer; gMetaballs metaballs; gParticlesRender particleRender; Settings appSettings; Axis axis; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 2 #define IDC_CHANGEDEVICE 3 #define IDC_TOGGLESPIN 4 #define IDC_VOLUME_SCALE 5 #define IDC_VOLUME_STATIC 6 #define IDC_TOGGLEWARP 7 #define IDC_META_STATIC 8 #define IDC_META_SCALE 9 #define IDC_RENDERTYPE 10 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ); void CALLBACK OnD3D11DestroyDevice( void* pUserContext ); void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ); void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void InitApp(); void RenderText(); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // DXUT will create and use the best device (either D3D10 or D3D11) // that is available on the system depending on which D3D callbacks are set below // Set DXUT callbacks DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( KeyboardProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable ); DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice ); DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain ); DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender ); DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain ); DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice ); InitApp(); DXUTInit( true, true ); // Parse the command line, show msgboxes on error, and an extra cmd line param to force REF for now DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"Render11" ); DXUTCreateDevice( D3D_FEATURE_LEVEL_11_0, true, appSettings.screenWidth, appSettings.screenHeight ); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); } void DisableMetaballsGUI() { g_SampleUI.GetStatic(IDC_META_STATIC)->SetVisible(FALSE); g_SampleUI.GetSlider(IDC_META_SCALE)->SetVisible(FALSE); } void EnableMetaballsGUI() { g_SampleUI.GetStatic(IDC_META_STATIC)->SetVisible(TRUE); g_SampleUI.GetSlider(IDC_META_SCALE)->SetVisible(TRUE); } void InitGUI() { g_D3DSettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_SampleUI.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22, VK_F3 ); g_HUD.AddButton( IDC_TOGGLEWARP, L"Toggle WARP (F4)", 35, iY += 24, 125, 22, VK_F4 ); D3DXCOLOR bg( 0.0f, 0.125f, 0.3f, 0.2f); //g_SampleUI.SetBackgroundColors(bg, bg, bg, bg); g_SampleUI.SetCallback( OnGUIEvent ); iY = 10; g_SampleUI.AddComboBox( IDC_RENDERTYPE, 35, iY += 24, 120, 22, 0, false); g_SampleUI.GetComboBox( IDC_RENDERTYPE)->SetDropHeight(40); g_SampleUI.GetComboBox( IDC_RENDERTYPE)->AddItem( L"Metaballs", (void*) 0); g_SampleUI.GetComboBox( IDC_RENDERTYPE)->AddItem( L"Particles", (void*) 1); WCHAR sz[100]; iY += 24; swprintf_s( sz, 100, L"Volume scale: %0.2f", g_fScale ); g_SampleUI.AddStatic( IDC_VOLUME_STATIC, sz, 35, iY += 24, 125, 22 ); g_SampleUI.AddSlider( IDC_VOLUME_SCALE, 50, iY += 24, 100, 22, 0, appSettings.volumeResolution * 100, ( int )( g_fScale * 100.0f ) ); iY += 24; swprintf_s( sz, 100, L"Metaballs size: %0.2f", g_fMetaballsSize ); g_SampleUI.AddStatic( IDC_META_STATIC, sz, 35, iY += 24, 125, 22 ); g_SampleUI.AddSlider( IDC_META_SCALE, 50, iY += 24, 100, 22, 1, 128 * 100, ( int )( g_fMetaballsSize * 100.0f ) ); switch (appSettings.renderState) { case PARTICLES: { DisableMetaballsGUI(); g_SampleUI.GetComboBox( IDC_RENDERTYPE)->SetSelectedByIndex(1); break; } case METABALLS: { g_SampleUI.GetComboBox( IDC_RENDERTYPE)->SetSelectedByIndex(0); break; } } } //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { g_fScale = 40.0f; g_fMetaballsSize = 5.0f; g_bSpinning = false; appSettings.loadFromFile("settings.txt"); particlesContainer.init(appSettings.pathToFolder, appSettings.patternString, appSettings.firstFrame, appSettings.lastFrame, appSettings.stepFrame); InitGUI(); } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; if( ( DXUT_D3D9_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) || ( DXUT_D3D11_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) ) { DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } } return true; } //-------------------------------------------------------------------------------------- // Handle updates to the scene //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // Update the camera's position based on user input g_Camera.FrameMove( fElapsedTime ); if( g_bSpinning ) D3DXMatrixRotationY( &g_World, 60.0f * DEG2RAD((float)fTime) ); else D3DXMatrixRotationY( &g_World, DEG2RAD( 180.0f ) ); D3DXMATRIX mTranslate; D3DXMatrixTranslation(&mTranslate, -0.5f, -0.5f, -0.5f); D3DXMATRIX mRot; D3DXMatrixRotationX( &mRot, DEG2RAD( -90.0f ) ); g_World = mTranslate * mRot * g_World; D3DXMATRIX view = g_World * (*g_Camera.GetViewMatrix()); axis.onFrameMove(g_World * (*g_Camera.GetViewMatrix()) * (*g_Camera.GetProjMatrix()), view); switch(appSettings.renderState) { case METABALLS: { metaballs.onFrameMove(g_World * (*g_Camera.GetViewMatrix()) * (*g_Camera.GetProjMatrix())); break; } case PARTICLES: { particleRender.onFrameMove(g_World * (*g_Camera.GetViewMatrix()) * (*g_Camera.GetProjMatrix()), view); break; } } } //-------------------------------------------------------------------------------------- // Render the help and statistics text //-------------------------------------------------------------------------------------- void RenderText() { g_pTxtHelper->Begin(); g_pTxtHelper->SetInsertionPos( 2, 0 ); g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) ); g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() ); g_pTxtHelper->End(); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Pass messages to dialog resource manager calls so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass messages to settings dialog if its active if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { // Standard DXUT controls case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break; case IDC_TOGGLESPIN: { g_bSpinning = g_SampleUI.GetCheckBox( IDC_TOGGLESPIN )->GetChecked(); break; } case IDC_VOLUME_SCALE: { if (nEvent == EVENT_SLIDER_VALUE_CHANGED) { WCHAR sz[100]; g_fScale = ( float )( g_SampleUI.GetSlider( IDC_VOLUME_SCALE )->GetValue() * 0.01f ); swprintf_s( sz, 100, L"Volume scale: %0.2f", g_fScale ); g_SampleUI.GetStatic( IDC_VOLUME_STATIC )->SetText( sz ); if (appSettings.renderState == METABALLS) { metaballs.updateVolume(particlesContainer.getParticles(), particlesContainer.getParticlesCount(), g_fScale, g_fMetaballsSize); } else if (appSettings.renderState == PARTICLES) { particleRender.updateParticles(particlesContainer.getParticles(), g_fScale); } break; } } case IDC_META_SCALE: { if (nEvent == EVENT_SLIDER_VALUE_CHANGED) { WCHAR sz[100]; g_fMetaballsSize = ( float )( g_SampleUI.GetSlider( IDC_META_SCALE )->GetValue() * 0.01f ); swprintf_s( sz, 100, L"Metaballs scale: %0.2f", g_fMetaballsSize ); g_SampleUI.GetStatic( IDC_META_STATIC )->SetText( sz ); metaballs.updateVolume(particlesContainer.getParticles(), particlesContainer.getParticlesCount(), g_fScale, g_fMetaballsSize); break; } } case IDC_RENDERTYPE: { if (nEvent == EVENT_COMBOBOX_SELECTION_CHANGED) { int renderType = (int) g_SampleUI.GetComboBox(IDC_RENDERTYPE)->GetSelectedIndex(); if (renderType == 0) { appSettings.renderState = METABALLS; EnableMetaballsGUI(); metaballs.updateVolume(particlesContainer.getParticles(), particlesContainer.getParticlesCount(), g_fScale, g_fMetaballsSize); } else if (renderType == 1) { appSettings.renderState = PARTICLES; DisableMetaballsGUI(); particleRender.updateParticles(particlesContainer.getParticles(), g_fScale); } } } } } //-------------------------------------------------------------------------------------- // Reject any D3D11 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { return true; } ////-------------------------------------------------------------------------------------- //// Find and compile the specified shader ////-------------------------------------------------------------------------------------- //HRESULT CompileShaderFromFile( WCHAR* szFileName, D3D_SHADER_MACRO* pDefines, LPCSTR szEntryPoint, // LPCSTR szShaderModel, ID3DBlob** ppBlobOut ) //{ // HRESULT hr = S_OK; // // // find the file // WCHAR str[MAX_PATH]; // V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ) ); // // DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; //#if defined( DEBUG ) || defined( _DEBUG ) // // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders. // // Setting this flag improves the shader debugging experience, but still allows // // the shaders to be optimized and to run exactly the way they will run in // // the release configuration of this program. // dwShaderFlags |= D3DCOMPILE_DEBUG; //#endif // // ID3DBlob* pErrorBlob; // hr = D3DX11CompileFromFile( str, pDefines, NULL, szEntryPoint, szShaderModel, // dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL ); // if( FAILED(hr) ) // { // if( pErrorBlob != NULL ) // OutputDebugStringA( (char*)pErrorBlob->GetBufferPointer() ); // SAFE_RELEASE( pErrorBlob ); // return hr; // } // SAFE_RELEASE( pErrorBlob ); // // return S_OK; //} //-------------------------------------------------------------------------------------- // Create any D3D11 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; CComPtr<ID3D11DeviceContext> pd3dImmediateContext = DXUTGetD3D11DeviceContext(); V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) ); g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 ); // Initialize the world matrices D3DXMatrixIdentity( &g_World ); // Initialize the camera g_Camera.SetViewParams( &appSettings.cameraPos, &appSettings.cameraLookAt); metaballs.init(pd3dDevice, pd3dImmediateContext, appSettings.screenWidth, appSettings.screenHeight, appSettings.volumeResolution); metaballs.updateVolume(particlesContainer.getParticles(), particlesContainer.getParticlesCount(), g_fScale, g_fMetaballsSize); particleRender.init(pd3dDevice, pd3dImmediateContext); particleRender.updateParticles(particlesContainer.getParticles(), g_fScale); axis.init(pd3dDevice, pd3dImmediateContext); return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D11 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); V_RETURN( g_D3DSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); // Setup the camera's projection parameters float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; g_Camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.1f, 20.0f ); g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); g_Camera.SetButtonMasks( MOUSE_MIDDLE_BUTTON, MOUSE_WHEEL, MOUSE_LEFT_BUTTON ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, 170 ); g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 ); g_SampleUI.SetSize( 170, 300 ); switch(appSettings.renderState) { case METABALLS: { metaballs.onFrameResize(pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height); break; } case PARTICLES: { break; } } return S_OK; } void CaptureScreen(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pDevContext, char* fileName) { HRESULT hr; CComPtr<ID3D11RenderTargetView> pRTV = DXUTGetD3D11RenderTargetView(); CComPtr<ID3D11Resource> backbufferRes; pRTV->GetResource(&backbufferRes); D3D11_RENDER_TARGET_VIEW_DESC rtDesc; pRTV->GetDesc(&rtDesc); D3D11_TEXTURE2D_DESC texDesc; texDesc.ArraySize = 1; texDesc.BindFlags = 0; texDesc.CPUAccessFlags = 0; texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; texDesc.Width = appSettings.screenWidth; // must be same as backbuffer texDesc.Height = appSettings.screenHeight; // must be same as backbuffer texDesc.MipLevels = 1; texDesc.MiscFlags = 0; texDesc.SampleDesc.Count = 1; texDesc.SampleDesc.Quality = 0; texDesc.Usage = D3D11_USAGE_DEFAULT; CComPtr<ID3D11Texture2D> texture; HR( pd3dDevice->CreateTexture2D(&texDesc, 0, &texture) ); pDevContext->CopyResource(texture, backbufferRes); V( D3DX11SaveTextureToFileA(pDevContext, texture, D3DX11_IFF_PNG, fileName) ); //texture->Release(); //backbufferRes->Release(); } //-------------------------------------------------------------------------------------- // Render the scene using the D3D11 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ) { if (g_Capture) { char fileName[64] = {}; char date[32] = {}; char time[32] = {}; _strdate_s(date, sizeof(date)); _strtime_s(time, sizeof(time)); sprintf_s(fileName, "frame%d-(%c%c_%c%c_%c%c-%c%c_%c%c_%c%c).png", particlesContainer.getNumCurrFrame(), date[0], date[1], date[3], date[4], date[6], date[7], time[0], time[1], time[3], time[4], time[6], time[7]); CaptureScreen(pd3dDevice, pd3dImmediateContext, fileName); g_Capture = FALSE; } // If the settings dialog is being shown, then render it instead of rendering the app's scene if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.OnRender( fElapsedTime ); return; } // Clear the render target and depth stencil float ClearColor[4] = { 0.552f, 0.713f, 0.803f, 1.0f }; CComPtr<ID3D11RenderTargetView> pRTV = DXUTGetD3D11RenderTargetView(); pd3dImmediateContext->ClearRenderTargetView( pRTV, ClearColor ); CComPtr<ID3D11DepthStencilView> pDSV = DXUTGetD3D11DepthStencilView(); pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0, 0 ); axis.draw(); switch(appSettings.renderState) { case METABALLS: { metaballs.draw(); break; } case PARTICLES: { particleRender.draw(); break; } } // // Render the UI // g_HUD.OnRender( fElapsedTime ); g_SampleUI.OnRender( fElapsedTime ); // For debug only //if(particlesContainer.getNumCurrFrame() + 1 < appSettings.lastFrame) //{ // particlesContainer.getNextFrame(); // switch(appSettings.renderState) // { // case METABALLS: // { // metaballs.updateVolume(particlesContainer.getParticles(), particlesContainer.getParticlesCount(), g_fScale, g_fMetaballsSize); // break; // } // case PARTICLES: // { // particleRender.updateParticles(particlesContainer.getParticles(), g_fScale); // break; // } // } //} //else //{ // exit(0); //} // Render the HUD DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" ); g_HUD.OnRender( fElapsedTime ); g_SampleUI.OnRender( fElapsedTime ); RenderText(); DXUT_EndPerfEvent(); } //-------------------------------------------------------------------------------------- // Release D3D11 resources created in OnD3D10ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ) { g_DialogResourceManager.OnD3D11ReleasingSwapChain(); } //-------------------------------------------------------------------------------------- // Release D3D11 resources created in OnD3D10CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11DestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D11DestroyDevice(); g_DialogResourceManager.~CDXUTDialogResourceManager(); g_D3DSettingsDlg.OnD3D11DestroyDevice(); DXUTGetGlobalResourceCache().OnDestroyDevice(); SAFE_DELETE( g_pTxtHelper ); //metaballs.~gMetaballs(); //axis.~Axis(); //particleRender.~gParticlesRender(); } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { if( bKeyDown ) { switch( nChar ) { case VK_F1: break; case 'r': case 'R': { particlesContainer.getFrame(appSettings.firstFrame); switch(appSettings.renderState) { case METABALLS: { metaballs.updateVolume(particlesContainer.getParticles(), particlesContainer.getParticlesCount(), g_fScale, g_fMetaballsSize); break; } case PARTICLES: { particleRender.updateParticles(particlesContainer.getParticles(), g_fScale); break; } } break; } case 'n': case 'N': { particlesContainer.getNextFrame(); switch(appSettings.renderState) { case METABALLS: { metaballs.updateVolume(particlesContainer.getParticles(), particlesContainer.getParticlesCount(), g_fScale, g_fMetaballsSize); break; } case PARTICLES: { particleRender.updateParticles(particlesContainer.getParticles(), g_fScale); break; } } break; } case 'b': case 'B': { particlesContainer.getPrevFrame(); switch(appSettings.renderState) { case METABALLS: { metaballs.updateVolume(particlesContainer.getParticles(), particlesContainer.getParticlesCount(), g_fScale, g_fMetaballsSize); break; } case PARTICLES: { particleRender.updateParticles(particlesContainer.getParticles(), g_fScale); break; } } break; } case VK_F9: { g_Capture = true; break; } } } }
[ "[email protected]", "ilyakrukov@f2d442f5-4fb6-3e1e-f2a6-32ff9b5dcf3a" ]
[ [ [ 1, 35 ], [ 37, 192 ], [ 195, 242 ], [ 244, 389 ], [ 425, 433 ], [ 435, 494 ], [ 497, 513 ], [ 515, 518 ], [ 521, 549 ], [ 551, 551 ], [ 553, 625 ], [ 627, 629 ], [ 633, 713 ] ], [ [ 36, 36 ], [ 193, 194 ], [ 243, 243 ], [ 390, 424 ], [ 434, 434 ], [ 495, 496 ], [ 514, 514 ], [ 519, 520 ], [ 550, 550 ], [ 552, 552 ], [ 626, 626 ], [ 630, 632 ] ] ]
6878dafe1963f32d951965b3d43a1e52d82bde5e
0f457762985248f4f6f06e29429955b3fd2c969a
/irrlicht/sdk/irr_bullet/CBulletPhysicsUtils.h
d4c239a4e9e3d31041ea995959e6d17935be9ecf
[]
no_license
tk8812/ukgtut
f19e14449c7e75a0aca89d194caedb9a6769bb2e
3146ac405794777e779c2bbb0b735b0acd9a3f1e
refs/heads/master
2021-01-01T16:55:07.417628
2010-11-15T16:02:53
2010-11-15T16:02:53
37,515,002
0
0
null
null
null
null
UHC
C++
false
false
5,838
h
// Helper functions to use with CBulletPhysics #ifndef __C_BULLET_PHYSICS_UTILS_H_INCLUDED__ #define __C_BULLET_PHYSICS_UTILS_H_INCLUDED__ //! Irrlicht #include "irrlicht.h" class btTriangleIndexVertexArray; class btTriangleMesh; class btConvexHullShape; //! Bullet #include "LinearMath/btVector3.h" #include "LinearMath/btMatrix3x3.h" #include "LinearMath/btTransform.h" //! useful defines #define SAFE_DELETE(p) {if(p) {delete (p); (p)=0;}} #define SAFE_DELETE_ARRAY(p) {if(p) {delete [] (p); (p)=0;}} //! useful constants const double BPU_PI = 3.1415926535897932384626433832795; const double BPU_PI2 = 3.1415926535897932384626433832795/2.; const double BPU_360_PI2 = 360./(BPU_PI2); const double BPU_PI_180 = BPU_PI/180.; const double BPU_180_PI = 180./BPU_PI; //============================================================================== //============================================================================== //============================================================================== //------------------------------------------------------------------------------ //! Convert Quaternion to Euler (btQuaternion to irr::core::vector3df) //! euler is measured in radians SIMD_FORCE_INLINE void QuaternionToEulerXYZ(const btQuaternion& quat, irr::core::vector3df& euler) { irr::f32 w=quat.getW(), x=quat.getX(), y=quat.getY(), z=quat.getZ(); double sqx = x*x, sqy = y*y, sqz = z*z; // heading euler.Z = atan2(btScalar(2.0*(z*w+x*y)), btScalar(1.0 - 2.0*(sqy + sqz))); // bank euler.X = atan2(btScalar(2.0*(x*w+y*z)), btScalar(1.0 - 2.0*(sqx + sqy))); // attitude euler.Y = asin(btScalar(2.0*(-x*z + y*w))); } //------------------------------------------------------------------------------ //! Convert Euler to Quaternion (irr::core::vector3df to btQuaternion) //! euler is measured in radians SIMD_FORCE_INLINE void EulerXYZToQuaternion(const irr::core::vector3df& euler, btQuaternion &quat) { btScalar _heading = (btScalar)(euler.Z*0.5); btScalar _attitude= (btScalar)(euler.Y*0.5); btScalar _bank = (btScalar)(euler.X*0.5); btScalar c1 = cos(_heading); btScalar s1 = sin(_heading); btScalar c2 = cos(_attitude); btScalar s2 = sin(_attitude); btScalar c3 = cos(_bank); btScalar s3 = sin(_bank); double c1c2 = c1*c2; double s1s2 = s1*s2; //w quat.setW((btScalar) (c1c2*c3 + s1s2*s3)); //x quat.setX((btScalar) (c1c2*s3 - s1s2*c3)); //y quat.setY((btScalar) (c1*s2*c3 + s1*c2*s3)); //z quat.setZ((btScalar) (s1*c2*c3 - c1*s2*s3)); } //============================================================================== //============================================================================== //============================================================================== //------------------------------------------------------------------------------ //! Extract node position to btTransform SIMD_FORCE_INLINE void GetNodeTransform(irr::scene::ISceneNode* pNode, btTransform& pTransform) { pTransform.setIdentity(); irr::core::vector3df rot = pNode->getRotation(); rot *= (irr::f32)BPU_PI_180; btQuaternion btq; EulerXYZToQuaternion(rot, btq); pTransform.setRotation(btq); irr::core::vector3df pos = pNode->getPosition(); btVector3 btv(pos.X, pos.Y, pos.Z); pTransform.setOrigin(btv); } //------------------------------------------------------------------------------ //! Convert irrlicht to bullet SIMD_FORCE_INLINE void Irrlicht2Bullet(irr::core::vector3df &in,btVector3 &out) { //out.setValue(in.X,in.Y,in.Z,0); out.setValue(in.X,in.Y,in.Z); } SIMD_FORCE_INLINE void Irrlicht2Bullet(irr::core::quaternion &in,btQuaternion &out) { out.setValue(in.X,in.Y,in.Z,in.W); } //이건 100%검증안됨.. SIMD_FORCE_INLINE void Irrlicht2Bullet(irr::core::matrix4 &in,btTransform &out) { out.getBasis()[0].setValue(in[0],in[4],in[8]); out.getBasis()[1].setValue(in[1],in[5],in[9]); out.getBasis()[2].setValue(in[2],in[6],in[10]); } //------------------------------------------------------------------------------ //! Convert bullet to irrlicht SIMD_FORCE_INLINE void Bullet2Irrlicht(btVector3 &in,irr::core::vector3df &out) { out = irr::core::vector3df(in.getX(),in.getY(),in.getZ()); } SIMD_FORCE_INLINE void Bullet2Irrlicht(btQuaternion &in,irr::core::quaternion &out) { out = irr::core::quaternion(in.getX(),in.getY(),in.getZ(),in.getW()); } //------------------------------------------------------------------------------ //! ConvertIrrMeshToBulletTriangleArray //! Irrlicht uses u16 index buffer, we should convert it to use with bullet //! (btTriangleIndexVertexArray seems to be slower than btTriangleMesh, strange) btTriangleIndexVertexArray* ConvertIrrMeshToBulletTriangleArray(irr::scene::IMesh* pMesh, const irr::core::vector3df& scaling = irr::core::vector3df(1.0f, 1.0f, 1.0f)); //------------------------------------------------------------------------------ //! ConvertIrrMeshToBulletTriangleMesh //! Convert to IMesh data to btTriangleMesh btTriangleMesh* ConvertIrrMeshToBulletTriangleMesh(irr::scene::IMesh* pMesh, const irr::core::vector3df& scaling = irr::core::vector3df(1.0f, 1.0f, 1.0f)); //------------------------------------------------------------------------------ //! ConvertIrrMeshToBulletConvexHullShape //! ConvexHullShape implements an implicit (getSupportingVertex) //! Convex Hull of a Point Cloud (vertices) //! No connectivity is needed. btConvexHullShape* ConvertIrrMeshToBulletConvexHullShape(irr::scene::IMesh* pMesh, const irr::core::vector3df& scaling = irr::core::vector3df(1.0f, 1.0f, 1.0f)); #endif //__C_BULLET_PHYSICS_UTILS_H_INCLUDED__
[ "gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b" ]
[ [ [ 1, 157 ] ] ]
870d668f488e37f19a2be34f09c091f5998c129e
daef491056b6a9e227eef3e3b820e7ee7b0af6b6
/Trunk/code/toolkit/platform/x11/x11_events.cpp
0473ae69413923b5dbb86db4a8f4a345a6e5623d
[ "BSD-3-Clause" ]
permissive
BackupTheBerlios/gut-svn
de9952b8b3e62cedbcfeb7ccba0b4d267771dd95
0981d3b37ccfc1ff36cd79000f6c6be481ea4546
refs/heads/master
2021-03-12T22:40:32.685049
2006-07-07T02:18:38
2006-07-07T02:18:38
40,725,529
0
0
null
null
null
null
UTF-8
C++
false
false
7,373
cpp
/********************************************************************** * GameGut - x11_events.cpp * Copyright (c) 1999-2005 Jason Perkins. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the BSD-style license that is * included with this library in the file LICENSE.txt. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * files LICENSE.txt for more details. **********************************************************************/ #include "core/core.h" #include "x11_platform.h" #include <stdio.h> static bool myKeyRepeating(XEvent* xevent); static int myTranslateKeycode(XEvent* event); static void mySendCharEvent(XEvent* xevent, utEvent* event); extern int utx_x11_keymap[]; /* This is hacky. The API requires me to send position deltas for the mouse, * but X11 passes in absolute window coordinates. So I use these to convert * coordinate systems between updates */ static int my_mouseX = -1; static int my_mouseY = -1; /**************************************************************************** * Called by utPollEvents(); empties the system message queue ****************************************************************************/ int utxPollEvents(int block) { /* If non-blocking and there are no events available, return immediately */ if (!block && !XPending(utx_display)) return true; /* Empty the queue */ do { XEvent xevent; XNextEvent(utx_display, &xevent); /* Find the window associated with this event. I'll need it in order * to populate a utEvent to send back to the host */ utWindow window = utFindWindowByHandle((void*)xevent.xany.window); if (window == NULL) continue; utEvent event; event.window = window; event.when = 0; event.arg0 = 0; event.arg1 = 0; event.arg2 = 0; switch (xevent.type) { case Expose: event.what = UT_EVENT_WINDOW_REDRAW; utxSendWindowEvent(&event); break; case ClientMessage: if ((Atom)(xevent.xclient.data.l[0]) == utx_wmDeleteAtom) { event.what = UT_EVENT_WINDOW_CLOSE; utxSendWindowEvent(&event); } break; case ConfigureNotify: event.what = UT_EVENT_WINDOW_RESIZE; event.arg0 = xevent.xconfigure.width; event.arg1 = xevent.xconfigure.height; if (event.arg0 != window->width || event.arg1 != window->height) { window->width = event.arg0; window->height = event.arg1; utxSendWindowEvent(&event); } break; case FocusIn: event.what = UT_EVENT_WINDOW_FOCUS; event.arg0 = 1; utxSendWindowEvent(&event); break; case FocusOut: event.what = UT_EVENT_WINDOW_FOCUS; event.arg0 = 0; utxSendWindowEvent(&event); break; case KeyPress: event.what = UT_EVENT_KEY; event.when = xevent.xkey.time; event.arg0 = 0; event.arg1 = myTranslateKeycode(&xevent); event.arg2 = MAX_INPUT; utxSendInputEvent(&event); mySendCharEvent(&xevent, &event); break; case KeyRelease: /* X autorepeat works by sending additional key release/press * pairs, to make it look like the key is getting tapped. */ event.when = xevent.xkey.time; event.arg0 = 0; event.arg1 = myTranslateKeycode(&xevent); if (myKeyRepeating(&xevent)) { event.what = UT_EVENT_KEY_REPEAT; event.arg2 = MAX_INPUT; utxSendInputEvent(&event); mySendCharEvent(&xevent, &event); } else { event.what = UT_EVENT_KEY; event.arg2 = 0; utxSendInputEvent(&event); } break; case MappingNotify: utxReleaseAllButtons(); XRefreshKeyboardMapping((XMappingEvent*)(&xevent)); break; case ButtonPress: case ButtonRelease: event.what = UT_EVENT_MOUSE_BUTTON; event.when = xevent.xbutton.time; event.arg0 = 0; /* Make button indices match Win32 */ event.arg1 = xevent.xbutton.button - 1; if (event.arg1 == 2) event.arg1 = 1; else if (event.arg1 == 1) event.arg1 = 2; event.arg2 = (xevent.type == ButtonPress) ? MAX_INPUT : 0; utxSendInputEvent(&event); break; case MotionNotify: if (my_mouseX < 0) my_mouseX = xevent.xmotion.x; if (my_mouseY < 0) my_mouseY = xevent.xmotion.y; event.what = UT_EVENT_MOUSE_AXIS; event.when = xevent.xmotion.time; event.arg0 = 0; if (xevent.xmotion.x != my_mouseX) { event.arg1 = 0; event.arg2 = xevent.xmotion.x - my_mouseX; utxSendInputEvent(&event); } if (xevent.xmotion.y != my_mouseY) { event.arg1 = 1; event.arg2 = xevent.xmotion.y - my_mouseY; utxSendInputEvent(&event); } my_mouseX = xevent.xmotion.x; my_mouseY = xevent.xmotion.y; break; } } while (XPending(utx_display)); return true; } /**************************************************************************** * Called by utxInputFocusChanged() in ut_input.cpp when the user has * switched to a different application. Unused for this platform. ****************************************************************************/ int utxResetInputPlatform() { return true; } /**************************************************************************** * Helper function to convert an X11 keycode into a Toolkit keycode ****************************************************************************/ static int myTranslateKeycode(XEvent* xevent) { /* Start by getting a keysym */ XKeyEvent* event = (XKeyEvent*)xevent; KeySym keysym = XLookupKeysym(event, 0); if (keysym == 0) { switch (event->keycode) { case 0x73: return UT_KEY_LEFTSYSTEM; case 0x74: return UT_KEY_RIGHTSYSTEM; case 0x75: return UT_KEY_MENU; } } /* Convert the keysym to a Toolkit keycode */ if (keysym & 0xff00) return (utx_x11_keymap[keysym & 0x00ff] >> 16); else return (utx_x11_keymap[keysym] & 0xffff); } /**************************************************************************** * Called when a key release event is detected; checks to see if it is * immediately followed by a key press, which is how X11 does autorepeat ****************************************************************************/ bool myKeyRepeating(XEvent* xevent) { /* XPeekEvent will block if there are no messages waiting */ if (XPending(utx_display)) { /* Get the next event without actually removing it from the queue */ XEvent next; XPeekEvent(utx_display, &next); /* Do the two messages match up? */ if (next.type == KeyPress && next.xkey.keycode == xevent->xkey.keycode && next.xkey.time == xevent->xkey.time) { /* It's a repeat, remove the event from the queue */ XNextEvent(utx_display, &next); return true; } } return false; } /**************************************************************************** * Translates a keycode into a ASCII character and sends a char event. I * have a feeling this is woefully insufficient but it is all I found ****************************************************************************/ void mySendCharEvent(XEvent* xevent, utEvent* event) { char buffer[2]; if (XLookupString((XKeyEvent*)xevent, buffer, sizeof(buffer), 0, 0) > 0) { event->what = UT_EVENT_CHAR; event->arg0 = 0; event->arg1 = buffer[0]; event->arg2 = MAX_INPUT; utxSendInputEvent(event); } }
[ "starkos@5eb1f239-c603-0410-9f17-9cbfe04d0a06" ]
[ [ [ 1, 267 ] ] ]
ee5c797083c5091d032214bae18503286b4798f0
b957e10ed5376dbe85c07bdef1f510f641984a1a
/Vulture.h
e49ed6e8f599c467225bfe1b9433d676ebb71244
[]
no_license
alexjshank/motors
063245c206df936a886f72a22f0f15c78e1129cb
7193b729466d8caece267f0b8ddbf16d99c13f8a
refs/heads/master
2016-09-10T15:47:20.906269
2009-11-04T18:41:21
2009-11-04T18:41:21
33,394,870
0
0
null
null
null
null
UTF-8
C++
false
false
202
h
#pragma once #include "unit.h" #include "peasant.h" class Vulture : public Unit { public: Vulture(); ~Vulture(); void init(); void Think(); float lastEatTime; Sheep *food; };
[ "alexjshank@0c9e2a0d-1447-0410-93de-f5a27bb8667b" ]
[ [ [ 1, 17 ] ] ]
0aecc6bf9025523f1c01dc9ea7c6782269a13952
d01196cdfc4451c4e1c88343bdb1eb4db9c5ac18
/source/server/ents/basefunc.cpp
70a76256a73e4cdd6c362cdbbde500ca1a2de169
[]
no_license
ferhan66h/Xash3D_ancient
7491cd4ff1c7d0b48300029db24d7e08ba96e88a
075e0a6dae12a0952065eb9b2954be4a8827c72f
refs/heads/master
2021-12-10T07:55:29.592432
2010-05-09T00:00:00
2016-07-30T17:37:36
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
71,877
cpp
//======================================================================= // Copyright (C) Shambler Team 2004 // basefunc.cpp - brush based entities: tanks, // cameras, vehicles etc //======================================================================= #include "extdll.h" #include "utils.h" #include "cbase.h" #include "sfx.h" #include "decals.h" #include "client.h" #include "saverestore.h" #include "gamerules.h" #include "basebrush.h" #include "defaults.h" #include "player.h" //======================================================================= // STATIC BRUSHES //======================================================================= //======================================================================= // func_wall - standard not moving wall. affect to physics //======================================================================= class CFuncWall : public CBaseBrush { public: void Spawn( void ); void TurnOn( void ); void TurnOff( void ); void Precache( void ){ CBaseBrush::Precache(); } void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); }; LINK_ENTITY_TO_CLASS( func_wall, CFuncWall ); LINK_ENTITY_TO_CLASS( func_static, CFuncWall ); LINK_ENTITY_TO_CLASS( func_wall_toggle, CFuncWall ); LINK_ENTITY_TO_CLASS( func_illusionary, CFuncWall ); void CFuncWall :: Spawn( void ) { CBaseBrush::Spawn(); if( FClassnameIs( pev, "func_illusionary" )) { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; } else { pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; } UTIL_SetModel( ENT(pev), pev->model ); // Smart field system ® if (!FStringNull( pev->angles ) && FStringNull( pev->origin )) { pev->angles = g_vecZero; ALERT( at_console, "\n======/Xash SmartField System/======\n\n"); ALERT( at_console, "Create origin brush for %s,\nif we want correctly set angles\n\n", STRING( pev->classname )); } pev->angles[1] = 0 - pev->angles[1]; if( pev->spawnflags & SF_START_ON ) TurnOn(); else TurnOff(); } void CFuncWall :: TurnOff( void ) { if(FClassnameIs(pev, "func_wall_toggle" )) { pev->solid = SOLID_NOT; pev->effects |= EF_NODRAW; UTIL_SetOrigin( this, pev->origin ); } else pev->frame = 0; m_iState = STATE_OFF; } void CFuncWall :: TurnOn( void ) { if(FClassnameIs(pev, "func_wall_toggle" )) { pev->solid = SOLID_BSP; pev->effects &= ~EF_NODRAW; UTIL_SetOrigin( this, pev->origin ); } else pev->frame = 1; m_iState = STATE_ON; } void CFuncWall :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_TOGGLE ) { if( pev->frame ) useType = USE_OFF; else useType = USE_ON; } if ( useType == USE_ON ) TurnOn(); else if ( useType == USE_OFF ) TurnOff(); else if ( useType == USE_SET ) // make wall invisible { pev->solid = SOLID_NOT; pev->effects |= EF_NODRAW; UTIL_SetOrigin( this, pev->origin ); } else if ( useType == USE_RESET ) // make wall visible { if(!( pev->spawnflags & SF_NOTSOLID )) pev->solid = SOLID_BSP; pev->effects &= ~EF_NODRAW; UTIL_SetOrigin( this, pev->origin ); } else if ( useType == USE_SHOWINFO ) { ALERT( at_console, "======/Xash Debug System/======\n" ); ALERT( at_console, "classname: %s\n", STRING( pev->classname )); ALERT( at_console, "State: %s, Visible: %s\n", GetStringForState( GetState()), pev->effects & EF_NODRAW ? "No" : "Yes" ); ALERT( at_console, "Contents: %s, Texture frame: %.f\n", GetContentsString( pev->skin ), pev->frame ); } } //======================================================================= // func_breakable - generic breakable brush. //======================================================================= class CFuncBreakable : public CBaseBrush { public: void Spawn( void ); void Precache( void ){ CBaseBrush::Precache(); } void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); }; LINK_ENTITY_TO_CLASS( func_breakable, CFuncBreakable ); void CFuncBreakable :: Spawn( void ) { CBaseBrush::Spawn(); UTIL_SetModel( ENT( pev ), pev->model ); if ( FBitSet( pev->spawnflags, SF_BREAK_TRIGGER_ONLY )) pev->takedamage = DAMAGE_NO; else pev->takedamage = DAMAGE_YES; } void CFuncBreakable :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( IsBreakable( )) { Die(); // simple huh ? } } //======================================================================= // func_lamp - switchable brush light. //======================================================================= class CFuncLamp : public CBaseBrush { public: void Spawn( void ); void Precache( void ){ CBaseBrush::Precache(); } void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); virtual int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ); void TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType ); void EXPORT Flicker( void ); void Die( void ); }; // please don't this in current Xash3D version // lightstyles on arealights currently not supported // LINK_ENTITY_TO_CLASS( func_lamp, CFuncLamp ); LINK_ENTITY_TO_CLASS( func_lamp, CFuncWall ); // temporary moved here void CFuncLamp :: Spawn( void ) { m_Material = Glass; CBaseBrush::Spawn(); UTIL_SetModel( ENT( pev ), pev->model ); if( pev->spawnflags & SF_START_ON ) Use( this, this, USE_ON, 0 ); else Use( this, this, USE_OFF, 0 ); } void CFuncLamp :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if(IsLockedByMaster( useType )) return; if(m_iState == STATE_DEAD && useType != USE_SHOWINFO)return;//lamp is broken if (useType == USE_TOGGLE) { if(m_iState == STATE_OFF) useType = USE_ON; else useType = USE_OFF; } if (useType == USE_ON) { if(m_flDelay)//make flickering delay { pev->frame = 0;//light texture is on m_iState = STATE_TURN_ON; LIGHT_STYLE(m_iStyle, "mmamammmmammamamaaamammma"); SetThink( Flicker ); SetNextThink(m_flDelay); } else { //instantly enable m_iState = STATE_ON; pev->frame = 0;//light texture is on LIGHT_STYLE(m_iStyle, "k"); UTIL_FireTargets( pev->target, this, this, USE_ON );//lamp enable } } else if (useType == USE_OFF) { pev->frame = 1; // light texture is off LIGHT_STYLE( m_iStyle, "a" ); UTIL_FireTargets( pev->target, this, this, USE_OFF ); // lamp disable m_iState = STATE_OFF; } else if ( useType == USE_SET ) { Die(); // broke lamp with sfx } else if ( useType == USE_RESET ) // broke lamp silent { pev->frame = 1; // light texture is off LIGHT_STYLE( m_iStyle, "a" ); m_iState = STATE_DEAD; pev->health = 0; } else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "State: %s, Light style %d\n", GetStringForState( GetState()), m_iStyle ); ALERT( at_console, "Texture frame: %.f. Health %.f\n", pev->frame, pev->health ); } } void CFuncLamp::TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType ) { if(m_iState == STATE_DEAD) return; const char *pTextureName; Vector start = pevAttacker->origin + pevAttacker->view_ofs; Vector end = start + vecDir * 1024; edict_t *pWorld = ptr->pHit; if ( pWorld )pTextureName = TRACE_TEXTURE( pWorld, start, end ); if ( strstr( pTextureName, "+0~" ) || strstr( pTextureName, "~" )) // take damage only at light texture { UTIL_Sparks( ptr->vecEndPos ); pev->oldorigin = ptr->vecEndPos;//save last point of damage pev->takedamage = DAMAGE_YES;//inflict damage only at light texture } else pev->takedamage = DAMAGE_NO; CBaseLogic::TraceAttack( pevAttacker, flDamage, vecDir, ptr, bitsDamageType ); } int CFuncLamp::TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ) { if ( bitsDamageType & DMG_BLAST ) flDamage *= 3; else if ( bitsDamageType & DMG_CLUB) flDamage *= 2; else if ( bitsDamageType & DMG_SONIC ) flDamage *= 1.2; else if ( bitsDamageType & DMG_SHOCK ) flDamage *= 10; // !!!! over voltage else if ( bitsDamageType & DMG_BULLET) flDamage *= 0.5;// half damage at bullet pev->health -= flDamage;//calculate health if ( pev->health <= 0 ) { Die(); return 0; } CBaseBrush::DamageSound(); return 1; } void CFuncLamp::Die( void ) { // lamp is random choose die style if( m_iState == STATE_OFF ) { pev->frame = 1; // light texture is off LIGHT_STYLE( m_iStyle, "a" ); DontThink(); } else { // simple randomization pev->impulse = RANDOM_LONG(1, 2); SetThink( Flicker ); SetNextThink( 0.1 + (RANDOM_LONG( 1, 2 ) * 0.1 )); } m_iState = STATE_DEAD; // lamp is die pev->health = 0; // set health to NULL pev->takedamage = DAMAGE_NO; UTIL_FireTargets( pev->target, this, this, USE_OFF ); // lamp broken switch ( RANDOM_LONG( 0, 1 )) { case 0: EMIT_SOUND( ENT( pev ), CHAN_VOICE, "materials/glass/bustglass1.wav", 0.7, ATTN_IDLE ); break; case 1: EMIT_SOUND( ENT( pev ), CHAN_VOICE, "materials/glass/bustglass2.wav", 0.8, ATTN_IDLE ); break; } Vector vecSpot = pev->origin + (pev->mins + pev->maxs) * 0.5; // spawn glass gibs SFX_MakeGibs( m_idShard, vecSpot, pev->size, g_vecZero, 50, BREAK_GLASS ); } void CFuncLamp :: Flicker( void ) { if ( m_iState == STATE_TURN_ON ) // flickering on enable { LIGHT_STYLE( m_iStyle, "k" ); UTIL_FireTargets( pev->target, this, this, USE_ON );//Lamp enabled m_iState = STATE_ON; DontThink(); return; } if ( pev->impulse == 1 ) // fadeout on break { pev->frame = 1; // light texture is off LIGHT_STYLE( m_iStyle, "a" ); SetThink( NULL ); return; } if ( pev->impulse == 2 ) // broken flickering { //make different flickering switch ( RANDOM_LONG( 0, 3 )) { case 0: LIGHT_STYLE(m_iStyle, "abcaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); break; case 1: LIGHT_STYLE(m_iStyle, "acaaabaaaaaaaaaaaaaaaaaaaaaaaaaaa"); break; case 2: LIGHT_STYLE(m_iStyle, "aaafbaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); break; case 3: LIGHT_STYLE(m_iStyle, "aaaaaaaaaaaaagaaaaaaaaacaaaacaaaa"); break; } pev->frags = RANDOM_FLOAT(0.5, 10); UTIL_Sparks( pev->oldorigin ); switch ( RANDOM_LONG( 0, 2 )) { case 0: EMIT_SOUND( ENT(pev), CHAN_VOICE, "materials/spark1.wav", 0.4, ATTN_IDLE ); break; case 1: EMIT_SOUND( ENT(pev), CHAN_VOICE, "materials/spark2.wav", 0.3, ATTN_IDLE ); break; case 2: EMIT_SOUND( ENT(pev), CHAN_VOICE, "materials/spark3.wav", 0.35, ATTN_IDLE ); break; } if( pev->frags > 6.5f ) pev->impulse = 1; // stop sparking obsolete } SetNextThink( pev->frags ); } //======================================================================= // func_conveyor - conveyor belt //======================================================================= class CFuncConveyor : public CBaseBrush { public: void Spawn( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); }; LINK_ENTITY_TO_CLASS( func_conveyor, CFuncConveyor ); void CFuncConveyor :: Spawn( void ) { SetObjectClass( ED_BSPBRUSH ); CBaseBrush::Spawn(); UTIL_LinearVector( this ); // movement direction if( !m_pParent ) pev->flags |= FL_WORLDBRUSH; UTIL_SetModel( ENT(pev), STRING( pev->model )); if( pev->spawnflags & SF_NOTSOLID ) pev->movetype = MOVETYPE_NONE; else pev->movetype = MOVETYPE_CONVEYOR; // smart field system ® if( pev->speed == 0 ) pev->speed = 100; pev->frags = pev->speed; // save initial speed if( pev->spawnflags & SF_START_ON || FStringNull( pev->targetname )) Use( this, this, USE_ON, 0 ); } void CFuncConveyor :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if(IsLockedByMaster( useType )) return; if( useType == USE_TOGGLE ) { if( m_iState == STATE_ON ) useType = USE_OFF; else useType = USE_ON; } if( useType == USE_ON ) { pev->speed = pev->frags; // restore speed UTIL_FireTargets( pev->target, this, this, USE_ON, pev->speed ); if(!( pev->spawnflags & SF_NOTSOLID )) // don't push pev->movetype = MOVETYPE_CONVEYOR; m_iState = STATE_ON; } else if( useType == USE_OFF ) { pev->speed = 0.0f; UTIL_FireTargets( pev->target, this, this, USE_OFF, pev->speed ); pev->movetype = MOVETYPE_NONE; m_iState = STATE_OFF; } else if( useType == USE_SET ) // set new speed { if( value != 0.0f ) pev->frags = value; // set new speed ( can be negative ) else pev->frags = -pev->frags; // just reverse if( m_iState == STATE_ON ) pev->speed = pev->frags; } else if( useType == USE_RESET ) // restore default speed { pev->frags = 100.0f; if( m_iState == STATE_ON ) pev->speed = pev->frags; } else if( useType == USE_SHOWINFO ) { ALERT( at_console, "======/Xash Debug System/======\n" ); ALERT( at_console, "classname: %s\n", STRING( pev->classname )); ALERT( at_console, "State: %s, Conveyor speed %f\n\n", GetStringForState( GetState()), pev->speed ); } } //======================================================================= // func_mirror - breakable mirror brush (engine feature) //======================================================================= class CFuncMirror : public CBaseBrush { public: void Spawn( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); STATE GetState( void ) { return (pev->effects & EF_NODRAW) ? STATE_OFF : STATE_ON; } }; LINK_ENTITY_TO_CLASS( func_mirror, CFuncMirror ); void CFuncMirror :: Spawn( void ) { m_Material = Glass; CBaseBrush::Spawn(); // setup mirror SetObjectClass( ED_PORTAL ); pev->oldorigin = pev->origin; } void CFuncMirror :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_TOGGLE ) { if( GetState() == STATE_ON ) useType = USE_OFF; else useType = USE_ON; } if ( useType == USE_ON ) { pev->effects &= ~EF_NODRAW; } else if ( useType == USE_OFF ) { pev->effects |= EF_NODRAW; } if( useType == USE_SET ) Die(); if( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "State: %s, halth %g\n\n", GetStringForState( GetState()), pev->health ); } } //======================================================================= // func_monitor - A monitor that renders the view from a camera entity. //======================================================================= class CFuncMonitor : public CBaseBrush { public: void Spawn( void ); void Precache( void ){ CBaseBrush::Precache(); } void StartMessage( CBasePlayer *pPlayer ); void ChangeCamera( string_t newcamera ); void KeyValue( KeyValueData *pkvd ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); virtual BOOL IsFuncScreen( void ) { return TRUE; } virtual STATE GetState( void ) { return pev->body ? STATE_ON:STATE_OFF; }; virtual int ObjectCaps( void ); BOOL OnControls( entvars_t *pevTest ); CBaseEntity *pCamera; }; LINK_ENTITY_TO_CLASS( func_monitor, CFuncMonitor ); void CFuncMonitor::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "camera")) { pev->target = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } if (FStrEq(pkvd->szKeyName, "type")) { pev->impulse = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } if (FStrEq(pkvd->szKeyName, "mode")) { pev->skin = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseBrush::KeyValue( pkvd ); } void CFuncMonitor :: Spawn() { m_Material = Computer; CBaseBrush::Spawn(); if(pev->spawnflags & SF_NOTSOLID)//make illusionary wall { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; } else { pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; } UTIL_SetModel(ENT(pev), pev->model ); //enable monitor if(pev->spawnflags & SF_START_ON)pev->body = 1; } int CFuncMonitor :: ObjectCaps( void ) { if ( pev->impulse ) return (CBaseEntity::ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | FCAP_IMPULSE_USE; else return (CBaseEntity::ObjectCaps() & ~FCAP_ACROSS_TRANSITION); } void CFuncMonitor::StartMessage( CBasePlayer *pPlayer ) { // send monitor index ChangeCamera( pev->target ); } void CFuncMonitor::ChangeCamera( string_t newcamera ) { pCamera = UTIL_FindEntityByTargetname( NULL, STRING( newcamera )); if( pCamera ) pev->sequence = pCamera->entindex(); else if( pev->body ) pev->frame = 1; // noise if not found camera // member newcamera name pev->target = newcamera; } void CFuncMonitor :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if(IsLockedByMaster( useType )) return; if (useType == USE_TOGGLE) { if(pev->body) useType = USE_OFF; else useType = USE_ON; } if (useType == USE_ON)pev->body = 1; else if (useType == USE_OFF) { pev->body = 0; pev->frame = 0; } else if ( useType == USE_SET ) { if( pActivator->IsPlayer()) { if ( value ) { UTIL_SetView( pActivator, iStringNull, 0 ); } else if ( pev->body ) { UTIL_SetView( pev->target, CAMERA_ON ); m_pController = (CBasePlayer*)pActivator; m_pController->m_pMonitor = this; if (m_pParent) m_vecPlayerPos = m_pController->pev->origin - m_pParent->pev->origin; else m_vecPlayerPos = m_pController->pev->origin; } } } else if (useType == USE_SHOWINFO) { DEBUGHEAD; Msg( "State: %s, Mode: %s\n", GetStringForState( GetState()), pev->skin ? "Color" : "B&W"); Msg( "Type: %s. Camera Name: %s\n", pev->impulse ? "Duke Nukem Style" : "Half-Life 2 Style", STRING( pev->target) ); } } BOOL CFuncMonitor :: OnControls( entvars_t *pevTest ) { if(m_pParent && ((m_vecPlayerPos + m_pParent->pev->origin) - pevTest->origin).Length() <= 30) return TRUE; else if((m_vecPlayerPos - pevTest->origin).Length() <= 30 ) return TRUE; return FALSE; } //======================================================================= // func_teleport - classic XASH portal //======================================================================= class CFuncTeleport : public CFuncMonitor { public: void Spawn( void ); void Touch ( CBaseEntity *pOther ); void KeyValue( KeyValueData *pkvd ); void StartMessage( CBasePlayer *pPlayer ); }; LINK_ENTITY_TO_CLASS( func_portal, CFuncTeleport ); LINK_ENTITY_TO_CLASS( trigger_teleport, CFuncTeleport ); void CFuncTeleport :: Spawn( void ) { pev->solid = SOLID_TRIGGER; pev->movetype = MOVETYPE_NONE; UTIL_SetModel(ENT(pev), pev->model); if (FClassnameIs(pev, "func_portal")) //portal mode { pev->impulse = 0;//can't use teleport pev->body = 1;//enabled } else SetBits( pev->effects, EF_NODRAW );//classic mode } void CFuncTeleport::StartMessage( CBasePlayer *pPlayer ) { ChangeCamera( pev->target ); } void CFuncTeleport :: KeyValue( KeyValueData *pkvd ) { if ( FStrEq( pkvd->szKeyName, "landmark" )) { pev->message = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else if ( FStrEq( pkvd->szKeyName, "firetarget" )) { pev->netname = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseLogic::KeyValue( pkvd ); } void CFuncTeleport :: Touch( CBaseEntity *pOther ) { entvars_t* pevToucher = pOther->pev; CBaseEntity *pTarget = NULL; // only teleport monsters or clients or projectiles if( !FBitSet( pevToucher->flags, FL_CLIENT|FL_MONSTER|FL_PROJECTILE ) && !pOther->IsPushable()) return; if( IsLockedByMaster( pOther )) return; pTarget = UTIL_FindEntityByTargetname( pTarget, STRING( pev->target )); if( !pTarget ) return; CBaseEntity *pLandmark = UTIL_FindEntityByTargetname( NULL, STRING( pev->message )); if ( pLandmark ) { Vector vecOriginOffs = pTarget->pev->origin - pLandmark->pev->origin; if( pOther->pev->flags & FL_PROJECTILE ) { pOther->pev->angles = UTIL_VecToAngles( pOther->pev->velocity ); } // do we need to rotate the entity? if ( pLandmark->pev->angles != pTarget->pev->angles ) { Vector vecVA; float ydiff = pTarget->pev->angles.y - pLandmark->pev->angles.y; // set new angle to face pOther->pev->angles.y -= ydiff; if( pOther->IsPlayer()) { pOther->pev->angles.x = pOther->pev->viewangles.x; pOther->pev->fixangle = TRUE; } // set new velocity vecVA = UTIL_VecToAngles( pOther->pev->velocity ); vecVA.y += ydiff; UTIL_MakeVectors(vecVA); pOther->pev->velocity = gpGlobals->v_forward * pOther->pev->velocity.Length(); pOther->pev->velocity.z = -pOther->pev->velocity.z; // set new origin Vector vecPlayerOffs = pOther->pev->origin - pLandmark->pev->origin; vecVA = UTIL_VecToAngles(vecPlayerOffs); UTIL_MakeVectors(vecVA); vecVA.y += ydiff; UTIL_MakeVectors(vecVA); Vector vecPlayerOffsNew = gpGlobals->v_forward * vecPlayerOffs.Length(); vecPlayerOffsNew.z = -vecPlayerOffsNew.z; vecOriginOffs = vecOriginOffs + vecPlayerOffsNew - vecPlayerOffs; } UTIL_SetOrigin( pOther, pOther->pev->origin + vecOriginOffs ); } else { Vector tmp = pTarget->pev->origin; if( pOther->IsPlayer( )) tmp.z -= pOther->pev->mins.z; // make origin adjustments tmp.z++; UTIL_SetOrigin( pOther, tmp ); UTIL_MakeVectors( pTarget->pev->angles ); pOther->pev->angles = pTarget->pev->angles; pOther->pev->velocity = gpGlobals->v_forward * 300; if( pOther->IsPlayer( )) { pOther->pev->viewangles = pTarget->pev->angles; pOther->pev->fixangle = TRUE; } } ChangeCamera( pev->target ); // update PVS pevToucher->flags &= ~FL_ONGROUND; pevToucher->fixangle = TRUE; pevToucher->teleport_time = gpGlobals->time + 0.7; UTIL_FireTargets( pev->netname, pOther, this, USE_TOGGLE ); // fire target } //======================================================================= // ANGULAR MOVING BRUSHES //======================================================================= //======================================================================= // func_rotate - typically non moving wall. affect to physics //======================================================================= class CFuncRotating : public CBaseBrush { public: void Spawn( void ); void Precache( void ); void KeyValue( KeyValueData* pkvd); void Touch ( CBaseEntity *pOther ); void Blocked( CBaseEntity *pOther ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void Think( void ); void PostActivate ( void ); void RampPitchVol ( void ); void SetSpeed( float newspeed ); void SetAngularImpulse( float impulse ); float flDegree; }; LINK_ENTITY_TO_CLASS( func_rotating, CFuncRotating ); void CFuncRotating :: KeyValue( KeyValueData* pkvd) { if( FStrEq( pkvd->szKeyName, "spintime" )) { pev->frags = atof(pkvd->szValue); pkvd->fHandled = TRUE; } if( FStrEq( pkvd->szKeyName, "spawnorigin" )) { Vector tmp; UTIL_StringToVector( tmp, pkvd->szValue ); if( tmp != g_vecZero ) pev->origin = tmp; pkvd->fHandled = TRUE; } else CBaseBrush::KeyValue( pkvd ); } void CFuncRotating :: Precache( void ) { CBaseBrush::Precache(); int m_sounds = UTIL_LoadSoundPreset( m_iMoveSound ); switch( m_sounds ) { case 1: pev->noise3 = UTIL_PrecacheSound( "fans/fan1.wav" ); break; case 2: pev->noise3 = UTIL_PrecacheSound( "fans/fan2.wav" ); break; case 3: pev->noise3 = UTIL_PrecacheSound( "fans/fan3.wav" ); break; case 4: pev->noise3 = UTIL_PrecacheSound( "fans/fan4.wav" ); break; case 5: pev->noise3 = UTIL_PrecacheSound( "fans/fan5.wav" ); break; case 0: pev->noise3 = UTIL_PrecacheSound( "common/null.wav" ); break; default: pev->noise3 = UTIL_PrecacheSound( m_sounds ); break; } } void CFuncRotating :: Spawn( void ) { Precache(); CBaseBrush::Spawn(); if ( pev->spawnflags & SF_NOTSOLID ) { pev->solid = SOLID_NOT; pev->skin = CONTENTS_EMPTY; pev->movetype = MOVETYPE_PUSH; } else { pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; } SetBits (pFlags, PF_ANGULAR);//enetity has angular velocity m_iState = STATE_OFF; m_pitch = PITCH_NORM - 1; pev->dmg_save = 0;//cur speed is NULL pev->button = pev->speed;//member start speed AxisDir(); UTIL_SetOrigin(this, pev->origin); UTIL_SetModel( ENT(pev), pev->model ); } void CFuncRotating :: Touch ( CBaseEntity *pOther ) { // don't hurt toucher - just apply velocity him entvars_t *pevOther = pOther->pev; pevOther->velocity = (pevOther->origin - VecBModelOrigin(pev) ).Normalize() * pev->dmg; } void CFuncRotating :: Blocked( CBaseEntity *pOther ) { if(m_pParent && m_pParent->edict() && pFlags & PF_PARENTMOVE) m_pParent->Blocked( pOther ); UTIL_AssignAngles(this, pev->angles ); if ( gpGlobals->time < m_flBlockedTime)return; m_flBlockedTime = gpGlobals->time + 0.1; if((m_iState == STATE_OFF || m_iState == STATE_TURN_OFF) && pev->avelocity.Length() < 350) { SetAngularImpulse(-(pev->dmg_save + RANDOM_FLOAT( 5, 10))); return; } if(pOther->TakeDamage( pev, pev, fabs(pev->speed), DMG_CRUSH ))//blocked entity died ? { SetAngularImpulse(-(pev->dmg_save + RANDOM_FLOAT( 10, 20))); UTIL_FireTargets( pev->target, this, this, USE_SET );//damage } else if (RANDOM_LONG(0,1)) { SetSpeed( 0 );//fan damaged - disable it UTIL_FireTargets( pev->target, this, this, USE_SET ); //fan damaged( we can use counter and master for bloked broken fan) } if(!pOther->IsPlayer() && !pOther->IsMonster())//crash fan { if(IsBreakable())//if set strength - give damage myself CBaseBrush::TakeDamage( pev, pev, fabs(pev->speed/100), DMG_CRUSH );//if we give damage } } void CFuncRotating :: PostActivate () { if( pev->spawnflags & SF_START_ON ) SetSpeed( pev->speed ); ClearBits( pev->spawnflags, SF_START_ON ); if(m_iState == STATE_ON ) // restore sound if needed EMIT_SOUND_DYN( ENT(pev), CHAN_STATIC, (char *)STRING(pev->noise3), m_flVolume, ATTN_NORM, SND_CHANGE_PITCH | SND_CHANGE_VOL, m_pitch); SetNextThink( 0.05 ); // force to think } void CFuncRotating :: RampPitchVol ( void ) { float fpitch; int pitch; float speedfactor = fabs(pev->dmg_save/pev->button); m_flVolume = speedfactor; //slowdown volume ramps down to 0 fpitch = PITCHMIN + (PITCHMAX - PITCHMIN) * speedfactor; pitch = (int)fpitch; if( pitch == PITCH_NORM ) pitch = PITCH_NORM-1; // normalize volume and pitch if( m_flVolume > 1.0 ) m_flVolume = 1.0; if( m_flVolume < 0.0 ) m_flVolume = 0.0; if( pitch < PITCHMIN ) pitch = PITCHMIN; if( pitch > 255 ) pitch = 255; m_pitch = pitch;//refresh pitch EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, (char *)STRING(pev->noise3), m_flVolume, ATTN_NORM, SND_CHANGE_PITCH|SND_CHANGE_VOL, m_pitch ); } void CFuncRotating :: SetSpeed( float newspeed ) { float speedfactor = fabs(pev->dmg_save/pev->speed);//speedfactor pev->armortype = gpGlobals->time; //starttime pev->armorvalue = newspeed - pev->dmg_save; //speed offset pev->scale = pev->dmg_save; //cur speed //any speed change is turn on //may be it's wrong, but nice working :) if((pev->dmg_save > 0 && newspeed < 0) || (pev->dmg_save < 0 && newspeed > 0))//detect fast reverse { if(m_iState != STATE_OFF)pev->dmg_take = pev->frags * speedfactor;//fast reverse else pev->dmg_take = pev->frags;//get normal time m_iState = STATE_TURN_ON; } else if(newspeed == 0) { m_iState = STATE_TURN_OFF; pev->dmg_take = pev->frags * 2.5 * speedfactor;//spin down is longer } else //just change speed, not zerocrossing { m_iState = STATE_TURN_ON; pev->dmg_take = pev->frags;//get normal time } SetNextThink( 0.05 );//force to think } void CFuncRotating :: SetAngularImpulse( float impulse ) { if( fabs(impulse) < 20)pev->scale = fabs(impulse / MAX_AVELOCITY); else pev->scale = 0.01;//scale factor m_iState = STATE_OFF;//impulse disable fan pev->dmg_save = pev->dmg_save + impulse;//add our impulse to curspeed //normalize avelocity if(pev->dmg_save > MAX_AVELOCITY)pev->dmg_save = MAX_AVELOCITY; pev->max_health = MatFrictionTable( m_Material);//set friction coefficient SetNextThink(0.05);//pushable entity must thinking for apply velocity } void CFuncRotating :: Think( void ) { if(m_iState == STATE_TURN_ON || m_iState == STATE_TURN_OFF) { flDegree = (gpGlobals->time - pev->armortype)/pev->dmg_take; if (flDegree >= 1)//full spin { if(m_iState == STATE_TURN_ON) { m_iState = STATE_ON; pev->dmg_save = pev->speed;//normalize speed UTIL_SetAvelocity(this, pev->movedir * pev->speed);//set normalized avelocity EMIT_SOUND_DYN(ENT(pev), CHAN_STATIC, (char *)STRING(pev->noise3), m_flVolume, ATTN_NORM, SND_CHANGE_PITCH | SND_CHANGE_VOL, m_pitch); UTIL_FireTargets( pev->target, this, this, USE_ON );//fan is full on } if(m_iState == STATE_TURN_OFF) { m_iState = STATE_OFF; if (pev->movedir == Vector(0,0,1)) SetAngularImpulse(RANDOM_FLOAT(3.9, 6.8) * -pev->dmg_save); //set small negative impulse for pretty phys effect :) } } else { //calc new speed every frame pev->dmg_save = pev->scale + pev->armorvalue * flDegree; UTIL_SetAvelocity(this, pev->movedir * pev->dmg_save); RampPitchVol(); //play pitched sound } } if(m_iState == STATE_OFF)//apply impulse and friction { if(pev->dmg_save > 0)pev->dmg_save -= pev->max_health * pev->scale + 0.01; else if(pev->dmg_save < 0)pev->dmg_save += pev->max_health * pev->scale + 0.01; UTIL_SetAvelocity(this, pev->movedir * pev->dmg_save); RampPitchVol(); //play pitched sound } //ALERT(at_console, "pev->avelocity %.2f %.2f %.2f\n", pev->avelocity.x, pev->avelocity.y, pev->avelocity.z); SetNextThink( 0.05 ); if(pev->avelocity.Length() < 0.5)//watch for speed { UTIL_SetAvelocity(this, g_vecZero);//stop EMIT_SOUND_DYN(ENT(pev), CHAN_STATIC, (char *)STRING(pev->noise3), 0, 0, SND_STOP, m_pitch); DontThink();//break thinking UTIL_FireTargets( pev->target, this, this, USE_OFF );//fan is full stopped } } void CFuncRotating :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if(IsLockedByMaster( useType )) return; if ( useType == USE_TOGGLE ) { if( m_iState == STATE_TURN_OFF || m_iState == STATE_OFF ) useType = USE_ON; else useType = USE_OFF; } if ( useType == USE_ON ) SetSpeed( pev->speed ); else if( useType == USE_OFF ) SetSpeed( 0 ); else if ( useType == USE_SET ) // reverse speed { // write new speed if( value ) { if( pev->speed < 0 ) pev->speed = -value; if( pev->speed > 0 ) pev->speed = value; } else pev->speed = -pev->speed; // just reverse // apply speed immediately if fan no off or not turning off if( m_iState != STATE_OFF && m_iState != STATE_TURN_OFF ) SetSpeed( pev->speed ); } else if ( useType == USE_RESET ) // set angular impulse. use with caution! { float imp; if( value ) imp = value; else imp = pev->speed; SetAngularImpulse( imp / 10 ); } else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "State: %s, CurSpeed %.1f\n", GetStringForState( GetState()), pev->dmg_save ); ALERT( at_console, "SpinTime: %.2f, MaxSpeed %.f\n", pev->frags, pev->speed ); } } //======================================================================= // func_pendulum - swinging brush (thanks for Lazarus Q2 mod) //======================================================================= //======================================================================= // func_pendulum - swinging brush //======================================================================= class CPendulum : public CBaseBrush { public: void Spawn ( void ); void Precache( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void Think( void ); void Blocked( CBaseEntity *pOther ); void KeyValue( KeyValueData *pkvd ); void Touch( CBaseEntity *pOther ); void SetImpulse( float speed ); void SetSwing( float speed ); void PostActivate( void ); int dir;//FIXME }; LINK_ENTITY_TO_CLASS( func_pendulum, CPendulum ); void CPendulum :: KeyValue( KeyValueData *pkvd ) { if ( FStrEq( pkvd->szKeyName, "distance" )) { pev->scale = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else if ( FStrEq( pkvd->szKeyName, "damp" )) { pev->max_health = atof( pkvd->szValue ) * 0.01f; if( pev->max_health > 0.01 ) pev->max_health = 0.01f; pkvd->fHandled = TRUE; } else CBaseBrush::KeyValue( pkvd ); } void CPendulum :: Precache( void ) { CBaseBrush::Precache(); int m_sounds = UTIL_LoadSoundPreset( m_iMoveSound ); switch (m_sounds) { case 1: pev->noise3 = UTIL_PrecacheSound ( "pendulum/swing1.wav" ); break; case 2: pev->noise3 = UTIL_PrecacheSound ( "pendulum/swing2.wav" ); break; case 0: pev->noise3 = UTIL_PrecacheSound ( "common/null.wav" ); break; default: pev->noise3 = UTIL_PrecacheSound( m_sounds ); break; } } void CPendulum :: Spawn( void ) { Precache(); CBaseBrush::Spawn(); if ( pev->spawnflags & SF_NOTSOLID ) { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_PUSH; } else { pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; } SetBits ( pFlags, PF_ANGULAR ); dir = 1; // evil stuff... m_iState = STATE_OFF; pev->dmg_save = 0; // cur speed is NULL UTIL_AngularVector( this ); UTIL_SetOrigin( this, pev->origin ); UTIL_SetModel( ENT( pev ), pev->model ); } void CPendulum :: PostActivate( void ) { if ( pev->spawnflags & SF_START_ON ) SetSwing( pev->speed ); ClearBits( pev->spawnflags, SF_START_ON ); if( m_iState == STATE_ON ) SetNextThink( 0.05 ); // force to think } void CPendulum :: Touch ( CBaseEntity *pOther ) { //don't hurt toucher - just apply velocity him entvars_t *pevOther = pOther->pev; pevOther->velocity = (pevOther->origin - VecBModelOrigin(pev) ).Normalize() * pev->dmg; } void CPendulum::Blocked( CBaseEntity *pOther ) { // what can do pendulum on blocking ? // Nothing :) pev->armortype = gpGlobals->time; } void CPendulum :: SetImpulse( float speed ) { if( dir == pev->impulse ) return; dir = pev->impulse; SetSwing( speed ); } void CPendulum :: SetSwing( float speed ) { if( m_iState == STATE_OFF ) pev->armorvalue = speed; // save our speed else pev->armorvalue = pev->armorvalue + speed; // apply impulse // silence normalize speed if needed if( pev->armorvalue > MAX_AVELOCITY ) pev->armorvalue = MAX_AVELOCITY; // normalize speed at think time // calc min distance at this speed float factor = MAX_AVELOCITY * 0.01f; // max avelocity * think time float mindist = ( pev->armorvalue / factor ) * 2; // full minimal dist if( mindist > pev->scale ) { pev->scale = mindist; // set minimal distance for this speed if( m_iState == STATE_OFF ) { ALERT( at_warning, "\n======/Xash SmartFiled System/======\n\n"); ALERT( at_warning, "%s has too small distance for current speed!\n", STRING( pev->classname )); ALERT( at_warning, "Smart field normalize distance to %.f\n\n", pev->scale ); } } if( m_iState == STATE_OFF ) pev->dmg_take = pev->scale * 0.5; // calc half distance else pev->dmg_take = pev->dmg_take + sqrt( speed ); pev->dmg_save = pev->armorvalue; // at center speed is maximum // random choose starting dir if ( m_iState == STATE_OFF ) { if( RANDOM_LONG( 0, 1 )) pev->impulse = -1; // backward else pev->impulse = 1; // forward m_iState = STATE_ON; } SetNextThink( 0.01); // force to think } void CPendulum :: Think( void ) { float m_flDegree = (gpGlobals->time - pev->armortype) / pev->frags; float m_flAngle = UTIL_CalcDistance( pev->angles ); float m_flAngleOffset = pev->dmg_take - m_flAngle; float m_flStep = (( pev->armorvalue * 0.01 ) / ( pev->dmg_take * 0.01 )) / M_PI; float m_damping = pev->max_health; if( m_iState == STATE_TURN_OFF ) m_damping = 0.09; // HACKHACK to disable pendulum if( m_flDegree >= 1 && m_flAngleOffset <= 0.5f ) // extremum point { // recalc time pev->armortype = gpGlobals->time; pev->frags = pev->dmg_take / pev->armorvalue; pev->impulse = -pev->impulse; // change movedir } if( pev->avelocity.Length() > pev->armorvalue * 0.6 && m_damping ) // apply damp { pev->armorvalue -= pev->armorvalue * m_damping; pev->dmg_take -= pev->dmg_take * m_damping; } if( pev->avelocity.Length() > pev->armorvalue * 0.95 && pev->dmg_take > 5.0f ) // zerocrossing { EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, STRING( pev->noise3 ), m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); UTIL_FireTargets( pev->target, this, this, USE_OFF ); } pev->dmg_save = pev->armorvalue * ( m_flAngleOffset / pev->dmg_take ); UTIL_SetAvelocity( this, pev->movedir * pev->dmg_save * pev->impulse ); SetNextThink( 0.01f ); if( pev->avelocity.Length() < 0.5f && pev->dmg_take < 2.0f ) // watch for speed and dist { UTIL_SetAvelocity( this, g_vecZero );//stop UTIL_AssignAngles( this, pev->angles ); EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, STRING( pev->noise3 ), 0, 0, SND_STOP, m_pitch ); DontThink(); // break thinking UTIL_FireTargets( pev->target, this, this, USE_OFF ); // pendulum is full stopped m_iState = STATE_OFF; } } void CPendulum :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if(IsLockedByMaster( useType )) return; if ( useType == USE_TOGGLE ) { if( m_iState == STATE_OFF ) useType = USE_ON; else useType = USE_OFF; } if ( useType == USE_ON ) SetSwing( pev->speed ); else if ( useType == USE_OFF ) m_iState = STATE_TURN_OFF; else if ( useType == USE_SET ) { if( value ) pev->speed = value; else SetImpulse( pev->speed ); // any idea ??? } else if ( useType == USE_RESET ) SetImpulse( pev->speed ); else if ( useType == USE_SHOWINFO) { ALERT( at_console, "======/Xash Debug System/======\n"); ALERT( at_console, "classname: %s\n", STRING( pev->classname )); ALERT( at_console, "State: %s, CurSpeed %.1f\n", GetStringForState( GetState()), pev->dmg_save ); ALERT( at_console, "Distance: %.2f, Swing Time %.f\n", pev->dmg_take, pev->frags ); } } //======================================================================= // func_clock - simply rotating clock from Quake1.Scourge Of Armagon //======================================================================= class CFuncClock : public CBaseLogic { public: void Spawn ( void ); virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } void Think( void ); void PostActivate( void ); void KeyValue( KeyValueData *pkvd ); Vector curtime, finaltime; int bellcount;//calc hours }; LINK_ENTITY_TO_CLASS( func_clock, CFuncClock ); void CFuncClock :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "type")) { switch(atoi( pkvd->szValue )) { case 1: pev->impulse = MINUTES; break; // minutes case 2: pev->impulse = HOURS; break; // hours case 0: // default: default: pev->impulse = SECONDS; break; // seconds } pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "curtime")) { UTIL_StringToVector( curtime, pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "event")) { pev->netname = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } } void CFuncClock :: Spawn ( void ) { pev->solid = SOLID_NOT; UTIL_SetModel( ENT(pev), pev->model ); // NOTE: I'm doesn't have better idea than it // So, field "angles" setting movedir only // Turn your brush into your fucking worldcraft! UTIL_AngularVector( this ); SetBits( pFlags, PF_ANGULAR ); if( pev->impulse == HOURS ) //d o time operations { // normalize our time if( curtime.x > 11 ) curtime.x = 0; if( curtime.y > 59 ) curtime.y = 0; if( curtime.z > 59 ) curtime.z = 0; // member full hours pev->team = curtime.x; // calculate seconds finaltime.z = curtime.z * ( SECONDS / 60 ); // seconds finaltime.y = curtime.y * ( MINUTES / 60 ) + finaltime.z; finaltime.x = curtime.x * ( HOURS / 12 ) + finaltime.y; } } void CFuncClock :: PostActivate( void ) { // NOTE: We should be sure what all entities has be spawned // else we called this from Activate() if( pev->frags ) return; if( pev->impulse == HOURS && curtime != g_vecZero ) // it's hour entity and time set { // try to find minutes and seconds entity CBaseEntity *pEntity = NULL; while( pEntity = UTIL_FindEntityInSphere( pEntity, pev->origin, pev->size.z )) { if( FClassnameIs( pEntity, "func_clock" )) { //write start hours, minutes and seconds if( pEntity->pev->impulse == HOURS ) pEntity->pev->dmg_take = finaltime.x; if( pEntity->pev->impulse == MINUTES ) pEntity->pev->dmg_take = finaltime.y; if( pEntity->pev->impulse == SECONDS ) pEntity->pev->dmg_take = finaltime.z; } } } pev->frags = 1; // clock init m_iState = STATE_ON;// always on SetNextThink( 0 ); // force to think } void CFuncClock :: Think ( void ) { float seconds, ang, pos; seconds = gpGlobals->time + pev->dmg_take; pos = seconds / pev->impulse; pos = pos - floor( pos ); ang = 360 * pos; UTIL_SetAngles( this, pev->movedir * ang ); if(pev->impulse == HOURS) // play bell sound { pev->button = pev->angles.Length() / 30; // half hour if ( pev->team != pev->button ) // new hour { // member new hour bellcount = pev->team = pev->button; if( bellcount == 0 ) bellcount = 12; // merge for 0.00.00 UTIL_FireTargets( pev->netname, this, this, USE_SET, bellcount ); // send hours info UTIL_FireTargets( pev->netname, this, this, USE_ON );//activate bell or logic_generator } } SetNextThink( 1 ); // refresh at one second } //======================================================================= // func_healthcharger - brush healthcharger //======================================================================= class CWallCharger : public CBaseBrush { public: void Spawn( ); void Precache( void ); void Think (void); void KeyValue( KeyValueData* pkvd); virtual int ObjectCaps( void ) { int flags = CBaseBrush:: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; if(m_iState == STATE_DEAD) return flags; return flags | FCAP_CONTINUOUS_USE; } void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); float m_flNextCharge; float m_flSoundTime; }; LINK_ENTITY_TO_CLASS(func_healthcharger, CWallCharger); LINK_ENTITY_TO_CLASS(func_recharge, CWallCharger); void CWallCharger :: KeyValue( KeyValueData* pkvd) { if( FStrEq( pkvd->szKeyName, "chargetime" )) { //affect only in multiplayer pev->speed = atof( pkvd->szValue ); if( pev->speed <= 0 ) pev->speed = 1.0f; pkvd->fHandled = TRUE; } else CBaseBrush::KeyValue( pkvd ); } void CWallCharger::Spawn( void ) { Precache(); CBaseBrush::Spawn(); pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; UTIL_SetOrigin(this, pev->origin); UTIL_SetSize(pev, pev->mins, pev->maxs); UTIL_SetModel(ENT(pev), pev->model ); if( pev->speed <= 0 ) pev->speed = 1.0f; m_iState = STATE_OFF; pev->frame = 0; // set capacity if ( FClassnameIs( this, "func_recharge" )) pev->frags = SUIT_CHARGER_CAP; else pev->frags = HEATH_CHARGER_CAP; pev->dmg_save = pev->frags; } void CWallCharger::Precache( void ) { CBaseBrush::Precache(); if ( FClassnameIs( this, "func_recharge" )) { UTIL_PrecacheSound( "items/suitcharge1.wav" ); UTIL_PrecacheSound( "items/suitchargeno1.wav" ); UTIL_PrecacheSound( "items/suitchargeok1.wav" ); } else { UTIL_PrecacheSound( "items/medshot4.wav" ); UTIL_PrecacheSound( "items/medshotno1.wav" ); UTIL_PrecacheSound( "items/medcharge4.wav" ); } } void CWallCharger::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if(IsLockedByMaster( useType )) return; if(useType == USE_SHOWINFO)//show info { ALERT(at_console, "======/Xash Debug System/======\n"); ALERT(at_console, "classname: %s\n", STRING(pev->classname)); ALERT(at_console, "State: %s, Volume %.1f\n", GetStringForState( GetState()), m_flVolume ); ALERT(at_console, "Texture frame: %.f. ChargeLevel: %.f\n", pev->frame, pev->dmg_save); } else if(pActivator && pActivator->IsPlayer()) // take health { if( pev->dmg_save <= 0 ) { if( m_iState == STATE_IN_USE || m_iState == STATE_ON ) { pev->frame = 1; if( FClassnameIs( this, "func_recharge" )) STOP_SOUND( ENT(pev), CHAN_STATIC, "items/suitcharge1.wav" ); else STOP_SOUND( ENT(pev), CHAN_STATIC, "items/medcharge4.wav" ); m_iState = STATE_DEAD;//recharge in multiplayer if( IsMultiplayer( )) SetNextThink( 3.0f ); //delay before recahrge else DontThink(); } } if(( m_iState == STATE_DEAD ) || (!(((CBasePlayer *)pActivator)->pev->weapons & ITEM_SUIT ))) { if ( m_flSoundTime <= gpGlobals->time ) { m_flSoundTime = gpGlobals->time + 0.62; if( FClassnameIs( this, "func_recharge" )) EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, "items/suitchargeno1.wav", m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); else EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, "items/medshotno1.wav", m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); } return; } SetNextThink( 0.25f ); // time before disable if ( m_flNextCharge >= gpGlobals->time ) return; if ( m_iState == STATE_OFF ) { m_iState = STATE_ON; if ( FClassnameIs( this, "func_recharge" )) EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, "items/suitchargeok1.wav", m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); else EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, "items/medshot4.wav", m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); m_flSoundTime = 0.56 + gpGlobals->time; } if ( m_iState == STATE_ON && m_flSoundTime <= gpGlobals->time ) { m_iState = STATE_IN_USE; if ( FClassnameIs( this, "func_recharge" )) EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, "items/suitcharge1.wav", m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); else EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, "items/medcharge4.wav", m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); } if ( FClassnameIs( this, "func_recharge" )) { if ( m_hActivator->pev->armorvalue < 100 ) { UTIL_FireTargets( pev->target, this, this, USE_OFF, pev->dmg_save ); // decrement counter pev->dmg_save--; m_hActivator->pev->armorvalue++; } } else { if ( pActivator->TakeHealth(1, DMG_GENERIC )) { UTIL_FireTargets( pev->target, this, this, USE_OFF, pev->dmg_save ); // decrement counter pev->dmg_save--; } } m_flNextCharge = gpGlobals->time + 0.1; } } void CWallCharger :: Think( void ) { if ( m_iState == STATE_IN_USE || m_iState == STATE_ON ) { if ( FClassnameIs( this, "func_recharge" )) STOP_SOUND( ENT(pev), CHAN_STATIC, "items/suitcharge1.wav" ); else STOP_SOUND( ENT(pev), CHAN_STATIC, "items/medcharge4.wav" ); m_iState = STATE_OFF; DontThink(); return; } if( m_iState == STATE_DEAD && IsMultiplayer( )) // recharge { pev->dmg_save++; // ressurection UTIL_FireTargets( pev->target, this, this, USE_ON, pev->dmg_save ); // increment counter if(pev->dmg_save >= pev->frags) { //take full charge if ( FClassnameIs( this, "func_recharge" )) EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, "items/suitchargeok1.wav", m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); else EMIT_SOUND_DYN( ENT( pev ), CHAN_STATIC, "items/medshot4.wav", m_flVolume, ATTN_IDLE, SND_CHANGE_VOL, PITCH_NORM ); pev->dmg_save = pev->frags; // normalize pev->frame = 0; // enable m_iState = STATE_OFF; // can use DontThink(); return; } } SetNextThink( pev->speed ); } //======================================================================= // func_button - standard linear button from Quake1 //======================================================================= class CBaseButton : public CBaseMover { public: void Spawn( void ); void PostSpawn( void ); void Precache( void ); virtual void KeyValue( KeyValueData* pkvd); virtual int ObjectCaps( void ) { int flags = CBaseMover:: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; if(m_iState == STATE_DEAD) return flags; return flags | FCAP_IMPULSE_USE | FCAP_ONLYDIRECT_USE; } void EXPORT ButtonUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void EXPORT ShowInfo ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void EXPORT ButtonTouch( CBaseEntity *pOther ); void EXPORT ButtonReturn( void ); void EXPORT ButtonDone( void ); void ButtonActivate( void ); }; LINK_ENTITY_TO_CLASS( func_button, CBaseButton ); void CBaseButton::KeyValue( KeyValueData *pkvd ) { // rename standard fields for button if (FStrEq(pkvd->szKeyName, "locksound" )) { m_iStopSound = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "pushsound" )) { m_iStartSound = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "offtarget" )) { pev->netname = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "value" )) { m_flValue = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseMover::KeyValue( pkvd ); } void CBaseButton::Precache( void ) { CBaseBrush::Precache();//precache damage sound int m_sounds = UTIL_LoadSoundPreset(m_iStartSound); switch (m_sounds)//load pushed sounds (sound will play at activate or pushed button) { case 1: pev->noise = UTIL_PrecacheSound ("buttons/blip1.wav");break; case 2: pev->noise = UTIL_PrecacheSound ("buttons/blip2.wav");break; case 3: pev->noise = UTIL_PrecacheSound ("buttons/blip3.wav");break; case 4: pev->noise = UTIL_PrecacheSound ("buttons/blip4.wav");break; case 5: pev->noise = UTIL_PrecacheSound ("buttons/blip5.wav");break; case 6: pev->noise = UTIL_PrecacheSound ("buttons/blip6.wav");break; case 0: pev->noise = UTIL_PrecacheSound ("common/null.wav"); break; default: pev->noise = UTIL_PrecacheSound(m_sounds); break;//custom sound or sentence } if (!FStringNull(m_sMaster))//button has master { m_sounds = UTIL_LoadSoundPreset(m_iStopSound); switch (m_sounds)//load locked sounds { case 1: pev->noise3 = UTIL_PrecacheSound ("buttons/latchlocked1.wav");break; case 2: pev->noise3 = UTIL_PrecacheSound ("buttons/latchlocked2.wav");break; case 0: pev->noise3 = UTIL_PrecacheSound ("common/null.wav"); break; default: pev->noise3 = UTIL_PrecacheSound(m_sounds); break;//custom sound or sentence } } } void CBaseButton::Spawn( ) { Precache(); CBaseBrush::Spawn(); if(pev->spawnflags & SF_NOTSOLID)//not solid button { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; pev->skin = CONTENTS_EMPTY; } else { pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; } UTIL_SetModel(ENT(pev), pev->model); //determine work style if(m_iMode == 0)//classic HL button - only USE { SetUse ( ButtonUse ); SetTouch ( NULL ); } if(m_iMode == 1)//classic QUAKE button - only TOUCH { SetUse ( ShowInfo );//show info only SetTouch ( ButtonTouch ); } if(m_iMode == 2)//combo button - USE and TOUCH { SetUse ( ButtonUse ); SetTouch ( ButtonTouch ); } //as default any button is toggleable, but if mapmaker set waittime > 0 //button will transformed into timebased button //if waittime is -1 - button forever stay pressed if(m_flWait == 0) pev->impulse = 1;//toggleable button if (m_flLip == 0) m_flLip = 4;//standart offset from Quake1 m_iState = STATE_OFF; // disable at spawn UTIL_LinearVector( this ); // movement direction m_vecPosition1 = pev->origin; m_vecPosition2 = m_vecPosition1 + (pev->movedir * (fabs( pev->movedir.x * (pev->size.x-2) ) + fabs( pev->movedir.y * (pev->size.y-2) ) + fabs( pev->movedir.z * (pev->size.z-2) ) - m_flLip)); // Is this a non-moving button? if( pev->speed == 0 ) m_vecPosition2 = m_vecPosition1; } void CBaseButton :: PostSpawn( void ) { if (m_pParent) m_vecPosition1 = pev->origin - m_pParent->pev->origin; else m_vecPosition1 = pev->origin; m_vecPosition2 = m_vecPosition1 + (pev->movedir * (fabs( pev->movedir.x * (pev->size.x-2) ) + fabs( pev->movedir.y * (pev->size.y-2) ) + fabs( pev->movedir.z * (pev->size.z-2) ) - m_flLip)); // Is this a non-moving button? if ( pev->speed == 0 ) m_vecPosition2 = m_vecPosition1; } void CBaseButton :: ShowInfo ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if( useType == USE_SHOWINFO ) // show info { DEBUGHEAD; ALERT( at_console, "State: %s, Speed %.2f\n", GetStringForState( GetState()), pev->speed ); ALERT( at_console, "Texture frame: %.f. WaitTime: %.2f\n", pev->frame, m_flWait ); } } void CBaseButton :: ButtonUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator;//save our activator if(IsLockedByMaster( useType )) // passed only USE_SHOWINFO { EMIT_SOUND( ENT( pev ), CHAN_VOICE, STRING( pev->noise3 ), 1, ATTN_NORM ); return; } if( useType == USE_SHOWINFO ) // show info { ALERT( at_console, "======/Xash Debug System/======\n" ); ALERT( at_console, "classname: %s\n", STRING( pev->classname )); ALERT( at_console, "State: %s, Speed %.2f\n", GetStringForState( GetState()), pev->speed ); ALERT( at_console, "Texture frame: %.f. WaitTime: %.2f\n", pev->frame, m_flWait ); } else if( m_iState != STATE_DEAD ) // activate button { // NOTE: STATE_DEAD is better method for simulate m_flWait -1 without fucking SetThink() if( pActivator && pActivator->IsPlayer( )) // code for player { if( pev->impulse == 1 ) // toggleable button { if ( m_iState == STATE_TURN_ON || m_iState == STATE_TURN_OFF ) return; // buton in-moving else if ( m_iState == STATE_ON ) // button is active, disable { ButtonReturn(); } else if( m_iState == STATE_OFF ) // activate { ButtonActivate(); } } else // time based button { // can activate only disabled button if( m_iState == STATE_OFF ) ButtonActivate(); else return; // does nothing :) } } else // activate button from other entity { // NOTE: Across activation just passed fire through UTIL_FireTargets( pev->target, pActivator, pCaller, useType, m_flValue ); } } } void CBaseButton:: ButtonTouch( CBaseEntity *pOther ) { //make delay before retouching if ( gpGlobals->time < m_flBlockedTime ) return; m_flBlockedTime = gpGlobals->time + 1.0f; if( pOther->IsPlayer( )) ButtonUse ( pOther, this, USE_TOGGLE, 1.0f ); // player always sending 1 } void CBaseButton::ButtonActivate( void ) { ASSERT( m_iState == STATE_OFF ); m_iState = STATE_TURN_ON; EMIT_SOUND( ENT( pev ), CHAN_VOICE, STRING( pev->noise ), 1, ATTN_NORM ); if ( pev->speed ) { SetMoveDone( ButtonDone ); LinearMove( m_vecPosition2, pev->speed); } else ButtonDone(); // immediately switch } void CBaseButton::ButtonDone( void ) { if ( m_iState == STATE_TURN_ON ) // turn on { m_iState = STATE_ON; pev->frame = 1; // change skin if ( pev->impulse ) UTIL_FireTargets( pev->target, m_hActivator, this, USE_ON, m_flValue ); // fire target else UTIL_FireTargets( pev->target, m_hActivator, this, USE_TOGGLE, m_flValue ); // fire target if ( m_flWait == -1 ) { m_iState = STATE_DEAD; // keep button in this position return; } if ( pev->impulse == 0 ) // time base button { SetThink( ButtonReturn ); SetNextThink( m_flWait ); } } if ( m_iState == STATE_TURN_OFF ) // turn off { m_iState = STATE_OFF; // just change state :) UTIL_FireTargets( pev->netname, m_hActivator, this, USE_OFF, m_flValue ); // fire target } } void CBaseButton::ButtonReturn( void ) { ASSERT( m_iState == STATE_ON ); m_iState = STATE_TURN_OFF; pev->frame = 0; // use normal textures // make sound for toggleable button if ( pev->impulse ) { EMIT_SOUND( ENT( pev ), CHAN_VOICE, STRING( pev->noise ), 1, ATTN_NORM ); UTIL_FireTargets( pev->target, m_hActivator, this, USE_OFF, m_flValue ); // fire target } if ( pev->speed ) { SetMoveDone( ButtonDone ); LinearMove( m_vecPosition1, pev->speed ); } else ButtonDone(); // immediately switch } //======================================================================= // func_lever - momentary rotating button //======================================================================= class CFuncLever : public CBaseMover { public: void Spawn ( void ); void Precache( void ); void KeyValue( KeyValueData *pkvd ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); virtual int ObjectCaps( void ) { int flags = CBaseMover:: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; if(m_iState == STATE_DEAD) return flags; return flags | FCAP_CONTINUOUS_USE; } BOOL MaxRange( void ) { if(pev->impulse == 1 && m_flMoveDistance > 0) return TRUE; if(pev->impulse == -1 && m_flMoveDistance < 0) return TRUE; return FALSE; } BOOL BackDir( void )//determine start direction { if( pev->dmg_save && m_flMoveDistance < 0) return TRUE; if(!pev->dmg_save && m_flMoveDistance > 0) return TRUE; return FALSE; } void PlayMoveSound( void ); void CalcValue( void ); void Think( void ); float mTimeToReverse, SendTime, nextplay; }; LINK_ENTITY_TO_CLASS( func_lever, CFuncLever ); void CFuncLever::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "backspeed")) { pev->dmg_save = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "movesound")) { m_iMoveSound = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "stopsound")) { m_iStopSound = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseMover::KeyValue( pkvd ); } void CFuncLever::Precache( void ) { int m_sounds = UTIL_LoadSoundPreset(m_iMoveSound); switch (m_sounds)//load pushed sounds (sound will play at activate or pushed button) { case 1: pev->noise = UTIL_PrecacheSound ("buttons/lever1.wav");break; case 2: pev->noise = UTIL_PrecacheSound ("buttons/lever2.wav");break; case 3: pev->noise = UTIL_PrecacheSound ("buttons/lever3.wav");break; case 4: pev->noise = UTIL_PrecacheSound ("buttons/lever4.wav");break; case 5: pev->noise = UTIL_PrecacheSound ("buttons/lever5.wav");break; case 0: pev->noise = UTIL_PrecacheSound ("common/null.wav"); break; default: pev->noise = UTIL_PrecacheSound(m_sounds); break;//custom sound or sentence } m_sounds = UTIL_LoadSoundPreset(m_iStopSound); switch (m_sounds)//load locked sounds { case 1: pev->noise2 = UTIL_PrecacheSound ("buttons/lstop1.wav");break; case 0: pev->noise2 = UTIL_PrecacheSound ("common/null.wav"); break; default: pev->noise2 = UTIL_PrecacheSound( m_sounds ); break;//custom sound or sentence } } void CFuncLever::Spawn( void ) { Precache(); if( pev->spawnflags & SF_NOTSOLID ) // not solid button { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; pev->skin = CONTENTS_EMPTY; } else { pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; } UTIL_SetModel( ENT( pev ), pev->model ); UTIL_SetOrigin( this, pev->origin ); AxisDir(); SetBits (pFlags, PF_ANGULAR); //Smart field system ® if( pev->speed == 0 ) pev->speed = 100;//check null speed if( pev->speed > 800) pev->speed = 800;//check max speed if( fabs(m_flMoveDistance) < pev->speed/2) { if(m_flMoveDistance > 0)m_flMoveDistance = -pev->speed/2; if(m_flMoveDistance < 0)m_flMoveDistance = pev->speed/2; if(m_flMoveDistance ==0)m_flMoveDistance = 45; } //check for direction (right direction will be set at first called use) if(BackDir())pev->impulse = -1;//backward dir else pev->impulse = 1;//forward dir } void CFuncLever::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if(IsLockedByMaster( useType ))//strange stuff... { EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise2), 1, ATTN_NORM); return; } if(useType == USE_SHOWINFO) { ALERT(at_console, "======/Xash Debug System/======\n"); ALERT(at_console, "classname: %s\n", STRING(pev->classname)); ALERT(at_console, "State: %s, Value %.2f\n", GetStringForState( GetState()), pev->ideal_yaw ); ALERT(at_console, "Distance: %.f. Speed %.2f\n", m_flMoveDistance, pev->speed ); } else if(m_iState != STATE_DEAD) { if(pActivator && pActivator->IsPlayer())//code only for player { if(gpGlobals->time > mTimeToReverse && !pev->dmg_save)//don't switch if backspeed set pev->impulse = -pev->impulse; mTimeToReverse = gpGlobals->time + 0.3;//max time to change dir pev->frags = pev->speed;//send speed m_iState = STATE_IN_USE;//in use SetNextThink(0.01); } } } void CFuncLever::Think( void ) { UTIL_SetAvelocity(this, pev->movedir * pev->frags * pev->impulse);//set speed and dir if(m_iState == STATE_TURN_OFF && pev->dmg_save)pev->frags = -pev->dmg_save;//backspeed if(!pev->dmg_save)pev->frags -= pev->frags * 0.05; CalcValue(); PlayMoveSound(); //wacthing code if(pev->avelocity.Length() < 0.5)m_iState = STATE_OFF;//watch min speed if(pev->ideal_yaw <= 0.01)//min range { if(pev->dmg_save && m_iState != STATE_IN_USE) { UTIL_SetAvelocity(this, g_vecZero); m_iState = STATE_OFF;//off } else if(!MaxRange())UTIL_SetAvelocity(this, g_vecZero); } if(pev->ideal_yaw >= 0.99)//max range { if(pev->dmg_save && m_iState == STATE_IN_USE) { UTIL_SetAvelocity(this, g_vecZero); if(pev->spawnflags & SF_START_ON)//Stay open flag m_iState = STATE_DEAD;//dead else m_iState = STATE_TURN_OFF;//must return } else if(MaxRange() && m_iState == STATE_IN_USE) { UTIL_SetAvelocity(this, g_vecZero); if(pev->spawnflags & SF_START_ON)//Stay open flag m_iState = STATE_DEAD;//dead else m_iState = STATE_OFF;//dist is out } } if(m_iState == STATE_IN_USE)m_iState = STATE_TURN_OFF;//try disable SetNextThink(0.01); if(m_iState == STATE_OFF || m_iState == STATE_DEAD)//STATE_DEAD is one end way { if(pev->dmg_save)//play sound only auto return EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise2), 1, ATTN_NORM); UTIL_SetAvelocity(this, g_vecZero); UTIL_AssignAngles( this, pev->angles ); DontThink();//break thinking } //ALERT(at_console, "Ideal Yaw %f\n", pev->ideal_yaw); } void CFuncLever::CalcValue( void ) { //calc value to send //pev->ideal_yaw = UTIL_CalcDistance(pev->angles) / fabs(m_flMoveDistance); pev->ideal_yaw = pev->angles.Length() / fabs(m_flMoveDistance); if(pev->ideal_yaw >= 1)pev->ideal_yaw = 1;//normalize value else if(pev->ideal_yaw <= 0)pev->ideal_yaw = 0;//normalize value if(gpGlobals->time > SendTime) { UTIL_FireTargets( pev->target, this, this, USE_SET, pev->ideal_yaw );//send value SendTime = gpGlobals->time + 0.01;//time to nextsend } } void CFuncLever::PlayMoveSound( void ) { if(m_iState == STATE_TURN_OFF && pev->dmg_save ) nextplay = fabs((pev->dmg_save * 0.01) / (m_flMoveDistance * 0.01)); else nextplay = fabs((pev->frags * 0.01) / (m_flMoveDistance * 0.01)); nextplay = 1/(nextplay * 5); if(gpGlobals->time > m_flBlockedTime) { EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise), 1, ATTN_NORM); m_flBlockedTime = gpGlobals->time + nextplay; } } //======================================================================= // func_ladder - makes an area vertically negotiable //======================================================================= class CLadder : public CBaseEntity { public: void Spawn( void ); void Precache( void ); }; LINK_ENTITY_TO_CLASS( func_ladder, CLadder ); void CLadder :: Precache( void ) { pev->solid = SOLID_NOT; pev->skin = CONTENTS_LADDER; pev->effects |= EF_NODRAW; } void CLadder :: Spawn( void ) { Precache(); UTIL_SetModel( ENT( pev ), pev->model ); // set size and link into world pev->movetype = MOVETYPE_PUSH; } //======================================================================= // func_scaner - retinal scaner //======================================================================= class CFuncScaner : public CBaseBrush { public: void Spawn( void ); void KeyValue( KeyValueData *pkvd ); void Precache( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void PostActivate( void ); void Think( void ); BOOL VisionCheck( void ); BOOL CanSee(CBaseEntity *pLooker ); CBaseEntity *pSensor; CBaseEntity *pLooker; }; LINK_ENTITY_TO_CLASS( func_scaner, CFuncScaner ); void CFuncScaner::KeyValue( KeyValueData *pkvd ) { if ( FStrEq( pkvd->szKeyName, "sensor" )) { pev->message = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else if ( FStrEq( pkvd->szKeyName, "acesslevel" )) { pev->impulse = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } else if ( FStrEq( pkvd->szKeyName, "sensitivity" )) { pev->health = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseLogic::KeyValue( pkvd ); } void CFuncScaner :: Precache( void ) { CBaseBrush::Precache(); UTIL_PrecacheSound( "buttons/blip1.wav" ); UTIL_PrecacheSound( "buttons/blip2.wav" ); UTIL_PrecacheSound( "buttons/button7.wav" ); UTIL_PrecacheSound( "buttons/button11.wav" ); } void CFuncScaner :: Spawn( void ) { Precache(); pev->solid = SOLID_BSP; pev->movetype = MOVETYPE_PUSH; if( !pev->health ) pev->health = 15; UTIL_SetModel( ENT( pev ), pev->model ); UTIL_SetOrigin( this, pev->origin ); m_flDelay = 0.1; SetNextThink( 1 ); } void CFuncScaner :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "State: %s, Acess Level %d\n", GetStringForState( GetState()), pev->impulse ); ALERT( at_console, "FOV: %g\n", pev->health ); } else if ( useType == USE_SET ) { if ( value ) { pev->armorvalue = (int)value; // set new acess level for looker pev->frame = 1; } } } void CFuncScaner :: Think( void ) { if ( VisionCheck() && m_iState != STATE_ON && m_iState != STATE_DEAD ) { if ( pev->armorvalue ) { m_iState = STATE_DEAD; pLooker->m_iAcessLevel = (int)pev->armorvalue; pev->armorvalue = 0; // change acess level sound EMIT_SOUND( edict(), CHAN_BODY, "buttons/blip2.wav", 1.0, ATTN_NORM ); } else if ( m_iState == STATE_OFF ) // scaner is off { // ok, we have seen entity if( pLooker->pev->flags & FL_CLIENT ) m_flDelay = 0.1; else m_flDelay = 0.9; m_iState = STATE_TURN_ON; } else if( m_iState == STATE_TURN_ON ) // scaner is turn on { EMIT_SOUND( edict(), CHAN_BODY, "buttons/blip1.wav", 1.0, ATTN_NORM ); pev->frame = 1; m_flDelay = 0.3; pev->button++; if( pev->button > 9 ) { m_iState = STATE_ON; pev->team = pLooker->m_iAcessLevel; // save our level acess pev->button = 0; } } } else if ( m_iState == STATE_ON ) // scaner is on { EMIT_SOUND( edict(), CHAN_BODY, "buttons/blip1.wav", 1.0, ATTN_NORM ); m_flDelay = 0.1; pev->button++; if( pev->button > 9 ) { m_iState = STATE_OFF; pev->frame = 0; pev->button = 0; m_flDelay = 2.0; if( pev->team >= pev->impulse ) // acees level is math or higher ? { EMIT_SOUND( edict(), CHAN_BODY, "buttons/button7.wav", 1.0, ATTN_NORM ); UTIL_FireTargets( pev->target, this, this, USE_TOGGLE ); } else { EMIT_SOUND( edict(), CHAN_BODY, "buttons/button11.wav", 1.0, ATTN_NORM ); UTIL_FireTargets( pev->netname, this, this, USE_TOGGLE ); } } } else if ( m_iState == STATE_TURN_ON ) { EMIT_SOUND( edict(), CHAN_BODY, "buttons/button11.wav", 1.0, ATTN_NORM ); m_iState = STATE_OFF; pev->button = 0; pev->frame = 0; m_flDelay = 2.0; } else if ( m_iState == STATE_DEAD ) { m_iState = STATE_OFF; pev->button = 0; m_flDelay = 2.0; } // is this a sensible rate? SetNextThink( m_flDelay ); } void CFuncScaner :: PostActivate( void ) { if ( pev->message ) { pSensor = UTIL_FindEntityByTargetname( NULL, STRING( pev->message )); if( !pSensor ) pSensor = this; } else pSensor = this; } BOOL CFuncScaner :: VisionCheck( void ) { pLooker = UTIL_FindEntityInSphere( NULL, pSensor->pev->origin, 30 ); if ( pLooker ) { while( pLooker != NULL ) { if( pLooker && pLooker->pev->flags & ( FL_MONSTER|FL_CLIENT )) return CanSee( pLooker ); // looker found pLooker = UTIL_FindEntityInSphere( pLooker, pSensor->pev->origin, 30 ); } } return FALSE;//no lookers } BOOL CFuncScaner :: CanSee( CBaseEntity *pLooker ) { if( !pSensor || !pLooker ) return FALSE; if (( pLooker->EyePosition() - pSensor->pev->origin ).Length() > 30 ) return FALSE; // copied from CBaseMonster's FInViewCone function Vector2D vec2LOS; float flDot, flComp = cos( pev->health / 2 * M_PI / 180.0 ); UTIL_MakeVectors ( pLooker->pev->angles ); vec2LOS = ( pSensor->pev->origin - pLooker->pev->origin ).Make2D(); vec2LOS = vec2LOS.Normalize(); flDot = DotProduct ( vec2LOS , gpGlobals->v_forward.Make2D() ); if (flDot <= flComp) return FALSE; return TRUE; }
[ [ [ 1, 2340 ] ] ]
bec43b6e2682ff8e69483ef2c008a7426cca3fec
bd89d3607e32d7ebb8898f5e2d3445d524010850
/adaptationlayer/tsy/nokiatsy_dll/inc/cmmphonebookoperationread.h
9ebaffacf88750c371676102bf6bc756cf7b8bc5
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,217
h
/* * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef _CMMPHONEBOOK_OPERATION_READ_H #define _CMMPHONEBOOK_OPERATION_READ_H // INCLUDES #include <ctsy/pluginapi/cmmdatapackage.h> #include <e32base.h> #include "cmmphonebookstoreoperationbase.h" // CONSTANTS // None // MACROS // None // DATA TYPES // None // EXTERNAL DATA STRUCTURES // None // FUNCTION PROTOTYPES // None // CLASS DECLARATION /** * CMmPhoneBookOperationInit is used to create and send GSM-specific * PBStore ISI messages to PhoNet via PhoNetSender relating to read. */ class CMmPhoneBookOperationRead : public CMmPhoneBookStoreOperationBase { public: // Constructors and destructor /** * By default Symbian OS constructor is private. */ CMmPhoneBookOperationRead(); /** * Two-phased constructor. * @return CMmPhoneBookOperationRead*: created object */ static CMmPhoneBookOperationRead* NewL( CMmPhoneBookStoreMessHandler* aMmPhoneBookStoreMessHandler, CMmUiccMessHandler* aUiccMessHandler, const CMmDataPackage* aDataPackage, TInt aIpc ); /** * Destructor. */ ~CMmPhoneBookOperationRead(); /** * Sends Request To Get Read and Write Size * for Msisdn PB * @param TUint8 aTransId : TransactionId * @return TInt: KErrNone or error value. */ TInt USimReadWriteSizeReq( TUint8 aTransId ); /** * Construct UICC Req to read Entry * @param * @return TInt: KErrNone or error value. */ TInt USimPbReqRead( TInt aRecordNo, TUint8 aTransId ); /** * Appends Correct record numner to request * @param aParams * @return TInt: KErrNone or error value. */ TInt AddParamToReadReq( TUiccReadLinearFixed& aParams ); /** * Handles SimPbResp ISI -message * @param aStatus * @param aTransId * @param aFileData * @param pbFileId * @param fileIdExt * @parma arrayIndex * @return TInt: KErrNone or error value. */ TBool USimPbReadRespL( TInt aStatus, TUint8 aTransId, const TDesC8 &aFileData ); /** * Handles response for Msisdn read Write size request * @param TDesC8 &aFileData : Response Data * @return TInt: KErrNone or error value. */ TBool USimReadWriteSizeResp( const TDesC8 &aFileData, TInt aStatus ); private: /** * Separates different IPC requests for each other. * @param TInt aIpc: Identify number of request. * @param const CMmDataPackage* aDataPackage: Packaged data. * @return TInt: KErrNone or error value. */ TInt UICCCreateReq( TInt aIpc, const CMmDataPackage* aDataPackage, TUint8 aTransId ); /** * Handles read resp for main Entry * @param aFileData * @param aTransId * @param aEmptyEntry : Entry is EMpty or not * @param aEntryStore : ENtry is store in internal list or not * @return TInt: KErrNone or error value. */ void HandleReadResp( const TDesC8 &aFileData, TUint8 aTransId, TInt &aEmptyEntry, TBool &aEntryStore ); /** * Handles read resp for main Entry when Entry is present * @param aFileData * @param aTransId * @param aEntryStore : ENtry is store in internal list or not * @return TInt: KErrNone or error value. */ void HandleEntryPresentResp( const TDesC8 &aFileData, TUint8 aTransId, TBool &aEntryStore ); /** * Handles SimPbResp ISI -message * @param TIsiReceiveC& aIsiMessage * @param TBool& aComplete: Indicates if request can remove from * operationlist or not. * @return TInt: KErrNone or error value. */ TBool HandleUICCPbRespL( TInt aStatus, TUint8 aDetails, const TDesC8 &aFileData, TInt aTransId); /** * Handles EXT file read resp * @param aFIleData * @param aTransId * @return TInt: KErrNone or error value. */ void HandleExtReadResp( const TDesC8 &aFileData, TUint8 aTransId, TBool &aEntryStored ); /** * Class attributes are created in ConstructL. */ void ConstructL(); // Transmit /** * Constructs Data to read entry from USIM ADN Phonebook * @param * @return TInt: KErrNone or error value. */ TInt UICCHandleDataADNReadReq( TUiccReadLinearFixed& aParams, TUint16 aFileID, TUint8 aFileSFI ); // Receive /** * Handles SimPbResp ISI -message * @param TInt aTagValue * @param TDes8& aFileData * @return TInt: KErrNone or error value. */ TInt UICCHandleDataADNReadResp( const TDesC8& aFileData); /** * Store Entry to internal List and CacheArray * @param TBool &aEntryStored */ void StoreEntryToListL( TBool &aEntryStored ); /** * Store Own Number Entry to internal and compelte * @param TInt aRet */ void StoreAndCompleteOwnNumber( TInt aRet, TInt aEmptyEntry ); public: // Data // None protected: // Data // Attribute to hold the information how many entries left to read TInt iNumOfEntriesToRead; // Attribute to hold the information how many entries written into // array TInt iNumOfEntriesFilled; // To Store the information about first valid Entry Search TBool iLocationSearch; // Attribute to Store Entry TPBEntry* iStoreEntry; // Saved IPC for complete TInt iSavedIPCForComplete; // Attribute store fileid TUint16 iFileId; // Attribute to store Ext File TUint16 iExtFileId; // Attribute to store Phonebook conf array index TUint8 iArrayIndex; private: // Data // Attribute to check what kind of read is ongoing TTypeOfFileToBeRead iTypeOfReading ; TBool iExtensionRead ; }; #endif // _CMMPHONEBOOK_OPERATION_READ_H // End of file
[ "dalarub@localhost", "[email protected]" ]
[ [ [ 1, 1 ], [ 3, 61 ], [ 65, 71 ], [ 76, 76 ], [ 78, 78 ], [ 85, 85 ], [ 92, 92 ], [ 106, 106 ], [ 114, 116 ], [ 176, 180 ], [ 183, 189 ], [ 192, 193 ], [ 195, 201 ], [ 214, 225 ], [ 244, 245 ], [ 249, 259 ] ], [ [ 2, 2 ], [ 62, 64 ], [ 72, 75 ], [ 77, 77 ], [ 79, 84 ], [ 86, 91 ], [ 93, 105 ], [ 107, 113 ], [ 117, 175 ], [ 181, 182 ], [ 190, 191 ], [ 194, 194 ], [ 202, 213 ], [ 226, 243 ], [ 246, 248 ] ] ]
77b8c5e9c9f1dee000c19f4d48c91c23ace0315a
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aosdesigner/view/ChangesView.hpp
7b6c191bca4da654fe72e57c6fe0954a1395b9b7
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
1,183
hpp
#ifndef HGUARD_AOSD_VIEW_CHANGESVIEW_HPP__ #define HGUARD_AOSD_VIEW_CHANGESVIEW_HPP__ #pragma once #include <memory> #include "view/EditionToolView.hpp" #include "view/model/ModelViewBinder.hpp" #include "core/EditionSessionId.hpp" class QTreeView; namespace aosd { namespace view { /** Display lists of changes between the current story stage and the previous one. **/ class ChangesView : public EditionToolView { Q_OBJECT public: ChangesView(); ~ChangesView(); private: std::unique_ptr< QTreeView > m_last_changes_view; ModelViewBinder<core::EditionSessionId> m_model_view_binder; void begin_edition_session( const core::EditionSession& edition_session ); void end_edition_session( const core::EditionSession& edition_session ); void connect_edition( const core::EditionSession& edition_session ); void disconnect_edition( const core::EditionSession& edition_session ); void update_last_changes( const core::EditionSession& edition_session ); void begin_model( const core::EditionSession& edition_session ); void end_model( const core::EditionSession& edition_session ); }; } } #endif
[ "klaim@localhost" ]
[ [ [ 1, 48 ] ] ]
5dedaf8954f74399aba70a876e3d075fff8fff97
94d9e8ec108a2f79068da09cb6ac903c16b77730
/graph/graphex.h
d511cee878d1b8430122c002446fc744ada431ae
[]
no_license
kiyoya/sociarium
d375c0e5abcce11ae4b087930677483d74864d09
b26c2c9cbd23c2f8ef219d0059e42370294865d1
refs/heads/master
2021-01-25T07:28:25.862346
2009-10-22T05:57:42
2009-10-22T05:57:42
318,115
1
0
null
null
null
null
UTF-8
C++
false
false
9,481
h
// C++ GRAPH LIBRARY: graphex.h // HASHIMOTO, Yasuhiro (E-mail: hy @ sys.t.u-tokyo.ac.jp) /* Copyright (c) 2005-2009, HASHIMOTO, Yasuhiro, All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the University of Tokyo nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef INCLUDE_GUARD_GRAPHEX_H #define INCLUDE_GUARD_GRAPHEX_H #include <cassert> #include <set> #include "graph.h" namespace hashimoto_ut { namespace { //////////////////////////////////////////////////////////////////////////////// std::tr1::shared_ptr<Graph> copy(std::tr1::shared_ptr<Graph const> g) { assert(g!=0); std::tr1::shared_ptr<Graph> retval = g->clone(); for (node_iterator i=g->nbegin(), end=g->nend(); i!=end; ++i) retval->add_node(); for (edge_iterator i=g->ebegin(), end=g->eend(); i!=end; ++i) retval->add_edge(retval->node((*i)->source()->index()), retval->node((*i)->target()->index())); return retval; } //////////////////////////////////////////////////////////////////////////////// void copy(std::tr1::shared_ptr<Graph const> const& g0, std::tr1::shared_ptr<Graph> const& g1) { assert(g0!=0); assert(g1!=0); g1->clear(); for (node_iterator i=g0->nbegin(), end=g0->nend(); i!=end; ++i) g1->add_node(); for (edge_iterator i=g0->ebegin(), end=g0->eend(); i!=end; ++i) g1->add_edge(g1->node((*i)->source()->index()), g1->node((*i)->target()->index())); } //////////////////////////////////////////////////////////////////////////////// void remove_loop_edges(std::tr1::shared_ptr<Graph> g, Node* n) { assert(g!=0); assert(n!=0 && g->node(n->index())==n); std::vector<Edge*> removed_edges; for (adjacency_list_iterator i=n->obegin(), end=n->oend(); i!=end; ++i) if ((*i)->target()==n) removed_edges.push_back(*i); g->remove_edges(removed_edges.begin(), removed_edges.end()); } //////////////////////////////////////////////////////////////////////////////// void remove_loop_edges(std::tr1::shared_ptr<Graph> g) { assert(g!=0); std::vector<Edge*> removed_edges; for (edge_iterator i=g->ebegin(), end=g->eend(); i!=end; ++i) if ((*i)->source()==(*i)->target()) removed_edges.push_back(*i); g->remove_edges(removed_edges.begin(), removed_edges.end()); } //////////////////////////////////////////////////////////////////////////////// void remove_parallel_edges(std::tr1::shared_ptr<Graph> g, Edge const* e) { assert(g!=0); Node* source = e->source(); Node* target = e->target(); std::vector<Edge*> removed_edges; for (adjacency_list_iterator i=source->obegin(), oend=source->oend(); i!=oend; ++i) if (*i!=e && target==(*i)->target()) removed_edges.push_back(*i); if (g->is_directed()) for (adjacency_list_iterator i=source->ibegin(), iend=source->iend(); i!=iend; ++i) if (*i!=e && target==(*i)->source()) removed_edges.push_back(*i); g->remove_edges(removed_edges.begin(), removed_edges.end()); } //////////////////////////////////////////////////////////////////////////////// void contract(std::tr1::shared_ptr<Graph> g, Node* n_remain, Node* n_vanish) { assert(g!=0); assert(n_remain!=0 && g->node(n_remain->index())==n_remain); assert(n_vanish!=0 && g->node(n_vanish->index())==n_vanish); std::vector<Edge*> oedges(n_vanish->obegin(), n_vanish->oend()); for (std::vector<Edge*>::iterator i=oedges.begin(), end=oedges.end(); i!=end; ++i) g->change_source(*i, n_remain); std::vector<Edge*> iedges(n_vanish->ibegin(), n_vanish->iend()); for (std::vector<Edge*>::iterator i=iedges.begin(), end=iedges.end(); i!=end; ++i) g->change_target(*i, n_remain); g->remove_node(n_vanish); } /* The total number of edges doesn't change after contracting. * The edges between @n_remain and @n_vanish remain as loop edges on @n_remain. */ //////////////////////////////////////////////////////////////////////////////// void contract(std::tr1::shared_ptr<Graph> g, Edge* e) { assert(g!=0); assert(e!=0 && g->edge(e->index())==e); Node* n_remain = e->source(); Node* n_vanish = e->target(); std::vector<Edge*> oedges(n_vanish->obegin(), n_vanish->oend()); for (std::vector<Edge*>::iterator i=oedges.begin(), end=oedges.end(); i!=end; ++i) if ((*i)->target()!=n_remain) g->change_source(*i, n_remain); std::vector<Edge*> iedges(n_vanish->ibegin(), n_vanish->iend()); for (std::vector<Edge*>::iterator i=iedges.begin(), end=iedges.end(); i!=end; ++i) if ((*i)->source()!=n_remain) g->change_target(*i, n_remain); g->remove_node(n_vanish); } /* @e and its parallel edges are removed. */ //////////////////////////////////////////////////////////////////////////////// std::vector<Node*> complementary_nodes( std::tr1::shared_ptr<Graph const> g, node_iterator first, node_iterator last) { assert(g!=0); size_t const num = size_t(last-first); assert(num<=g->nsize()); std::vector<Node*> retval; retval.reserve(g->nsize()-num); std::vector<int> flag(g->nsize(), 0); for (; first!=last; ++first) { assert(*first==g->node((*first)->index())); flag[(*first)->index()] = 1; } for (size_t i=0, sz=g->nsize(); i<sz; ++i) if (flag[i]==0) retval.push_back(g->node(i)); return retval; } //////////////////////////////////////////////////////////////////////////////// std::vector<Edge*> complementary_edges( std::tr1::shared_ptr<Graph const> g, edge_iterator first, edge_iterator last) { assert(g!=0); size_t const num = size_t(last-first); assert(num<=g->esize()); std::vector<Edge*> retval; retval.reserve(g->esize()-num); std::vector<int> flag(g->esize(), 0); for (; first!=last; ++first) { assert(*first==g->edge((*first)->index())); flag[(*first)->index()] = 1; } for (size_t i=0, esz=g->esize(); i<esz; ++i) if (flag[i]==0) retval.push_back(g->edge(i)); return retval; } //////////////////////////////////////////////////////////////////////////////// // Return edges whose either end falls in the range [first:last). std::vector<Edge*> incident_edges(node_iterator first, node_iterator last) { std::vector<Edge*> retval; std::set<Edge*> e; for (node_iterator i=first; i!=last; ++i) { for (adjacency_list_iterator j=(*i)->begin(), end=(*i)->end(); j!=end; ++j) { if (e.find(*j)==e.end()) { retval.push_back(*j); e.insert(*j); } } } return retval; } //////////////////////////////////////////////////////////////////////////////// // Return edges whose both ends fall in the range [first:last). std::vector<Edge*> induced_edges(node_iterator first, node_iterator last) { std::vector<Edge*> retval; std::set<Node*> n; std::set<Edge*> e; for (node_iterator i=first; i!=last; ++i) n.insert(*i); for (node_iterator i=first; i!=last; ++i) { for (adjacency_list_iterator j=(*i)->obegin(), end=(*i)->oend(); j!=end; ++j) { if (n.find((*j)->target())!=n.end() && e.find(*j)==e.end()) { retval.push_back(*j); e.insert(*j); } } } return retval; } } // The end of the anonymous namespace } // The end of the namespace "hashimoto_ut" #endif
[ [ [ 1, 259 ] ] ]
fb153e0bab437efd29a9d8db376fd2c71013832a
85685021d05506fe1cdfbc48b4476cf6a97281cc
/fireworlds-game/arm9/source/Particle.itcm.cpp
7ef55704656f60b046dd83cf11f04d39a934fffa
[]
no_license
btuduri/fireworlds
da66acd6a3d0b0a754a6047d16fa4c18767c1fd3
7abc7c82e7db0e179ec2f20fa5892111dfe0a03a
refs/heads/master
2016-09-06T00:02:03.798197
2011-08-17T20:13:57
2011-08-17T20:13:57
32,271,728
0
0
null
null
null
null
UTF-8
C++
false
false
3,217
cpp
#include "Particle.h" #include "textures.h" #include "music.h" Particle::Particle() { } inline f32 tof32(int f5) { f32 r = f5; r /= 32; return r; } void Particle::renderBlur(Scene* sc) { f32 vm = fsqrt((tof32(vx)-sc->vxCam)*(tof32(vx)-sc->vxCam) + (tof32(vy)-sc->vyCam)*(tof32(vy)-sc->vyCam)); f32 size = 4; f32 nvx = ((tof32(vx)-sc->vxCam)/ vm)*size; f32 nvy = ((tof32(vy)-sc->vyCam)/ vm)*size; int d = 2; f32 mvx = (tof32(vx)-sc->vxCam)*d+nvx; f32 mvy = (tof32(vy)-sc->vyCam)*d+nvy; glBegin(GL_QUAD); glColor3b(r,g,b); GFX_TEX_COORD = TEXTURE_PACK(inttot16(64), inttot16(0)); glVertex3f32(tof32(x)+mvx-nvy-sc->xCam, tof32(y)+mvy+nvx-sc->yCam, 0); GFX_TEX_COORD = TEXTURE_PACK(inttot16(64), inttot16(64)); glVertex3f32(tof32(x)+mvx+nvy-sc->xCam, tof32(y)+mvy-nvx-sc->yCam, 0); GFX_TEX_COORD = TEXTURE_PACK(inttot16(0), inttot16(64)); glVertex3f32(tof32(x)-mvx+nvy-sc->xCam, tof32(y)-mvy-nvx-sc->yCam, 0); GFX_TEX_COORD = TEXTURE_PACK(inttot16(0), inttot16(0)); glVertex3f32(tof32(x)-mvx-nvy-sc->xCam, tof32(y)-mvy+nvx-sc->yCam, 0); glEnd(); } /* void Particle::render(int z, Scene* sc) { setTexture(nTexture); int xcam = sc->xCam.tof5(); int ycam = sc->yCam.tof5(); glPolyFmt(POLY_ALPHA(a) | POLY_ID(z % 60) | POLY_CULL_NONE); //draw the obj int size; if(sizePerLife < 0) size = -sizePerLife*32; else size = life*sizePerLife; if(effect == FX_ALPHA) a = life/64+2; if(effect == FX_BLUR) { } else if(type == 5) { glColor3b(r,g,b); for(int i = 0; txt[i] != 0; i++) renderChar(txt[i], x-xcam+size*i*2, y+sinLerp(sc->time*400+i*8000)/30-ycam, size); } else { glBegin(GL_QUAD); glColor3b(r,g,b); GFX_TEX_COORD = TEXTURE_PACK(inttot16(64), inttot16(0)); glVertex3v16(x-size-xcam, y-size-ycam, 0); GFX_TEX_COORD = TEXTURE_PACK(inttot16(64), inttot16(64)); glVertex3v16(x+size-xcam, y-size-ycam, 0); GFX_TEX_COORD = TEXTURE_PACK(inttot16(0), inttot16(64)); glVertex3v16(x+size-xcam, y+size-ycam, 0); GFX_TEX_COORD = TEXTURE_PACK(inttot16(0), inttot16(0)); glVertex3v16(x-size-xcam, y+size-ycam, 0); glEnd(); } }*/ void Particle::move(Scene* sc) { /* //a = 30; if(type != 0) { x += vx; y += vy; if(type<4) { vx -= (vx+8)/16; vy -= (vy+8)/16; } } life--; //vy -= 1; switch(type) { case 0: { break; } case 1: r = 150; g = 100; b = 255; size = 80+irand(20); vx += vx2>>4; vy += vy2>>4; a = life*2+1; break; case 2: r += 3; if(r > 255) r = 255; g -= 4; if(g < 0) g = 0; b -= 1; if(b < 0) b = 0; size = 5*life; a = life+1; if(a > 31) a = 31; break; case 3: r = life/2+80; g = life/2+80; b = life/2+80; a = life/50+1; size = 500; break; case 4: a = life*2+1; if(a > 31) a = 31; break; }*/ } bool Particle::out(int xc, int yc) { // if(type == 0) return false; if(x < xc-150*32) return true; if(x > xc+150*32) return true; if(y < yc-150*32) return true; if(y > yc+150*32) return true; return false; }
[ "[email protected]@728844e9-ea54-d303-ac3c-f2c77ebcc567" ]
[ [ [ 1, 166 ] ] ]
5fb4015437cc5b9dca45bf83592eaa559b9e816b
f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae
/Exercises/Old Solutions/OpenGL_Tests/OpenGL_Tests/camera.cpp
223a27d73b4b903e5013d8f0c33c052647fc451b
[]
no_license
giacomof/gameengines2010itu
8407be66d1aff07866d3574a03804f2f5bcdfab1
bc664529a429394fe5743d5a76a3d3bf5395546b
refs/heads/master
2016-09-06T05:02:13.209432
2010-12-12T22:18:19
2010-12-12T22:18:19
35,165,366
0
0
null
null
null
null
UTF-8
C++
false
false
4,213
cpp
/* ********* CAMERA TEST CLASS ********** */ /* It is needed the vector class that giacomo is preparing */ #include <iostream> #include "camera.h" using namespace std; class Camera { private: void Camera::positionposition( float positionX, float positionY, float positionZ, float viewX, float viewY, float viewZ, float upX, float upY, float upZ ) { // this method places the camera somewhere, using positionX/Y/Z vector data // and inizializes the three foundamental vectors we are going to use // in the camera views and movements Vector vPosition(positionX, positionY, positionZ); Vector vView(viewX, viewY, viewZ); Vector vUp(upX, upY, upZ); } void Camera::move(float speed) { Vector distance = vView - vPosition; // vector that contains the information about the direction of the vector that starts in vPosition and ends in vView vPosition.x += distance.x * speed; vPosition.z += distance.z * speed; vView.x += distance.x * speed; vView.z += distance.z * speed; } void Camera::rotate(int rotX, int rotY, int rotZ) { Vector distance = vView - vPosition; // vector that contains the information about the direction of the vector that starts in vPosition and ends in vView if(rotX) { vView.z = vPosition.z + sin_table[rotX]*distance.y + cos_table[rotX]*distance.z; vView.y = vPosition.y + sin_table[rotX]*distance.y + cos_table[rotX]*distance.z; } if(rotY) { vView.z = vPosition.z + sin_table[rotY]*distance.x + cos_table[rotY]*distance.z; vView.x = vPosition.x + sin_table[rotY]*distance.x + cos_table[rotY]*distance.z; } if(rotZ) { vView.x = vPosition.x + sin_table[rotZ]*distance.y + cos_table[rotZ]*distance.x; vView.y = vPosition.y + sin_table[rotZ]*distance.y + cos_table[rotZ]*distance.x; } } void Camera::doViewTransform() { gluLookAt( vPosition.x, vPosition.y, vPosition.z, vView.x, vView.y, vView.z, vUp.x, vUp.y, vUp.z); } public: // Build the sin and cos look up tables to get // faster access to these values at runtime void BuilLookUpTables() { for(int angle=0; angle<360; angle++) { sin_table[angle] = (float) sin((double)angle*PI/180); cos_table[angle] = (float) cos((double)angle*PI/180); } } /* ************************************************* */ /* ************ THIS IS OLD CODE ******************* */ /* ************************************************* */ /* void Camera :: rotateY(float amount) { Vector target = m_target; Vector right = m_right; amount /= 57.2957795f; m_target.m_xyzw[0] = (cos(1.5708f + amount) * target.m_xyzw[0]) + (cos(amount) * right.m_xyzw[0]); m_target.m_xyzw[1] = (cos(1.5708f + amount) * target.m_xyzw[1]) + (cos(amount) * right.m_xyzw[1]); m_target.m_xyzw[2] = (cos(1.5708f + amount) * target.m_xyzw[2]) + (cos(amount) * right.m_xyzw[2]); m_right.m_xyzw[0] = (cos(amount) * target.m_xyzw[0]) + (cos(1.5708f - amount) * right.m_xyzw[0]); m_right.m_xyzw[1] = (cos(amount) * target.m_xyzw[1]) + (cos(1.5708f - amount) * right.m_xyzw[1]); m_right.m_xyzw[2] = (cos(amount) * target.m_xyzw[2]) + (cos(1.5708f - amount) * right.m_xyzw[2]); m_target.normalize(); m_right.normalize(); } void Camera :: lookAt(Vector target) { Vector projectedTarget; target = target - m_position; projectedTarget = target; if(fabs(target.m_xyzw[0]) < 0.00001f && fabs(target.m_xyzw[2]) < 0.00001f) { // YZ plane projectedTarget.m_xyzw[0] = 0.0f; projectedTarget.normalize(); m_right = Vector(1.0f, 0.0f, 0.0f); m_up = cross(projectedTarget, m_right); m_target = target; m_right = -cross(m_target, m_up); } else { // XZ plane projectedTarget.m_xyzw[1] = 0.0f; projectedTarget.normalize(); m_up = Vector(0.0f, 1.0f, 0.0f); m_right = -cross(projectedTarget, m_up); m_target = target; m_up = cross(m_target, m_right); } m_target.normalize(); m_right.normalize(); m_up.normalize(); } */ };
[ "[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d" ]
[ [ [ 1, 155 ] ] ]
78833e912601ecfd0553266cf70487f8e2c0b112
ddc9569f4950c83f98000a01dff485aa8fa67920
/naikai/windowing/src/win32/nkWindowingService.cpp
dcc9c6f2f7b587cba8205da1d5f744599ea65d45
[]
no_license
chadaustin/naikai
0a291ddabe725504cdd80c6e2c7ccb85dc5109da
83b590b049a7e8a62faca2b0ca1d7d33e2013301
refs/heads/master
2021-01-10T13:28:48.743787
2003-02-19T19:56:24
2003-02-19T19:56:24
36,420,940
0
0
null
null
null
null
UTF-8
C++
false
false
2,347
cpp
#include "nkWindowingService.h" #include "nkMenu.h" #include "nkWindow.h" nkWindowingService::nkWindowingService() { NS_INIT_REFCNT(); } NS_IMPL_ISUPPORTS1(nkWindowingService, nkIWindowingService); NS_IMETHODIMP nkWindowingService::CreateFrameWindow(nkIWindow** rv) { HINSTANCE instance = GetModuleHandle(NULL); // register the window class // don't bother checking to see if window class registration fails // if it does fail, window creation will WNDCLASS wc; memset(&wc, 0, sizeof(wc)); wc.style = CS_OWNDC; // required for the OpenGL renderer wc.lpfnWndProc = nkWindow::WindowProc; wc.hInstance = instance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = "NaikaiWindow"; RegisterClass(&wc); HWND window = ::CreateWindowA( "NaikaiWindow", "Naikai Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, instance, NULL); if (!window) { *rv = NULL; return NS_ERROR_FAILURE; } ::ShowWindow(window, SW_SHOW); ::UpdateWindow(window); *rv = new nkWindow(window); NS_ADDREF(*rv); return NS_OK; } NS_IMETHODIMP nkWindowingService::CreateMenu(nkIMenu** rv) { HMENU menu = ::CreateMenu(); if (!menu) { return NS_ERROR_FAILURE; } *rv = new nkMenu(menu); NS_ADDREF(*rv); return NS_OK; } NS_IMETHODIMP nkWindowingService::GetOnIdle(nkICommand** on_idle) { *on_idle = m_on_idle; return NS_OK; } NS_IMETHODIMP nkWindowingService::SetOnIdle(nkICommand* on_idle) { m_on_idle = on_idle; return NS_OK; } NS_IMETHODIMP nkWindowingService::Run() { MSG msg; while (true) { bool available = true; if (!m_on_idle) { if (GetMessage(&msg, NULL, 0, 0) <= 0) { return NS_OK; } } else { available = (0 != PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)); if (available && msg.message == WM_QUIT) { return NS_OK; } } if (available) { TranslateMessage(&msg); DispatchMessage(&msg); } if (m_on_idle) { m_on_idle->Execute(this); } } return NS_OK; } NS_IMETHODIMP nkWindowingService::PumpEvents() { return NS_ERROR_NOT_IMPLEMENTED; }
[ "aegis@ed5ae262-7be1-47e3-824f-6ab8bb33c1ce" ]
[ [ [ 1, 121 ] ] ]
26c56f491cd6d78abc81fab8169ff013f7d49ed7
bd37f7b494990542d0d9d772368239a2d44e3b2d
/client/src/Mensaje.h
fbc4e02a29783fe9cdfc3afda9776175cb419178
[]
no_license
nicosuarez/pacmantaller
b559a61355517383d704f313b8c7648c8674cb4c
0e0491538ba1f99b4420340238b09ce9a43a3ee5
refs/heads/master
2020-12-11T02:11:48.900544
2007-12-19T21:49:27
2007-12-19T21:49:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
807
h
/////////////////////////////////////////////////////////// // Mensaje.h // Implementation of the Class Mensaje // Created on: 21-Nov-2007 23:40:19 /////////////////////////////////////////////////////////// #if !defined(EA_00555EAD_A002_4386_8DDE_5962FC3B0BA9__INCLUDED_) #define EA_00555EAD_A002_4386_8DDE_5962FC3B0BA9__INCLUDED_ #include <string> #include "Paquetes.h" class Mensaje { protected: int sizePkt; public: static const int INIT_TYPE = 0; static const int START_TYPE = 1; static const int STATUS_TYPE = 2; static const int STOP_TYPE = 3; static const int QUIT_TYPE = 4; Mensaje(); virtual ~Mensaje(); virtual char* Serialize()=0; int getSize()const; }; #endif // !defined(EA_00555EAD_A002_4386_8DDE_5962FC3B0BA9__INCLUDED_)
[ "nicolas.suarez@5682bcf5-5c3f-0410-a8fd-ab24993f6fe8" ]
[ [ [ 1, 35 ] ] ]
494c3a75d303c8d2f200575fcd916b1ed607ba80
d0cf8820b4ad21333e15f7cec1e4da54efe1fdc5
/DES_GOBSTG/DES_GOBSTG/Header/BossInfo.h
a9902a5fedac53e7c3b93c419746336cf1175cfc
[]
no_license
CBE7F1F65/c1bf2614b1ec411ee7fe4eb8b5cfaee6
296b31d342e39d1d931094c3dfa887dbb2143e54
09ed689a34552e62316e0e6442c116bf88a5a88b
refs/heads/master
2020-05-30T14:47:27.645751
2010-10-12T16:06:11
2010-10-12T16:06:11
32,192,658
0
0
null
null
null
null
UTF-8
C++
false
false
1,382
h
#ifndef _BOSSINFO_H #define _BOSSINFO_H #include "MainDependency.h" #include "InfoQuad.h" #include "Const.h" #include "Effectsys.h" #define BOSSINFO_ENABLE 1 #define BOSSINFO_UP 2 #define BOSSINFO_COLLAPSE 4 #define BOSSINFO_TIMEOVER 8 #define BIAUTORANK_NONE 0 #define BIAUTORANK_SHOT 1 #define BIAUTORANK_BOMB 2 class BossInfo { public: BossInfo(){}; ~BossInfo(){}; void bossUp(); void bossCollapse(); bool action(); void quit(); void Render(); void RenderTimeCircle(); bool Fill(int sno); static void empty(); static bool Init(const char * fontname); static void Release(); public: char enemyname[M_STRMAX]; char enemypinyin[M_STRMAX]; char rangename[M_STRMAX]; InfoQuad blood; DWORD bonus; DWORD maxbonus; DWORD lastgraze; int get; int meet; int itemstack; bool exist; bool wait; WORD timer; BYTE limit; BYTE remain; static Effectsys effUp; static Effectsys effCollapse; static Effectsys effItem; static Effectsys effStore; static bool range; static bool failed; static bool uncircled; static int sno; static int turntoscene; static hgeSprite * cutin; static hgeSprite * timecircle; static hgeSprite * sprange; static hgeSprite * spbossx; static hgeFont * font; static BYTE flag; static BYTE autorank; }; extern BossInfo bossinfo; #endif
[ "CBE7F1F65@e00939f0-95ee-11de-8df0-bd213fda01be" ]
[ [ [ 1, 78 ] ] ]
ca8388efd7e08964ef3c10a54694265888d878f3
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/Aipi_Error.cpp
1b7d9631af1b297b416d1a5f0fbb2ab2c9c1e30f
[]
no_license
15831944/AiPI-1
2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4
9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8
refs/heads/master
2021-12-02T20:34:03.136125
2011-10-27T00:07:54
2011-10-27T00:07:54
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
13,359
cpp
// Aipi_Error.cpp: implementation of the CAipi_Error class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "AIPI.h" #include "Aipi_Error.h" #include "AIPIEditorDoc.h" #include "AIPIEditorView.h" #include "../MainFrm.h" #include "../ChildFrm.h" #include "../OutputTabView.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CAipi_Error::CAipi_Error() { } CAipi_Error::~CAipi_Error() { } CAipi_Error* CAipi_Error::addError(int index, CString msg, CString lnk, int categ ) { CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); CAipi_Error *pObject = new CAipi_Error(); try { pObject->setMessage(msg); pObject->setLink(lnk); pObject->setCateg(categ); pMainFrame->gmError.insert(CMainFrame::g_mError::value_type(index, *pObject)); } catch( CMemoryException* pErr) { AfxMessageBox(_T("Out of memory!!!"), MB_ICONSTOP | MB_OK); if(pObject) { delete pObject; pObject = NULL; } pErr->Delete(); } return pObject; } int CAipi_Error::findErrorMembers(int e) { CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); CMainFrame::g_mError::iterator iter; iter = pMainFrame->gmError.find(e); if( iter != pMainFrame->gmError.end()) { CAipi_Error err = (CAipi_Error)iter->second; m_ErrorMsg = err.getMessage(); m_ErrorLink = err.getLink(); m_ErrorCateg = err.getCateg(); return e; } return NOT_FOUND; } int CAipi_Error::openDocFile(LPCTSTR lpszPathName) { #define MAX_CHAR_PATH 254 CString currentDir; GetCurrentDirectory( MAX_PATH, currentDir.GetBufferSetLength(MAX_CHAR_PATH) ); AfxMessageBox(currentDir); currentDir.ReleaseBuffer(); CString execDir; GetModuleFileName( NULL, execDir.GetBufferSetLength(MAX_PATH), MAX_CHAR_PATH ); AfxMessageBox(execDir); execDir.ReleaseBuffer(); //lpszPathName = _T("D:\\Project AIPI VS6\\AIPI\\Examples\\array_test.txt"); /* if (!CScintillaDoc::OnOpenDocument(lpszPathName)) return FALSE; */ CAIPIApp* pApp = (CAIPIApp*)AfxGetApp(); pApp->UpdateDocumentView(lpszPathName); if( pApp == NULL ) { CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); pMainFrame->m_wndOutputTabView.AddMsg1(_T("The file was not found. Check the path and the name of the file.")); AfxMessageBox( _T("File was not found.")); return NOT_FOUND; } return FOUND; } void CAipi_Error::errorMark(unsigned int nLine) { CMDIFrameWnd* pFrame = (CMDIFrameWnd*)::AfxGetApp()->m_pMainWnd; CMDIChildWnd* pChild = (CMDIChildWnd*) pFrame->MDIGetActive(); CScintillaView* pView = (CScintillaView*) pChild->GetActiveView(); ASSERT(pView); //Find file path CAIPIEditorDoc* pDoc = (CAIPIEditorDoc*)pView->GetDocument(); ASSERT_VALID(pDoc); CString strPath = pDoc->GetPathName(); AfxMessageBox(strPath); CScintillaCtrl& rCtrl = pView->GetCtrl(); // Reset Scintilla Markers rCtrl.MarkerDeleteAll(0); // Initilaize error markers rCtrl.MarkerDefine(0, SC_MARK_ARROW); rCtrl.MarkerSetFore(0, RGB( 80, 0, 0 )); rCtrl.MarkerSetBack(0, RGB( 255, 0, 0 )); // Set error marker to proper line rCtrl.MarkerAdd((nLine - 1), 0); rCtrl.GotoLine(nLine - 1); } void CAipi_Error::displayGUIError(int e, int type, CString desc) { CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); TCHAR buff[64]; CMDIFrameWnd* pFrame = (CMDIFrameWnd*)::AfxGetApp()->m_pMainWnd; CMDIChildWnd* pChild = (CMDIChildWnd*) pFrame->MDIGetActive(); CScintillaView* pView = (CScintillaView*) pChild->GetActiveView(); ASSERT(pView); CScintillaCtrl& rCtrl = pView->GetCtrl(); LPTSTR lpsErrLine =_T("0"); LPTSTR lpsErrPos = _T("0"); LPTSTR lpsErrCode = _T("0"); LPTSTR lpsErrDesc = _T("No description has found for this error"); LPTSTR lpsErrFile = _T(" - "); //Handle Internationational LANGID dwLanguageID = GetSystemLanguagePrimaryID(); switch( dwLanguageID) { case LANG_SPANISH: //errLine = _bstr_t(_T("Línea: ")) + _itot( g_currentLine, buff, 10 ); //errPos = _bstr_t(_T("Pos. ")) + _itot(g_currentPos, buff, 10); break; default: //errLine = _bstr_t(_T("Line: ")) + _itot( g_currentLine, buff, 10 ); //errPos = _bstr_t(_T("Pos. ")) + _itot(g_currentPos, buff, 10); break; } //errorMark(g_currentLine); switch(type) { case LEX_ERROR: ++g_LexError; break; case SINTAX_ERROR: ++g_SintaxError; break; case SEMANT_ERROR: ++g_SemantError; break; case WARNING_ERROR: ++g_WarningError; break; case QUESTION_ERROR: ++g_QuestionError; break; case STOP_ERROR: ++g_StopError; break; case INFO_ERROR: ++g_InfoError; break; } findErrorMembers(e); lpsErrCode = _itot( e, buff, 10 ); CString strErrPos = _itot(g_currentPos, buff, 10); lpsErrPos = strErrPos.GetBuffer(0); strErrPos.ReleaseBuffer(); //CString strErrLine = _itot(g_currentLine, buff, 10); CString strErrLine = _itot(rCtrl.LineFromPosition(g_currentPos) + 1, buff, 10); lpsErrLine = strErrLine.GetBuffer(0); strErrLine.ReleaseBuffer(); CString strErrDesc = m_ErrorMsg + desc; lpsErrDesc = strErrDesc.GetBuffer(0); strErrDesc.ReleaseBuffer(); CString strErrFile = g_currentFile; lpsErrFile = g_currentFile.GetBuffer(0); strErrFile.ReleaseBuffer(); if ( pMainFrame->m_wndOutputTabView.IsVisible()) { pMainFrame->m_wndOutputTabView.m_TabViewContainer.SetActivePageIndex(1); LVITEM Item = pMainFrame->m_wndOutputTabView.AddListItem2(0, 0, _T(""), type); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 1, lpsErrLine); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 2, lpsErrPos); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 3, lpsErrDesc); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 4, lpsErrFile); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 5, lpsErrCode); } } void CAipi_Error::displayFileError(int e, int type, CString desc) { CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); TCHAR buff[64]; /* CMDIFrameWnd* pFrame = (CMDIFrameWnd*)::AfxGetApp()->m_pMainWnd; CMDIChildWnd* pChild = (CMDIChildWnd*) pFrame->MDIGetActive(); CScintillaView* pView = (CScintillaView*) pChild->GetActiveView(); ASSERT(pView); CScintillaCtrl& rCtrl = pView->GetCtrl(); */ LPTSTR lpsErrLine =_T("0"); LPTSTR lpsErrPos = _T("0"); LPTSTR lpsErrCode = _T("0"); LPTSTR lpsErrDesc = _T("No description has found for this error"); LPTSTR lpsErrFile = _T(" - "); //Handle Internationational LANGID dwLanguageID = GetSystemLanguagePrimaryID(); switch( dwLanguageID) { case LANG_SPANISH: //errLine = _bstr_t(_T("Línea: ")) + _itot( g_currentLine, buff, 10 ); //errPos = _bstr_t(_T("Pos. ")) + _itot(g_currentPos, buff, 10); break; default: //errLine = _bstr_t(_T("Line: ")) + _itot( g_currentLine, buff, 10 ); //errPos = _bstr_t(_T("Pos. ")) + _itot(g_currentPos, buff, 10); break; } //errorMark(g_currentLine); switch(type) { case LEX_ERROR: ++g_LexError; break; case SINTAX_ERROR: ++g_SintaxError; break; case SEMANT_ERROR: ++g_SemantError; break; case WARNING_ERROR: ++g_WarningError; break; case QUESTION_ERROR: ++g_QuestionError; break; case STOP_ERROR: ++g_StopError; break; case INFO_ERROR: ++g_InfoError; break; } findErrorMembers(e); lpsErrCode = _itot( e, buff, 10 ); CString strErrPos = _itot(g_fcurrentPos, buff, 10); lpsErrPos = strErrPos.GetBuffer(0); strErrPos.ReleaseBuffer(); CString strErrLine = _itot(g_currentLine, buff, 10); //CString strErrLine = _itot(rCtrl.LineFromPosition(g_fcurrentPos) + 1, buff, 10); lpsErrLine = strErrLine.GetBuffer(0); strErrLine.ReleaseBuffer(); CString strErrDesc = m_ErrorMsg + desc; lpsErrDesc = strErrDesc.GetBuffer(0); strErrDesc.ReleaseBuffer(); CString strErrFile = g_currentFile; lpsErrFile = g_currentFile.GetBuffer(0); strErrFile.ReleaseBuffer(); if ( pMainFrame->m_wndOutputTabView.IsVisible()) { pMainFrame->m_wndOutputTabView.m_TabViewContainer.SetActivePageIndex(1); LVITEM Item = pMainFrame->m_wndOutputTabView.AddListItem2(0, 0, _T(""), type); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 1, lpsErrLine); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 2, lpsErrPos); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 3, lpsErrDesc); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 4, lpsErrFile); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 5, lpsErrCode); } } void CAipi_Error::displayRunTimeFileError(int e, int type, CString path, CString desc) { CAIPIApp* pApp = (CAIPIApp*)AfxGetApp(); BOOL alreadyOpen = pApp->UpdateDocumentView(path); //if document is not already open then open it if( alreadyOpen == FALSE ) { pApp->m_pAIPIEditorDocTemplate->OpenDocumentFile(path); } CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); TCHAR buff[64]; CMDIFrameWnd* pFrame = (CMDIFrameWnd*)::AfxGetApp()->m_pMainWnd; CMDIChildWnd* pChild = (CMDIChildWnd*) pFrame->MDIGetActive(); CScintillaView* pView = (CScintillaView*) pChild->GetActiveView(); ASSERT(pView); CScintillaCtrl& rCtrl = pView->GetCtrl(); LPTSTR lpsErrLine =_T("0"); LPTSTR lpsErrPos = _T("0"); LPTSTR lpsErrCode = _T("0"); LPTSTR lpsErrDesc = _T("No description has found for this error"); LPTSTR lpsErrFile = _T(""); //Handle Internationational LANGID dwLanguageID = GetSystemLanguagePrimaryID(); switch( dwLanguageID) { case LANG_SPANISH: //errLine = _bstr_t(_T("Línea: ")) + _itot( g_currentLine, buff, 10 ); //errPos = _bstr_t(_T("Pos. ")) + _itot(g_currentPos, buff, 10); break; default: //errLine = _bstr_t(_T("Line: ")) + _itot( g_currentLine, buff, 10 ); //errPos = _bstr_t(_T("Pos. ")) + _itot(g_currentPos, buff, 10); break; } //errorMark(g_currentLine); switch(type) { case LEX_ERROR: ++g_LexError; break; case SINTAX_ERROR: ++g_SintaxError; break; case SEMANT_ERROR: ++g_SemantError; break; case WARNING_ERROR: ++g_WarningError; break; case QUESTION_ERROR: ++g_QuestionError; break; case STOP_ERROR: ++g_StopError; break; case INFO_ERROR: ++g_InfoError; break; } findErrorMembers(e); lpsErrCode = _itot( e, buff, 10 ); CString strErrPos = _itot(g_fcurrentPos, buff, 10); lpsErrPos = strErrPos.GetBuffer(0); strErrPos.ReleaseBuffer(); //CString strErrLine = _itot(g_currentLine, buff, 10); CString strErrLine = _itot(rCtrl.LineFromPosition(g_fcurrentPos) + 1, buff, 10); lpsErrLine = strErrLine.GetBuffer(0); strErrLine.ReleaseBuffer(); CString strErrDesc = m_ErrorMsg + desc; lpsErrDesc = strErrDesc.GetBuffer(0); strErrDesc.ReleaseBuffer(); CString strErrFile = g_currentFile; lpsErrFile = strErrFile.GetBuffer(0); lpsErrFile = strErrFile.GetBuffer(0); if ( pMainFrame->m_wndOutputTabView.IsVisible()) { pMainFrame->m_wndOutputTabView.m_TabViewContainer.SetActivePageIndex(1); LVITEM Item = pMainFrame->m_wndOutputTabView.AddListItem2(0, 0, _T(""), type); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 1, lpsErrLine); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 2, lpsErrPos); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 3, lpsErrDesc); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 4, lpsErrFile); pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 5, lpsErrCode); } } void CAipi_Error::printError() { CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd(); TCHAR buffer[16]; pMainFrame->m_wndOutputTabView.AddMsg1(_T("******* ERROR MSG *******")); //Print map container for( CMainFrame::g_mError::const_iterator iter = pMainFrame->gmError.begin(); iter!= pMainFrame->gmError.end(); ++iter) { CString strIndex =_T("N_ERROR_"); CString strCateg =_T("CATEG_"); pMainFrame->m_wndOutputTabView.AddMsg1(_T("******* Error Element *******")); pMainFrame->m_wndOutputTabView.AddMsg1(_T("No. Error: ")); strIndex += _itot( iter->first, buffer, 10 ); pMainFrame->m_wndOutputTabView.AddMsg1(strIndex); CAipi_Error e = (CAipi_Error)iter->second; tstring msg = e.getMessage(); tstring lnk = e.getLink(); int categ = e.getCateg(); pMainFrame->m_wndOutputTabView.AddMsg1(_T("Message: ")); pMainFrame->m_wndOutputTabView.AddMsg1(msg.data()); pMainFrame->m_wndOutputTabView.AddMsg1(_T("Link: ")); pMainFrame->m_wndOutputTabView.AddMsg1(lnk.data()); pMainFrame->m_wndOutputTabView.AddMsg1(_T("Category: ")); strCateg += _itot( categ, buffer, 10 ); pMainFrame->m_wndOutputTabView.AddMsg1(strCateg); } }
[ [ [ 1, 534 ] ] ]
24554f5b36d1971522467944cbef2056f148a996
993635387a5f4868e442df7d4a0d87cc215069c1
/OMV/OMV/SkeletonControlPanel.h
fdb5ef36c230ae1ebf908dcbaa3c82d5c0218dbf
[]
no_license
windrobin/ogremeshviewer
90475b25f53f9d1aee821c150a8517ee4ee4d37d
679a2979320af09469894a6d99a90ec1adc5f658
refs/heads/master
2021-01-10T02:18:50.523143
2011-02-16T01:06:03
2011-02-16T01:06:03
43,444,741
0
2
null
null
null
null
UTF-8
C++
false
false
2,907
h
/* ----------------------------------------------------------------------------- This source file is part of Tiger Viewer(An Ogre Mesh Viewer) For the latest info, see http://code.google.com/p/ogremeshviewer/ Copyright (c) 2010 Zhang Kun([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- This software also uses Microsoft Fluent UI. License terms to copy, use or distribute the Fluent UI are available separately. To learn more about our Fluent UI licensing program, please visit http://msdn.microsoft.com/officeui. Generally speaking, Fluent UI is free, if you do not use it make a contest software like Office. ----------------------------------------------------------------------------- */ #pragma once #include "afxwin.h" #include "afxcmn.h" #include "resource.h" // SkeletonControlPanel dialog class SkeletonControlPanel : public CDialog { DECLARE_DYNAMIC(SkeletonControlPanel) public: SkeletonControlPanel(CWnd* pParent = NULL); // standard constructor virtual ~SkeletonControlPanel(); void BuildSkeletonAnimInfo(const Ogre::String& strActorName); void OnReset(); // Dialog Data enum { IDD = IDD_DIALOG_ANIMATION }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support Ogre::MeshPtr _mesh; Ogre::String _strActorName; bool _bAnimPlaying; DECLARE_MESSAGE_MAP() public: CComboBox _comboAnims; CTreeCtrl _treeDetails; CSliderCtrl _sliderPos; BOOL _bCheckLoop; int _interPolateMode; float _fAnimSpeed; CEdit _editSelectedBone; virtual BOOL OnInitDialog(); afx_msg void OnBnClickedButtonPlay(); afx_msg void OnBnClickedButtonPause(); afx_msg void OnBnClickedButtonStop(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnCbnSelchangeComboAnims(); afx_msg void OnEnChangeEditSpeed(); afx_msg void OnBnClickedCheckLoop(); afx_msg void OnBnClickedRadioInterpolation(); afx_msg void OnTvnSelchangedTreeDetails(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); };
[ "zhk.tiger@b3cfb0ba-c873-51ca-4d9f-db82523f9d23" ]
[ [ [ 1, 85 ] ] ]
dd63f2ee13e91a4eb1cc2143de661aa589a0f547
78a3f22a051553018d343cec96c975d125528c08
/razno/main_standard.cpp
0ed537f6f154682fa1adfe042440d70c88ebed92
[]
no_license
kdomic/SP_zadatak_2
9b7f7c7e0c535c8a445cf8e597b974697a4a6935
5c6604549676c089c60cd590a5e8ed25cbd27126
refs/heads/master
2020-05-17T10:03:09.353039
2011-11-17T08:56:59
2011-11-17T08:56:59
2,789,362
0
0
null
null
null
null
UTF-8
C++
false
false
1,603
cpp
#include<iostream> //#include"lista_polja.h" #include"lista_pokazivaci.h" using namespace std; void unos(tlist *list){ system("cls"); tdata data; cout << "Unesite sifru: "; cin >> data.sifra; cin.ignore(); cout << "Naziv: "; cin.getline(data.naziv,50); PushS(data,list); cout << endl << "Dodano" << endl; system("pause"); } void ispis(tlist *list){ system("cls"); tdata data = TopS(list); cout << "Sifra: " << data.sifra << endl; cout << "Naziv: " << data.naziv << endl; system("pause"); } void brisanje(tlist *list){ system("cls"); if(PopS(list)) cout << "Zapis je uklonjen!" << endl; else cout << "Lista je prazna" << endl; system("pause"); } void prazna(tlist *list){ system("cls"); if(IsEmptyS(list)) cout << "Lista je prazna" << endl; else cout << "Lista nije prazna" << endl; system("pause"); } int main(){ int izbor; tlist *list = InitS(list); do{ system("cls"); cout << "1 - Unos(Push)" << endl; cout << "2 - Ispis zadnjeg(TopS)" << endl; cout << "3 - Brisi (PopS)" << endl; cout << "4 - Prazna?" << endl; cout << "0 - Kraj" << endl; cout << endl; cout << "Vas izbor:"; cin >> izbor; switch(izbor){ case 1: unos(list); break; case 2: ispis(list); break; case 3: brisanje(list); break; case 4: prazna(list); break; case 0: cout << "Kraj" << endl; break; default: cout << "Krivi unos" << endl; system("pause"); } }while(izbor); system("pause"); return 0; }
[ [ [ 1, 73 ] ] ]
2ef9776aba668cb828cf4c1a839e8b98d1a7efa8
57d74ff818cabf449d3ad457bcc54c5d78550352
/8.0/SpiraTestCompletePlugIn/atlstencil.h
dca5bdfbfdb9671b9f559c89f8256d67e3a8630f
[]
no_license
Inflectra/spira-testing-test-complete
f6e28f558b97689331ee2107501eb121341aabdb
9bcf5d3286dd3bba492bc432511be193becca547
refs/heads/main
2023-04-09T07:14:02.796898
2010-08-05T17:39:00
2010-08-05T17:39:00
359,174,921
0
0
null
null
null
null
UTF-8
C++
false
false
109,829
h
// This is a part of the Active Template Library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Active Template Library Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Active Template Library product. #ifndef __ATLSTENCIL_H__ #define __ATLSTENCIL_H__ #pragma once #include "atlisapi.h" #include <atlfile.h> #include <atlutil.h> #include <math.h> #ifdef ATL_DEBUG_STENCILS #include <atlsrvres.h> #ifndef ATL_STENCIL_MAX_ERROR_LEN #define ATL_STENCIL_MAX_ERROR_LEN 256 #endif #endif // ATL_DEBUG_STENCILS #ifndef ATL_NO_MLANG #include <mlang.h> #endif #ifndef _ATL_NO_DEFAULT_LIBS #pragma comment(lib, "shlwapi.lib") #endif // !_ATL_NO_DEFAULT_LIBS #pragma warning( push ) #pragma warning(disable: 4127) // conditional expression is constant #pragma warning(disable: 4511) // copy constructor could not be generated #pragma warning(disable: 4512) // assignment operator could not be generated #pragma warning(disable: 4702) // assignment operator could not be generated #pragma warning(disable: 4625) // copy constructor could not be generated because a base class copy constructor is inaccessible #pragma warning(disable: 4626) // assignment operator could not be generated because a base class assignment operator is inaccessible #pragma warning(disable: 4191) // unsafe conversion from 'functionptr1' to 'functionptr2' #pragma pack(push,_ATL_PACKING) namespace ATL { // Token types // These tags are token tags for the standard tag replacer implementation extern __declspec(selectany) const DWORD STENCIL_TEXTTAG = 0x00000000; extern __declspec(selectany) const DWORD STENCIL_REPLACEMENT = 0x00000001; extern __declspec(selectany) const DWORD STENCIL_ITERATORSTART = 0x00000002; extern __declspec(selectany) const DWORD STENCIL_ITERATOREND = 0x00000003; extern __declspec(selectany) const DWORD STENCIL_CONDITIONALSTART = 0x00000004; extern __declspec(selectany) const DWORD STENCIL_CONDITIONALELSE = 0x00000005; extern __declspec(selectany) const DWORD STENCIL_CONDITIONALEND = 0x00000006; extern __declspec(selectany) const DWORD STENCIL_STENCILINCLUDE = 0x00000007; extern __declspec(selectany) const DWORD STENCIL_STATICINCLUDE = 0x00000008; extern __declspec(selectany) const DWORD STENCIL_LOCALE = 0x00000009; extern __declspec(selectany) const DWORD STENCIL_CODEPAGE = 0x0000000a; // The base for user defined token types extern __declspec(selectany) const DWORD STENCIL_USER_TOKEN_BASE = 0x00001000; // Symbols to use in error handling in the stencil processor #define STENCIL_INVALIDINDEX 0xFFFFFFFF #define STENCIL_INVALIDOFFSET 0xFFFFFFFF // error codes #define STENCIL_SUCCESS HTTP_SUCCESS #define STENCL_FAIL HTTP_FAIL #define STENCIL_BASIC_MAP 0 #define STENCIL_ATTR_MAP 1 #ifndef ATL_MAX_METHOD_NAME_LEN #define ATL_MAX_METHOD_NAME_LEN 64 #endif #ifndef ATL_MAX_BLOCK_STACK #define ATL_MAX_BLOCK_STACK 128 #endif template <class TBase, typename T> struct CTagReplacerMethodsEx { typedef HTTP_CODE (TBase::*REPLACE_FUNC)(); typedef HTTP_CODE (TBase::*REPLACE_FUNC_EX)(T*); typedef HTTP_CODE (TBase::*PARSE_FUNC)(IAtlMemMgr *, LPCSTR, T**); typedef HTTP_CODE (TBase::*REPLACE_FUNC_EX_V)(void *); typedef HTTP_CODE (TBase::*PARSE_FUNC_V)(IAtlMemMgr *, LPCSTR, void**); static REPLACE_FUNC_EX_V CheckRepl(REPLACE_FUNC p) throw() { return (REPLACE_FUNC_EX_V) p; } static REPLACE_FUNC_EX_V CheckReplEx(REPLACE_FUNC_EX p) throw() { return (REPLACE_FUNC_EX_V) p; } static PARSE_FUNC_V CheckParse(PARSE_FUNC p) throw() { return (PARSE_FUNC_V) p; } }; template <class TBase> struct CTagReplacerMethods { union { HTTP_CODE (TBase::*pfnMethodEx)(void *); HTTP_CODE (TBase::*pfnMethod)(); }; HTTP_CODE (TBase::*pfnParse)(IAtlMemMgr *pMemMgr, LPCSTR, void **); }; #define REPLACEMENT_ENTRY_DEFAULT 0 #define REPLACEMENT_ENTRY_ARGS 1 template <class TBase> struct CTagReplacerMethodEntry { int nType; // REPLACEMENT_ENTRY_* LPCSTR szMethodName; CTagReplacerMethods<TBase> Methods; }; #define BEGIN_REPLACEMENT_METHOD_MAP(className)\ public:\ void GetReplacementMethodMap(const ATL::CTagReplacerMethodEntry<className> ** ppOut) const\ {\ typedef className __className;\ static const ATL::CTagReplacerMethodEntry<className> methods[] = { #define REPLACEMENT_METHOD_ENTRY(methodName, methodFunc)\ { 0, methodName, { ATL::CTagReplacerMethodsEx<__className, void>::CheckRepl(&__className::methodFunc), NULL } }, #define REPLACEMENT_METHOD_ENTRY_EX(methodName, methodFunc, paramType, parseFunc)\ { 1, methodName, { ATL::CTagReplacerMethodsEx<__className, paramType>::CheckReplEx(&__className::methodFunc), ATL::CTagReplacerMethodsEx<__className, paramType>::CheckParse(&__className::parseFunc) } }, #define REPLACEMENT_METHOD_ENTRY_EX_STR(methodName, methodFunc) \ { 1, methodName, { ATL::CTagReplacerMethodsEx<__className, char>::CheckReplEx(&__className::methodFunc), ATL::CTagReplacerMethodsEx<__className, char>::CheckParse(&__className::DefaultParseString) } }, #define END_REPLACEMENT_METHOD_MAP()\ { 0, NULL, NULL } };\ *ppOut = methods;\ } #define BEGIN_ATTR_REPLACEMENT_METHOD_MAP(className)\ public:\ void GetAttrReplacementMethodMap(const CTagReplacerMethodEntry<className> ** ppOut) const\ {\ typedef className __className;\ static const ATL::CTagReplacerMethodEntry<className> methods[] = { #define END_ATTR_REPLACEMENT_METHOD_MAP()\ { NULL, NULL, NULL } };\ *ppOut = methods;\ } template <class T> class ITagReplacerImpl : public ITagReplacer { protected: IWriteStream *m_pStream; public: typedef HTTP_CODE (T::*REPLACEMENT_METHOD)(); typedef HTTP_CODE (T::*REPLACEMENT_METHOD_EX)(void *pvParam); ITagReplacerImpl() throw() :m_pStream(NULL) { } IWriteStream *SetStream(IWriteStream *pStream) { IWriteStream *pRetStream = m_pStream; m_pStream = pStream; return pRetStream; } // Looks up the replacement method offset. Optionally, it will // look up the replacement method and object offset of an alternate // tag replacer. HTTP_CODE FindReplacementOffset( LPCSTR szMethodName, DWORD *pdwMethodOffset, LPCSTR szHandlerName, DWORD *pdwHandlerOffset, DWORD *pdwMap, void **ppvParam, IAtlMemMgr *pMemMgr) { ATLENSURE(szMethodName != NULL); ATLENSURE(pdwMethodOffset != NULL); ATLENSURE((szHandlerName == NULL && pdwHandlerOffset == NULL) || (szHandlerName != NULL && pdwHandlerOffset != NULL)); ATLENSURE(pdwMap != NULL); ATLENSURE(ppvParam != NULL); ATLENSURE(pMemMgr != NULL); // we at least have to be looking up a method offset if (!pdwMethodOffset || !szMethodName) return AtlsHttpError(500, ISE_SUBERR_UNEXPECTED); *pdwMethodOffset = STENCIL_INVALIDOFFSET; HTTP_CODE hcErr = HTTP_FAIL; T *pT = static_cast<T *>(this); char szName[ATL_MAX_METHOD_NAME_LEN+1]; // if a handler name was supplied, we will try to // find a different object to handle the method if (szHandlerName && *szHandlerName) { if (!pdwHandlerOffset) return AtlsHttpError(500, ISE_SUBERR_UNEXPECTED); hcErr = pT->GetHandlerOffset(szHandlerName, pdwHandlerOffset); // got the alternate handler, now look up the method offset on // the handler. if (!hcErr) { CComPtr<ITagReplacer> spAltTagReplacer; hcErr = pT->GetReplacementObject(*pdwHandlerOffset, &spAltTagReplacer); if (!hcErr) hcErr = spAltTagReplacer->FindReplacementOffset(szMethodName, pdwMethodOffset, NULL, NULL, pdwMap, ppvParam, pMemMgr); return hcErr; } else return hcErr; } if (!SafeStringCopy(szName, szMethodName)) { return AtlsHttpError(500, ISE_SUBERR_LONGMETHODNAME); } // check for params char *szLeftPar = strchr(szName, '('); if (szLeftPar) { *szLeftPar = '\0'; szLeftPar++; char *szRightPar = strchr(szLeftPar, ')'); if (!szRightPar) return AtlsHttpError(500, ISE_SUBERR_UNEXPECTED); *szRightPar = '\0'; szMethodName = szName; } // No handler name is specified, so we look up the method name in // T's replacement method map const CTagReplacerMethodEntry<T> *pEntry = NULL; pT->GetReplacementMethodMap(&pEntry); hcErr = FindReplacementOffsetInMap(szMethodName, pdwMethodOffset, pEntry); if (hcErr != HTTP_SUCCESS) { pT->GetAttrReplacementMethodMap(&pEntry); hcErr = FindReplacementOffsetInMap(szMethodName, pdwMethodOffset, pEntry); if (hcErr == HTTP_SUCCESS) *pdwMap = STENCIL_ATTR_MAP; } else { *pdwMap = STENCIL_BASIC_MAP; } // This assert will be triggered if arguments are passed to a replacement method that doesn't handle them ATLASSERT( szLeftPar == NULL || (szLeftPar != NULL && (pEntry != NULL && pEntry[*pdwMethodOffset].Methods.pfnParse != NULL)) ); if (hcErr == HTTP_SUCCESS && pEntry && pEntry[*pdwMethodOffset].Methods.pfnParse) hcErr = (pT->*pEntry[*pdwMethodOffset].Methods.pfnParse)(pMemMgr, szLeftPar, ppvParam); return hcErr; } HTTP_CODE FindReplacementOffsetInMap( LPCSTR szMethodName, LPDWORD pdwMethodOffset, const CTagReplacerMethodEntry<T> *pEntry) throw() { if (pEntry == NULL) return HTTP_FAIL; const CTagReplacerMethodEntry<T> *pEntryHead = pEntry; while (pEntry->szMethodName) { if (strcmp(pEntry->szMethodName, szMethodName) == 0) { if (pEntry->Methods.pfnMethod) { *pdwMethodOffset = (DWORD)(pEntry-pEntryHead); return HTTP_SUCCESS; } } pEntry++; } return HTTP_FAIL; } // Used to render a single replacement tag into a stream. // Looks up a pointer to a member function in user code by offseting into the users // replacement map. Much faster than the other overload of this function since // no string compares are performed. HTTP_CODE RenderReplacement(DWORD dwFnOffset, DWORD dwObjOffset, DWORD dwMap, void *pvParam) { HTTP_CODE hcErr = HTTP_FAIL; T *pT = static_cast<T *>(this); // if we were not passed an object offset, then we assume // that the function at dwFnOffset is in T's replacement // map if (dwObjOffset == STENCIL_INVALIDOFFSET) { // call a function in T's replacement map ATLASSERT(dwFnOffset != STENCIL_INVALIDOFFSET); const CTagReplacerMethodEntry<T> *pEntry = NULL; if (dwMap == STENCIL_BASIC_MAP) pT->GetReplacementMethodMap(&pEntry); else pT->GetAttrReplacementMethodMap(&pEntry); if (pEntry) { if (pEntry[dwFnOffset].nType == REPLACEMENT_ENTRY_DEFAULT) { REPLACEMENT_METHOD pfn = NULL; pfn = pEntry[dwFnOffset].Methods.pfnMethod; ATLASSERT(pfn); if (pfn) { hcErr = (pT->*pfn)(); } } else if (pEntry[dwFnOffset].nType == REPLACEMENT_ENTRY_ARGS) { REPLACEMENT_METHOD_EX pfn = NULL; pfn = pEntry[dwFnOffset].Methods.pfnMethodEx; ATLASSERT(pfn); if (pfn) { hcErr = (pT->*pfn)(pvParam); } } else { // unknown entry type ATLASSERT(FALSE); } } } else { // otherwise, we were passed an object offset. The object // offset is a dword ID that T can use to look up the // ITagReplacer* of a tag replacer that will render this // replacement. CComPtr<ITagReplacer> spAltReplacer = NULL; if (!pT->GetReplacementObject(dwObjOffset, &spAltReplacer)) { spAltReplacer->SetStream(m_pStream); hcErr = spAltReplacer->RenderReplacement(dwFnOffset, STENCIL_INVALIDOFFSET, dwMap, pvParam); } } return hcErr; } // Default GetHandlerOffset, does nothing HTTP_CODE GetHandlerOffset(LPCSTR /*szHandlerName*/, DWORD* pdwOffset) { if (pdwOffset) *pdwOffset = 0; return HTTP_FAIL; } // Default GetReplacementObject, does nothing HTTP_CODE GetReplacementObject(DWORD /*dwObjOffset*/, ITagReplacer **ppReplacer) { if (ppReplacer) *ppReplacer = NULL; return HTTP_FAIL; } void GetReplacementMethodMap(const CTagReplacerMethodEntry<T> ** ppOut) const { static const CTagReplacerMethodEntry<T> methods[] = { { NULL, NULL } }; *ppOut = methods; } void GetAttrReplacementMethodMap(const CTagReplacerMethodEntry<T> **ppOut) const { static const CTagReplacerMethodEntry<T> methods[] = { { NULL, NULL } }; *ppOut = methods; } HRESULT GetContext(REFIID, void**) { return E_NOINTERFACE; } virtual HINSTANCE GetResourceInstance() { return GetModuleHandle(NULL); } HTTP_CODE DefaultParseString(IAtlMemMgr *pMemMgr, LPCSTR szParams, char **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); size_t nLen = strlen(szParams); if (nLen) { nLen++; *ppParam = (char *) pMemMgr->Allocate(nLen); if (*ppParam) Checked::memcpy_s(*ppParam, nLen, szParams, nLen); else return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseUChar(IAtlMemMgr *pMemMgr, LPCSTR szParams, unsigned char **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (unsigned char *) pMemMgr->Allocate(sizeof(unsigned char)); if (*ppParam) { char *szEnd; **ppParam = (unsigned char) strtoul(szParams, &szEnd, 10); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseShort(IAtlMemMgr *pMemMgr, LPCSTR szParams, short **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (short *) pMemMgr->Allocate(sizeof(short)); if (*ppParam) { **ppParam = (short)atoi(szParams); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseUShort(IAtlMemMgr *pMemMgr, LPCSTR szParams, unsigned short **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (unsigned short *) pMemMgr->Allocate(sizeof(short)); if (*ppParam) { char *szEnd; **ppParam = (unsigned short) strtoul(szParams, &szEnd, 10); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseInt(IAtlMemMgr *pMemMgr, LPCSTR szParams, int **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (int *) pMemMgr->Allocate(sizeof(int)); if (*ppParam) { **ppParam = atoi(szParams); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseUInt(IAtlMemMgr *pMemMgr, LPCSTR szParams, unsigned int **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (unsigned int *) pMemMgr->Allocate(sizeof(unsigned int)); if (*ppParam) { char *szEnd; **ppParam = strtoul(szParams, &szEnd, 10); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseInt64(IAtlMemMgr *pMemMgr, LPCSTR szParams, __int64 **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (__int64 *) pMemMgr->Allocate(sizeof(__int64)); if (*ppParam) { **ppParam = _atoi64(szParams); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseUInt64(IAtlMemMgr *pMemMgr, LPCSTR szParams, unsigned __int64 **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (unsigned __int64 *) pMemMgr->Allocate(sizeof(unsigned __int64)); if (*ppParam) { char *szEnd; **ppParam = _strtoui64(szParams, &szEnd, 10); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseBool(IAtlMemMgr *pMemMgr, LPCSTR szParams, bool **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (bool *) pMemMgr->Allocate(sizeof(bool)); if (*ppParam) { if (!_strnicmp(szParams, "true", sizeof("true")-sizeof('\0'))) **ppParam = true; else **ppParam = false; } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseDouble(IAtlMemMgr *pMemMgr, LPCSTR szParams, double **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); *ppParam = (double *) pMemMgr->Allocate(sizeof(double)); if (*ppParam) { **ppParam = atof(szParams); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } HTTP_CODE DefaultParseFloat(IAtlMemMgr *pMemMgr, LPCSTR szParams, float **ppParam) throw(...) { ATLENSURE( pMemMgr != NULL ); ATLENSURE( szParams != NULL ); ATLENSURE( ppParam != NULL ); errno_t errnoValue = 0; *ppParam = (float *) pMemMgr->Allocate(sizeof(float)); if (*ppParam) { errno_t saveErrno = Checked::get_errno(); Checked::set_errno(0); **ppParam = (float) atof(szParams); errnoValue = Checked::get_errno(); Checked::set_errno(saveErrno); } else { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } if ((**ppParam == -HUGE_VAL) || (**ppParam == HUGE_VAL) || (errnoValue == ERANGE)) { return HTTP_FAIL; } return HTTP_SUCCESS; } }; inline LPCSTR SkipSpace(LPCSTR sz, WORD nCodePage) throw() { if (sz == NULL) return NULL; while (isspace(static_cast<unsigned char>(*sz))) sz = CharNextExA(nCodePage, sz, 0); return sz; } inline LPCSTR RSkipSpace(LPCSTR pStart, LPCSTR sz, WORD nCodePage) throw() { if (sz == NULL || pStart == NULL) return NULL; while (isspace(static_cast<unsigned char>(*sz)) && sz != pStart) sz = CharPrevExA(nCodePage, pStart, sz, 0); return sz; } // // StencilToken // The stencil class will create an array of these tokens during the parse // phase and use them during rendering to render the stencil struct StencilToken { LPCSTR pStart; // Start of fragment to be rendered LPCSTR pEnd; // End of fragment to be rendered DWORD type; // Type of token DWORD dwFnOffset; // Offset into the replacement map for the handler function. DWORD dwMap; DWORD dwObjOffset; // An identifier for the caller to use in identifiying the // object that will render this token. CHAR szHandlerName[ATL_MAX_HANDLER_NAME_LEN + 1]; // Name of handler object. CHAR szMethodName[ATL_MAX_METHOD_NAME_LEN + 1]; // Name of handler method. DWORD dwLoopIndex; // Offset into array of StencilTokens of the other loop tag DWORD_PTR dwData; BOOL bDynamicAlloc; }; // // Class CStencil // The CStencil class is used to map in a stencil from a file or resource // and parse the stencil into an array of StencilTokens. We then render // the stencil from the array of tokens. This class's parse and render // functions depend on an IReplacementHandlerLookup interface pointer to be // passed so it can retrieve the IReplacementHandler interface pointer of the // handler object that will be called to render replacement tags class CStencil : public IMemoryCacheClient { private: LPCSTR m_pBufferStart; // Beginning of CHAR buffer that holds the stencil. // For mapped files this is the beginning of the mapping. LPCSTR m_pBufferEnd; // End of CHAR buffer that holds the stencil. CAtlArray<StencilToken> m_arrTokens; //An array of tokens. FILETIME m_ftLastModified; // Last modified time (0 for resource) FILETIME m_ftLastChecked; // Last time we retrieved last modified time (0 for resource) HCACHEITEM m_hCacheItem; WORD m_nCodePage; BOOL m_bUseLocaleACP; char m_szDllPath[MAX_PATH]; char m_szHandlerName[ATL_MAX_HANDLER_NAME_LEN+1]; // Room for the path, the handler // the '/' and the '\0' #ifdef ATL_DEBUG_STENCILS struct ParseError { char m_szError[ATL_STENCIL_MAX_ERROR_LEN]; LPCSTR m_szPosition; LPCSTR m_szStartLine; LPCSTR m_szEndLine; int m_nLineNumber; bool operator==(const ParseError& that) const throw() { return (m_nLineNumber == that.m_nLineNumber); } }; CSimpleArray<ParseError> m_Errors; HINSTANCE m_hResInst; class CParseErrorProvider : public ITagReplacerImpl<CParseErrorProvider>, public CComObjectRootEx<CComSingleThreadModel> { public: BEGIN_COM_MAP(CParseErrorProvider) COM_INTERFACE_ENTRY(ITagReplacer) END_COM_MAP() CSimpleArray<ParseError> *m_pErrors; int m_nCurrentError; CParseErrorProvider() throw() : m_pErrors(NULL), m_nCurrentError(-1) { } void Initialize(CSimpleArray<ParseError> *pErrors) throw() { m_pErrors = pErrors; } HTTP_CODE OnGetNextError() throw() { m_nCurrentError++; if (m_nCurrentError >= m_pErrors->GetSize() || m_nCurrentError < 0 ) { m_nCurrentError = -1; return HTTP_S_FALSE; } else return HTTP_SUCCESS; } HTTP_CODE OnGetErrorLineNumber() throw(...) { if (m_pErrors->GetSize() == 0) return HTTP_SUCCESS; if (m_nCurrentError > m_pErrors->GetSize() || m_nCurrentError < 0) m_nCurrentError = 0; CWriteStreamHelper c(m_pStream); if (!c.Write((*m_pErrors)[m_nCurrentError].m_nLineNumber)) return HTTP_FAIL; return HTTP_SUCCESS; } HTTP_CODE OnGetErrorText() throw(...) { if (m_pErrors->GetSize() == 0) return HTTP_SUCCESS; if (m_nCurrentError > m_pErrors->GetSize() || m_nCurrentError < 0) m_nCurrentError = 0; CWriteStreamHelper c(m_pStream); if (!c.Write(static_cast<LPCSTR>((*m_pErrors)[m_nCurrentError].m_szError))) return HTTP_FAIL; return HTTP_SUCCESS; } HTTP_CODE OnGetErrorLine() throw(...) { ATLASSUME(m_pStream != NULL); if (m_pErrors->GetSize() == 0) return HTTP_SUCCESS; if (m_nCurrentError > m_pErrors->GetSize() || m_nCurrentError < 0) m_nCurrentError = 0; m_pStream->WriteStream((*m_pErrors)[m_nCurrentError].m_szStartLine, (int)((*m_pErrors)[m_nCurrentError].m_szEndLine - (*m_pErrors)[m_nCurrentError].m_szStartLine), NULL); return HTTP_SUCCESS; } BEGIN_REPLACEMENT_METHOD_MAP(CParseErrorProvider) REPLACEMENT_METHOD_ENTRY("GetNextError", OnGetNextError) REPLACEMENT_METHOD_ENTRY("GetErrorText", OnGetErrorText) REPLACEMENT_METHOD_ENTRY("GetErrorLine", OnGetErrorLine) REPLACEMENT_METHOD_ENTRY("GetErrorLineNumber", OnGetErrorLineNumber) END_REPLACEMENT_METHOD_MAP() }; #else bool m_bErrorsOccurred; #endif class CSaveThreadLocale { LCID m_locale; public: CSaveThreadLocale() throw() { m_locale = GetThreadLocale(); } ~CSaveThreadLocale() throw() { SetThreadLocale(m_locale); } }; HTTP_CODE LoadFromResourceInternal(HINSTANCE hInstRes, HRSRC hRsrc) throw() { ATLASSERT( hRsrc != NULL ); HGLOBAL hgResource = NULL; hgResource = LoadResource(hInstRes, hRsrc); if (!hgResource) { return HTTP_FAIL; } DWORD dwSize = SizeofResource(hInstRes, hRsrc); if (dwSize != 0) { m_pBufferStart = (LPSTR)LockResource(hgResource); if (m_pBufferStart != NULL) { m_pBufferEnd = m_pBufferStart+dwSize; return HTTP_SUCCESS; } } // failed to load resource return HTTP_FAIL; } protected: ITagReplacer *m_pReplacer; IAtlMemMgr *m_pMemMgr; static CCRTHeap m_crtHeap; inline BOOL CheckTag(LPCSTR szTag, DWORD dwTagLen, LPCSTR szStart, DWORD dwLen) throw() { if (dwLen < dwTagLen) return FALSE; if (memcmp(szStart, szTag, dwTagLen)) return FALSE; if (isspace(static_cast<unsigned char>(szStart[dwTagLen])) || szStart[dwTagLen] == '}') return TRUE; return FALSE; } inline void FindTagArgs(LPCSTR& szstart, LPCSTR& szend, int nKeywordChars) throw() { // this function should only be called after finding a valid tag // the first two characters of szstart should be {{ ATLASSERT(szstart[0] == '{' && szstart[1] == '{'); if (*szstart == '{') szstart += 2; // move past {{ szstart = SkipSpace(szstart, m_nCodePage); // move past whitespace szstart += nKeywordChars; // move past keyword szstart = SkipSpace(szstart, m_nCodePage); // move past whitespace after keyword if (*szend == '}') szend -=2; // chop off }} szend = RSkipSpace(szstart, szend, m_nCodePage); // chop of trailing whitespace } DWORD CheckTopAndPop(DWORD *pBlockStack, DWORD *pdwTop, DWORD dwToken) throw() { if (*pdwTop == 0) return STENCIL_INVALIDINDEX; if (m_arrTokens[pBlockStack[*pdwTop]].type == dwToken) { *pdwTop = (*pdwTop) - 1; return pBlockStack[(*pdwTop)+1]; } return STENCIL_INVALIDINDEX; } DWORD PushToken(DWORD *pBlockStack, DWORD *pdwTop, DWORD dwIndex) throw() { if (*pdwTop < (ATL_MAX_BLOCK_STACK-1)) { *pdwTop = (*pdwTop) + 1; pBlockStack[*pdwTop] = dwIndex; } else { dwIndex = STENCIL_INVALIDINDEX; } return dwIndex; } public: enum PARSE_TOKEN_RESULT { INVALID_TOKEN, NORMAL_TOKEN, RESERVED_TOKEN }; CStencil(IAtlMemMgr *pMemMgr=NULL) throw() { m_pBufferStart = NULL; m_pBufferEnd = NULL; m_hCacheItem = NULL; m_ftLastModified.dwLowDateTime = 0; m_ftLastModified.dwHighDateTime = 0; m_ftLastChecked.dwLowDateTime = 0; m_ftLastChecked.dwHighDateTime = 0; m_arrTokens.SetCount(0, 128); m_nCodePage = CP_ACP; m_bUseLocaleACP = TRUE; m_szHandlerName[0] = '\0'; m_szDllPath[0] = '\0'; m_pMemMgr = pMemMgr; if (!pMemMgr) m_pMemMgr = &m_crtHeap; #ifdef ATL_DEBUG_STENCILS m_hResInst = NULL; #else m_bErrorsOccurred = false; #endif } virtual ~CStencil() throw() { Uninitialize(); } #ifdef ATL_DEBUG_STENCILS bool RenderErrors(IWriteStream *pStream) throw(...) { if (pStream == NULL) { return false; } CComObjectStackEx<CParseErrorProvider> Errors; Errors.Initialize(&m_Errors); CStencil ErrorStencil; if (m_hResInst != NULL) { CFixedStringT<CStringA, 256> strErrorStencil; _ATLTRY { if (strErrorStencil.LoadString(m_hResInst, IDS_STENCIL_ERROR_STENCIL) == FALSE) { return false; } } _ATLCATCHALL() { return false; } HTTP_CODE hcRet = ErrorStencil.LoadFromString(strErrorStencil, strErrorStencil.GetLength()); if (hcRet == HTTP_SUCCESS) { if (ErrorStencil.ParseReplacements(static_cast<ITagReplacer *>(&Errors)) != false) { ErrorStencil.FinishParseReplacements(); if (ErrorStencil.ParseSuccessful() != false) { hcRet = ErrorStencil.Render(static_cast<ITagReplacer *>(&Errors), pStream); if (HTTP_ERROR_CODE(hcRet) < 400) { return true; } } } } } return false; } void SetErrorResource(HINSTANCE hResInst) { m_hResInst = hResInst; } bool ParseSuccessful() { return (m_Errors.GetSize() == 0); } bool AddErrorInternal(LPCSTR szErrorText, LPCSTR szPosition) throw() { int nLineNum = 0; LPCSTR szStartLine = NULL; LPCSTR szPtr = m_pBufferStart; while (szPtr < szPosition) { if (*szPtr == '\n') { szStartLine = szPtr + 1; nLineNum++; } LPSTR szNext = CharNextExA(m_nCodePage, szPtr, 0); if (szNext == szPtr) { break; } szPtr = szNext; } LPCSTR szEndLine = szPtr; while (*szPtr) { if (*szPtr == '\n') break; szEndLine = szPtr; LPSTR szNext = CharNextExA(m_nCodePage, szPtr, 0); if (szNext == szPtr) { break; } szPtr = szNext; } ParseError p; SafeStringCopy(p.m_szError, szErrorText); p.m_szPosition = szPosition; p.m_nLineNumber = nLineNum; p.m_szStartLine = szStartLine; p.m_szEndLine = szEndLine; return (m_Errors.Add(p) == TRUE); } bool AddError(UINT uID, LPCSTR szPosition) throw() { if (m_hResInst != NULL) { _ATLTRY { CFixedStringT<CStringA, 256> strRes; if (strRes.LoadString(m_hResInst, uID) != FALSE) { return AddErrorInternal(strRes, szPosition); } } _ATLCATCHALL() { } } return AddErrorInternal("Could not load resource for error string", szPosition); } bool AddReplacementError(LPCSTR szReplacement, LPCSTR szPosition) throw() { if (m_hResInst != NULL) { _ATLTRY { CFixedStringT<CStringA, 256> strRes; if (strRes.LoadString(m_hResInst, IDS_STENCIL_UNRESOLVED_REPLACEMENT) != FALSE) { CFixedStringT<CStringA, 256> strErrorText; strErrorText.Format(strRes, szReplacement); return AddErrorInternal(strErrorText, szPosition); } else { return AddErrorInternal("Could not load resource for error string", szPosition); } } _ATLCATCHALL() { return false; } } return false; } #else bool ParseSuccessful() { return !m_bErrorsOccurred; } bool AddError(UINT /*uID*/, LPCSTR /*szPosition*/) throw() { m_bErrorsOccurred = true; return true; } bool AddReplacementError(LPCSTR /*szReplacement*/, LPCSTR /*szPosition*/) throw() { m_bErrorsOccurred = true; return true; } void SetErrorResource(HINSTANCE) throw() { } #endif // Call Uninitialize if you want to re-use an already initialized CStencil void Uninitialize() throw() { int nSize = (int) m_arrTokens.GetCount(); for (int nIndex = 0; nIndex < nSize; nIndex++) { if (m_arrTokens[nIndex].bDynamicAlloc) delete [] m_arrTokens[nIndex].pStart; if (m_arrTokens[nIndex].dwData != 0 && m_arrTokens[nIndex].type != STENCIL_LOCALE) m_pMemMgr->Free((void *) m_arrTokens[nIndex].dwData); } m_arrTokens.RemoveAll(); if ((m_ftLastModified.dwLowDateTime || m_ftLastModified.dwHighDateTime) && m_pBufferStart) { delete [] m_pBufferStart; } m_pBufferStart = NULL; m_pBufferEnd = NULL; } void GetLastModified(FILETIME *pftLastModified) { ATLENSURE(pftLastModified); *pftLastModified = m_ftLastModified; } void GetLastChecked(FILETIME *pftLastChecked) { ATLENSURE(pftLastChecked); *pftLastChecked = m_ftLastChecked; } void SetLastChecked(FILETIME *pftLastChecked) { ATLENSURE(pftLastChecked); m_ftLastChecked = *pftLastChecked; } HCACHEITEM GetCacheItem() { return m_hCacheItem; } void SetCacheItem(HCACHEITEM hCacheItem) { ATLASSUME(m_hCacheItem == NULL); m_hCacheItem = hCacheItem; } bool GetHandlerName(__out_ecount_z(nPathLen) LPSTR szDllPath, __in size_t nPathLen, __out_ecount_z(nHandlerNameLen) LPSTR szHandlerName, __in size_t nHandlerNameLen) throw() { if(strlen(m_szDllPath) >= nPathLen) { return false; } if(strlen(m_szHandlerName) >= nHandlerNameLen) { return false; } if(0 != strcpy_s(szDllPath, nPathLen, m_szDllPath)) { return false; } if(0 != strcpy_s(szHandlerName, nHandlerNameLen, m_szHandlerName)) { return false; } return true; } // Adds a token to the token array, handler name, method name // and handler function offset are optional ATL_NOINLINE DWORD AddToken( LPCSTR pStart, LPCSTR pEnd, DWORD dwType, LPCSTR szHandlerName = NULL, LPCSTR szMethodName = NULL, DWORD dwFnOffset = STENCIL_INVALIDOFFSET, DWORD dwObjOffset = STENCIL_INVALIDOFFSET, DWORD_PTR dwData = 0, DWORD dwMap = 0, BOOL bDynamicAlloc = 0) throw() { StencilToken t; memset(&t, 0x00, sizeof(t)); t.pStart = pStart; t.pEnd = pEnd; t.type = dwType; t.dwLoopIndex = STENCIL_INVALIDINDEX; t.dwFnOffset = dwFnOffset; t.dwObjOffset = dwObjOffset; t.dwData = dwData; t.dwMap = dwMap; t.bDynamicAlloc = bDynamicAlloc; // this should never assert unless the user has overriden something incorrectly if ((szHandlerName != NULL) && (*szHandlerName)) { ATLVERIFY( SafeStringCopy(t.szHandlerName, szHandlerName) ); } if ((szMethodName != NULL) && (*szMethodName)) { ATLVERIFY( SafeStringCopy(t.szMethodName, szMethodName) ); } _ATLTRY { return (DWORD) m_arrTokens.Add(t); } _ATLCATCHALL() { return STENCIL_INVALIDINDEX; } } HTTP_CODE LoadFromFile(LPCSTR szFileName) throw() { HRESULT hr = E_FAIL; ULONGLONG dwLen = 0; CAtlFile file; _ATLTRY { hr = file.Create(CA2CTEX<MAX_PATH>(szFileName), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING); if (FAILED(hr) || GetFileType(file) != FILE_TYPE_DISK) return AtlsHttpError(500, ISE_SUBERR_STENCIL_LOAD_FAIL); // couldn't load SRF! if (GetFileTime(file, NULL, NULL, &m_ftLastModified)) { if (SUCCEEDED(file.GetSize(dwLen))) { ATLASSERT(!m_pBufferStart); GetSystemTimeAsFileTime(&m_ftLastChecked); m_pBufferStart = NULL; CAutoVectorPtr<char> buffer; if (!buffer.Allocate((size_t) dwLen)) return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); // out of memory DWORD dwRead = 0; hr = file.Read(buffer, (DWORD) dwLen, dwRead); if (FAILED(hr)) return AtlsHttpError(500, ISE_SUBERR_READFILEFAIL); // ReadFile failed m_pBufferStart = buffer.Detach(); m_pBufferEnd = m_pBufferStart + dwRead; } } } _ATLCATCHALL() { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); } return HTTP_SUCCESS; } // loads a stencil from the specified resource. HTTP_CODE LoadFromResource(HINSTANCE hInstRes, LPCSTR szID, LPCSTR szType = NULL) throw() { if (szType == NULL) { szType = (LPCSTR) RT_HTML; } HRSRC hRsrc = FindResourceA(hInstRes, szID, szType); if (hRsrc != NULL) { return LoadFromResourceInternal(hInstRes, hRsrc); } return HTTP_FAIL; } HTTP_CODE LoadFromResourceEx(HINSTANCE hInstRes, LPCSTR szID, WORD wLanguage, LPCSTR szType = NULL) throw() { if (szType == NULL) { szType = (LPCSTR) RT_HTML; } HRSRC hRsrc = FindResourceExA(hInstRes, szType, szID, wLanguage); if (hRsrc != NULL) { return LoadFromResourceInternal(hInstRes, hRsrc); } return HTTP_FAIL; } // loads a stencil from the specified resource HTTP_CODE LoadFromResource(HINSTANCE hInstRes, UINT nId, LPCSTR szType = NULL) throw() { return LoadFromResource(hInstRes, MAKEINTRESOURCEA(nId), szType); } HTTP_CODE LoadFromResourceEx(HINSTANCE hInstRes, UINT nId, WORD wLanguage, LPCSTR szType = NULL) throw() { return LoadFromResourceEx(hInstRes, MAKEINTRESOURCEA(nId), wLanguage, szType); } // loads a stencil from a string HTTP_CODE LoadFromString(LPCSTR szString, DWORD dwSize) throw() { m_pBufferStart = szString; m_pBufferEnd = m_pBufferStart+dwSize; return HTTP_SUCCESS; } // Cracks the loaded stencil into an array of StencilTokens in preparation for // rendering. LoadStencil must be called prior to calling this function. virtual bool ParseReplacements(ITagReplacer* pReplacer) throw(...) { return ParseReplacementsFromBuffer(pReplacer, GetBufferStart(), GetBufferEnd()); } virtual bool FinishParseReplacements() throw(...) { DWORD dwSize = (DWORD) m_arrTokens.GetCount(); for (DWORD dwIndex = 0; dwIndex < dwSize; dwIndex++) { StencilToken& token = m_arrTokens[dwIndex]; bool bUnclosedBlock = ((token.type == STENCIL_CONDITIONALSTART || token.type == STENCIL_CONDITIONALELSE || token.type == STENCIL_ITERATORSTART) && token.dwLoopIndex == STENCIL_INVALIDINDEX); if ((token.szMethodName[0] && token.dwFnOffset == STENCIL_INVALIDOFFSET) || bUnclosedBlock) { if (bUnclosedBlock || m_pReplacer->FindReplacementOffset( token.szMethodName, &token.dwFnOffset, token.szHandlerName, &token.dwObjOffset, &token.dwMap, (void **)(&token.dwData), m_pMemMgr) != HTTP_SUCCESS) { if (bUnclosedBlock && token.type == STENCIL_CONDITIONALSTART) { AddError(IDS_STENCIL_UNCLOSEDBLOCK_IF, token.pStart); } else if (bUnclosedBlock && token.type == STENCIL_CONDITIONALELSE) { AddError(IDS_STENCIL_UNCLOSEDBLOCK_ELSE, token.pStart); } else if (bUnclosedBlock && token.type == STENCIL_ITERATORSTART) { AddError(IDS_STENCIL_UNCLOSEDBLOCK_WHILE, token.pStart); } else { AddReplacementError(token.szMethodName, token.pStart); } // unresolved replacement, convert it to a text token token.type = STENCIL_TEXTTAG; // convert all linked tokens to text tokens as well // this includes: endif, else, endwhile DWORD dwLoopIndex = token.dwLoopIndex; while (dwLoopIndex != dwIndex && dwLoopIndex != STENCIL_INVALIDINDEX) { m_arrTokens[dwLoopIndex].type = STENCIL_TEXTTAG; dwLoopIndex = m_arrTokens[dwLoopIndex].dwLoopIndex; } } } } return ParseSuccessful(); } virtual bool Parse(ITagReplacer *pReplacer) throw( ... ) { if (ParseReplacements(pReplacer)) { return FinishParseReplacements(); } return false; } DWORD ParseReplacement( LPCSTR szTokenStart, LPCSTR szTokenEnd, DWORD dwTokenType = STENCIL_REPLACEMENT, DWORD dwKeywordLen = 0) throw() { // hold on to the start and end pointers (before removing curlies and whitespace) // this is needed so that we can convert the token to a text token if the method // is not resolved (in FinishParseReplacements) LPCSTR szStart = szTokenStart; LPCSTR szEnd = szTokenEnd; FindTagArgs(szTokenStart, szTokenEnd, dwKeywordLen); char szMethodName[ATL_MAX_METHOD_NAME_LEN+1]; char szHandlerName[ATL_MAX_HANDLER_NAME_LEN+1]; DWORD dwIndex; //look up the handler name, method name and handler interface if (HTTP_SUCCESS == GetHandlerAndMethodNames(szTokenStart, szTokenEnd, szMethodName, ATL_MAX_METHOD_NAME_LEN+1, szHandlerName, ATL_MAX_HANDLER_NAME_LEN+1)) dwIndex = AddToken(szStart, szEnd, dwTokenType, szHandlerName, szMethodName, STENCIL_INVALIDINDEX, STENCIL_INVALIDINDEX, 0, STENCIL_BASIC_MAP); else dwIndex = STENCIL_INVALIDINDEX; return dwIndex; } DWORD ParseWhile(LPCSTR szTokenStart, LPCSTR szTokenEnd, DWORD *pBlockStack, DWORD *pdwTop) throw() { DWORD dwIndex = ParseReplacement(szTokenStart, szTokenEnd, STENCIL_ITERATORSTART, sizeof("while")-1); if (dwIndex == STENCIL_INVALIDINDEX) return dwIndex; return PushToken(pBlockStack, pdwTop, dwIndex); } DWORD ParseEndWhile(LPCSTR szTokenStart, LPCSTR szTokenEnd, DWORD *pBlockStack, DWORD *pdwTop) throw() { DWORD dwTopIndex = CheckTopAndPop(pBlockStack, pdwTop, STENCIL_ITERATORSTART); if (dwTopIndex == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_UNOPENEDBLOCK_ENDWHILE, szTokenStart); return dwTopIndex; } DWORD dwIndex = AddToken(szTokenStart, szTokenEnd, STENCIL_ITERATOREND); if (dwIndex != STENCIL_INVALIDINDEX) { m_arrTokens[dwTopIndex].dwLoopIndex = dwIndex; m_arrTokens[dwIndex].dwLoopIndex = dwTopIndex; } return dwIndex; } DWORD ParseIf(LPCSTR szTokenStart, LPCSTR szTokenEnd, DWORD *pBlockStack, DWORD *pdwTop) throw() { DWORD dwIndex = ParseReplacement(szTokenStart, szTokenEnd, STENCIL_CONDITIONALSTART, sizeof("if")-1); if (dwIndex == STENCIL_INVALIDINDEX) return dwIndex; return PushToken(pBlockStack, pdwTop, dwIndex); } DWORD ParseElse(LPCSTR szTokenStart, LPCSTR szTokenEnd, DWORD *pBlockStack, DWORD *pdwTop) throw() { DWORD dwTopIndex = CheckTopAndPop(pBlockStack, pdwTop, STENCIL_CONDITIONALSTART); if (dwTopIndex == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_UNOPENEDBLOCK_ELSE, szTokenStart); return dwTopIndex; } DWORD dwIndex = AddToken(szTokenStart, szTokenEnd, STENCIL_CONDITIONALELSE); if (dwIndex != STENCIL_INVALIDINDEX) { m_arrTokens[dwTopIndex].dwLoopIndex = dwIndex; return PushToken(pBlockStack, pdwTop, dwIndex); } return dwIndex; } DWORD ParseEndIf(LPCSTR szTokenStart, LPCSTR szTokenEnd, DWORD *pBlockStack, DWORD *pdwTop) throw() { DWORD dwTopIndex = CheckTopAndPop(pBlockStack, pdwTop, STENCIL_CONDITIONALSTART); if (dwTopIndex == STENCIL_INVALIDINDEX) { dwTopIndex = CheckTopAndPop(pBlockStack, pdwTop, STENCIL_CONDITIONALELSE); if (dwTopIndex == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_UNOPENEDBLOCK_ENDIF, szTokenStart); return dwTopIndex; } } DWORD dwIndex = AddToken(szTokenStart, szTokenEnd, STENCIL_CONDITIONALEND); if (dwIndex != STENCIL_INVALIDINDEX) { m_arrTokens[dwTopIndex].dwLoopIndex = dwIndex; } return dwIndex; } DWORD ParseLocale(LPCSTR szTokenStart, LPCSTR szTokenEnd) throw() { LPCSTR szstart = szTokenStart; LPCSTR szend = szTokenEnd; LCID locale = 0xFFFFFFFF; FindTagArgs(szstart, szend, 6); #ifndef ATL_NO_MLANG if (isdigit(static_cast<unsigned char>(szstart[0]))) { locale = (LCID) atoi(szstart); } else { HRESULT hr; CComPtr<IMultiLanguage> pML; hr = pML.CoCreateInstance(__uuidof(CMultiLanguage), NULL, CLSCTX_INPROC_SERVER); if (FAILED(hr)) { ATLTRACE(atlTraceStencil, 0, _T("Couldn't create CMultiLanguage object. check MLANG installation.")); AddError(IDS_STENCIL_MLANG_COCREATE, szTokenStart); } else { CStringW str(szstart, (int)((szend-szstart)+1)); #ifdef __IMultiLanguage2_INTERFACE_DEFINED__ // use IMultiLanguage2 if possible CComPtr<IMultiLanguage2> spML2; hr = pML.QueryInterface(&spML2); if (FAILED(hr) || !spML2.p) hr = pML->GetLcidFromRfc1766(&locale, CComBSTR(str)); else hr = spML2->GetLcidFromRfc1766(&locale, CComBSTR(str)); #else // __IMultiLanguage2_INTERFACE_DEFINED__ hr = pML->GetLcidFromRfc1766(&locale, CComBSTR(str)); #endif // __IMultiLanguage2_INTERFACE_DEFINED__ if (FAILED(hr)) { AddError(IDS_STENCIL_MLANG_LCID, szTokenStart); } } if (FAILED(hr)) locale = 0xFFFFFFFF; } #else locale = (LCID) atoi(szstart); #endif if (m_bUseLocaleACP) { TCHAR szACP[7]; if (GetLocaleInfo(locale, LOCALE_IDEFAULTANSICODEPAGE, szACP, 7) != 0) { m_nCodePage = (WORD) _ttoi(szACP); } else { AddError(IDS_STENCIL_MLANG_GETLOCALE, szTokenStart); } } DWORD dwCurrentTokenIndex = STENCIL_INVALIDINDEX; if (locale != 0xFFFFFFFF) dwCurrentTokenIndex = AddToken(NULL, NULL, STENCIL_LOCALE, NULL, NULL, STENCIL_INVALIDOFFSET, STENCIL_INVALIDOFFSET, locale); else return STENCIL_INVALIDINDEX; return dwCurrentTokenIndex; } DWORD ParseCodepage(LPCSTR szTokenStart, LPCSTR szTokenEnd) throw() { LPCSTR szstart = szTokenStart; LPCSTR szend = szTokenEnd; WORD nCodePage = 0xFFFF; FindTagArgs(szstart, szend, 8); #ifndef ATL_NO_MLANG if (isdigit(static_cast<unsigned char>(szstart[0]))) { nCodePage = (WORD) atoi(szstart); } else { HRESULT hr; CComPtr<IMultiLanguage> pML; hr = pML.CoCreateInstance(__uuidof(CMultiLanguage), NULL, CLSCTX_INPROC_SERVER); if (FAILED(hr)) { ATLTRACE(atlTraceStencil, 0, _T("Couldn't create CMultiLanguage object. check MLANG installation.")); AddError(IDS_STENCIL_MLANG_COCREATE, szTokenStart); } else { CStringW str(szstart, (int)((szend-szstart)+1)); MIMECSETINFO info; #ifdef __IMultiLanguage2_INTERFACE_DEFINED__ // use IMultiLanguage2 if possible CComPtr<IMultiLanguage2> spML2; hr = pML.QueryInterface(&spML2); if (FAILED(hr) || !spML2.p) hr = pML->GetCharsetInfo(CComBSTR(str), &info); else hr = spML2->GetCharsetInfo(CComBSTR(str), &info); #else // __IMultiLanguage2_INTERFACE_DEFINED__ hr = pML->GetCharsetInfo(CComBSTR(str), &info); #endif // __IMultiLanguage2_INTERFACE_DEFINED__ // for most character sets, uiCodePage and uiInternetEncoding // are the same. UTF-8 is the exception that we're concerned about. // for that character set, we want uiInternetEncoding (65001 - UTF-8) // instead of uiCodePage (1200 - UCS-2) if (SUCCEEDED(hr)) { nCodePage = (WORD) info.uiInternetEncoding; } else { AddError(IDS_STENCIL_MLANG_GETCHARSET, szTokenStart); } } if (FAILED(hr)) nCodePage = 0xFFFF; } #else nCodePage = (WORD) atoi(szstart); #endif if (nCodePage != 0xFFFF) m_nCodePage = nCodePage; m_bUseLocaleACP = FALSE; return STENCIL_INVALIDINDEX; } PARSE_TOKEN_RESULT ParseHandler(LPCSTR szTokenStart, LPCSTR szTokenEnd) throw() { LPCSTR szstart = szTokenStart; LPCSTR szend = szTokenEnd; if (m_szHandlerName[0] && m_szDllPath[0]) return RESERVED_TOKEN; // already found the handler and path dll names FindTagArgs(szstart, szend, 7); size_t nlen = (szend-szstart)+1; char szHandlerDllName[MAX_PATH + ATL_MAX_HANDLER_NAME_LEN + 1]; if (nlen < MAX_PATH + ATL_MAX_HANDLER_NAME_LEN + 1) { Checked::memcpy_s(szHandlerDllName, MAX_PATH + ATL_MAX_HANDLER_NAME_LEN + 1, szstart, szend-szstart+1); szHandlerDllName[szend-szstart+1] = '\0'; DWORD dwDllPathLen = MAX_PATH; DWORD dwHandlerNameLen = ATL_MAX_HANDLER_NAME_LEN+1; if (!_AtlCrackHandler(szHandlerDllName, m_szDllPath, &dwDllPathLen, m_szHandlerName, &dwHandlerNameLen)) { AddError(IDS_STENCIL_INVALID_HANDLER, szTokenStart); return INVALID_TOKEN; } } return RESERVED_TOKEN; } virtual PARSE_TOKEN_RESULT ParseToken(LPCSTR szTokenStart, LPCSTR szTokenEnd, DWORD *pBlockStack, DWORD *pdwTop) { LPCSTR pStart = szTokenStart; pStart += 2; //skip curlies pStart = SkipSpace(pStart, m_nCodePage); DWORD dwLen = (DWORD)(szTokenEnd - szTokenStart); DWORD dwIndex = STENCIL_INVALIDINDEX; PARSE_TOKEN_RESULT ret = RESERVED_TOKEN; if (CheckTag("endwhile", 8, pStart, dwLen)) dwIndex = ParseEndWhile(szTokenStart, szTokenEnd, pBlockStack, pdwTop); else if (CheckTag("while", 5, pStart, dwLen)) dwIndex = ParseWhile(szTokenStart, szTokenEnd, pBlockStack, pdwTop); else if (CheckTag("endif", 5, pStart, dwLen)) dwIndex = ParseEndIf(szTokenStart, szTokenEnd, pBlockStack, pdwTop); else if (CheckTag("else", 4, pStart, dwLen)) dwIndex = ParseElse(szTokenStart, szTokenEnd, pBlockStack, pdwTop); else if (CheckTag("if", 2, pStart, dwLen)) dwIndex = ParseIf(szTokenStart, szTokenEnd, pBlockStack, pdwTop); else if (CheckTag("locale", 6, pStart, dwLen)) dwIndex = ParseLocale(szTokenStart, szTokenEnd); else if (CheckTag("handler", 7, pStart, dwLen)) { return ParseHandler(szTokenStart, szTokenEnd); } else if (CheckTag("codepage", 8, pStart, dwLen)) { ParseCodepage(szTokenStart, szTokenEnd); return RESERVED_TOKEN; } else { dwIndex = ParseReplacement(szTokenStart, szTokenEnd, STENCIL_REPLACEMENT); if (dwIndex == STENCIL_INVALIDINDEX) return INVALID_TOKEN; ret = NORMAL_TOKEN; } if (dwIndex == STENCIL_INVALIDINDEX) return INVALID_TOKEN; return ret; } virtual bool ParseReplacementsFromBuffer(ITagReplacer* pReplacer, LPCSTR pStart, LPCSTR pEnd) { LPCSTR szCurr = pStart; DWORD BlockStack[ATL_MAX_BLOCK_STACK]; DWORD dwTop = 0; m_pReplacer = pReplacer; DWORD dwCurrentTokenIndex = 0; if (!szCurr) { ATLASSERT(FALSE); AddError(IDS_STENCIL_NULLPARAM, NULL); return false; } LPCSTR szEnd = pEnd; if (szEnd <= szCurr) { ATLASSERT(FALSE); AddError(IDS_STENCIL_INVALIDSTRING, NULL); return true; } while(szCurr < szEnd) { //mark the start of this block, then find the end of the block //the end is denoted by an opening curly LPCSTR szStart = szCurr; while (szCurr < szEnd && (*szCurr != '{' || szCurr[1] != '{')) { LPSTR szNext = CharNextExA(m_nCodePage, szCurr, 0); if (szNext == szCurr) { // embedded null AddError(IDS_STENCIL_EMBEDDED_NULL, NULL); return true; } szCurr = szNext; } //special case for the last text block, if there is one if (szCurr >= szEnd) { // add the last token. This is everything after the last // double curly block, which is text. dwCurrentTokenIndex = AddToken(szStart, szEnd-1, STENCIL_TEXTTAG); break; } //if there are any characters between szStart and szCurr inclusive, //copy them to a text token. if (szCurr-1 >= szStart) dwCurrentTokenIndex = AddToken(szStart, szCurr-1, STENCIL_TEXTTAG); if (dwCurrentTokenIndex == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_OUTOFMEMORY, pStart); return false; } //find the end of the tag LPSTR szEndTag; szStart = szCurr; szCurr += 2; // Skip over the two '{' s while (szCurr < szEnd) { if (szCurr[0] == '}' && szCurr[1] == '}') break; else if (szCurr[0] == '{') break; LPSTR szNext = CharNextExA(m_nCodePage, szCurr, 0); if (szNext == szCurr) { // embedded null AddError(IDS_STENCIL_EMBEDDED_NULL, NULL); return true; } szCurr = szNext; } if (szCurr >= szEnd) { AddError(IDS_STENCIL_UNMATCHED_TAG_START, szStart); if (AddToken(szStart, szCurr-1, STENCIL_TEXTTAG) == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_OUTOFMEMORY, pStart); return false; } break; } if (szCurr[0] == '{') { if (szCurr[1] != '{') { szCurr--; } AddError(IDS_STENCIL_MISMATCHED_TAG_START, szStart); if (AddToken(szStart, szCurr-1, STENCIL_TEXTTAG) == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_OUTOFMEMORY, pStart); return false; } continue; } szEndTag = CharNextExA(m_nCodePage, szCurr, 0); if (szEndTag == szCurr) { // embedded null AddError(IDS_STENCIL_EMBEDDED_NULL, NULL); return true; } PARSE_TOKEN_RESULT ret = ParseToken(szStart, szEndTag, BlockStack, &dwTop); if (ret == INVALID_TOKEN) { dwCurrentTokenIndex = AddToken(szStart, szEndTag, STENCIL_TEXTTAG); if (dwCurrentTokenIndex == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_OUTOFMEMORY, pStart); return false; } szCurr = CharNextExA(m_nCodePage, szEndTag, 0); continue; } szCurr = CharNextExA(m_nCodePage, szEndTag, 0); if (szEndTag == szCurr) { // embedded null AddError(IDS_STENCIL_EMBEDDED_NULL, NULL); return true; } if (ret == RESERVED_TOKEN) { if (szCurr < szEnd && *szCurr == '\n') szCurr++; else if ((szCurr+1 < szEnd && *szCurr == '\r' && *(szCurr+1) == '\n')) szCurr += 2; } } return true; } HTTP_CODE GetHandlerAndMethodNames( __in LPCSTR pStart, __in LPCSTR pEnd, __out_ecount_z(nMethodNameLen) LPSTR pszMethodName, __in size_t nMethodNameLen, __out_ecount_z(nHandlerNameLen) LPSTR pszHandlerName, __in size_t nHandlerNameLen) throw() { ATLASSERT(pStart); ATLASSERT(pEnd); ATLASSERT(pEnd > pStart); if (!pszMethodName || !pszHandlerName || nMethodNameLen < 1 || nHandlerNameLen < 1) { ATLASSERT(FALSE); AddError(IDS_STENCIL_BAD_PARAMETER, pStart); return AtlsHttpError(500, ISE_SUBERR_UNEXPECTED); } *pszMethodName = '\0'; *pszHandlerName = '\0'; CHAR szMethodString[ATL_MAX_METHOD_NAME_LEN + ATL_MAX_HANDLER_NAME_LEN+1]; HTTP_CODE hcErr = HTTP_SUCCESS; // // copy the method string // size_t nMethodLen = (pEnd-pStart)+1; if (nMethodLen >= (ATL_MAX_METHOD_NAME_LEN + ATL_MAX_HANDLER_NAME_LEN+1)) { AddError(IDS_STENCIL_METHODNAME_TOO_LONG, pStart); return AtlsHttpError(500, ISE_SUBERR_LONGMETHODNAME); } Checked::memcpy_s(szMethodString, ATL_MAX_METHOD_NAME_LEN + ATL_MAX_HANDLER_NAME_LEN+1, pStart, nMethodLen); szMethodString[nMethodLen] = '\0'; // // now crack the method string and get the handler // id and function name // LPSTR szParen = strchr(szMethodString, '('); LPSTR szDot = strchr(szMethodString, '.'); if (szDot && (!szParen || (szDot < szParen))) { *szDot = '\0'; szDot++; // copy method name if (strlen(szDot) < nMethodNameLen) Checked::strcpy_s(pszMethodName, nMethodNameLen, szDot); else { AddError(IDS_STENCIL_METHODNAME_TOO_LONG, pStart + (szDot - szMethodString)); hcErr = AtlsHttpError(500, ISE_SUBERR_LONGMETHODNAME); } // copy handler name if (!hcErr) { if (strlen(szMethodString) < nHandlerNameLen) Checked::strcpy_s(pszHandlerName, nHandlerNameLen, szMethodString); else { AddError(IDS_STENCIL_HANDLERNAME_TOO_LONG, pStart); hcErr = AtlsHttpError(500, ISE_SUBERR_LONGHANDLERNAME); } } } else { // only a method name so just copy it. if (strlen(szMethodString) < nMethodNameLen) Checked::strcpy_s(pszMethodName, nMethodNameLen, szMethodString); else { AddError(IDS_STENCIL_METHODNAME_TOO_LONG, pStart); hcErr = AtlsHttpError(500, ISE_SUBERR_LONGMETHODNAME); } } return hcErr; } virtual HTTP_CODE Render( ITagReplacer *pReplacer, IWriteStream *pWriteStream, CStencilState* pState = NULL) const throw(...) { ATLENSURE(pReplacer != NULL); ATLENSURE(pWriteStream != NULL); HTTP_CODE hcErrorCode = HTTP_SUCCESS; DWORD dwIndex = 0; DWORD dwArraySize = GetTokenCount(); // set up locale info CSaveThreadLocale lcidSave; if (pState) { dwIndex = pState->dwIndex; // restore the locale if we're restarting rendering if (pState->locale != CP_ACP) SetThreadLocale(pState->locale); } pReplacer->SetStream(pWriteStream); while (dwIndex < dwArraySize) { // RenderToken advances dwIndex appropriately for us. dwIndex = RenderToken(dwIndex, pReplacer, pWriteStream, &hcErrorCode, pState); if (dwIndex == STENCIL_INVALIDINDEX || hcErrorCode != HTTP_SUCCESS) break; } if (IsAsyncStatus(hcErrorCode)) { ATLASSERT( pState != NULL ); // state is required for async if (pState) pState->dwIndex = dwIndex; } // lcidSave destructor will restore the locale info in case it was changed return hcErrorCode; } inline BOOL IsValidIndex(DWORD dwIndex) const throw() { if (dwIndex == STENCIL_INVALIDINDEX) return FALSE; if (dwIndex < GetTokenCount()) return TRUE; else return FALSE; } virtual DWORD RenderToken( DWORD dwIndex, ITagReplacer *pReplacer, IWriteStream *pWriteStream, HTTP_CODE *phcErrorCode, CStencilState* pState = NULL) const throw(...) { ATLENSURE(pReplacer != NULL); ATLENSURE(pWriteStream != NULL); const StencilToken* pToken = GetToken(dwIndex); DWORD dwNextToken = 0; HTTP_CODE hcErrorCode = HTTP_SUCCESS; if (!pToken) return STENCIL_INVALIDINDEX; switch (pToken->type) { case STENCIL_TEXTTAG: { pWriteStream->WriteStream(pToken->pStart, (int)((pToken->pEnd-pToken->pStart)+1), NULL); dwNextToken = dwIndex+1; } break; case STENCIL_ITERATORSTART: { HTTP_CODE hcErr = STENCIL_SUCCESS; #ifdef ATL_DEBUG_STENCILS // A 'while' token has to at least be followed by an endwhile! if (!IsValidIndex(dwIndex+1)) { // This should have been caught at parse time dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = AtlsHttpError(500, ISE_SUBERR_STENCIL_INVALIDINDEX); ATLASSERT(FALSE); break; } // End of loop should be valid if (!IsValidIndex(pToken->dwLoopIndex)) { // This should have been caught at parse time dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = AtlsHttpError(500, ISE_SUBERR_STENCIL_MISMATCHWHILE); ATLASSERT(FALSE); break; } if (pToken->dwFnOffset == STENCIL_INVALIDOFFSET) { // This should have been caught at parse time dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = AtlsHttpError(500, ISE_SUBERR_STENCIL_INVALIDFUNCOFFSET); ATLASSERT(FALSE); break; } #endif // ATL_DEBUG_STENCILS DWORD dwLoopIndex = pToken->dwLoopIndex; // points to the end of the loop // Call the replacement method // if it returns HTTP_SUCCESS, enter the loop // if it returns HTTP_S_FALSE, terminate the loop hcErr = pReplacer->RenderReplacement(pToken->dwFnOffset, pToken->dwObjOffset, pToken->dwMap, (void *) pToken->dwData); if (hcErr == HTTP_SUCCESS) { dwNextToken = dwIndex+1; hcErrorCode = HTTP_SUCCESS; } else if (hcErr == HTTP_S_FALSE) { dwNextToken = dwLoopIndex+1; hcErrorCode = HTTP_SUCCESS; } else { dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = hcErr; break; } } break; case STENCIL_REPLACEMENT: { #ifdef ATL_DEBUG_STENCILS if (pToken->dwFnOffset == STENCIL_INVALIDOFFSET) { // This should have been caught at parse time ATLASSERT(FALSE); dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = AtlsHttpError(500, ISE_SUBERR_STENCIL_INVALIDFUNCOFFSET); break; } #endif // ATL_DEBUG_STENCILS hcErrorCode = pReplacer->RenderReplacement(pToken->dwFnOffset, pToken->dwObjOffset, pToken->dwMap, (void *)pToken->dwData); if (IsAsyncContinueStatus(hcErrorCode)) dwNextToken = dwIndex; // call the tag again after we get back else { dwNextToken = dwIndex + 1; // when returned from a handler, these indicate that the handler is done // and that we should move on to the next handler when called back if (hcErrorCode == HTTP_SUCCESS_ASYNC_DONE) hcErrorCode = HTTP_SUCCESS_ASYNC; else if (hcErrorCode == HTTP_SUCCESS_ASYNC_NOFLUSH_DONE) hcErrorCode = HTTP_SUCCESS_ASYNC_NOFLUSH; } } break; case STENCIL_ITERATOREND: { dwNextToken = pToken->dwLoopIndex; hcErrorCode = HTTP_SUCCESS; ATLASSERT(GetToken(dwNextToken)->type == STENCIL_ITERATORSTART); } break; case STENCIL_CONDITIONALSTART: { #ifdef ATL_DEBUG_STENCILS if (pToken->type == STENCIL_CONDITIONALSTART && pToken->dwFnOffset == STENCIL_INVALIDOFFSET) { // This should have been caught at parse time ATLASSERT(FALSE); dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = AtlsHttpError(500, ISE_SUBERR_STENCIL_INVALIDFUNCOFFSET); break; } if (pToken->dwLoopIndex == STENCIL_INVALIDINDEX) { // This should have been caught at parse time ATLASSERT(FALSE); dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = AtlsHttpError(500, ISE_SUBERR_STENCIL_MISMATCHIF); break; } #endif // ATL_DEBUG_STENCILS DWORD dwLoopIndex = pToken->dwLoopIndex; // points to the end of the loop HTTP_CODE hcErr; // Call the replacement method. // If it returns HTTP_SUCCESS, we render everything up to // the end of the conditional. // if it returns HTTP_S_FALSE, the condition is not met and we // render the else part if it exists or jump past the endif otherwise hcErr = pReplacer->RenderReplacement(pToken->dwFnOffset, pToken->dwObjOffset, pToken->dwMap, (void *)pToken->dwData); if (hcErr == HTTP_SUCCESS) { dwNextToken = dwIndex+1; hcErrorCode = HTTP_SUCCESS; } else if (hcErr == HTTP_S_FALSE) { dwNextToken = dwLoopIndex+1; hcErrorCode = HTTP_SUCCESS; } else { dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = hcErr; break; } } break; case STENCIL_CONDITIONALELSE: { #ifdef ATL_DEBUG_STENCILS if (pToken->dwLoopIndex == STENCIL_INVALIDINDEX) { // This should have been caught at parse time ATLASSERT(FALSE); dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = AtlsHttpError(500, ISE_SUBERR_STENCIL_MISMATCHIF); break; } #endif // ATL_DEBUG_STENCILS dwNextToken = pToken->dwLoopIndex+1; hcErrorCode = HTTP_SUCCESS; } break; case STENCIL_CONDITIONALEND: { dwNextToken = dwIndex+1; hcErrorCode = HTTP_SUCCESS; } break; case STENCIL_LOCALE: { if (pState) { pState->locale = (LCID) pToken->dwData; } SetThreadLocale((LCID) pToken->dwData); dwNextToken = dwIndex + 1; } break; default: { ATLASSERT(FALSE); dwNextToken = STENCIL_INVALIDINDEX; hcErrorCode = AtlsHttpError(500, ISE_SUBERR_STENCIL_UNEXPECTEDTYPE); break; } } ATLASSERT(dwNextToken != dwIndex || IsAsyncContinueStatus(hcErrorCode)); if (phcErrorCode) *phcErrorCode = hcErrorCode; return dwNextToken; } DWORD GetTokenCount() const throw() { return (DWORD) m_arrTokens.GetCount(); } const StencilToken* GetToken(DWORD dwIndex) const throw() { return &(m_arrTokens[dwIndex]); } StencilToken* GetToken(DWORD dwIndex) throw() { return &(m_arrTokens[dwIndex]); } LPCSTR GetBufferStart() const throw() { return m_pBufferStart; } LPCSTR GetBufferEnd() const throw() { return m_pBufferEnd; } WORD GetCodePage() const throw() { return m_nCodePage; } // IMemoryCacheClient STDMETHOD(QueryInterface)(REFIID riid, void **ppv) { if (!ppv) return E_POINTER; if (InlineIsEqualGUID(riid, __uuidof(IUnknown)) || InlineIsEqualGUID(riid, __uuidof(IMemoryCacheClient))) { *ppv = static_cast<IMemoryCacheClient*>(this); return S_OK; } *ppv = NULL; return E_NOINTERFACE; } STDMETHOD_(ULONG, AddRef)() { return 1; } STDMETHOD_(ULONG, Release)() { return 1; } STDMETHOD(Free)(const void *pData) { if (!pData) return E_POINTER; ATLASSERT(*((void **) pData) == static_cast<void*>(this)); delete this; return S_OK; } }; // class CStencil struct StencilIncludeInfo { public: CHAR m_szQueryString[ATL_URL_MAX_URL_LENGTH+1]; CHAR m_szFileName[MAX_PATH]; }; class CIncludeServerContext : public CComObjectRootEx<CComMultiThreadModel>, public CWrappedServerContext { public: BEGIN_COM_MAP(CIncludeServerContext) COM_INTERFACE_ENTRY(IHttpServerContext) END_COM_MAP() IWriteStream * m_pStream; const StencilIncludeInfo * m_pIncludeInfo; CIncludeServerContext() throw() { m_pStream = NULL; m_pIncludeInfo = NULL; } void Initialize( IWriteStream *pStream, IHttpServerContext* pServerContext, const StencilIncludeInfo * pIncludeInfo) throw() { ATLASSERT(pStream != NULL); ATLASSERT(pServerContext != NULL); ATLASSERT(pIncludeInfo != NULL); m_pStream = pStream; m_spParent = pServerContext; m_pIncludeInfo = pIncludeInfo; } void Initialize(CIncludeServerContext *pOtherContext) { ATLENSURE(pOtherContext != NULL); m_pStream = pOtherContext->m_pStream; m_spParent = pOtherContext->m_spParent; m_pIncludeInfo = pOtherContext->m_pIncludeInfo; } LPCSTR GetRequestMethod() { return "GET"; } LPCSTR GetQueryString() { ATLASSUME(m_pIncludeInfo != NULL); return m_pIncludeInfo->m_szQueryString; } LPCSTR GetPathTranslated() { ATLASSUME(m_pIncludeInfo != NULL); return m_pIncludeInfo->m_szFileName; } LPCSTR GetScriptPathTranslated() { ATLASSUME(m_pIncludeInfo != NULL); return m_pIncludeInfo->m_szFileName; } DWORD GetTotalBytes() { return 0; } DWORD GetAvailableBytes() { return 0; } BYTE *GetAvailableData() { return NULL; } LPCSTR GetContentType() { return 0; } BOOL WriteClient(void *pvBuffer, DWORD *pdwBytes) { ATLASSUME(m_pStream != NULL); ATLENSURE(pvBuffer != NULL); ATLENSURE(pdwBytes != NULL); HRESULT hr = S_OK; _ATLTRY { hr = m_pStream->WriteStream((LPCSTR) pvBuffer, *pdwBytes, pdwBytes); } _ATLCATCHALL() { hr = E_FAIL; } return SUCCEEDED(hr); } BOOL ReadClient(void * /*pvBuffer*/, DWORD * /*pdwSize*/) { return FALSE; } BOOL AsyncReadClient(void * /*pvBuffer*/, DWORD * /*pdwSize*/) { return FALSE; } BOOL SendRedirectResponse(LPCSTR /*pszRedirectURL*/) { return FALSE; } BOOL SendResponseHeader( LPCSTR /*pszHeader*/, LPCSTR /*pszStatusCode*/, BOOL /*fKeepConn*/) { return TRUE; } BOOL DoneWithSession(DWORD /*dwHttpStatusCode*/) { return TRUE; } BOOL RequestIOCompletion(PFN_HSE_IO_COMPLETION /*pfn*/, DWORD * /*pdwContext*/) { return FALSE; } }; // class CIncludeServerContext class CIDServerContext : public CComObjectRootEx<CComMultiThreadModel>, public CWrappedServerContext { public: CHttpResponse *m_pResponse; CHttpRequest *m_pRequest; BEGIN_COM_MAP(CIDServerContext) COM_INTERFACE_ENTRY(IHttpServerContext) END_COM_MAP() CIDServerContext() throw() : m_pResponse(NULL), m_pRequest(NULL) { } BOOL Initialize( CHttpResponse *pResponse, CHttpRequest *pRequest) throw() { ATLASSERT(pResponse != NULL); ATLASSERT(pRequest != NULL); m_pResponse = pResponse; m_pRequest = pRequest; if(!m_pRequest) { return FALSE; } HRESULT hr = m_pRequest->GetServerContext(&m_spParent); return (SUCCEEDED(hr)); } LPCSTR GetRequestMethod() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetMethodString(); } LPCSTR GetQueryString() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetQueryString(); } LPCSTR GetPathInfo() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetPathInfo(); } LPCSTR GetPathTranslated() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetPathTranslated(); } DWORD GetTotalBytes() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetTotalBytes(); } DWORD GetAvailableBytes() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetAvailableBytes(); } BYTE *GetAvailableData() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetAvailableData(); } LPCSTR GetContentType() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetContentType(); } LPCSTR GetScriptPathTranslated() { ATLASSUME(m_pRequest != NULL); return m_pRequest->GetScriptPathTranslated(); } BOOL WriteClient(void *pvBuffer, DWORD *pdwBytes) { ATLASSUME(m_pResponse != NULL); return m_pResponse->WriteLen((LPCSTR)pvBuffer, *pdwBytes); } BOOL ReadClient(void *pvBuffer, DWORD *pdwSize) { ATLASSUME(m_pRequest != NULL); return m_pRequest->ReadData((LPSTR)pvBuffer, pdwSize); } BOOL SendRedirectResponse(LPCSTR pszRedirectURL) { ATLASSUME(m_pResponse != NULL); return m_pResponse->Redirect(pszRedirectURL); } BOOL TransmitFile( HANDLE hFile, PFN_HSE_IO_COMPLETION pfn, void *pContext, LPCSTR szStatusCode, DWORD dwBytesToWrite, DWORD dwOffset, void *pvHead, DWORD dwHeadLen, void *pvTail, DWORD dwTailLen, DWORD dwFlags) { ATLASSUME(m_pResponse != NULL); ATLASSUME(m_spParent != NULL); m_pResponse->Flush(); return m_spParent->TransmitFile(hFile, pfn, pContext, szStatusCode, dwBytesToWrite, dwOffset, pvHead, dwHeadLen, pvTail, dwTailLen, dwFlags); } }; // class CIDServerContext // // CHtmlStencil // CHtmlStencil is a specialization of CStencil. CHtmlStencil adds the following // capabilities to CStencil: // // Support for rendering {{include }} tags // The {{include }} tags specify another stencil to be included in-place during // stencil rendering. The {{include }} tag takes a single parameter which is the // URL of the stencil to include. That URL can optionally include parameters. // An example: // {{include mystencil.srf?param1=value1}} // // We also grab the handler name and the name of any subhandlers. The syntax for the // handler specification is: // {{handler MyDynamicHandler.dll/Default}} // which would cause the MyDynamicHandler.dll to be loaded. Once loaded, the stencil // processor will ask for the IReplacementHandler interface of the object named "Default". // // Additional handlers can be specified after the default handler. An example of an // additional handler would be: // {{subhandler OtherHandler MyOtherHandler.dll/Default}} // would cause the MyOtherHandler.dll to be loaded. Once loaded, the stencil processor will // ask for the IReplacementHandler interface of the object named "Default" and use it in // processing the stencil anywhere it sees a stencil tag of the form // {{OtherHandler.RenderReplacement}} struct CStringPair { typedef CFixedStringT<CStringA, MAX_PATH> PathStrType; typedef CFixedStringT<CStringA, ATL_MAX_HANDLER_NAME_LEN+1> HdlrNameStrType; PathStrType strDllPath; HdlrNameStrType strHandlerName; CStringPair()throw() { } CStringPair(PathStrType &strDllPath_, HdlrNameStrType &strHandlerName_) throw(...) :strDllPath(strDllPath_), strHandlerName(strHandlerName_) { } CStringPair(CStringA &strDllPath_, CStringA &strHandlerName_) throw(...) :strDllPath(strDllPath_), strHandlerName(strHandlerName_) { } }; class CStringPairElementTraits : public CElementTraitsBase< CStringPair > { private: static ULONG HashStr( ULONG nHash, CStringElementTraits<CStringA>::INARGTYPE str ) { ATLENSURE( str != NULL ); const CStringA::XCHAR* pch = str; while( *pch != 0 ) { nHash = (nHash<<5)+nHash+(*pch); pch++; } return( nHash ); } public: static ULONG Hash( INARGTYPE pair ) throw() { ULONG nHash = HashStr(0, pair.strDllPath); return HashStr(nHash, pair.strHandlerName); } static bool CompareElements( INARGTYPE pair1, INARGTYPE pair2 ) throw() { return( (pair1.strDllPath == pair2.strDllPath) && (pair1.strHandlerName == pair2.strHandlerName) ); } static int CompareElementsOrdered( INARGTYPE pair1, INARGTYPE pair2 ) throw() { return( pair1.strDllPath.Compare( pair2.strDllPath ) ); } }; class CHtmlStencil : public CStencil { private: ATL_NOINLINE HTTP_CODE RenderInclude( ITagReplacer *pReplacer, const StencilToken *pToken, IWriteStream *pWriteStream, CStencilState *pState) const { ATLASSUME(m_spServiceProvider); CComPtr<IHttpServerContext> spServerContext; CComPtr<IHttpRequestLookup> spLookup; if (FAILED(pReplacer->GetContext(__uuidof(IHttpServerContext), (VOID**) &spServerContext))) { return AtlsHttpError(500, 0); } if (FAILED(pReplacer->GetContext(__uuidof(IHttpRequestLookup), (VOID**) &spLookup))) { return AtlsHttpError(500, 0); } return RenderInclude(m_spServiceProvider, pWriteStream, (StencilIncludeInfo *)pToken->dwData, spServerContext, spLookup, pState); } ATL_NOINLINE HTTP_CODE NoCachePage(ITagReplacer *pReplacer) const { CComPtr<IHttpServerContext> spContext; HRESULT hr = pReplacer->GetContext(__uuidof(IHttpServerContext), (void **)&spContext); if (hr == S_OK && spContext) { CComQIPtr<IPageCacheControl> spControl; spControl = spContext; if (spControl) spControl->Cache(FALSE); } return HTTP_SUCCESS; } // CAllocIncludeAsyncContext is an unsupported implementation detail of RenderInclude class CAllocIncludeAsyncContext : public CAllocContextBase { public: CAllocIncludeAsyncContext(CIncludeServerContext *pBase) : m_pBase(pBase) { } HTTP_CODE Alloc(IHttpServerContext **ppNewContext) { ATLASSUME(m_pBase); if (!ppNewContext) return AtlsHttpError(500, ISE_SUBERR_UNEXPECTED); *ppNewContext = NULL; CComObjectNoLock<CIncludeServerContext>* pNewServerContext = NULL; ATLTRY(pNewServerContext = new CComObjectNoLock<CIncludeServerContext>); if (pNewServerContext == NULL) return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); pNewServerContext->Initialize(m_pBase); pNewServerContext->AddRef(); *ppNewContext = pNewServerContext; return HTTP_SUCCESS; } private: CIncludeServerContext *m_pBase; }; // CAllocIncludeAsyncContext ATL_NOINLINE HTTP_CODE RenderInclude( IServiceProvider *pServiceProvider, IWriteStream *pWriteStream, const StencilIncludeInfo *pIncludeInfo, IHttpServerContext *pServerContext, IHttpRequestLookup *pLookup, CStencilState* pState = NULL) const throw(...) { CComObjectStackEx<CIncludeServerContext> serverContext; serverContext.Initialize(pWriteStream, pServerContext, pIncludeInfo); CAllocIncludeAsyncContext AsyncAllocObj(&serverContext); return _AtlRenderInclude(static_cast<IHttpServerContext*>(&serverContext), pIncludeInfo->m_szFileName, pIncludeInfo->m_szQueryString, GetCodePage(), &AsyncAllocObj, pServiceProvider, pLookup, pState); } protected: CAtlMap<CStringA, CStringPair, CStringElementTraits<CStringA>, CStringPairElementTraits > m_arrExtraHandlers; CHAR m_szBaseDir[MAX_PATH]; CComPtr<IServiceProvider> m_spServiceProvider; CComPtr<IIsapiExtension> m_spExtension; CComPtr<IStencilCache> m_spStencilCache; CComPtr<IDllCache> m_spDllCache; public: typedef CAtlMap<CStringA, CStringPair, CStringElementTraits<CStringA>, CStringPairElementTraits > mapType; typedef CStencil baseType; CHtmlStencil(IAtlMemMgr *pMemMgr=NULL) throw() : CStencil(pMemMgr) { } void Initialize(IServiceProvider *pProvider) throw(...) { ATLENSURE(pProvider); if (m_spServiceProvider) m_spServiceProvider.Release(); m_spServiceProvider = pProvider; if (!m_spDllCache) pProvider->QueryService(__uuidof(IDllCache), __uuidof(IDllCache), (void **) &m_spDllCache); if (!m_spExtension) pProvider->QueryInterface(__uuidof(IIsapiExtension), (void **) &m_spExtension); } BOOL GetIncludeInfo(LPCSTR szParamBegin, LPCSTR szParamEnd, StencilIncludeInfo *pInfo) const { ATLENSURE(szParamBegin != NULL); ATLENSURE(szParamEnd != NULL); ATLENSURE(pInfo != NULL); LPCSTR szQueryBegin = szParamBegin; while (*szQueryBegin && *szQueryBegin != '?' && *szQueryBegin != '}') { LPSTR szNext = CharNextExA(GetCodePage(), szQueryBegin, 0); if (szNext == szQueryBegin) { return FALSE; } szQueryBegin = szNext; } CFixedStringT<CStringA, MAX_PATH> strPath; _ATLTRY { DWORD dwPrefixLen = 0; if (*szParamBegin == '"') { szParamBegin++; } if (!IsFullPathA(szParamBegin)) { if (*szParamBegin != '\\') { strPath = m_szBaseDir; } else { LPCSTR szBackslash = strchr(m_szBaseDir, '\\'); if (szBackslash) { #pragma warning(push) #pragma warning(disable: 6204) /* prefast noise VSW 492749 */ strPath.SetString(m_szBaseDir, (int)(szBackslash-m_szBaseDir)); #pragma warning(pop) } else { strPath = m_szBaseDir; } } dwPrefixLen = strPath.GetLength(); } if (*szQueryBegin=='?') { size_t nMinus = (*(szQueryBegin-1) == '"') ? 1 : 0; strPath.Append(szParamBegin, (int)(szQueryBegin-szParamBegin-nMinus)); if ((szParamEnd-szQueryBegin) > ATL_URL_MAX_PATH_LENGTH || ((szParamEnd - szQueryBegin) < 0)) { // query string is too long return FALSE; } Checked::memcpy_s(pInfo->m_szQueryString, ATL_URL_MAX_URL_LENGTH+1, szQueryBegin + 1, szParamEnd - szQueryBegin); pInfo->m_szQueryString[szParamEnd - szQueryBegin] = '\0'; } else { pInfo->m_szQueryString[0] = '\0'; size_t nAdd = (*szParamEnd == '"') ? 0 : 1; strPath.Append(szParamBegin, (int)(szParamEnd - szParamBegin + nAdd)); } } _ATLCATCHALL() { // out of memory return FALSE; } if (strPath.GetLength() > MAX_PATH-1) { // path is too long return FALSE; } // strPath is <= MAX_PATH-1 return PathCanonicalizeA(pInfo->m_szFileName, strPath); } DWORD ParseInclude(LPCSTR szTokenStart, LPCSTR szTokenEnd) throw(...) { ATLENSURE(szTokenStart != NULL); ATLENSURE(szTokenEnd != NULL); LPCSTR szStart = szTokenStart; LPCSTR szEnd = szTokenEnd; FindTagArgs(szStart, szEnd, 7); CFixedStringT<CStringA, MAX_PATH> strFileNameRelative; CFixedStringT<CString, MAX_PATH> strFileName; _ATLTRY { strFileNameRelative.SetString(szStart, (int)(szEnd-szStart + 1)); if (!IsFullPathA(strFileNameRelative)) { CFixedStringT<CStringA, MAX_PATH> strTemp; if (*((LPCSTR)strFileNameRelative) != '\\') { strTemp = m_szBaseDir; } else { LPCSTR szBackslash = strchr(m_szBaseDir, '\\'); if (szBackslash) { #pragma warning(push) #pragma warning(disable: 6204) #pragma warning(disable: 6535) /* prefast noise VSW 492749 */ /* prefast noise VSW 493256 */ strTemp.SetString(m_szBaseDir, (int)(szBackslash-m_szBaseDir)); #pragma warning(pop) } else { strTemp = m_szBaseDir; } } strTemp.Append(strFileNameRelative, strFileNameRelative.GetLength()); CFixedStringT<CString, MAX_PATH> strConv = (LPCTSTR) CA2CT(strTemp); LPTSTR szFileBuf = strFileName.GetBuffer(strConv.GetLength()+1); if (szFileBuf == NULL) { AddError(IDS_STENCIL_OUTOFMEMORY, szTokenStart); return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } if (!PathCanonicalize(szFileBuf, strConv)) { return STENCIL_INVALIDINDEX; } strFileName.ReleaseBuffer(); } else { strFileName = CA2CTEX<MAX_PATH>(strFileNameRelative); } } _ATLCATCHALL() { AddError(IDS_STENCIL_OUTOFMEMORY, szTokenStart); return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } LPCTSTR szFileName = strFileName; LPCTSTR szDot = NULL; LPCTSTR szExtra = _tcschr(szFileName, '?'); if (!szExtra) { szExtra = _tcschr(szFileName, '#'); if (!szExtra) { szDot = _tcsrchr(szFileName, '.'); } } if (szExtra != NULL) { // there is some extra information LPCTSTR szDotTmp = szFileName; do { szDot = szDotTmp; szDotTmp = _tcschr(szDotTmp+1, '.'); } while (szDotTmp && szDotTmp < szExtra); } if (!szDot || *szDot != '.') { AddError(IDS_STENCIL_UNEXPECTED, szTokenStart); return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } LPCTSTR szExtEnd = szDot; while (true) { szExtEnd++; if (!*szExtEnd || *szExtEnd == '/' || *szExtEnd == '\\' || *szExtEnd == '?' || *szExtEnd == '#' || *szExtEnd == '"') break; } if (szDot && (size_t)(szExtEnd-szDot) == _tcslen(c_tAtlDLLExtension) && !_tcsnicmp(szDot, c_tAtlDLLExtension, _tcslen(c_tAtlDLLExtension))) { // Do .dll stuff DWORD dwIndex = AddToken(szStart, szEnd, STENCIL_STENCILINCLUDE); if (dwIndex == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_OUTOFMEMORY, szTokenStart); return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } StencilIncludeInfo *pInfo = (StencilIncludeInfo *)m_pMemMgr->Allocate(sizeof(StencilIncludeInfo)); if (!pInfo) { return STENCIL_INVALIDINDEX; } if (!GetIncludeInfo(szStart, szEnd, pInfo)) { return STENCIL_INVALIDINDEX; } GetToken(dwIndex)->dwData = (DWORD_PTR) pInfo; return dwIndex; } else if (szDot && (size_t)(szExtEnd-szDot) == _tcslen(c_tAtlSRFExtension) && !_tcsnicmp(szDot, c_tAtlSRFExtension, _tcslen(c_tAtlSRFExtension))) { // Do .srf stuff DWORD dwIndex = AddToken(szStart, szEnd, STENCIL_STENCILINCLUDE); if (dwIndex == STENCIL_INVALIDINDEX) { AddError(IDS_STENCIL_OUTOFMEMORY, szTokenStart); return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } StencilIncludeInfo *pInfo = (StencilIncludeInfo *)m_pMemMgr->Allocate(sizeof(StencilIncludeInfo)); if (!pInfo) { return STENCIL_INVALIDINDEX; } if (!GetIncludeInfo(szStart, szEnd, pInfo)) { return STENCIL_INVALIDINDEX; } GetToken(dwIndex)->dwData = (DWORD_PTR) pInfo; return dwIndex; } else { // Assume static content CAtlFile file; HRESULT hr = file.Create(szFileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING); if (FAILED(hr) || GetFileType(file) != FILE_TYPE_DISK) { if (FAILED(hr)) { AddError(IDS_STENCIL_INCLUDE_ERROR, szTokenStart); } else { AddError(IDS_STENCIL_INCLUDE_INVALID, szTokenStart); } return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } CAutoVectorPtr<CHAR> szBufferStart; LPSTR szBufferEnd = NULL; ULONGLONG dwLen = 0; if (FAILED(file.GetSize(dwLen))) { return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } if (!szBufferStart.Allocate((size_t) dwLen)) { AddError(IDS_STENCIL_OUTOFMEMORY, szTokenStart); return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } DWORD dwRead; if (FAILED(file.Read(szBufferStart, (DWORD) dwLen, dwRead))) { return AddToken(szTokenStart, szTokenEnd, STENCIL_TEXTTAG); } szBufferEnd = szBufferStart + dwRead-1; DWORD dwIndex = AddToken(szBufferStart, szBufferEnd, STENCIL_STATICINCLUDE); if (dwIndex != STENCIL_INVALIDINDEX) { GetToken(dwIndex)->bDynamicAlloc = TRUE; szBufferStart.Detach(); } return dwIndex; } } PARSE_TOKEN_RESULT ParseSubhandler(LPCSTR szTokenStart, LPCSTR szTokenEnd) throw() { ATLASSERT(szTokenStart != NULL); ATLASSERT(szTokenEnd != NULL); LPCSTR szStart = szTokenStart; LPCSTR szEnd = szTokenEnd; // move to the start of the arguments // (the first char past 'subhandler' FindTagArgs(szStart, szEnd, 10); // skip any space to bring us to the start // of the id for the subhandler. szStart = SkipSpace(szStart, GetCodePage()); // id names cannot contain spaces. Mark the // beginning and end if the subhandler id LPCSTR szIdStart = szStart; while (!isspace(static_cast<unsigned char>(*szStart)) && *szStart != '}') { if (!isalnum(static_cast<unsigned char>(*szStart))) { // id names can only contain alphanumeric characters return INVALID_TOKEN; } LPSTR szNext = CharNextExA(GetCodePage(), szStart, 0); if (szNext == szStart) { // embedded null AddError(IDS_STENCIL_EMBEDDED_NULL, NULL); return INVALID_TOKEN; } szStart = szNext; } LPCSTR szIdEnd = szStart; // skip space to bring us to the beginning of the // the dllpath/handlername szStart = SkipSpace(szStart, GetCodePage()); // everything up to the end if the tag is // part of the dllpath/handlername LPCSTR szHandlerStart = szStart; while (*szStart != '}') { LPCSTR szNext = CharNextExA(GetCodePage(), szStart, 0); if (szNext == szStart) { // embedded null AddError(IDS_STENCIL_EMBEDDED_NULL, NULL); return INVALID_TOKEN; } szStart = szNext; } LPCSTR szHandlerEnd = szStart; _ATLTRY { CStringPair::HdlrNameStrType strName(szIdStart, (int)(szIdEnd-szIdStart)); CStringPair::PathStrType strPath(szHandlerStart, (int)(szHandlerEnd-szHandlerStart)); CStringPair::PathStrType strDllPath; CStringPair::HdlrNameStrType strHandlerName; DWORD dwDllPathLen = MAX_PATH; DWORD dwHandlerNameLen = ATL_MAX_HANDLER_NAME_LEN+1; LPSTR szDllPath = strDllPath.GetBuffer(dwDllPathLen); LPSTR szHandlerName = strHandlerName.GetBuffer(dwHandlerNameLen); if (!_AtlCrackHandler(strPath, szDllPath, &dwDllPathLen, szHandlerName, &dwHandlerNameLen)) { strDllPath.ReleaseBuffer(); strHandlerName.ReleaseBuffer(); AddError(IDS_STENCIL_INVALID_SUBHANDLER, szTokenStart); return INVALID_TOKEN; } strDllPath.ReleaseBuffer(dwDllPathLen); strHandlerName.ReleaseBuffer(dwHandlerNameLen); m_arrExtraHandlers.SetAt(strName, CStringPair(strDllPath, strHandlerName)); } _ATLCATCHALL() { AddError(IDS_STENCIL_OUTOFMEMORY, NULL); return INVALID_TOKEN; } return RESERVED_TOKEN; } virtual PARSE_TOKEN_RESULT ParseToken(LPCSTR szTokenStart, LPCSTR szTokenEnd, DWORD *pBlockStack, DWORD *pdwTop) { ATLASSERT(szTokenStart != NULL); ATLASSERT(szTokenEnd != NULL); LPCSTR pStart = szTokenStart; pStart += 2; //skip curlies pStart = SkipSpace(pStart, GetCodePage()); DWORD dwLen = (DWORD)(szTokenEnd - szTokenStart); DWORD dwIndex = STENCIL_INVALIDINDEX; if (CheckTag("include", sizeof("include")-1, pStart, dwLen)) { dwIndex = ParseInclude(szTokenStart, szTokenEnd); } else if (dwLen > 3 && !memcmp("!--", pStart, 3)) { return RESERVED_TOKEN; } else if (dwLen > 2 && !memcmp("//", pStart, 2)) { return RESERVED_TOKEN; } else if (CheckTag("subhandler", sizeof("subhandler")-1, pStart, dwLen)) { return ParseSubhandler(szTokenStart, szTokenEnd); } else { return CStencil::ParseToken(szTokenStart, szTokenEnd, pBlockStack, pdwTop); } if (dwIndex == STENCIL_INVALIDINDEX) { return INVALID_TOKEN; } return RESERVED_TOKEN; } mapType* GetExtraHandlers() throw() { return &m_arrExtraHandlers; } BOOL SetBaseDirFromFile(LPCSTR szBaseDir) { if (!SafeStringCopy(m_szBaseDir, szBaseDir)) { return FALSE; } LPSTR szSlash = strrchr(m_szBaseDir, '\\'); if (szSlash) { szSlash++; *szSlash = '\0'; } else { *m_szBaseDir = '\0'; } return TRUE; } LPCSTR GetBaseDir() { return m_szBaseDir; } DWORD RenderToken( DWORD dwIndex, ITagReplacer* pReplacer, IWriteStream *pWriteStream, HTTP_CODE *phcErrorCode, CStencilState* pState = NULL) const throw(...) { DWORD dwNextToken = STENCIL_INVALIDINDEX; HTTP_CODE hcErrorCode = HTTP_SUCCESS; const StencilToken* pToken = GetToken(dwIndex); if (pToken) { if (pToken->type == STENCIL_STENCILINCLUDE) { hcErrorCode = RenderInclude(pReplacer, pToken, pWriteStream, pState); if (hcErrorCode == HTTP_SUCCESS || IsAsyncDoneStatus(hcErrorCode)) { dwNextToken = dwIndex+1; } else if (IsAsyncContinueStatus(hcErrorCode)) { dwNextToken = dwIndex; } } else if (pToken->type == STENCIL_STATICINCLUDE) { pWriteStream->WriteStream(pToken->pStart, (int)((pToken->pEnd-pToken->pStart)+1), NULL); dwNextToken = dwIndex+1; } else { dwNextToken = baseType::RenderToken(dwIndex, pReplacer, pWriteStream, &hcErrorCode, pState); } } if (hcErrorCode == HTTP_SUCCESS_NO_CACHE) { hcErrorCode = NoCachePage(pReplacer); } if (phcErrorCode) { *phcErrorCode = hcErrorCode; } return dwNextToken; } }; // class CHtmlStencil __declspec(selectany) CCRTHeap CStencil::m_crtHeap; // // CHtmlTagReplacer // This class manages CStencil based objects for HTTP requests. This class will retrieve // CStencil based objects from the stencil cache, store CStencil based objects in the // stencil cache and allocate and initialize CStencil based objects on a per reqeust // basis. Typically, one instance of this class is created for each HTTP request. The // instance is destroyed once the request has been completed. template <class THandler, class StencilType=CHtmlStencil> class CHtmlTagReplacer : public ITagReplacerImpl<THandler> { protected: typedef StencilType StencilType; CSimpleArray<HINSTANCE> m_hInstHandlers; typedef CAtlMap<CStringA, IRequestHandler*, CStringElementTraits<CStringA> > mapType; mapType m_Handlers; StencilType *m_pLoadedStencil; WORD m_nCodePage; CComPtr<IStencilCache> m_spStencilCache; AtlServerRequest m_RequestInfo; public: // public members CHtmlTagReplacer() throw() : m_pLoadedStencil(NULL) { memset(&m_RequestInfo, 0x00, sizeof(m_RequestInfo)); m_nCodePage = CP_THREAD_ACP; } ~CHtmlTagReplacer() throw() { // you should call FreeHandlers before // the object is destructed ATLASSUME(m_hInstHandlers.GetSize() == 0); } HTTP_CODE Initialize(AtlServerRequest *pRequestInfo, IHttpServerContext *pSafeSrvCtx=NULL) throw(...) { ATLASSERT(pRequestInfo != NULL); CComPtr<IServiceProvider> spServiceProvider; THandler *pT = static_cast<THandler*>(this); HRESULT hr = pT->GetContext(__uuidof(IServiceProvider), (void **)&spServiceProvider); if (FAILED(hr)) return HTTP_FAIL; spServiceProvider->QueryService(__uuidof(IStencilCache), __uuidof(IStencilCache), (void **) &m_spStencilCache); if (!m_spStencilCache) { ATLASSERT(FALSE); return HTTP_FAIL; } // copy the AtlServerRequest into the safe version Checked::memcpy_s(&m_RequestInfo, sizeof(m_RequestInfo), pRequestInfo, sizeof(m_RequestInfo)); // override appropriate fields m_RequestInfo.cbSize = sizeof(m_RequestInfo); m_RequestInfo.pServerContext = pSafeSrvCtx; return HTTP_SUCCESS; } HTTP_CODE LoadStencilResource( HINSTANCE hInstResource, LPCSTR szResourceID, LPCSTR szResourceType = NULL, LPCSTR szStencilName=NULL) throw(...) { if (!szResourceType) szResourceType = (LPCSTR) (RT_HTML); // look up stencil in cache HTTP_CODE hcErr = HTTP_SUCCESS; // check the cache first StencilType *pStencil = FindCacheStencil(szStencilName ? szStencilName : szResourceID); if (!pStencil) { // create a new stencil pStencil = GetNewCacheStencil(); if (!pStencil) { return AtlsHttpError(500,ISE_SUBERR_OUTOFMEM); } THandler *pT = static_cast<THandler*>(this); LPCSTR szFileName = pT->m_spServerContext->GetScriptPathTranslated(); if (!szFileName) return HTTP_FAIL; if (!pStencil->SetBaseDirFromFile(szFileName)) { return HTTP_FAIL; } pStencil->SetErrorResource(GetResourceInstance()); // load the stencil and parse its replacements if (HTTP_SUCCESS == pStencil->LoadFromResource(hInstResource, szResourceID, szResourceType)) { _ATLTRY { if (!pStencil->ParseReplacements(this)) { return AtlsHttpError(500, ISE_SUBERR_BADSRF); } hcErr = FinishLoadStencil(pStencil, NULL); if (!hcErr) { #ifdef ATL_DEBUG_STENCILS pStencil->FinishParseReplacements(); #else if (!pStencil->FinishParseReplacements()) { return AtlsHttpError(500, ISE_SUBERR_BADSRF); } #endif // ATL_DEBUG_STENCILS } } _ATLCATCHALL() { return HTTP_FAIL; } } else { hcErr = HTTP_FAIL; } // if everything went OK, put the stencil in the stencil cache. if (!hcErr) { hcErr = CacheStencil(szStencilName ? szStencilName : szResourceID, pStencil); } if (pStencil && hcErr) // something went wrong, free the stencil data { FreeCacheStencil(pStencil); } } else { hcErr = FinishLoadStencil(pStencil); } return hcErr; } HTTP_CODE LoadStencilResource(HINSTANCE hInstResource, UINT nID, LPCSTR szResourceType = NULL) throw(...) { if (!szResourceType) szResourceType = (LPCSTR) RT_HTML; char szName[80]; int nResult = sprintf_s(szName, sizeof(szName), "%p/%u", hInstResource, nID); if ((nResult < 0) || (nResult == sizeof(szName))) { return HTTP_FAIL; } return LoadStencilResource(hInstResource, MAKEINTRESOURCEA(nID), szResourceType, szName); } HTTP_CODE LoadStencil(LPCSTR szFileName, IHttpRequestLookup * pLookup = NULL) throw(...) { if (!szFileName) { return HTTP_FAIL; } HTTP_CODE hcErr = HTTP_FAIL; // try to find the stencil in the cache StencilType *pStencil = FindCacheStencil(szFileName); if (!pStencil) { // not in cache. Create a new one pStencil = GetNewCacheStencil(); if (!pStencil) { return AtlsHttpError(500, ISE_SUBERR_OUTOFMEM); // out of memory! } if (!pStencil->SetBaseDirFromFile(szFileName)) { return HTTP_FAIL; } pStencil->SetErrorResource(GetResourceInstance()); // finish loading hcErr = pStencil->LoadFromFile(szFileName); if (!hcErr) { _ATLTRY { if (!pStencil->ParseReplacements(static_cast<ITagReplacer*>(this))) { return AtlsHttpError(500, ISE_SUBERR_BADSRF); } hcErr = FinishLoadStencil(pStencil, pLookup); if (!hcErr) { #ifdef ATL_DEBUG_STENCILS pStencil->FinishParseReplacements(); #else if (!pStencil->FinishParseReplacements()) { return AtlsHttpError(500, ISE_SUBERR_BADSRF); } #endif // ATL_DEBUG_STENCILS } } _ATLCATCHALL() { return HTTP_FAIL; } } // if everything is OK, cache the stencil if (!hcErr) { hcErr = CacheStencil(szFileName, pStencil); } if (pStencil && hcErr) // something went wrong, free stencil data FreeCacheStencil(pStencil); } else { hcErr = FinishLoadStencil(pStencil, pLookup); } return hcErr; } HTTP_CODE RenderStencil(IWriteStream* pStream, CStencilState* pState = NULL) throw(...) { if (!m_pLoadedStencil) return AtlsHttpError(500, ISE_SUBERR_UNEXPECTED); WORD nCodePage = m_pLoadedStencil->GetCodePage(); if (nCodePage != CP_ACP) m_nCodePage = nCodePage; HTTP_CODE hcErr = HTTP_FAIL; hcErr = m_pLoadedStencil->Render(static_cast<ITagReplacer*>(this), pStream, pState); if (!IsAsyncStatus(hcErr) && m_pLoadedStencil->GetCacheItem()) m_spStencilCache->ReleaseStencil(m_pLoadedStencil->GetCacheItem()); return hcErr; } //Implementation void FreeHandlers() throw(...) { POSITION pos = m_Handlers.GetStartPosition(); while (pos) { m_Handlers.GetValueAt(pos)->UninitializeHandler(); m_Handlers.GetNextValue(pos)->Release(); } m_Handlers.RemoveAll(); int nLen = m_hInstHandlers.GetSize(); if (nLen != 0) { THandler *pT = static_cast<THandler *>(this); CComPtr<IDllCache> spDllCache; pT->m_spServiceProvider->QueryService(__uuidof(IDllCache), __uuidof(IDllCache), (void **)&spDllCache); for (int i=0; i<nLen; i++) { spDllCache->Free(m_hInstHandlers[i]); } m_hInstHandlers.RemoveAll(); } } StencilType* GetNewCacheStencil() throw(...) { StencilType *pStencil = NULL; THandler *pT = static_cast<THandler *>(this); IAtlMemMgr *pMemMgr; if (FAILED(pT->m_spServiceProvider->QueryService(__uuidof(IAtlMemMgr), __uuidof(IAtlMemMgr), (void **)&pMemMgr))) pMemMgr = NULL; ATLTRY(pStencil = new StencilType(pMemMgr)); if (pStencil != NULL) { pStencil->Initialize(pT->m_spServiceProvider); } return pStencil; } HTTP_CODE CacheStencil( LPCSTR szName, StencilType* pStencilData) throw() { THandler *pT = static_cast<THandler *>(this); HRESULT hr = E_FAIL; HCACHEITEM hCacheItem = NULL; hr = m_spStencilCache->CacheStencil(szName, pStencilData, sizeof(StencilType*), &hCacheItem, pT->m_hInstHandler, static_cast<IMemoryCacheClient*>(pStencilData)); if (hr == S_OK && hCacheItem) { _ATLTRY { pStencilData->SetCacheItem(hCacheItem); } _ATLCATCHALL() { hr = E_FAIL; } } return (hr == S_OK) ? HTTP_SUCCESS : HTTP_FAIL; } StencilType *FindCacheStencil(LPCSTR szName) throw() { if (!szName || !m_spStencilCache) return NULL; StencilType *pStencilData = NULL; HCACHEITEM hStencil; if (m_spStencilCache->LookupStencil(szName, &hStencil) != S_OK) return NULL; m_spStencilCache->GetStencil(hStencil, reinterpret_cast<void **>(&pStencilData)); return pStencilData; } void FreeCacheStencil(StencilType* pStencilData) { ATLASSERT( pStencilData != NULL ); if(!pStencilData) { return; } IMemoryCacheClient *pMemCacheClient = static_cast<IMemoryCacheClient *>(pStencilData); if(!pMemCacheClient) { return; } _ATLTRY { pMemCacheClient->Free(pStencilData); } _ATLCATCHALL() { } } HTTP_CODE GetHandlerOffset(LPCSTR szHandlerName, DWORD* pdwOffset) { if (!pdwOffset) return HTTP_FAIL; mapType::CPair *p = m_Handlers.Lookup(szHandlerName); if (p) { DWORD dwIndex = 0; POSITION pos = m_Handlers.GetStartPosition(); while (pos) { const mapType::CPair *p1 = m_Handlers.GetNext(pos); if (p1 == p) { *pdwOffset = dwIndex; return HTTP_SUCCESS; } dwIndex++; } ATLASSERT(FALSE); } *pdwOffset = 0; return HTTP_FAIL; } HTTP_CODE GetReplacementObject(DWORD dwObjOffset, ITagReplacer **ppReplacer) { HRESULT hr = E_FAIL; POSITION pos = m_Handlers.GetStartPosition(); for (DWORD dwIndex=0; dwIndex < dwObjOffset; dwIndex++) m_Handlers.GetNext(pos); ATLASSERT(pos != NULL); IRequestHandler *pHandler = NULL; pHandler = m_Handlers.GetValueAt(pos); ATLENSURE(pHandler != NULL); hr = pHandler->QueryInterface(__uuidof(ITagReplacer), (void**)ppReplacer); if (hr != S_OK) return HTTP_FAIL; return HTTP_SUCCESS; } // This is where we would actually load any extra request // handlers the HTML stencil might have parsed for us. HTTP_CODE FinishLoadStencil(StencilType *pStencil, IHttpRequestLookup * pLookup = NULL) throw(...) { THandler *pT = static_cast<THandler *>(this); ATLASSERT(pStencil); if (!pStencil) return AtlsHttpError(500, ISE_SUBERR_UNEXPECTED); // unexpected condition m_pLoadedStencil = pStencil; //load extra handlers if there are any StencilType::mapType *pExtraHandlersMap = pStencil->GetExtraHandlers(); if (pExtraHandlersMap) { POSITION pos = pExtraHandlersMap->GetStartPosition(); CStringA name; CStringPair path; IRequestHandler *pHandler; HINSTANCE hInstHandler; while(pos) { pExtraHandlersMap->GetNextAssoc(pos, name, path); pHandler = NULL; hInstHandler = NULL; HTTP_CODE hcErr = pT->m_spExtension->LoadRequestHandler(path.strDllPath, path.strHandlerName, pT->m_spServerContext, &hInstHandler, &pHandler); if (!hcErr) { _ATLTRY { //map the name to the pointer to request handler m_Handlers.SetAt(name, pHandler); //store HINSTANCE of handler m_hInstHandlers.Add(hInstHandler); } _ATLCATCHALL() { return HTTP_FAIL; } if (pLookup) { hcErr = pHandler->InitializeChild(&m_RequestInfo, pT->m_spServiceProvider, pLookup); if (hcErr != HTTP_SUCCESS) return hcErr; } } else return hcErr; } } return HTTP_SUCCESS; } }; // class CHtmlTagReplacer // CRequestHandlerT // This is the base class for all user request handlers. This class implements // the IReplacementHandler interface whose methods will be called to render HTML // into a stream. The stream will be returned as the HTTP response upon completion // of the HTTP request. template < class THandler, class ThreadModel=CComSingleThreadModel, class TagReplacerType=CHtmlTagReplacer<THandler> > class CRequestHandlerT : public TagReplacerType, public CComObjectRootEx<ThreadModel>, public IRequestHandlerImpl<THandler> { protected: CStencilState m_state; CComObjectStackEx<CIDServerContext> m_SafeSrvCtx; typedef CRequestHandlerT<THandler, ThreadModel, TagReplacerType> _requestHandler; public: BEGIN_COM_MAP(_requestHandler) COM_INTERFACE_ENTRY(IRequestHandler) COM_INTERFACE_ENTRY(ITagReplacer) END_COM_MAP() // public CRequestHandlerT members CHttpResponse m_HttpResponse; CHttpRequest m_HttpRequest; ATLSRV_REQUESTTYPE m_dwRequestType; AtlServerRequest* m_pRequestInfo; CRequestHandlerT() throw() { m_hInstHandler = NULL; m_dwAsyncFlags = 0; m_pRequestInfo = NULL; } ~CRequestHandlerT() throw() { _ATLTRY { FreeHandlers(); // free handlers held by CTagReplacer } _ATLCATCHALL() { } } void ClearResponse() throw() { m_HttpResponse.ClearResponse(); } // Where user initialization should take place HTTP_CODE ValidateAndExchange() { return HTTP_SUCCESS; // continue processing request } // Where user Uninitialization should take place HTTP_CODE Uninitialize(HTTP_CODE hcError) { return hcError; } HTTP_CODE InitializeInternal(AtlServerRequest *pRequestInfo, IServiceProvider *pProvider) { // Initialize our internal references to required services m_pRequestInfo = pRequestInfo; m_state.pParentInfo = pRequestInfo; m_hInstHandler = pRequestInfo->hInstDll; m_spServerContext = pRequestInfo->pServerContext; m_spServiceProvider = pProvider; return HTTP_SUCCESS; } HTTP_CODE InitializeHandler( AtlServerRequest *pRequestInfo, IServiceProvider *pProvider) { HTTP_CODE hcErr = HTTP_FAIL; ATLASSERT(pRequestInfo); ATLASSERT(pProvider); THandler* pT = static_cast<THandler*>(this); hcErr = pT->InitializeInternal(pRequestInfo, pProvider); if (!hcErr) { m_HttpResponse.Initialize(m_spServerContext); hcErr = pT->CheckValidRequest(); if (!hcErr) { hcErr = HTTP_FAIL; if (m_HttpRequest.Initialize(m_spServerContext, pT->MaxFormSize(), pT->FormFlags())) { if (m_SafeSrvCtx.Initialize(&m_HttpResponse, &m_HttpRequest)) { hcErr = TagReplacerType::Initialize(pRequestInfo, &m_SafeSrvCtx); if (!hcErr) { hcErr = pT->ValidateAndExchange(); } } } } } return hcErr; } HTTP_CODE InitializeChild( AtlServerRequest *pRequestInfo, IServiceProvider *pProvider, IHttpRequestLookup *pRequestLookup) { ATLASSERT(pRequestInfo); ATLASSERT(pProvider); THandler *pT = static_cast<THandler*>(this); HTTP_CODE hcErr = pT->InitializeInternal(pRequestInfo, pProvider); if (hcErr) return hcErr; if (pRequestLookup) { // initialize with the pRequestLookup if(!m_HttpResponse.Initialize(pRequestLookup)) { return HTTP_FAIL; } // Initialize with the IHttpServerContext if it exists // the only time this is different than the previous call to // initialize is if the user passes a different IHttpServerContext // in pRequestInfo than the one extracted from pRequestLookup. if (m_spServerContext) { if(!m_HttpResponse.Initialize(m_spServerContext)) { return HTTP_FAIL; } } hcErr = pT->CheckValidRequest(); if (hcErr) { return hcErr; } // initialize with the pRequestLookup to chain query parameters m_HttpRequest.Initialize(pRequestLookup); // initialize with the m_spServerContext to get additional query params // if they exist. if (m_spServerContext) { m_HttpRequest.Initialize(m_spServerContext); } } m_HttpResponse.SetBufferOutput(false); // child cannot buffer // initialize the safe server context if (!m_SafeSrvCtx.Initialize(&m_HttpResponse, &m_HttpRequest)) { return HTTP_FAIL; } hcErr = TagReplacerType::Initialize(pRequestInfo, &m_SafeSrvCtx); if (hcErr) { return hcErr; } return pT->ValidateAndExchange(); } // HandleRequest is called to perform default processing of HTTP requests. Users // can override this function in their derived classes if they need to perform // specific initialization prior to processing this request or want to change the // way the request is processed. HTTP_CODE HandleRequest( AtlServerRequest *pRequestInfo, IServiceProvider* /*pServiceProvider*/) { ATLENSURE(pRequestInfo); THandler *pT = static_cast<THandler *>(this); HTTP_CODE hcErr = HTTP_SUCCESS; if (pRequestInfo->dwRequestState == ATLSRV_STATE_BEGIN) { m_dwRequestType = pRequestInfo->dwRequestType; if (pRequestInfo->dwRequestType==ATLSRV_REQUEST_STENCIL) { LPCSTR szFileName = pRequestInfo->pServerContext->GetScriptPathTranslated(); hcErr = HTTP_FAIL; if (szFileName) hcErr = pT->LoadStencil(szFileName, static_cast<IHttpRequestLookup *>(&m_HttpRequest)); } } else if (pRequestInfo->dwRequestState == ATLSRV_STATE_CONTINUE) m_HttpResponse.ClearContent(); #ifdef ATL_DEBUG_STENCILS if (m_pLoadedStencil && !m_pLoadedStencil->ParseSuccessful()) { // An error or series of errors occurred in parsing the stencil _ATLTRY { m_pLoadedStencil->RenderErrors(static_cast<IWriteStream*>(&m_HttpResponse)); } _ATLCATCHALL() { return HTTP_FAIL; } } #endif if (hcErr == HTTP_SUCCESS && m_pLoadedStencil) { // if anything other than HTTP_SUCCESS is returned during // the rendering of replacement tags, we return that value // here. hcErr = pT->RenderStencil(static_cast<IWriteStream*>(&m_HttpResponse), &m_state); if (hcErr == HTTP_SUCCESS && !m_HttpResponse.Flush(TRUE)) hcErr = HTTP_FAIL; } if (IsAsyncFlushStatus(hcErr)) { pRequestInfo->pszBuffer = LPCSTR(m_HttpResponse.m_strContent); pRequestInfo->dwBufferLen = m_HttpResponse.m_strContent.GetLength(); } if (pRequestInfo->dwRequestState == ATLSRV_STATE_BEGIN || IsAsyncDoneStatus(hcErr)) return pT->Uninitialize(hcErr); else if (!IsAsyncStatus(hcErr)) m_HttpResponse.ClearContent(); return hcErr; } HTTP_CODE ServerTransferRequest(LPCSTR szRequest, bool bContinueAfterTransfer=false, WORD nCodePage = 0, CStencilState *pState = NULL) throw(...) { return m_spExtension->TransferRequest( m_pRequestInfo, m_spServiceProvider, static_cast<IWriteStream*>(&m_HttpResponse), static_cast<IHttpRequestLookup*>(&m_HttpRequest), szRequest, nCodePage == 0 ? m_nCodePage : nCodePage, bContinueAfterTransfer, pState); } inline DWORD MaxFormSize() { return DEFAULT_MAX_FORM_SIZE; } inline DWORD FormFlags() { return ATL_FORM_FLAG_IGNORE_FILES; } // Override this function to check if the request // is valid. This function is called after m_HttpResponse // has been initialized, so you can use it if you need // to return an error to the client. This is also a // good place to initialize any internal class data needed // to handle the request. CRequestHandlerT::CheckValidRequest // is called after CRequestHandlerT::InitializeInternal is // called, so your override of this method will have access to // m_pRequestInfo (this request's AtlServerRequest structure), // m_hInstHandler (the HINSTANCE of this handler dll), // m_spServerContext (the IHttpServerContext interface for this request), // m_spServiceProvider (the IServiceProvider interface for this request). // You should call CRequestHandlerT::CheckValidRequest in your override // if you override this function. // // Note that m_HttpRequest has not been initialized, so // you cannot use it. This function is intended to // do simple checking throught IHttpServerContext to avoid // expensive initialization of m_HttpRequest. HTTP_CODE CheckValidRequest() { LPCSTR szMethod = NULL; ATLASSUME(m_pRequestInfo); szMethod = m_pRequestInfo->pServerContext->GetRequestMethod(); if (strcmp(szMethod, "GET") && strcmp(szMethod, "POST") && strcmp(szMethod, "HEAD")) return HTTP_NOT_IMPLEMENTED; return HTTP_SUCCESS; } HRESULT GetContext(REFIID riid, void** ppv) { if (!ppv) return E_POINTER; if (InlineIsEqualGUID(riid, __uuidof(IHttpServerContext))) { return m_spServerContext.CopyTo((IHttpServerContext **)ppv); } if (InlineIsEqualGUID(riid, __uuidof(IHttpRequestLookup))) { *ppv = static_cast<IHttpRequestLookup*>(&m_HttpRequest); m_HttpRequest.AddRef(); return S_OK; } if (InlineIsEqualGUID(riid, __uuidof(IServiceProvider))) { *ppv = m_spServiceProvider; m_spServiceProvider.p->AddRef(); return S_OK; } return E_NOINTERFACE; } HINSTANCE GetResourceInstance() { if (m_pRequestInfo != NULL) { return m_pRequestInfo->hInstDll; } return NULL; } template <typename Interface> HRESULT GetContext(Interface** ppInterface) throw(...) { return GetContext(__uuidof(Interface), reinterpret_cast<void**>(ppInterface)); } }; // class CRequestHandlerT } // namespace ATL #pragma pack(pop) #pragma warning( pop ) #endif // __ATLSTENCIL_H__
[ "asandman@5d4b435c-4d46-d949-aab2-e601ca53af14" ]
[ [ [ 1, 4152 ] ] ]
d58f526be56428ee479875f0d3c6f6f5bf2eec76
eaa64753cb11194ab175ec8c386924cd7edd502b
/WinBridge/DirectShow/MediaTypes.cpp
2d00039d6ea311822f8995f781212e44b97d6f50
[]
no_license
venkatvishnu/win-bridge
e0a51e56eeb730df1b30cc453ac7e73744927ee8
ea4542160f1bcea442a28e7051a75743970d5eaa
refs/heads/master
2021-01-25T06:01:03.215370
2011-07-29T04:21:36
2011-07-29T04:21:36
41,912,274
0
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
#include "StdAfx.h" #include "MediaTypes.h" using namespace WinBridge::DirectShow; MediaTypes::MediaTypes(void) { }
[ [ [ 1, 8 ] ] ]
27e380e6e6a98275be366c34706715dd1299619b
f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae
/Exercises/Old Solutions/OpenGL4/OpenGL4/entitySpectator.cpp
9e1b23d98048e7231ea17c63629b5064bcaad261
[]
no_license
giacomof/gameengines2010itu
8407be66d1aff07866d3574a03804f2f5bcdfab1
bc664529a429394fe5743d5a76a3d3bf5395546b
refs/heads/master
2016-09-06T05:02:13.209432
2010-12-12T22:18:19
2010-12-12T22:18:19
35,165,366
0
0
null
null
null
null
UTF-8
C++
false
false
4,390
cpp
#include "entitySpectator.h" entitySpectator::entitySpectator(void) { //mutex_object = SDL_CreateMutex(); camera = NULL; yaw = 0.0f; pitch = 0.0f; position[0] = 0.0f; position[1] = 0.0f; position[2] = 0.0f; shouldMoveForward = false; shouldMoveBackward = false; shouldStrafeLeft = false; shouldStrafeRight = false; lookDeltaXAmount = 0.0f; lookDeltaYAmount = 0.0f; } entitySpectator::~entitySpectator(void) { //SDL_DestroyMutex ( mutex_object ); /*if (camera != NULL) delete camera;*/ } void entitySpectator::update() { AssetManager::lockMutex( SceneObject::mutex_object ); // hardcode speed constant for now float camSpeed = 0.5; // Update pitch and yaw yaw = yaw + lookDeltaXAmount; pitch = pitch + lookDeltaYAmount; lookDeltaXAmount = 0.0f; lookDeltaYAmount = 0.0f; // Limits camera pitch if (pitch>90.0f) pitch = 90.0f; else if (pitch<-90.0f) pitch = -90.0f; // Rolls over yaw while(yaw<=0.0f) yaw += 360.0f; while(yaw>=360.0f) yaw -= 360.0f; // Starting camera orientation Vector vForward (0.0, 0.0, -1.0 ); Vector vSideways (1.0, 0.0, 0.0 ); Vector vUp (0.0, 1.0, 0.0 ); // Calculate rotation matrix from pitch and yaw Matrix oMatrix; oMatrix = Matrix::generateAxesRotationMatrix(Vector(1.0,0.0,0.0),pitch).getTranspose(); oMatrix = Matrix::generateAxesRotationMatrix(Vector(0.0,1.0,0.0),yaw).getTranspose() * oMatrix; // Calculate the orientation vectors vForward = oMatrix * vForward; vSideways = oMatrix * vSideways; vUp = oMatrix * vUp; // Forward if (shouldMoveForward && !shouldMoveBackward) { position[0] -= vForward[0] * camSpeed; position[1] -= vForward[1] * camSpeed; position[2] -= vForward[2] * camSpeed; } // Backwards if (shouldMoveBackward && !shouldMoveForward) { position[0] += vForward[0] * camSpeed; position[1] += vForward[1] * camSpeed; position[2] += vForward[2] * camSpeed; } // Left if (shouldStrafeLeft && !shouldStrafeRight) { position[0] += vSideways[0] * camSpeed; position[1] += vSideways[1] * camSpeed; position[2] += vSideways[2] * camSpeed; } // Right if (shouldStrafeRight && !shouldStrafeLeft) { position[0] -= vSideways[0] * camSpeed; position[1] -= vSideways[1] * camSpeed; position[2] -= vSideways[2] * camSpeed; } // Update camera if (camera != NULL) { //camera->lock(); AssetManager::lockMutex( SceneObject::mutex_object ); camera->setPosition(position[0],position[1],position[2]); camera->setForwardVector(vForward[0],vForward[1],vForward[2]); camera->setUpVector(vUp[0],vUp[1],vUp[2]); camera->setPitchYaw(pitch, yaw); AssetManager::unlockMutex( SceneObject::mutex_object ); //camera->unlock(); } AssetManager::unlockMutex( SceneObject::mutex_object ); } void entitySpectator::setCamera(entityCamera *newcamera) { AssetManager::lockMutex( SceneObject::mutex_object ); camera = newcamera; AssetManager::unlockMutex( SceneObject::mutex_object ); } entityCamera* entitySpectator::getCamera() { return camera; } void entitySpectator::moveForward(bool shouldMove) { AssetManager::lockMutex( SceneObject::mutex_object ); shouldMoveForward = shouldMove; AssetManager::unlockMutex( SceneObject::mutex_object ); } void entitySpectator::moveBackward(bool shouldMove) { AssetManager::lockMutex( SceneObject::mutex_object ); shouldMoveBackward = shouldMove; AssetManager::unlockMutex( SceneObject::mutex_object ); } void entitySpectator::strafeLeft(bool shouldMove) { AssetManager::lockMutex( SceneObject::mutex_object ); shouldStrafeLeft = shouldMove; AssetManager::unlockMutex( SceneObject::mutex_object ); } void entitySpectator::strafeRight(bool shouldMove) { AssetManager::lockMutex( SceneObject::mutex_object ); shouldStrafeRight = shouldMove; AssetManager::unlockMutex( SceneObject::mutex_object ); } void entitySpectator::lookDeltaX(float deltaLook) { AssetManager::lockMutex( SceneObject::mutex_object ); lookDeltaXAmount = lookDeltaXAmount + deltaLook; AssetManager::unlockMutex( SceneObject::mutex_object ); } void entitySpectator::lookDeltaY(float deltaLook) { AssetManager::lockMutex( SceneObject::mutex_object ); lookDeltaYAmount = lookDeltaYAmount + deltaLook; AssetManager::unlockMutex( SceneObject::mutex_object ); }
[ "[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d", "[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d", "[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d" ]
[ [ [ 1, 4 ], [ 6, 19 ], [ 26, 27 ], [ 29, 96 ], [ 99, 102 ], [ 105, 106 ], [ 108, 111 ], [ 113, 113 ], [ 115, 123 ], [ 125, 125 ], [ 127, 130 ], [ 132, 132 ], [ 134, 137 ], [ 139, 139 ], [ 141, 144 ], [ 146, 146 ], [ 148, 151 ], [ 153, 153 ], [ 155, 158 ], [ 160, 160 ], [ 162, 162 ] ], [ [ 5, 5 ], [ 22, 24 ], [ 28, 28 ], [ 97, 98 ], [ 103, 104 ], [ 107, 107 ], [ 112, 112 ], [ 114, 114 ], [ 124, 124 ], [ 126, 126 ], [ 131, 131 ], [ 133, 133 ], [ 138, 138 ], [ 140, 140 ], [ 145, 145 ], [ 147, 147 ], [ 152, 152 ], [ 154, 154 ], [ 159, 159 ], [ 161, 161 ] ], [ [ 20, 21 ], [ 25, 25 ] ] ]
824f4e9847a024f0da1126560a66cc9e1759d179
2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83
/BasicOgreFramework/PhysxSDK/Samples/SampleContactStreamIterator/src/NxSampleContactStreamIterator.cpp
8da0b07459bc1c37d254eb8a69ac855d69c1ad6d
[]
no_license
mgq812/simengines-g2-code
5908d397ef2186e1988b1d14fa8b73f4674f96ea
699cb29145742c1768857945dc59ef283810d511
refs/heads/master
2016-09-01T22:57:54.845817
2010-01-11T19:26:51
2010-01-11T19:26:51
32,267,377
0
0
null
null
null
null
UTF-8
C++
false
false
14,417
cpp
// =============================================================================== // // AGEIA PhysX SDK Sample Program // // Title: Contact Stream Iterator // Description: This sample program shows how to use contact report and the // contact stream iterator. // Toggle between per pair or per point contact forces with 'c'. Per // point forces are only provided for box-plane contacts in this example. // // Originally written by: Pierre Terdiman (04-02-04) // Additions by: // // =============================================================================== #include <stdio.h> #include <GL/glut.h> // Physics code #undef random #include "NxPhysics.h" #include "ErrorStream.h" #include "Utilities.h" #include "SamplesVRDSettings.h" static bool gPause = false; static bool showPointContacts = false; static NxPhysicsSDK* gPhysicsSDK = NULL; static NxScene* gScene = NULL; static NxVec3 gDefaultGravity(0.0f, -9.81f, 0.0f); static ErrorStream gErrorStream; static NxActor* gGroundActor = NULL; static NxU32 gNbReports = 0; struct MyCubeObject { int size; NxU32 events; }; static NxActor* lastActor = NULL; static void CreateCube(const NxVec3& pos, int size=2, const NxVec3* initial_velocity=NULL) { // Create body NxBodyDesc BodyDesc; BodyDesc.angularDamping = 0.5f; // BodyDesc.maxAngularVelocity = 10.0f; if(initial_velocity) BodyDesc.linearVelocity = *initial_velocity; NxBoxShapeDesc BoxDesc; BoxDesc.dimensions = NxVec3(float(size), float(size), float(size)); NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&BoxDesc); ActorDesc.body = &BodyDesc; ActorDesc.density = 0.1f; ActorDesc.globalPose.t = pos; // Binds a user-defined structure to the Nx object MyCubeObject* Object = new MyCubeObject; // Note those ones are never released in this sample Object->size = size; Object->events = 0; NxActor * a = gScene->createActor(ActorDesc); a->userData = Object; lastActor = a; #ifdef TEST_SPECIFIC_SHAPES if(gGroundActor && a) { gScene->setActorPairFlags(*a, *gGroundActor, NX_NOTIFY_ON_START_TOUCH|NX_NOTIFY_ON_TOUCH|NX_NOTIFY_ON_END_TOUCH); } #endif } static void CreateStack(int size) { float CubeSize = 2.0f; // float Spacing = 0.01f; float Spacing = 0.0001f; NxVec3 Pos(0.0f, CubeSize, 0.0f); float Offset = -size * (CubeSize * 2.0f + Spacing) * 0.5f; while(size) { for(int i=0;i<size;i++) { Pos.x = Offset + float(i) * (CubeSize * 2.0f + Spacing); CreateCube(Pos, (int)CubeSize); } Offset += CubeSize; Pos.y += (CubeSize * 2.0f + Spacing); size--; } } static void CreateTower(int size) { float CubeSize = 2.0f; float Spacing = 0.01f; NxVec3 Pos(0.0f, CubeSize, 0.0f); while(size) { CreateCube(Pos, (int)CubeSize); Pos.y += (CubeSize * 2.0f + Spacing); size--; } } class MyContactReport : public NxUserContactReport { public: virtual void onContactNotify(NxContactPair& pair, NxU32 events) { gNbReports++; if(!pair.isDeletedActor[0]) { MyCubeObject* Object = (MyCubeObject*)pair.actors[0]->userData; if(Object) Object->events = events; } if(!pair.isDeletedActor[1]) { MyCubeObject* Object = (MyCubeObject*)pair.actors[1]->userData; if(Object) Object->events = events; } // if(events & NX_NOTIFY_ON_START_TOUCH) printf("Start touch\n"); // if(events & NX_NOTIFY_ON_END_TOUCH) printf("End touch\n"); // Iterate through contact points NxContactStreamIterator i(pair.stream); //user can call getNumPairs() here while(i.goNextPair()) { //user can also call getShape() and getNumPatches() here while(i.goNextPatch()) { //user can also call getPatchNormal() and getNumPoints() here const NxVec3& contactNormal = i.getPatchNormal(); while(i.goNextPoint()) { //user can also call getPoint() and getSeparation() here const NxVec3& contactPoint = i.getPoint(); // printf("%f - %f\n", i.getPointNormalForce(), pair.sumNormalForce.magnitude()); NxVec3 contactForce = (showPointContacts /*&& i.getShapeFlags()&NX_SF_POINT_CONTACT_FORCE*/) ? contactNormal * i.getPointNormalForce() : pair.sumNormalForce; NxVec3 contactArrowForceTip = contactPoint + contactForce * 0.1f; NxVec3 contactArrowFrictionTip = contactPoint + pair.sumFrictionForce* 0.1f; NxVec3 contactArrowPenetrationTip = contactPoint - contactNormal * i.getSeparation() * 20.0f; glDisable(GL_LIGHTING); // Draw the contact glColor4f(1.0f, 0.0f, 0.0f, 1.0f); float line1[2][3] = { {contactPoint.x,contactPoint.y,contactPoint.z}, {contactArrowForceTip.x,contactArrowForceTip.y,contactArrowForceTip.z}}; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, line1); glDrawArrays(GL_LINES, 0, 2); // Draw friction glColor4f(0.0f, 1.0f, 0.0f, 1.0f); float line2[2][3] = { {contactPoint.x,contactPoint.y,contactPoint.z}, {contactArrowFrictionTip.x,contactArrowFrictionTip.y,contactArrowFrictionTip.z}}; glVertexPointer(3, GL_FLOAT, 0, line2); glDrawArrays(GL_LINES, 0, 2); // Draw the penetration part glColor4f(1.0f, 1.0f, 0.0f, 1.0f); float line3[2][3] = { {contactPoint.x,contactPoint.y,contactPoint.z}, {contactArrowPenetrationTip.x,contactArrowPenetrationTip.y,contactArrowPenetrationTip.z}}; glVertexPointer(3, GL_FLOAT, 0, line3); glDrawArrays(GL_LINES, 0, 2); glDisableClientState(GL_VERTEX_ARRAY); } } } } }gMyContactReport; static bool InitNx() { // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &gErrorStream, desc, &errorCode); if(gPhysicsSDK == NULL) { printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode)); return false; } #if SAMPLES_USE_VRD // The settings for the VRD host and port are found in SampleCommonCode/SamplesVRDSettings.h if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger() && !gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected()) gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(SAMPLES_VRD_HOST, SAMPLES_VRD_PORT, SAMPLES_VRD_EVENTMASK); #endif gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.025f); // Create a scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.userContactReport = &gMyContactReport; gScene = gPhysicsSDK->createScene(sceneDesc); if(gScene == NULL) { printf("\nError: Unable to create a PhysX scene, exiting the sample.\n\n"); return false; } #ifndef TEST_SPECIFIC_SHAPES gScene->setActorGroupPairFlags(0,0,NX_NOTIFY_ON_START_TOUCH|NX_NOTIFY_ON_TOUCH|NX_NOTIFY_ON_END_TOUCH); #endif NxMaterial * defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); // Create ground plane NxPlaneShapeDesc PlaneDesc; PlaneDesc.shapeFlags |= NX_SF_POINT_CONTACT_FORCE; NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&PlaneDesc); gGroundActor = gScene->createActor(ActorDesc); return true; } // Render code static int gMainHandle; static bool gShadows = true; static NxVec3 Eye(50.0f, 50.0f, 50.0f); static NxVec3 Dir(-0.6,-0.2,-0.7); static NxVec3 N; static int mx = 0; static int my = 0; static void KeyboardCallback(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; case ' ': CreateCube(NxVec3(0.0f, 20.0f, 0.0f), 1+(rand()&3)); break; case 'o': case 'O': { if(lastActor) gScene->releaseActor(*lastActor); lastActor = (gScene->getNbActors() > 1) ? gScene->getActors()[gScene->getNbActors()-1] : NULL; } break; case 's': case 'S': CreateStack(10); break; case 'b': case 'B': CreateStack(30); break; case 't': case 'T': CreateTower(30); break; case 'x': case 'X': gShadows = !gShadows; break; case 'p': case 'P': gPause = !gPause; break; case 101: case '8': Eye += Dir * 2.0f; break; case 103: case '2': Eye -= Dir * 2.0f; break; case 100: case '4': Eye -= N * 2.0f; break; case 102: case '6': Eye += N * 2.0f; break; case 'c': case 'C': showPointContacts = !showPointContacts; break; case 'w': case 'W': { NxVec3 t = Eye; NxVec3 Vel = Dir; Vel.normalize(); Vel*=200.0f; CreateCube(t, 8, &Vel); } break; } } static void ArrowKeyCallback(int key, int x, int y) { KeyboardCallback(key,x,y); } static void MouseCallback(int button, int state, int x, int y) { mx = x; my = y; } static void MotionCallback(int x, int y) { int dx = mx - x; int dy = my - y; Dir.normalize(); N.cross(Dir,NxVec3(0,1,0)); NxQuat qx(NxPiF32 * dx * 20/ 180.0f, NxVec3(0,1,0)); qx.rotate(Dir); NxQuat qy(NxPiF32 * dy * 20/ 180.0f, N); qy.rotate(Dir); mx = x; my = y; } static void RenderCallback() { //some timing code to prevent it from going too fast on new PCs. //Here we don't just skip the physics update because we also do some //rendering in physics which would get cleared off the screen too fast. #ifdef WIN32 static DWORD PreviousTime = 0; DWORD CurrentTime = timeGetTime(); DWORD ElapsedTime = CurrentTime - PreviousTime; if (ElapsedTime < 10.0f) return; PreviousTime = CurrentTime; #endif if(gScene && !gPause) { gNbReports = 0; gScene->simulate(1.0f/60.0f); //Note: a real application would compute and pass the elapsed time here. gScene->flushStream(); } float glmat[16]; // Clear buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup camera glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)glutGet(GLUT_WINDOW_WIDTH)/(float)glutGet(GLUT_WINDOW_HEIGHT), 1.0f, 10000.0f); gluLookAt(Eye.x, Eye.y, Eye.z, Eye.x + Dir.x, Eye.y + Dir.y, Eye.z + Dir.z, 0.0f, 1.0f, 0.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Physics code // We moved the physics code here because we want to render the contacts in contact report callbacks, and the callbacks are // fired when we execute the following call. Note that this is bad practice however, the simulation shouldn't be performed // in the middle of the rendering loop. if(gScene && !gPause) { gScene->fetchResults(NX_RIGID_BODY_FINISHED, true); // printf("%d\n", gNbReports); } // ~Physics code glEnable(GL_LIGHTING); // Keep physics & graphics in sync int nbActors = gScene->getNbActors(); NxActor** actors = gScene->getActors(); while(nbActors--) { NxActor* actor = *actors++; // Get our object back MyCubeObject* Object = (MyCubeObject*)actor->userData; if(!Object) continue; // Setup object's color according to events if(Object->events & NX_NOTIFY_ON_START_TOUCH) { glColor4f(0.0f, 1.0f, 0.0f, 1.0f); } else if(Object->events & NX_NOTIFY_ON_END_TOUCH) { glColor4f(1.0f, 0.0f, 0.0f, 1.0f); } else { glColor4f(1.0f, 1.0f, 1.0f, 1.0f); } // Render cube glPushMatrix(); actor->getGlobalPose().getColumnMajor44(glmat); glMultMatrixf(glmat); glutSolidCube(float(Object->size)*2.0f); glPopMatrix(); // Handle shadows if(gShadows) { glPushMatrix(); const static float ShadowMat[]={ 1,0,0,0, 0,0,0,0, 0,0,1,0, 0,0,0,1 }; glMultMatrixf(ShadowMat); glMultMatrixf(glmat); glDisable(GL_LIGHTING); glColor4f(0.1f, 0.2f, 0.3f, 1.0f); glutSolidCube(float(Object->size)*2.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); glPopMatrix(); } // Reset events. If we don't do that the events bitmask is not updated as soon as objects don't collide // anymore, so the bitmask stay red (comment that line below, to see this behaviour). Object->events = 0; } glutSwapBuffers(); } static void ReshapeCallback(int width, int height) { glViewport(0, 0, width, height); } static void IdleCallback() { glutPostRedisplay(); } static void ExitCallback() { if (gPhysicsSDK) { if (gScene) gPhysicsSDK->releaseScene(*gScene); gPhysicsSDK->release(); } } int main(int argc, char** argv) { printf("Use the arrow keys or 2, 4, 6 and 8 to move the camera.\n"); printf("Use the mouse to rotate the camera.\n"); printf("Press p to pause the simulation.\n"); printf("Press x to toggle shadows.\n"); printf("Press c to toggle contact normal force display for each contact or only ground plane contacts.\n"); printf("Press the keys w,space,s,b, and t to create various things.\n"); printf("Press o to remove the last created thing.\n"); #if defined(_XBOX) || defined(__CELLOS_LV2__) glutRemapButtonExt(9, 'c', false); //Right shoulder to display normals #endif // Initialize Glut glutInit(&argc, argv); glutInitWindowSize(512, 512); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); gMainHandle = glutCreateWindow("SampleContactStreamIterator"); glutSetWindow(gMainHandle); glutDisplayFunc(RenderCallback); glutReshapeFunc(ReshapeCallback); glutIdleFunc(IdleCallback); glutKeyboardFunc(KeyboardCallback); glutSpecialFunc(ArrowKeyCallback); glutMouseFunc(MouseCallback); glutMotionFunc(MotionCallback); MotionCallback(0,0); atexit(ExitCallback); // Setup default render states glClearColor(0.3f, 0.4f, 0.5f, 1.0); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glEnable(GL_CULL_FACE); // Setup lighting glEnable(GL_LIGHTING); float AmbientColor[] = { 0.0f, 0.1f, 0.2f, 0.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientColor); float DiffuseColor[] = { 1.0f, 1.0f, 1.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseColor); float SpecularColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularColor); float Position[] = { 100.0f, 100.0f, 400.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_POSITION, Position); glEnable(GL_LIGHT0); // Initialize physics scene and start the application main loop if scene was created if (InitNx()) glutMainLoop(); return 0; }
[ "erucarno@789472dc-e1c3-11de-81d3-db62269da9c1" ]
[ [ [ 1, 508 ] ] ]
b2b745efdfcaeefa52e6b66a06e95d7a739bef8e
7969164c2b9f3f12f99a7df28e83551c8b6e5db8
/sorce/fish/Garcon.h
2f401b73086e0aa66c890f4d1f3b9d34753db549
[ "MIT" ]
permissive
montoyamoraga/shbobo
9e9ab91e0ab8b8404d63fa71b15bfb446ade11ea
48246bbc29f2aa5b55644241b369d74e37e9f916
refs/heads/main
2023-07-04T19:02:16.494183
2008-08-14T01:42:07
2008-08-14T01:42:07
326,004,619
1
1
MIT
2021-04-11T23:47:58
2021-01-01T15:27:42
C
UTF-8
C++
false
false
2,057
h
#include <map> struct HouseCommands { enum CommandIDs { newPhile = 0x2000,newFromClip, openPhile, savePhile, saveAsPhile, printBouillabaisse, undoEdit, redoEdit, copyToClip, cutEdit, copyEdit, pasteEdit, dupEdit, dupEditRef, zoomIn, zoomOut, upLoad, upLoadTab, upLoadMatrix, gwonzify }; }; struct Atom; class Garcon : public UndoManager, public ApplicationCommandManager, public MenuBarModel, public HouseCommands, public LookAndFeel_V2 { public: //Menu m; Font f; Font sf; File currentFile; File currentBinar; std::map<String,Atom*> urmap; Atom * selected; Garcon(); Font getLabelFont (Label & l) { if (l.getName()=="b") return f.italicised();//f.setItalic(true); return f; } const Font& getSubFont() { return sf; } int sizico; void zoomInn() { sizico++; f.setHeight(sizico*4); sf.setHeight(sizico*2); bsi = BorderSize<int>(0,sizico*2,0,sizico*2); gsi = BorderSize<int>(0,sizico,0,sizico); } void zoomOutt() { sizico = (sizico > 1 ? sizico-1 : 1); f.setHeight(sizico*4); sf.setHeight(sizico*2); bsi = BorderSize<int>(0,sizico*2,0,sizico*2); gsi = BorderSize<int>(0,sizico,0,sizico); } int getSubHeight() { return sf.getHeight(); } int getHeight() { return f.getHeight() +sf.getHeight(); } Image mulbTILE; const Image& imago() { Image r(Image::RGB, 2, 2, true); int n = rand()%256; r.setPixelAt(1,1,Colour(n,n,0));//.withAlpha((float)0.25)); n = rand()%256; r.setPixelAt(0,0,Colour(n,n,0));//.withAlpha((float)0.25)); n = rand()%256; r.setPixelAt(0,1,Colour(n,n,0));//.withAlpha((float)0.25)); n = rand()%256; r.setPixelAt(1,0,Colour(n,n,0));//.withAlpha((float)0.25)); mulbTILE = r.rescaled(rand()%16+1,rand()%16+1,Graphics::lowResamplingQuality); return mulbTILE; } StringArray getMenuBarNames(); PopupMenu getMenuForIndex (int menuIndex, const String&); void menuItemSelected(int menuItemID, int) {} void menuBarActivated(bool isActive) {} };
[ [ [ 1, 90 ] ] ]
477f17729f1c4673e46b0c91923cc9980e15d671
252e638cde99ab2aa84922a2e230511f8f0c84be
/reflib/src/BusSimpleEditForm.h
2533c94ad6807a2d6fb0cb6cf6ef062cfc327501
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
963
h
//--------------------------------------------------------------------------- #ifndef BusSimpleEditFormH #define BusSimpleEditFormH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "BusSimpleProcessForm.h" #include "VStringStorage.h" #include <ExtCtrls.hpp> //--------------------------------------------------------------------------- class TTourBusSimpleEditForm : public TTourBusSimpleProcessForm { __published: // IDE-managed Components private: // User declarations public: // User declarations __fastcall TTourBusSimpleEditForm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TTourBusSimpleEditForm *TourBusSimpleEditForm; //--------------------------------------------------------------------------- #endif
[ [ [ 1, 24 ] ] ]
0275745dd0df5c78c6731ea03a370fc6be8eabd3
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/ngeomipmap/src/ngeomipmap/ncterraingmm_cmds.cc
a6e3faa9637f5d7848e68b4e08369cacfcd8464f
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
452
cc
//------------------------------------------------------------------------------ // ncterraingmm_cmds.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "precompiled/pchngeomipmap.h" #include "ngeomipmap/ncterraingmm.h" //------------------------------------------------------------------------------ NSCRIPT_INITCMDS_BEGIN(ncTerrainGMM) NSCRIPT_INITCMDS_END()
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 10 ] ] ]
6d4d26e46072c4c564d3b9464b570c78163b24d6
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume CI/10193.cpp
afb0cad2766795a161ba4900fafb0f8faf85260c
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
719
cpp
///////////////////////////////// // 10193 - All You Need Is Love ///////////////////////////////// #include<cstdio> #include<cstring> char a[32], b[32]; unsigned int cnum,i,k,w,x,y; char lena, lenb, it; unsigned int gcd(unsigned int a, unsigned int b){ if(a) return gcd(b%a,a); return b; } int main(void){ scanf("%u\n",&cnum); for(i = 0; i != cnum;){ i++; gets(a); gets(b); for(x = 0,w = 1, it = strlen(a); it; it--) x += w*(a[it-1]-'0'),w*=2; for(y = 0,w = 1, it = strlen(b); it; it--) y += w*(b[it-1]-'0'),w*=2; if(y>x) k = gcd(x,y); else k = gcd(y,x); if(k!=1) printf("Pair #%u: All you need is love!\n",i); else printf("Pair #%u: Love is not all you need!\n",i); } return 0; }
[ [ [ 1, 30 ] ] ]
7f18512ef9a793476f61d1455c178b11f3089db9
9ef88cf6a334c82c92164c3f8d9f232d07c37fc3
/Libraries/QuickGUI/include/QuickGUITextArea.h
5eb507693972128e3724100c8dfe0ae198bf56e3
[]
no_license
Gussoh/bismuthengine
eba4f1d6c2647d4b73d22512405da9d7f4bde88a
4a35e7ae880cebde7c557bd8c8f853a9a96f5c53
refs/heads/master
2016-09-05T11:28:11.194130
2010-01-10T14:09:24
2010-01-10T14:09:24
33,263,368
0
0
null
null
null
null
UTF-8
C++
false
false
12,629
h
#ifndef QUICKGUITEXTAREA_H #define QUICKGUITEXTAREA_H #include "QuickGUIText.h" #include "QuickGUITextCursor.h" #include "QuickGUITimerManager.h" #include "QuickGUIContainerWidget.h" namespace QuickGUI { class _QuickGUIExport TextAreaDesc : public ContainerWidgetDesc { public: friend class DescFactory; protected: TextAreaDesc(); virtual ~TextAreaDesc() {} public: /// Amount of time until a cursor changes from visible to not visible, or vice versa. float textarea_cursorBlinkTime; ColourValue textarea_defaultColor; Ogre::String textarea_defaultFontName; /// Pixel Padding added to left/right side of client area, to allow drawing of text cursor float textarea_horizontalPadding; unsigned int textarea_maxCharacters; /// Sets the text to read only bool textarea_readOnly; Ogre::String textarea_textCursorDefaultSkinTypeName; /// Describes the Text used in this TextBox TextDesc textDesc; /** * Returns the class of Desc object this is. */ virtual Ogre::String getClass() { return "TextAreaDesc"; } /** * Returns the class of Widget this desc object is meant for. */ virtual Ogre::String getWidgetClass() { return "TextArea"; } /** * Restore properties to default values */ virtual void resetToDefault(); /** * Outlines how the desc class is written to XML and read from XML. */ virtual void serialize(SerialBase* b); }; class _QuickGUIExport TextArea : public ContainerWidget { public: // Skin Constants static const Ogre::String BACKGROUND; static const Ogre::String TEXTOVERLAY; // Define Skin Structure static void registerSkinDefinition(); public: friend class WidgetFactory; public: /** * Internal function, do not use. */ virtual void _initialize(WidgetDesc* d); /** * Adds a character in front of the TextCursor, and increments the TextCursor * position. */ void addCharacter(Ogre::UTFString::code_point cp); /** * Adds text to this object. */ void addText(Ogre::UTFString s, Ogre::FontPtr fp, const ColourValue& cv); /** * Adds text to this object. */ void addText(Ogre::UTFString s, const Ogre::String& fontName, const ColourValue& cv); /** * Adds text to this object. */ void addText(Ogre::UTFString s); /** * Adds Text using Text Segments. */ void addText(std::vector<TextSegment> segments); /** * Adds text to this object. */ void addTextLine(Ogre::UTFString s, Ogre::FontPtr fp, const ColourValue& cv); /** * Adds text to this object. */ void addTextLine(Ogre::UTFString s, const Ogre::String& fontName, const ColourValue& cv); /** * Adds text to this object. */ void addTextLine(Ogre::UTFString s); /** * Adds Text using Text Segments. */ void addTextLine(std::vector<TextSegment> segments); /** * Clears the Text of this widget. */ void clearText(); /** * Returns the class name of this Widget. */ virtual Ogre::String getClass(); /** * Returns the position of the index relative to the widget. */ Point getCursorIndexPosition(int index); /** * Gets the color used when adding characters to the TextBox. */ ColourValue getDefaultColor(); /** * Gets the font used when adding character to the TextBox. */ Ogre::String getDefaultFont(); /** * Gets the horizontal alignment of text. */ HorizontalTextAlignment getHorizontalAlignment(); /** * Returns the number of pixels padded on the left and right side of the TextArea, allowing * the Cursor to be drawn. (Otherwise the cursor may get partially clipped) */ float getHorizontalPadding(); /** * Returns true if the text cannot be manipulated via input, false otherwise. */ bool getReadOnly(); /** * Gets the area of the TextBox that is drawn on screen */ Rect getScreenRect(); /** * Returns the filtering used when drawing the text of this widget. */ BrushFilterMode getTextBrushFilterMode(); /** * Gets the TextCursor's skin type. */ Ogre::String getTextCursorSkinType(); /** * Gets the text in UTFString form. */ Ogre::UTFString getText(); /** * Returns a list of Text Segments. Each Text Segment has the same color and font. */ std::vector<TextSegment> getTextSegments(); /** * Returns the number of pixels placed between each line of text, if there * are multiple lines of text. */ float getVerticalLineSpacing(); /** * Returns true if the index is above the currently shown portion of text, false otherwise. */ bool isCursorIndexAboveViewableText(int index); /** * Returns true if the index is below the currently shown portion of text, false otherwise. */ bool isCursorIndexBelowViewableText(int index); /** * Returns true if the index is visible in the currently shown portion of text, false otherwise. */ bool isCursorIndexVisible(int index); /** * Moves Text Cursor to the character below the cursor. */ void moveCursorDown(); /** * Moves Text Cursor to the character to the left of the cursor. */ void moveCursorLeft(); /** * Moves Text Cursor to the character to the right of the cursor. */ void moveCursorRight(); /** * Moves Text Cursor to the character above the cursor. */ void moveCursorUp(); void onWindowDrawn(const EventArgs& args); /** * Removes a character from the text at the index given, and * positions the text cursor before that character. * NOTE: If the cursor index is -1 it will stay -1. */ void removeCharacter(int index); /** * Sets the cursor to the bottom of the text, scrolling the text into view. */ void scrollToBottom(); /** * Sets the cursor to the top of the text, scrolling the text into view. */ void scrollToTop(); /** * Sets the index of the text cursor. A cursor index represents the position * to the left of the character with the same index. -1 represents the right most * position. */ void setCursorIndex(int index); /** * Sets the color used when adding characters to the TextBox. */ void setDefaultColor(const ColourValue& cv); /** * Sets the font used when adding character to the TextBox. */ void setDefaultFont(const Ogre::String& fontName); /** * Sets all characters of the text to the specified font. */ virtual void setFont(const Ogre::String& fontName); /** * Sets the character at the index given to the specified font. */ void setFont(const Ogre::String& fontName, unsigned int index); /** * Sets all characters within the defined range to the specified font. */ void setFont(const Ogre::String& fontName, unsigned int startIndex, unsigned int endIndex); /** * Searches text for c. If allOccurrences is true, all characters of text matching c * will be changed to the font specified, otherwise only the first occurrence is changed. */ void setFont(const Ogre::String& fontName, Ogre::UTFString::code_point c, bool allOccurrences); /** * Searches text for s. If allOccurrences is true, all sub strings of text matching s * will be changed to the font specified, otherwise only the first occurrence is changed. */ void setFont(const Ogre::String& fontName, Ogre::UTFString s, bool allOccurrences); /** * Sets the horizontal alignment of text. */ void setHorizontalAlignment(HorizontalTextAlignment a); /** * Sets the number of pixels padded on the left and right side of the TextBox, allowing * the Cursor to be drawn. (Otherwise the cursor may get partially clipped) */ void setHorizontalPadding(float padding); /** * Sets the maximum number of characters that this TextBox will support. */ void setMaxCharacters(unsigned int max); /** * Internal function to set a widget's parent, updating its window reference and position. */ virtual void setParent(Widget* parent); /** * Sets the text for this object. */ void setText(Ogre::UTFString s, Ogre::FontPtr fp, const ColourValue& cv); /** * Sets the text for this object. */ void setText(Ogre::UTFString s, const Ogre::String& fontName, const ColourValue& cv); /** * Sets the text for this object. */ void setText(Ogre::UTFString s); /** * Sets the Text using Text Segments. */ void setText(std::vector<TextSegment> segments); /** * Sets the filtering used when drawing the text. */ void setTextBrushFilterMode(BrushFilterMode m); /** * Sets all characters of the text to the specified color. */ virtual void setTextColor(const ColourValue& cv); /** * Sets the character at the index given to the specified color. */ void setTextColor(const ColourValue& cv, unsigned int index); /** * Sets all characters within the defined range to the specified color. */ void setTextColor(const ColourValue& cv, unsigned int startIndex, unsigned int endIndex); /** * Searches text for c. If allOccurrences is true, all characters of text matching c * will be colored, otherwise only the first occurrence is colored. */ void setTextColor(const ColourValue& cv, Ogre::UTFString::code_point c, bool allOccurrences); /** * Searches text for s. If allOccurrences is true, all sub strings of text matching s * will be colored, otherwise only the first occurrence is colored. */ void setTextColor(const ColourValue& cv, Ogre::UTFString s, bool allOccurrences); /** * Sets the TextCursor's skin type. */ void setTextCursorSkinType(const Ogre::String& skinTypeName); /** * If set, the TextCursor will not display, and text cannot be added or removed using mouse/keyboard input. */ void setReadOnly(bool readOnly); /** * Sets the number of pixels placed between each line of text, if there * are multiple lines of text. */ void setVerticalLineSpacing(float distance); /** * Recalculate Client dimensions, relative to Widget's actual dimensions. */ virtual void updateClientDimensions(); /** * Recalculate Screen and client dimensions and force a redrawing of the widget. */ virtual void updateTexturePosition(); /** * Recalculate Virtual dimensions, the minimum size required to encapsulate the client area and all Child widgets. */ virtual void updateVirtualDimensions(); public: // Here we have to call out any protected Widget set accesors we want to expose using Widget::drag; using Widget::resize; using Widget::setConsumeKeyboardEvents; using Widget::setDimensions; using Widget::setDragable; using Widget::setHeight; using Widget::setHorizontalAnchor; using Widget::setMaxSize; using Widget::setMinSize; using Widget::setPosition; using Widget::setPositionRelativeToParentClientDimensions; using Widget::setResizeFromAllSides; using Widget::setResizeFromBottom; using Widget::setResizeFromLeft; using Widget::setResizeFromRight; using Widget::setResizeFromTop; using Widget::setScrollable; using Widget::setSerialize; using Widget::setSize; using Widget::setTransparencyPicking; using Widget::setVerticalAnchor; using Widget::setVisible; using Widget::setWidth; protected: TextArea(const Ogre::String& name); virtual ~TextArea(); Text* mText; TextCursor* mTextCursor; int mCursorIndex; Point mCursorPosition; Point _convertScreenToTextCoordinates(const Point& p); /// Position of Text, used for scrolling support Point mTextPosition; /// Storing reference to font for quick use. Ogre::FontPtr mCurrentFont; /// Timer that toggles cursor on and off. Timer* mBlinkTimer; /** * Toggles blinker on and off. */ void blinkTimerCallback(); // Pointer pointing to mWidgetDesc object, but casted for quick use. TextAreaDesc* mDesc; // Store the clip region so the cursor can be clipped properly. Rect mTextBoxClipRegion; /** * Outlines how the widget is drawn to the current render target */ virtual void onDraw(); void onCharEntered(const EventArgs& args); void onKeyDown(const EventArgs& args); void onKeyboardInputGain(const EventArgs& args); void onKeyboardInputLose(const EventArgs& args); void onMouseButtonDown(const EventArgs& args); void onTripleClick(const EventArgs& args); void onVisibleChanged(const EventArgs& args); virtual void _setScrollY(float percentage); private: }; } #endif
[ "rickardni@aefdbfa2-c794-11de-8410-e5b1e99fc78e" ]
[ [ [ 1, 417 ] ] ]
dee7f61849f47312f4ac244161e6fb3ac98f9d16
2bd485a1b68c396d80d455d1f68a052359a28fbd
/DigBuild/DigBuild/Screen.cpp
c8b47110e7358823fda97e00152201a52d17ad85
[]
no_license
dks-project-repository/dks-project-repository
f7cba5f5df207bd2a24306bf56b58587e6c395c6
8c3622b8ab173e8043557e55186b3b482a05d8bf
refs/heads/master
2021-01-10T18:45:58.502005
2011-02-28T18:37:03
2011-02-28T18:37:03
32,180,420
0
0
null
null
null
null
UTF-8
C++
false
false
2,744
cpp
#include "Screen.h" #if _WIN32 #include "wglext.h" #endif int Screen::Width = 800; int Screen::Height = 600; int Screen::FullWidth; int Screen::FullHeight; bool Screen::Fullscreen = false; Uint32 Screen::MaxFpsInverse = 1000 / 60; Screen::Screen() { SDL_Rect** modes = SDL_ListModes(NULL, SDL_OPENGL | SDL_FULLSCREEN); for (int i = 0; modes[i] != 0; i++) { if (modes[i]->w > FullWidth) FullWidth = modes[i]->w; if (modes[i]->h > FullHeight) FullHeight = modes[i]->h; } } bool Screen::Resize() { int w = Fullscreen ? FullWidth : Width; int h = Fullscreen ? FullHeight : Height; if (SDL_SetVideoMode(w, h, 32, SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE | (Fullscreen ? SDL_FULLSCREEN : 0)) == NULL) return false; glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, static_cast<double>(w) / static_cast<double>(h), 0.1, 1000.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); if(glGetError() != GL_NO_ERROR) return false; return true; } void Screen::HandleInput(const SDL_Event& event) { if (event.type == SDL_RESIZABLE) { Width = event.resize.w; Height = event.resize.h; Resize(); } else if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_f: Fullscreen = !Fullscreen; Resize(); break; case SDLK_v: ToggleVsync(); break; case SDLK_EQUALS: MaxFpsInverse /= 2; if (MaxFpsInverse == 0) { MaxFpsInverse = 1; } break; case SDLK_MINUS: MaxFpsInverse *= 2; break; } } } void Screen::ToggleVsync() { #if _WIN32 // http://stackoverflow.com/questions/589064/how-to-enable-vertical-sync-in-opengl // this is pointer to function which returns pointer to string with list of all wgl extensions PFNWGLGETEXTENSIONSSTRINGEXTPROC _wglGetExtensionsStringEXT = NULL; // determine pointer to wglGetExtensionsStringEXT function _wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT"); if (strstr(_wglGetExtensionsStringEXT(), "WGL_EXT_swap_control") == NULL) { // not found return; } // Extension is supported, init pointers. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL; PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = NULL; wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT"); wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) wglGetProcAddress("wglGetSwapIntervalEXT"); wglSwapIntervalEXT(!wglGetSwapIntervalEXT()); #endif }
[ "sbarnett87@28314c55-5b4b-0410-b444-2fc7fe15ad56" ]
[ [ [ 1, 109 ] ] ]
a2a3f84119c80d3e97d491650feef87295f03873
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/wave/test/testwave/testfiles/t_6_030.hpp
c0cdcc83b6816e997c653bddf3383a27e2317d6d
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,328
hpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) The tests included in this file were initially taken from the mcpp V2.5 preprocessor validation suite and were modified to fit into the Boost.Wave unit test requirements. The original files of the mcpp preprocessor are distributed under the license reproduced at the end of this file. =============================================================================*/ // Tests error reporting: ill-formed group in a source file. // 17.6: Errorneous unterminated #if section in an included file. #define UNBAL2 1 #if UNBAL2 #else /*- * Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
[ "metrix@Blended.(none)" ]
[ [ [ 1, 48 ] ] ]
ab65632a71350d6f85dc827245dd0bb580868709
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_shared/shared/socket/notifypkt.h
b9a40c3e722478bfe5046cfa8e5bc02934179b14
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
818
h
#ifndef __NOTIFY_PKT__ #define __NOTIFY_PKT__ #include <time.h> #include "shared/SVectorT.h" struct NotifyRec { time_t m_ctime; BYTE m_flags; NotifyRec(time_t _ctime=0, BYTE _flags=0); void init(time_t _ctime, BYTE _flags); NotifyRec& operator= (const NotifyRec& obj); NotifyRec& operator= (int i); bool operator== (time_t _ctime) const; bool operator== (const NotifyRec& obj) const; bool operator!= (const NotifyRec& obj) const; bool operator!= (int i) const; }; class NotifyVect : public SVectorT<ULONG, NotifyRec> { public: UINT insert(ULONG _mediaid, time_t _ctime, BYTE _flags); BOOL update(ULONG _mediaid, time_t _ctime); BOOL update(ULONG _mediaid, time_t _ctime, BYTE _flags); }; #endif //__NOTIFY_PKT__
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 37 ] ] ]
23ca8550d5f17826f05d1b45ebc716020b6ccfc3
50a99f63bb5bd82fca78efb9dd0bedec9a08fdef
/inc/Accelerometer.h
5cfb4903eb1b23f878f7e97bd865a56990e48d3d
[]
no_license
gonet/phonegap-bada
360d24a2a93b274e40be0157054e6a864241f262
1a5d4daf981f832a5c5224147f592f2cb39437ad
refs/heads/master
2016-09-06T03:30:26.279921
2011-03-09T23:22:23
2011-03-09T23:22:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
701
h
/* * Accelerometer.h * * Created on: Mar 8, 2011 * Author: Anis Kadri */ #ifndef ACCELEROMETER_H_ #define ACCELEROMETER_H_ #include "PhoneGapCommand.h" #include "FUix.h" using namespace Osp::Uix; class Accelerometer: public PhoneGapCommand, ISensorEventListener { public: Accelerometer(); Accelerometer(Web* pWeb, ArrayList* settings); virtual ~Accelerometer(); public: virtual void Run(const String& command); bool StartSensor(void); bool StopSensor(void); bool IsStarted(void); void OnDataReceived(SensorType sensorType, SensorData& sensorData, result r); private: SensorManager __sensorMgr; bool started; }; #endif /* ACCELEROMETER_H_ */
[ [ [ 1, 33 ] ] ]
a2665c6cfc4855eebb51f4e2b69d348ba8ac663b
0799179a3ee04268f474819d1d13f57cb8f78a4e
/bk/APIDSAA/ch5_binary_tree/BST/BSTDict.cc
143ecf2627debc9c8467b0317f1400073ba55828
[]
no_license
brianm6/jcyangs-alg-trunk
5089185cf1554f7069cc43e86eebffdb8d6e4eec
b9cccc0de6e7eaf11f9f03e3a2c4abc3f24c2c89
refs/heads/master
2020-04-06T05:23:02.591366
2010-02-26T02:54:15
2010-02-26T02:54:15
32,643,574
0
0
null
null
null
null
UTF-8
C++
false
false
560
cc
// Module Name: BSTDict.cc // Objective: demonstrate the usage of the generic BSTDic implementation // Author: jcyang[at]ymail.com // Date: 28.Jan.2010 // Revision: alpha #include <string> #include "BSTDict.h" #include "Comp.h" using namespace std; int main() { int size; string* keyArr, valArr; int method; cout << "dict size = "; cin >> size; cout << endl; cout << "manual(0) or random(1) = "; cin >> method; if (method == 0) { keyArr = new string[ BSTDict dict<string, StringComparator, string, StringComparator>(
[ "jcyangzh@18ebaf90-01a2-11df-b136-7f7962f7bc17" ]
[ [ [ 1, 26 ] ] ]
7cab8c7794ec07a1d1baa481877a64a00c2844ca
7fae7848ccc0644e2b0a85804c989603c4a850c4
/Season4/Source/Config/MoveReq.cpp
064adc699105b2d8b46f6a6d23020ba6728c07e9
[]
no_license
brunohkbx/pendmu-server
9a67a08b812517a9ac7dc35dddef4770c362ee9a
2ff144a75739db45755a6bfba2dba8ee6ad28728
refs/heads/master
2021-01-21T12:03:32.243128
2010-10-10T17:01:29
2010-10-10T17:01:29
39,051,181
1
1
null
null
null
null
UTF-8
C++
false
false
8,946
cpp
#include "stdafx.h" #include "movereq.h" #include "WzMemScript.h" #include "Log.h" #include "GameServer.h" #include "Utils.h" CMoveSystem g_MoveReq; void CMoveSystem::Init() { for(int i=0;i<MAX_MOVES;i++) { this->m_MoveData[i].iIndex = 0; this->m_MoveData[i].iMoney = 0; this->m_MoveData[i].iLevel = 0; this->m_MoveData[i].iGate = 0; } } void CMoveSystem::InitGate() { for(int i=0;i<MAX_GATES;i++) { this->m_GateData[i].iIndex = 0; this->m_GateData[i].iType = 0; this->m_GateData[i].iMapNum = 0; this->m_GateData[i].iX1 = 0; this->m_GateData[i].iY1 = 0; this->m_GateData[i].iX2 = 0; this->m_GateData[i].iY2 = 0; this->m_GateData[i].iTarget = 0; this->m_GateData[i].iDir = 0; this->m_GateData[i].iLevel = 0; } } void CMoveSystem::LoadFile(char *filename) { this->Init(); if((SMDFile = fopen(filename, "r")) == NULL) { MessageBoxA(0,"CMoveManager::LoadFile() error","CRITICAL ERROR",0); ExitProcess(1); return; } SMDToken Token; int iIndex; char szMoveKor[40] = {0}; char szMoveEng[40] = {0}; int iMoney = 0; int iLevel = 0; int iGate = 0; int MoveReqs = 0; while(true) { Token = GetToken(); if(MoveReqs == 255) break; iIndex = TokenNumber; Token = GetToken(); memcpy(szMoveKor,TokenString,sizeof(szMoveKor)); Token = GetToken(); memcpy(szMoveEng,TokenString,sizeof(szMoveEng)); Token = GetToken(); iMoney = TokenNumber; Token = GetToken(); iLevel = TokenNumber; Token = GetToken(); iGate = TokenNumber; //Log.outInfo("%d '%s' '%s' %d %d %d",iIndex,szMoveKor,szMoveEng,iMoney,iLevel,iGate); this->Insert(iIndex,szMoveKor,szMoveEng,iMoney,iLevel,iGate); MoveReqs++; } fclose(SMDFile); conLog.ConsoleOutput("[Pendulum] File [%s] is Loaded",filename); return; } void CMoveSystem::LoadGate(char *filename) { this->InitGate(); if((SMDFile = fopen(filename, "r")) == NULL) { MessageBoxA(0,"g_MoveManager::LoadGate() error","CRITICAL ERROR",0); ExitProcess(1); return; } SMDToken Token; int iIndex; int iType = 0; int iMapNum = 0; int iX1 = 0; int iY1 = 0; int iX2 = 0; int iY2 = 0; int iTarget = 0; int iDir = 0; int iLevel = 0; int GateReqs = 0; while(true) { Token = GetToken(); if(GateReqs == 290) break; iIndex = TokenNumber; Token = GetToken(); iType = TokenNumber; Token = GetToken(); iMapNum = TokenNumber; Token = GetToken(); iX1 = TokenNumber; Token = GetToken(); iY1 = TokenNumber; Token = GetToken(); iX2 = TokenNumber; Token = GetToken(); iY2 = TokenNumber; Token = GetToken(); iTarget = TokenNumber; Token = GetToken(); iDir = TokenNumber; Token = GetToken(); iLevel = TokenNumber; //Log.outInfo("%d %d %d %d %d %d %d %d %d %d",iIndex,iType,iMapNum,iX1,iY1,iX2,iY2,iTarget,iDir,iLevel); this->InsertGate(iIndex,iType,iMapNum,iX1,iY1,iX2,iY2,iTarget,iDir,iLevel); GateReqs++; } fclose(SMDFile); conLog.ConsoleOutput("[Pendulum] File [%s] is Loaded",filename); return; } void CMoveSystem::InsertGate(int iIndex,int iType,int iMapNum,int iX1,int iY1,int iX2,int iY2,int iTarget,int iDir,int iLevel) { this->m_GateData[iIndex].iIndex = iIndex; this->m_GateData[iIndex].iType = iType; this->m_GateData[iIndex].iMapNum = iMapNum; this->m_GateData[iIndex].iX1 = iX1; this->m_GateData[iIndex].iY1 = iY1; this->m_GateData[iIndex].iX2 = iX2; this->m_GateData[iIndex].iY2 = iY2; this->m_GateData[iIndex].iTarget = iTarget; this->m_GateData[iIndex].iDir = iDir; this->m_GateData[iIndex].iLevel = iLevel; } void CMoveSystem::Insert(int iIndex,char *szMoveKor,char *szMoveEng, int iMoney,int iLevel,int iGate) { this->m_MoveData[iIndex].iIndex = iIndex; strcpy(this->m_MoveData[iIndex].szMoveKor,szMoveKor); strcpy(this->m_MoveData[iIndex].szMoveEng,szMoveEng); this->m_MoveData[iIndex].iMoney = iMoney; this->m_MoveData[iIndex].iLevel = iLevel; this->m_MoveData[iIndex].iGate = iGate; } void CMoveSystem::MoveTeleport(int aIndex,char *MapName) { GOBJSTRUCT *gObj = (GOBJSTRUCT*)OBJECT_POINTER(aIndex); for(int i=0;i<MAX_MOVES;i++) { if(!_strcmpi(MapName, this->m_MoveData[i].szMoveEng)) { int TeleportMap; int iError = 0; //Messages.outNormal(aIndex,"Finded %s %d",MapName,i); if(this->m_GateData[this->m_MoveData[i].iGate].iX1 == this->m_GateData[this->m_MoveData[i].iGate].iX2) this->m_GateData[this->m_MoveData[i].iGate].iX2++; if(this->m_GateData[this->m_MoveData[i].iGate].iY1 == this->m_GateData[this->m_MoveData[i].iGate].iY2) this->m_GateData[this->m_MoveData[i].iGate].iY2++; int FinalX = min(this->m_GateData[this->m_MoveData[i].iGate].iX1,this->m_GateData[this->m_MoveData[i].iGate].iX2)+rand()%(max(this->m_GateData[this->m_MoveData[i].iGate].iX1,this->m_GateData[this->m_MoveData[i].iGate].iX2)-min(this->m_GateData[this->m_MoveData[i].iGate].iX1,this->m_GateData[this->m_MoveData[i].iGate].iX2)); int FinalY = min(this->m_GateData[this->m_MoveData[i].iGate].iY1,this->m_GateData[this->m_MoveData[i].iGate].iY2)+rand()%(max(this->m_GateData[this->m_MoveData[i].iGate].iY1,this->m_GateData[this->m_MoveData[i].iGate].iY2)-min(this->m_GateData[this->m_MoveData[i].iGate].iY1,this->m_GateData[this->m_MoveData[i].iGate].iY2)); #ifdef Season5 if(IsExistWingItem(aIndex) == 65535 && this->m_GateData[this->m_MoveData[i].iGate].iMapNum == 10) { //return no wings gObjTeleport(aIndex, gObj->MapNumber, gObj->X,gObj->Y); iError = 1; } if(iError == 1) { if(IsExistPetItem(aIndex) != 6659 && this->m_GateData[this->m_MoveData[i].iGate].iMapNum == 10) { //return no dinorant Messages.outNormal(aIndex,"You are currently not able to warp."); gObjTeleport(aIndex, gObj->MapNumber, gObj->X,gObj->Y); iError = 0; return; } } #endif if(gObj->Level < this->m_MoveData[i].iLevel) { Messages.outNormal(aIndex,"You need %d level to warp. %d",this->m_MoveData[i].iLevel,gObj->Level); return; } if(gObj->Money < this->m_MoveData[i].iMoney) { Messages.outNormal(aIndex,"Not enought zen."); return; } gObj->Money -= this->m_MoveData[i].iMoney; GCMoneySend(aIndex,gObj->Money); TeleportMap = this->m_GateData[this->m_MoveData[i].iGate].iMapNum; gObjTeleport(aIndex, TeleportMap, FinalX,FinalY); } } } void CMoveSystem::Teleport(int aIndex, int MovNum) { GOBJSTRUCT *gObj = (GOBJSTRUCT*)OBJECT_POINTER(aIndex); int TeleportMap; int iError = 0; if(this->m_GateData[this->m_MoveData[MovNum].iGate].iX1 == this->m_GateData[this->m_MoveData[MovNum].iGate].iX2) this->m_GateData[this->m_MoveData[MovNum].iGate].iX2++; if(this->m_GateData[this->m_MoveData[MovNum].iGate].iY1 == this->m_GateData[this->m_MoveData[MovNum].iGate].iY2) this->m_GateData[this->m_MoveData[MovNum].iGate].iY2++; int FinalX = min(this->m_GateData[this->m_MoveData[MovNum].iGate].iX1,this->m_GateData[this->m_MoveData[MovNum].iGate].iX2)+rand()%(max(this->m_GateData[this->m_MoveData[MovNum].iGate].iX1,this->m_GateData[this->m_MoveData[MovNum].iGate].iX2)-min(this->m_GateData[this->m_MoveData[MovNum].iGate].iX1,this->m_GateData[this->m_MoveData[MovNum].iGate].iX2)); int FinalY = min(this->m_GateData[this->m_MoveData[MovNum].iGate].iY1,this->m_GateData[this->m_MoveData[MovNum].iGate].iY2)+rand()%(max(this->m_GateData[this->m_MoveData[MovNum].iGate].iY1,this->m_GateData[this->m_MoveData[MovNum].iGate].iY2)-min(this->m_GateData[this->m_MoveData[MovNum].iGate].iY1,this->m_GateData[this->m_MoveData[MovNum].iGate].iY2)); /* if(gObj->m_PK_Level > 3) { Messages.outNormal(aIndex,"PK can't use warp menu"); return; }*/ #ifdef Season5 if(IsExistWingItem(aIndex) == 65535 && this->m_GateData[this->m_MoveData[MovNum].iGate].iMapNum == 10) { //return no wings gObjTeleport(aIndex, gObj->MapNumber, gObj->X,gObj->Y); iError = 1; } if(iError == 1) { if(IsExistPetItem(aIndex) != 6659 && this->m_GateData[this->m_MoveData[MovNum].iGate].iMapNum == 10) { //return no dinorant Messages.outNormal(aIndex,"You are currently not able to warp."); gObjTeleport(aIndex, gObj->MapNumber, gObj->X,gObj->Y); iError = 0; return; } } #endif if(gObj->Level < this->m_MoveData[MovNum].iLevel) { Messages.outNormal(aIndex,"You need %d level to warp. %d",this->m_MoveData[MovNum].iLevel,gObj->Level); return; } if(gObj->Money < this->m_MoveData[MovNum].iMoney) { Messages.outNormal(aIndex,"Not enought zen."); return; } gObj->Money -= this->m_MoveData[MovNum].iMoney; GCMoneySend(aIndex,gObj->Money); TeleportMap = this->m_GateData[this->m_MoveData[MovNum].iGate].iMapNum; gObjTeleport(aIndex, TeleportMap, FinalX,FinalY); }
[ "hackeralin@9c614f3a-9621-f771-f2fc-7608378cfbb4" ]
[ [ [ 1, 305 ] ] ]
0752e5aad88b7798cd3a16e33fdda79d13a4be72
c9f274dcf30c4a1911e39bc96190a810bb4216bc
/URLResolver/urlresolver.cpp
9146764618239a7e4770a618aaf5106dc0cc6021
[]
no_license
beatgammit/cs240
e88d054b3b9c489dfabc107351ded4a692f47015
8acd99469259d5fdb34ad5d43c8c82c02437ac73
refs/heads/master
2023-08-31T06:28:02.494209
2011-04-12T19:42:26
2011-04-12T19:42:26
1,467,628
0
1
null
null
null
null
UTF-8
C++
false
false
631
cpp
#include "urlresolver.h" #include "stdio.h" #include "string.h" URLResolver::URLResolver(){ } void URLResolver::resolve(URL* baseURL, char* relativeURL, char** output){ int iIndex = 0; URL tURL(baseURL, relativeURL[0] == '#'); if(relativeURL[0] == '/'){ // we're starting from the base tURL.killPath(); iIndex++; } if(relativeURL[0] != '#' && relativeURL[0] != '?'){ tURL.removeFilename(); } char* token = strtok(&relativeURL[iIndex], "/"); while(token){ tURL.updateURL(token); token = strtok(NULL, "/"); } tURL.toString(output); } URLResolver::~URLResolver(){ if(baseURL){ delete baseURL; } }
[ "jameson@ubun64-lap.(none)" ]
[ [ [ 1, 33 ] ] ]
25b9cb0361dbb3b54b413db90a9c59d28eae881a
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume CVIII/10852.cpp
0d8a66677eda9e87cbf02e661c491e889a0d86f8
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
593
cpp
///////////////////////////////// // 10852 - Less Prime ///////////////////////////////// #include<cstdio> #include<cstring> bool sieve[5005]; unsigned short int i,j; unsigned int cnum,lim,n; int main(void){ memset(sieve,1,sizeof(sieve)); sieve[0] = sieve[1] = 0; for(i = 4; i < 5005; i+=2) sieve[i] = 0; for(i = 3; i < 70; i+=2) if(sieve[i]) for(j = i*i; j < 5005; j+=i) sieve[j] = 0; scanf("%u",&cnum); while(cnum--){ scanf("%u",&n); if(n&1) lim = ((n+1)>>1); else lim = ((n+2)>>1); if(!(lim&1)) lim++; while(!sieve[lim]) lim+=2; printf("%u\n",lim); } return 0; }
[ [ [ 1, 26 ] ] ]
a6ee2032237b31f691ea2f2cca39348d179aeacc
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/property_map/example1.cpp
806c23e53218582db7d3bd3488160f3bdc0cc2f3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,471
cpp
// (C) Copyright Jeremy Siek 2002. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <map> #include <string> #include <boost/property_map.hpp> template <typename AddressMap> void foo(AddressMap address) { typedef typename boost::property_traits<AddressMap>::value_type value_type; typedef typename boost::property_traits<AddressMap>::key_type key_type; value_type old_address, new_address; key_type fred = "Fred"; old_address = get(address, fred); new_address = "384 Fitzpatrick Street"; put(address, fred, new_address); key_type joe = "Joe"; value_type& joes_address = address[joe]; joes_address = "325 Cushing Avenue"; } int main() { std::map<std::string, std::string> name2address; boost::associative_property_map< std::map<std::string, std::string> > address_map(name2address); name2address.insert(make_pair(std::string("Fred"), std::string("710 West 13th Street"))); name2address.insert(make_pair(std::string("Joe"), std::string("710 West 13th Street"))); foo(address_map); for (std::map<std::string, std::string>::iterator i = name2address.begin(); i != name2address.end(); ++i) std::cout << i->first << ": " << i->second << "\n"; return EXIT_SUCCESS; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 48 ] ] ]
074f4ce0061b5b7311c8836e9ccce2fcaad961db
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Approximation/Wm4ApprEllipseFit2.cpp
870d5b3d1eb9f590f5056a1334519c6c009bdf88
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
4,037
cpp
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4ApprEllipseFit2.h" #include "Wm4ContBox2.h" #include "Wm4DistVector2Ellipse2.h" #include "Wm4MinimizeN.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> EllipseFit2<Real>::EllipseFit2 (int iQuantity, const Vector2<Real>* akPoint, Vector2<Real>& rkU, Matrix2<Real>& rkR, Real afD[2], Real& rfError) { // Energy function is E : R^5 -> R where // V = (V0,V1,V2,V3,V4) // = (D[0],D[1],U.x,U,y,atan2(R[1][0],R[1][1])). m_iQuantity = iQuantity; m_akPoint = akPoint; m_akTemp = WM4_NEW Vector2<Real>[iQuantity]; MinimizeN<Real> kMinimizer(5,Energy,8,8,32,this); InitialGuess(iQuantity,akPoint,rkU,rkR,afD); Real fAngle = Math<Real>::ACos(rkR[0][0]); Real fE0 = afD[0]*Math<Real>::FAbs(rkR[0][0]) + afD[1]*Math<Real>::FAbs(rkR[0][1]); Real fE1 = afD[0]*Math<Real>::FAbs(rkR[1][0]) + afD[1]*Math<Real>::FAbs(rkR[1][1]); Real afV0[5] = { ((Real)0.5)*afD[0], ((Real)0.5)*afD[1], rkU.X() - fE0, rkU.Y() - fE1, (Real)0.0 }; Real afV1[5] = { ((Real)2.0)*afD[0], ((Real)2.0)*afD[1], rkU.X() + fE0, rkU.Y() + fE1, Math<Real>::PI }; Real afVInitial[5] = { afD[0], afD[1], rkU.X(), rkU.Y(), fAngle }; Real afVMin[5]; kMinimizer.GetMinimum(afV0,afV1,afVInitial,afVMin,rfError); afD[0] = afVMin[0]; afD[1] = afVMin[1]; rkU.X() = afVMin[2]; rkU.Y() = afVMin[3]; rkR.FromAngle(afVMin[4]); WM4_DELETE[] m_akTemp; } //---------------------------------------------------------------------------- template <class Real> void EllipseFit2<Real>::InitialGuess (int iQuantity, const Vector2<Real>* akPoint, Vector2<Real>& rkU, Matrix2<Real>& rkR, Real afD[2]) { Box2<Real> kBox = ContOrientedBox(iQuantity,akPoint); rkU = kBox.Center; rkR[0][0] = kBox.Axis[0].X(); rkR[0][1] = kBox.Axis[0].Y(); rkR[1][0] = kBox.Axis[1].X(); rkR[1][1] = kBox.Axis[1].Y(); afD[0] = kBox.Extent[0]; afD[1] = kBox.Extent[1]; } //---------------------------------------------------------------------------- template <class Real> Real EllipseFit2<Real>::Energy (const Real* afV, void* pvData) { EllipseFit2& rkSelf = *(EllipseFit2*)pvData; // build rotation matrix Matrix2<Real> kRot(afV[4]); Ellipse2<Real> kEllipse(Vector2<Real>::ZERO,Vector2<Real>::UNIT_X, Vector2<Real>::UNIT_Y,afV[0],afV[1]); // transform the points to the coordinate system of U and R Real fEnergy = (Real)0.0; for (int i = 0; i < rkSelf.m_iQuantity; i++) { Vector2<Real> kDiff( rkSelf.m_akPoint[i].X() - afV[2], rkSelf.m_akPoint[i].Y() - afV[3]); rkSelf.m_akTemp[i] = kDiff*kRot; Real fDist = DistVector2Ellipse2<Real>(rkSelf.m_akTemp[i],kEllipse).Get(); fEnergy += fDist; } return fEnergy; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class EllipseFit2<float>; template WM4_FOUNDATION_ITEM class EllipseFit2<double>; //---------------------------------------------------------------------------- }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 134 ] ] ]
84386baec05efa41ee52540fda9f0a14423ddca9
b5ab57edece8c14a67cc98e745c7d51449defcff
/Captain's Log/MainGame/Source/GameObjects/CHUD.h
87ba264ebbd63c19b3de8cf376b58aa4b6534662
[]
no_license
tabu34/tht-captainslog
c648c6515424a6fcdb628320bc28fc7e5f23baba
72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2
refs/heads/master
2020-05-30T15:09:24.514919
2010-07-30T17:05:11
2010-07-30T17:05:11
32,187,254
0
0
null
null
null
null
UTF-8
C++
false
false
446
h
#ifndef CHUD_h__ #define CHUD_h__ #include "..\Managers\CCamera.h" #include <string> #include "CBMPFont.h" using namespace std; class CHUD { int m_nHUDImageID; int m_nMarkerImageID; int** m_nCharacterHealth; string m_strDialogue; CBMPFont m_cFont; public: void Setup(int* nC1Health, int* nC2Health, int* nC3Health, int* nC4Health); void Update(float fElapsedTime); void Render(); }; #endif // CHUD_h__
[ "notserp007@34577012-8437-c882-6fb8-056151eb068d" ]
[ [ [ 1, 23 ] ] ]