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
a606db813d56ca765ef19d161b2d3dd9097cab50
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/FontViewer/DemoKeeper.h
0fe1d728bf06028b86c398a33116566e0ec80b44
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
476
h
/*! @file @author Albert Semenov @date 09/2008 */ #ifndef __DEMO_KEEPER_H__ #define __DEMO_KEEPER_H__ #include "BaseManager.h" #include "FontPanel.h" namespace demo { class DemoKeeper : public base::BaseManager { public: DemoKeeper(); virtual void createScene(); virtual void destroyScene(); private: virtual void setupResources(); private: FontPanel* mFontPanel; }; } // namespace demo #endif // __DEMO_KEEPER_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 32 ] ] ]
b9a39f93568002afe959684a4b36420c4785726a
7e68ef369eff945f581e22595adecb6b3faccd0e
/code/minifw/eventhandler.cpp
ead2d008f5e40b34bc96fd70503a9a8c71fb0c7d
[]
no_license
kimhmadsen/mini-framework
700bb1052227ba18eee374504ff90f41e98738d2
d1983a68c6b1d87e24ef55ca839814ed227b3956
refs/heads/master
2021-01-01T05:36:55.074091
2008-12-16T00:33:10
2008-12-16T00:33:10
32,415,758
0
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
#include "StdAfx.h" #include "eventhandler.h" EventHandler::EventHandler(void) { } EventHandler::~EventHandler(void) { } HANDLE EventHandler::GetHandle(void) { return handle; } void EventHandler::SetHandle(HANDLE handle) { this->handle = handle; }
[ "kim.hedegaard.madsen@77f6bdef-6155-0410-8b08-fdea0229669f", "[email protected]@77f6bdef-6155-0410-8b08-fdea0229669f" ]
[ [ [ 1, 15 ], [ 21, 21 ] ], [ [ 16, 20 ] ] ]
eb37d7498f782c6048c066db0392ec23fe89f187
ee2e06bda0a5a2c70a0b9bebdd4c45846f440208
/c++/Pattern/Source/FlyWeight/Main.cpp
c63b8bc924158bbff76f3bbe6e10c28ae8d41df7
[]
no_license
RobinLiu/Test
0f53a376e6753ece70ba038573450f9c0fb053e5
360eca350691edd17744a2ea1b16c79e1a9ad117
refs/heads/master
2021-01-01T19:46:55.684640
2011-07-06T13:53:07
2011-07-06T13:53:07
1,617,721
2
0
null
null
null
null
GB18030
C++
false
false
541
cpp
/******************************************************************** created: 2006/07/26 filename: Main.cpp author: 李创 http://www.cppblog.com/converse/ purpose: FlyWeight模式的测试代码 *********************************************************************/ #include "FlyWeight.h" int main() { FlyweightFactory flyweightfactory; flyweightfactory.GetFlyweight("hello"); flyweightfactory.GetFlyweight("world"); flyweightfactory.GetFlyweight("hello"); system("pause"); return 0; }
[ "[email protected]@43938a50-64aa-11de-9867-89bd1bae666e" ]
[ [ [ 1, 21 ] ] ]
2a470368daacc198ccce52a1aec86cc528f9085c
f978424f35fd0fb95bc8cd17466cb2b86ce7d04c
/GraphicsProject/src/graphics/graphics_zbuffer.h
c5b00224d13e0951a2e3990092c61203c49e0200
[]
no_license
omegahm/FoundationOfGraphics
9efadf3bc2a228c6867d71640858daf87efa98fc
a221589c38ff6d8b4c97c4fe182599046c0d8087
refs/heads/master
2021-01-22T02:34:50.483751
2010-03-08T19:47:00
2010-03-08T19:47:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,868
h
#ifndef GRAPHICS_ZBUFFER_H #define GRAPHICS_ZBUFFER_H // // Graphics Framework. // Copyright (C) 2007 Department of Computer Science, University of Copenhagen // // Overhauled by kaiip dec 17, 2009. // #include <iostream> #include <iomanip> #include <stdexcept> #include <vector> #include <algorithm> #include "graphics_state.h" namespace graphics { /** * A Z-Buffer. * A z-buffer is basically a 2D array of z-values. * Each row of the 2D array has ``width'' values and each column has ''height'' values. * Notice that the (0,0) entry of the array corresponds to the lower-left corner * on the ``screen'' (width-1,height-1) location corresponds to the upper right corner. */ template< typename math_types > class ZBuffer { public: /** * The basic type which is the the type of the elements of vectors and matrices. */ typedef typename math_types::real_type real_type; /** * A vector with 3 entries both of type real_type. */ typedef typename math_types::vector3_type vector3_type; protected: std::vector<float> m_values; ///< The Z-values. A row format is adopted. int m_width; ///< The number of pixels in a row. int m_height; ///< The number of pixels in a column. public: /** * Clear Z Buffer. * This method should be used to setup the z-buffer before * doing any kind of drawing. * * @param clear_value The value to be used to clear the buffer. Must be in the interval [0..1] otherwise an exception is thrown. * */ void clear(real_type const& clear_value) { #ifdef KENNY_ZBUFFER // Original Kenny if (clear_value < 0 || clear_value > 1) { throw std::invalid_argument("graphics_zbuffer::clear(real_type&): clear value must be in [0..1]"); } std::fill(m_values.begin(), m_values.end(), clear_value); #else // Changed by kaiip 06.12.2008 - 01:44 if (clear_value > 0 || clear_value < -1) { throw std::invalid_argument("graphics_zbuffer::clear(real_type&): clear value must be in [-1..0]"); } std::fill(m_values.begin(), m_values.end(), clear_value); #endif } /** * Set Resolution. * * @param width The number of pixels in a row. Must be larger than 1 otherwise an exception is thrown. * @param height The number of pixels in a colum. Must be larger than 1 otherwise an exception is thrown. */ void set_resolution(int width, int height) { if (width <= 1) throw std::invalid_argument("graphics_zbuffer::set_resolution: width must be larger than 1"); if (height <= 1) throw std::invalid_argument("graphics_zbuffer::set_resolution: height must be larger than 1"); m_values.resize(width*height); m_width = width; m_height = height; } /** * Write Z-value. * * @param x The current x location of the pixel. Must be within [0..width-1] otherwise an exception is thrown. * @param y The current y location of the pixel. Must be within [0..height-1] otherwise an exception is thrown. * @param value The z-value to be written. Must be in the interval [0..1] otherwise an exception is thrown. * */ void write(int x, int y, real_type const& z_value) { //--- Test to see if we actually got a real depth value #ifdef KENNY_ZBUFFER if (z_value < 0 || z_value > 1) throw std::invalid_argument("graphics_zbuffer::write: depth must be within [0...1]"); #else if (z_value > 0 || z_value < -1) throw std::invalid_argument("graphics_zbuffer::write: depth must be within [-1...0]"); #endif //--- Simple minded clipping against framebuffer if (x < 0) return; if (y < 0) return; if (x >= m_width) return; if(y >= m_height) return; //--- Determine memory location of the pixel that should be written int offset = (y * m_width + x); //--- Wtite the pixel to the frame buffer m_values[offset] = z_value; } /** * Read Z-value. * * @param x The current x location of the pixel. Must be within [0..width-1] otherwise an exception is thrown. * @param y The current y location of the pixel. Must be within [0..height-1] otherwise an exception is thrown. * */ real_type const& read(int x, int y) const { static real_type const off_screen = 0.0; //--- Simple minded clipping against framebuffer if (x < 0) return off_screen; if (y < 0) return off_screen; if (x >= m_width) return off_screen; if (y >= m_height) return off_screen; //--- Determine memory location of the z-value int offset = (y * m_width + x); return m_values[offset]; } }; }// end namespace graphics // GRAPHICS_ZBUFFER_H #endif
[ [ [ 1, 161 ] ] ]
6fcde92f88011b7fde7d3726621c19e445eade9c
1dba10648f60dea02c9be242c668f3488ae8dec4
/program/src/previewwidget.cpp
f75d2200600b011660eb5939b7cac509ed51780c
[]
no_license
hateom/si-air
f02ffc8ba9fac9777d12a40627f06044c92865f0
2094c98a04a6785078b4c8bcded8f8b4450c8b92
refs/heads/master
2021-01-15T17:42:12.887029
2007-01-21T17:48:48
2007-01-21T17:48:48
32,139,237
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
cpp
#include "previewwidget.h" #include <qtimer.h> #include <qlabel.h> ////////////////////////////////////////////////////////////////////////// previewWidget::previewWidget( preview * p, QWidget* parent, const char* name, WFlags f ) : prv(p), QWidget(parent, name, f ) { update_timer = new QTimer(); connect( update_timer, SIGNAL(timeout()), this, SLOT(on_timer()) ); update_timer->start( p->update_rate ); label = new QLabel( this, "label" ); label->setGeometry( QRect( 0, 0, 180, 24 ) ); } ////////////////////////////////////////////////////////////////////////// previewWidget::~previewWidget() { update_timer->stop(); delete update_timer; update_timer = NULL; } ////////////////////////////////////////////////////////////////////////// void previewWidget::on_timer() { static char buffer[256]; switch( prv->type ) { case PT_INT: case PT_BOOL: sprintf( buffer, "%d", *(int*)prv->ptr ); break; case PT_LONG: sprintf( buffer, "%ld", *(long*)prv->ptr ); break; case PT_FLOAT: case PT_DOUBLE: sprintf( buffer, "%3.2f", *(float*)prv->ptr ); break; } label->setText( tr(buffer) ); } //////////////////////////////////////////////////////////////////////////
[ "tomasz.huczek@9b5b1781-be22-0410-ac8e-a76ce1d23082" ]
[ [ [ 1, 49 ] ] ]
cbaa4afea07b360e04dc759f91c2a960119345b0
bcbe36507f65b110e91ae676b664705ea1c4fad7
/ cudaandmfc --username ct.radiate/CUDAD3DDisplay.h
5282213ba3b4ebf01466ffad4104008eb86a7c97
[]
no_license
kimjinchoul/cudaandmfc
7d22f968aa325823ca2b466daf1287d21a068908
3237b553b5cb212b0d74e54558afcd89c7e4636b
refs/heads/master
2020-12-24T15:32:19.590406
2008-12-17T09:08:50
2008-12-17T09:08:50
33,848,804
0
0
null
null
null
null
UTF-8
C++
false
false
3,619
h
#pragma once #pragma comment( lib, "dxerr.lib" ) #pragma comment( lib, "dxguid.lib" ) #if defined(DEBUG) || defined(_DEBUG) #pragma comment( lib, "d3dx9d.lib" ) #else #pragma comment( lib, "d3dx9.lib" ) #endif #pragma comment( lib, "d3d9.lib" ) #pragma comment( lib, "winmm.lib" ) #pragma comment( lib, "comctl32.lib" ) #pragma warning(disable:4819) //#include "PgmSlice.h" #include <d3d9.h> #include <d3dx9.h> #include <dxerr.h> //#include "CUDAUtility.h" #include "CUDAUtility.h" #define EPSILON 1e-6f typedef struct _tagStruCustomTexVertex { float fX, fY, fZ; float texfU, texfV; } StruCustomTexVertex, *LPStruCustomTexVertex; typedef struct _tagStruCustomVertex { float fX, fY, fZ; DWORD color; } StruCustomVertex, *LPStruCustomVertex; typedef struct _tagStruTextureInfo { int iTextWidth; int iTextHeight; D3DFORMAT StruTextFormat; int iPixelBytesNum; LPDIRECT3DTEXTURE9 pImageTexture; //IDirect3DTexture9 *pImageTexture; } StruTextureInfo, *LPStruTextureInfo; #define D3DFVF_CUSTOMTEXVERTEX (D3DFVF_XYZ | D3DFVF_TEX1) #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE) class CCUDAD3DDisplay { public: CCUDAD3DDisplay(void); virtual ~CCUDAD3DDisplay(void); bool InitCUDAD3DDisplay(HWND hDisplayDevice, int iTexWidth, int iTexHeight, D3DFORMAT StruTexFormat, int iPixelBytesNum); bool DisplayTexture(/*CPgmSlice *lpTexture,*/ D3DFORMAT StruTextFormat, int iPixelBytesNum); bool DisplayTexture(float fTime); bool DisplayVertex(float fTime); bool Cleanup(void); bool SetDisplayZoom(float fDisplayZoom); private: CCUDAD3DDisplay(const CCUDAD3DDisplay &ccdDisplay); CCUDAD3DDisplay& operator=(const CCUDAD3DDisplay &cddRhs); //D3D Element bool PreInit(void); bool InitD3D(void); bool PostInit(void); HRESULT PreRender(void); HRESULT Render(void); HRESULT PostRender(void); bool PreReset(void); bool PostReset(void); bool PreTerminate(void); bool PostTerminate(void); bool HandleMessage(MSG *pMessage); void SetupMatrices(void); //Function Modal void VerifyModes(void); HRESULT SetWindowedDevice(void); HRESULT CreateDevice(void); HRESULT SetupDevice(void); HRESULT RestoreDevice(void); HRESULT DestroyDevice(void); HRESULT CreateVerGeometry(void); HRESULT DestroyVerGeometry(void); HRESULT CreateTexGeometry(void); HRESULT DestroyTexGeometry(void); HRESULT CreateCUDATextures(void); HRESULT DestroyCUDATextures(void); HRESULT CreateCustomTextures(int iTextWidth, int iTextHeight, D3DFORMAT StruTextFormat, int iPixelBytesNum); HRESULT LoadTextureData(UCHAR *lpDataBuffer, int iTextWidth, int iTextHeight); HRESULT DestroyTextureObject(void); HRESULT DestroyD3D(void); //Basic Operation bool TextureSizeAdapt(int iOriginalTextWidth, int iOriginalTextHeight, int *lpAdaptedTextWidth, int *lpAdaptedTextHeight); HWND m_hDisplayWnd; float m_fDisplayZoom; //CPgmSlice *m_lpResetDataPointer; LPDIRECT3D9 m_pD3D; LPDIRECT3DDEVICE9 m_pD3DDevice; LPDIRECT3DVERTEXBUFFER9 m_pVertexBuffer; LPDIRECT3DVERTEXBUFFER9 m_pTexVertexBuffer; LPDIRECT3DTEXTURE9 m_pImageTexture; StruTextureInfo m_struCUDATextInfo; D3DXMATRIX m_struWorldMatrix; D3DXMATRIX m_struViewMatrix; D3DXMATRIX m_struProjMatrix; D3DCAPS9 m_struHALCaps; D3DDISPLAYMODE m_struCurrentMode; D3DPRESENT_PARAMETERS m_struPresentParameters; D3DDEVICE_CREATION_PARAMETERS m_struCreationParameters; int m_iControlWidth; int m_iControlHeight; int m_iMeshWidth; int m_iMeshHeight; int m_iNumVertices; //CUDA Method CCUDACLASS m_ccclass; };
[ "ct.radiate@c46f0c90-cbed-11dd-8ca8-e3ff79f713b6" ]
[ [ [ 1, 131 ] ] ]
92d828f85c1cb2d63d9a0b00acd273ffba0267f5
aab4966a757dddc72e3f52151dbfe3be6cb66a5d
/CptnCpp/xcode/CptnCpp/build/Debug/CptnCpp.app/Contents/Frameworks/Gosu.framework/Versions/A/Headers/ButtonsWin.hpp
554fc64f23f6275df1b89be99630e646b66af483
[]
no_license
jlnr/CptnCpp
a8f54d5f5af34689af13cc7991a0e573b9dfd0b9
70bbae46df6e1e65a237f5c28a02bdc3ac62eda5
refs/heads/master
2021-01-09T06:21:03.414334
2010-02-06T19:39:00
2010-02-06T19:39:00
505,425
1
1
null
null
null
null
UTF-8
C++
false
false
2,565
hpp
#ifndef GOSU_BUTTONSWIN_HPP #define GOSU_BUTTONSWIN_HPP namespace Gosu { enum ButtonName { kbRangeBegin = 1, kbEscape = 0x01, kbF1 = 0x3b, kbF2 = 0x3c, kbF3 = 0x3d, kbF4 = 0x3e, kbF5 = 0x3f, kbF6 = 0x40, kbF7 = 0x41, kbF8 = 0x42, kbF9 = 0x43, kbF10 = 0x44, kbF11 = 0x57, kbF12 = 0x58, kb0 = 0x0b, kb1 = 0x02, kb2 = 0x03, kb3 = 0x04, kb4 = 0x05, kb5 = 0x06, kb6 = 0x07, kb7 = 0x08, kb8 = 0x09, kb9 = 0x0a, kbTab = 0x0f, kbReturn = 0x1c, kbSpace = 0x39, kbLeftShift = 0x2a, kbRightShift = 0x36, kbLeftControl = 0x1d, kbRightControl = 0x9d, kbLeftAlt = 0x38, kbRightAlt = 0xb8, kbLeftMeta = 0xdb, kbRightMeta = 0xdc, kbBackspace = 0x0e, kbLeft = 0xcb, kbRight = 0xcd, kbUp = 0xc8, kbDown = 0xd0, kbHome = 0xc7, kbEnd = 0xcf, kbInsert = 0xd2, kbDelete = 0xd3, kbPageUp = 0xc9, kbPageDown = 0xd1, kbEnter = 0x9c, kbA = 0x1e, kbB = 0x30, kbC = 0x2e, kbD = 0x20, kbE = 0x12, kbF = 0x21, kbG = 0x22, kbH = 0x23, kbI = 0x17, kbJ = 0x24, kbK = 0x25, kbL = 0x26, kbM = 0x32, kbN = 0x31, kbO = 0x18, kbP = 0x19, kbQ = 0x10, kbR = 0x13, kbS = 0x1f, kbT = 0x14, kbU = 0x16, kbV = 0x2f, kbW = 0x11, kbX = 0x2d, kbY = 0x15, kbZ = 0x2c, kbNumpad0 = 0x52, kbNumpad1 = 0x4f, kbNumpad2 = 0x50, kbNumpad3 = 0x51, kbNumpad4 = 0x4b, kbNumpad5 = 0x4c, kbNumpad6 = 0x4d, kbNumpad7 = 0x47, kbNumpad8 = 0x48, kbNumpad9 = 0x49, kbNumpadAdd = 0x4e, kbNumpadSubtract = 0x4a, kbNumpadMultiply = 0x37, kbNumpadDivide = 0xb5, kbRangeEnd = 0xff, msRangeBegin, msLeft = msRangeBegin, msRight, msMiddle, msWheelUp, msWheelDown, msRangeEnd, gpRangeBegin, gpLeft = gpRangeBegin, gpRight, gpUp, gpDown, gpButton0, gpButton1, gpButton2, gpButton3, gpButton4, gpButton5, gpButton6, gpButton7, gpButton8, gpButton9, gpButton10, gpButton11, gpButton12, gpButton13, gpButton14, gpButton15, gpRangeEnd = gpButton15, kbNum = kbRangeEnd - kbRangeBegin + 1, msNum = msRangeEnd - msRangeBegin + 1, gpNum = gpRangeEnd - gpRangeBegin + 1, numButtons = gpRangeEnd, noButton = 0xffffffff }; } #endif
[ [ [ 1, 137 ] ] ]
2581636ecf3b7bf4a5873617be8bd65b6df3d828
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Engine/Source/SkyXWapper.cpp
86d0eb570e46fdf2cb108e57f9b947d338d11f79
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
2,147
cpp
#include "engpch.h" #include "SkyXWapper.h" // --------------------------------------------------------------------------- // Include SkyX header files // --------------------------------------------------------------------------- #include "SkyX.h" Kylin::SkyXWapper::SkyXWapper(Ogre::SceneManager* pSceneMnger, Ogre::Camera* pCamera) : m_pSkyX(NULL) { // Create SkyX m_pSkyX = KNEW SkyX::SkyX(pSceneMnger, pCamera); m_pSkyX->create(); // Volumetric clouds //m_pSkyX->getVCloudsManager()->create(); // No smooth fading m_pSkyX->getMeshManager()->setSkydomeFadingParameters(true); // A little change to default atmosphere settings :) SkyX::AtmosphereManager::Options atOpt = m_pSkyX->getAtmosphereManager()->getOptions(); atOpt.RayleighMultiplier = 0.0045f; atOpt.MieMultiplier = 0.00125f; atOpt.InnerRadius = 9.92f; atOpt.OuterRadius = 10.3311f; m_pSkyX->getAtmosphereManager()->setOptions(atOpt); // Add our ground atmospheric scattering pass to terrain material //Ogre::Terrain* pTer = terGroup->getTerrain(0, 0); //Ogre::MaterialPtr spMat = pTer->getMaterial(); // Add a basic cloud layer m_pSkyX->getCloudsManager()->add(SkyX::CloudLayer::Options(/* Default options */)); } Kylin::SkyXWapper::~SkyXWapper() { SAFE_CALL(m_pSkyX,remove()); SAFE_DEL(m_pSkyX); } KVOID Kylin::SkyXWapper::Tick( KFLOAT fElapsed ) { if (m_pSkyX) { m_pSkyX->setTimeMultiplier(0.001f); if (m_pSkyX->getVCloudsManager()->getVClouds()) { if (m_pSkyX->getVCloudsManager()->getVClouds()->getWindDirection().valueDegrees() < 0) { m_pSkyX->getVCloudsManager()->getVClouds()->setWindDirection(Ogre::Degree(0)); } if (m_pSkyX->getVCloudsManager()->getVClouds()->getWindDirection().valueDegrees() > 360) { m_pSkyX->getVCloudsManager()->getVClouds()->setWindDirection(Ogre::Degree(360)); } } m_pSkyX->update(fElapsed); } } KVOID Kylin::SkyXWapper::AddGroundPass( Ogre::MaterialPtr spMat ) { m_pSkyX->getGPUManager()->addGroundPass(spMat->getTechnique(0)->createPass(), 5000, Ogre::SBT_TRANSPARENT_COLOUR ); }
[ "[email protected]", "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 51 ], [ 53, 77 ] ], [ [ 52, 52 ] ] ]
a7cbdfa506fbb200684f89a74349ce2524965672
05f4bd87bd001ab38701ff8a71d91b198ef1cb72
/TPTaller/TP3/src/IncPad.h
4e7d7f8d3653d5aef72aae59e5dcd91871b6d068
[]
no_license
oscarcp777/tpfontela
ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12
2489442b81dab052cf87b6dedd33cbb51c2a0a04
refs/heads/master
2016-09-01T18:40:21.893393
2011-12-03T04:26:33
2011-12-03T04:26:33
35,110,434
0
0
null
null
null
null
UTF-8
C++
false
false
427
h
// IncPad.h: interface for the IncPad class. // ////////////////////////////////////////////////////////////////////// #ifndef __INCPAD_H__ #define __INCPAD_H__ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Bonus.h" class IncPad: public Bonus{ public: IncPad(); int aplicar(); ~IncPad(); }; #endif // !defined(AFX_INCPAD_H__ACF2D90A_CB1A_4370_9328_2B741AD9A6AC__INCLUDED_)
[ "rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b" ]
[ [ [ 1, 22 ] ] ]
0d6d102b3bc73422742dc4de2cffbd8e23b0bf1f
cb1c6c586d769f919ed982e9364d92cf0aa956fe
/include/TRTGridTraversal.h
bf84b74d84cb7985a26d8956f101bfc020b08b9a
[]
no_license
jrk/tinyrt
86fd6e274d56346652edbf50f0dfccd2700940a6
760589e368a981f321e5f483f6d7e152d2cf0ea6
refs/heads/master
2016-09-01T18:24:22.129615
2010-01-07T15:19:44
2010-01-07T15:19:44
462,454
3
0
null
null
null
null
UTF-8
C++
false
false
9,873
h
//===================================================================================================================== // // TRTGridTraversal.h // // Uniform grid traversal // // Part of the TinyRT Raytracing Library. // Author: Joshua Barczak // // Copyright 2008 Joshua Barczak. All rights reserved. // See Doc/LICENSE.txt for terms and conditions. // //===================================================================================================================== namespace TinyRT { //===================================================================================================================== /// \ingroup TinyRT /// \brief Structure which maintains the state of a DDA through a 3D grid /// /// The template parameters control how many bits are used for cell indices. Unsigned_T and Signed_T must /// be the corresponding unsigned and signed integer types for a particular bit width //===================================================================================================================== template< typename Unsigned_T, typename Signed_T > struct DDAState { Vec3<Unsigned_T> vCellIndices; ///< Current position in the grid Vec3<Unsigned_T> vCellCounts; ///< Number of cells in the grid Vec3<Signed_T> vStepSigns; ///< Directions to step in (1 if positive, -1 if negative) Vec3f vTNext; ///< Distance to next cell boundary Vec3f vDeltaT; ///< Change in T per single-cell step in X,Y,Z }; //===================================================================================================================== /// \ingroup TinyRT /// \brief Sets up a DDA through a 3D grid. /// /// \param rRay The ray to be traversed through the grid /// \param pGrid A grid through which the ray is to be traversed /// \param rState DDA state structure which is initialized for traversal of the ray through the grid /// /// \param Ray_T Must implement the Ray_C concept /// \param UniformGrid_T Must implement the UniformGrid_C concept /// \param DDA_T Must be an instance of TinyRT::DDAState //===================================================================================================================== template< typename Ray_T, typename UniformGrid_T, typename DDA_T > TRT_FORCEINLINE bool DDAInit( const Ray_T& rRay, const UniformGrid_T* pGrid, DDA_T& rState ) { const AxisAlignedBox& rBox = pGrid->GetBoundingBox(); float fTMin; if( !RayAABBTest( rBox.Min(), rBox.Max(), rRay, fTMin ) ) return false; fTMin = std::max( fTMin, rRay.MinDistance() ); rState.vCellCounts = pGrid->GetCellCounts(); Vec3f vBoxSize = rBox.Max() - rBox.Min(); Vec3f vStartPos = rRay.Origin() + (rRay.Direction()*fTMin); // location at which ray begins traversal through grid for( int i=0; i<3; i++ ) { float fInvDir = rRay.InvDirection()[i]; rState.vDeltaT[i] = fabs( fInvDir ) * ( vBoxSize[i] / rState.vCellCounts[i] ); // compute start position expressed in fractional cell coordinates // (0-N, where N is the number of cells. A value of N only occurs at the upper bound of the grid) float fCellCount = (float) rState.vCellCounts[i]; float fCellCoord = ((vStartPos[i] - rBox.Min()[i]) / vBoxSize[i]) * fCellCount; fCellCoord = std::max( 0.0f, fCellCoord ); fCellCoord = std::min( fCellCoord, fCellCount ); // compute index of initial cell float fCellIndex = floor( std::min( fCellCoord, fCellCount-1 ) ); rState.vCellIndices[i] = static_cast<uint32>( fCellIndex ); float fCellFrac = fCellCoord - fCellIndex; // fractional position within our initial cell (0-1) // compute distance to next cell boundary on this axis if( fInvDir > 0 ) { rState.vTNext[i] = fTMin + ((1.0f-fCellFrac) * rState.vDeltaT[i]); rState.vStepSigns[i] = 1; } else { rState.vTNext[i] = fTMin + (fCellFrac * rState.vDeltaT[i]); rState.vStepSigns[i] = -1; } } return true; } //===================================================================================================================== /// \ingroup TinyRT /// \brief Steps to the next cell in a uniform grid /// \param rState A DDA state structure built by 'TinyRT::DDAInit' /// \param rRay The ray used in the call to 'TinyRT::DDAInit' /// \return True if the ray continued to the next cell. False if the ray has left the grid, or if the /// next cell is beyond the ray's valid disatance /// /// \param DDA_T An instance of the TinyRT::DDAState template /// \param Ray_T Must implement the Ray_C concept //===================================================================================================================== template< typename DDA_T, typename Ray_T > TRT_FORCEINLINE bool DDAStep( DDA_T& rState, const Ray_T& rRay ) { if( rState.vTNext[1] < rState.vTNext[0] ) { if( rState.vTNext[2] < rState.vTNext[1] ) { if( rRay.MaxDistance() < rState.vTNext[2] ) return false; // step in Z rState.vTNext[2] += rState.vDeltaT[2]; rState.vCellIndices[2] += rState.vStepSigns[2]; // if stepping negatively, overflow will make us stop... return rState.vCellIndices[2] < rState.vCellCounts[2]; } else { if( rRay.MaxDistance() < rState.vTNext[1] ) return false; // step in Y rState.vTNext[1] += rState.vDeltaT[1]; rState.vCellIndices[1] += rState.vStepSigns[1]; // if stepping negatively, overflow will make us stop... return rState.vCellIndices[1] < rState.vCellCounts[1]; } } else { if( rState.vTNext[2] < rState.vTNext[0] ) { if( rRay.MaxDistance() < rState.vTNext[2] ) return false; // step in Z rState.vTNext[2] += rState.vDeltaT[2]; rState.vCellIndices[2] += rState.vStepSigns[2]; // if stepping negatively, overflow will make us stop... return rState.vCellIndices[2] < rState.vCellCounts[2]; } else { if( rRay.MaxDistance() < rState.vTNext[0] ) return false; // step in X rState.vTNext[0] += rState.vDeltaT[0]; rState.vCellIndices[0] += rState.vStepSigns[0]; // if stepping negatively, overflow will make us stop... return rState.vCellIndices[0] < rState.vCellCounts[0]; } } } //===================================================================================================================== /// \ingroup TinyRT /// \brief Searches for the first intersection between a ray and an object in a uniform grid /// \param pGrid The grid to be traversed /// \param pObjects The object set used to create the grid (or an equivalent one) /// \param rHitInfo Receives intersection information /// /// \param Mailbox_T Must implement the Mailbox_C concept /// \param UniformGrid_T Must implement the UniformGrid_C concept /// \param ObjectSet_T Must implement the ObjectSet_C concept /// \param HitInfo_T Must implement the HitInfo_C concept /// \param Ray_T Must implement the Ray_C concept //===================================================================================================================== template< typename Mailbox_T, typename UniformGrid_T, typename ObjectSet_T, typename HitInfo_T, typename Ray_T > void RaycastUniformGrid( const UniformGrid_T* pGrid, const ObjectSet_T* pObjects, Ray_T& rRay, HitInfo_T& rHitInfo ) { Mailbox_T mailbox(pObjects); const ObjectSet_T& rObjects = *pObjects; // DDA setup DDAState<typename UniformGrid_T::UnsignedCellIndex, typename UniformGrid_T::SignedCellIndex > ddaState; if( !DDAInit( rRay, pGrid, ddaState ) ) return; // missed grid completely while(1) { // Does this cell have objects? If it does, intersect them typename UniformGrid_T::CellIterator itBegin, itEnd; pGrid->GetCellObjectList( ddaState.vCellIndices, itBegin, itEnd ); while( itBegin != itEnd ) { typename UniformGrid_T::obj_id nObject = *itBegin; if( !mailbox.CheckMailbox( nObject ) ) rObjects.RayIntersect( rRay, rHitInfo, nObject ); ++itBegin; } // advance to next cell if( !DDAStep( ddaState, rRay ) ) return; // fell out of grid, or traversed past ray depth limit. In either case, bail out } } }
[ "jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809" ]
[ [ [ 1, 222 ] ] ]
e53bc24f6681a0722ed1c226da479cd2d381e4ec
9df2486e5d0489f83cc7dcfb3ccc43374ab2500c
/src/core/collision.h
69382c65f3f2ca2d72d5626c1272d69dace6577b
[]
no_license
renardchien/Eta-Chronicles
27ad4ffb68385ecaafae4f12b0db67c096f62ad1
d77d54184ec916baeb1ab7cc00ac44005d4f5624
refs/heads/master
2021-01-10T19:28:28.394781
2011-09-05T14:40:38
2011-09-05T14:40:38
1,914,623
1
2
null
null
null
null
UTF-8
C++
false
false
4,990
h
/*************************************************************************** * collision.h - header for the corresponding cpp file * * Copyright (C) 2005 - 2009 Florian Richter * Copyright (C) 2005 Amir Taaki ( Circle Collision tests ) - MIT License * Copyright (C) 2005 Magnus Norddahl ( Line Collision tests ) - BSD License ***************************************************************************/ /* 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 3 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SMC_COLLISION_H #define SMC_COLLISION_H #include "../core/global_basic.h" #include "../core/global_game.h" #include "../core/obj_manager.h" #include "SDL.h" namespace SMC { /* *** *** *** *** *** *** *** cObjectCollision *** *** *** *** *** *** *** *** *** *** */ // Object collision data class cObjectCollision { public: cObjectCollision( void ); ~cObjectCollision( void ); /* Set the collision direction * base - the base sprite * col - the colliding sprite */ void Set_Direction( const cSprite *base, const cSprite *col ); // returns the colliding object rect GL_rect Get_Collision_Object_Rect( void ); // valid type Col_Valid_Type valid_type; /* if true this is a receiving collision * and not a normal self detected collision */ bool received; // the object colliding with (only use it in the same frame for now !) cSprite *obj; // colliding object number int number; // direction ObjectDirection direction; // Colliding object array type ArrayType m_array; }; typedef vector<cObjectCollision *> cObjectCollision_List; /* *** *** *** *** *** *** *** cObjectCollisionType *** *** *** *** *** *** *** *** *** *** */ // collision type class class cObjectCollisionType : public cObject_Manager<cObjectCollision> { public: cObjectCollisionType( void ); virtual ~cObjectCollisionType( void ); // Add an object collision virtual void Add( cObjectCollision *obj ); // returns true if the given object was found in the list bool Is_Included( const cSprite *obj ); // returns true if the given array type was found in the list bool Is_Included( const ArrayType type ); // returns true if the sprite type was found in the list bool Is_Included( const SpriteType type ); // returns true if the validation type was found in the list bool Is_Included( const Col_Valid_Type type ); // returns the first found sprite if the given array type was found cObjectCollision *Find_First( const ArrayType type ); // returns the first found sprite if the given sprite type was found cObjectCollision *Find_First( const SpriteType type ); }; /* *** *** *** *** *** *** *** functions *** *** *** *** *** *** *** *** *** *** */ /* Returns the collision direction * base - the base sprite * col - the colliding sprite */ ObjectDirection Get_Collision_Direction( const cSprite *base, const cSprite *col ); // returns true if a collision is on the top bool Is_Collision_Top( const GL_rect &base_rect, const GL_rect &col_rect ); // returns true if a collision is on the bottom bool Is_Collision_Bottom( const GL_rect &base_rect, const GL_rect &col_rect ); // returns true if a collision is on the left bool Is_Collision_Left( const GL_rect &base_rect, const GL_rect &col_rect ); // returns true if a collision is on the right bool Is_Collision_Right( const GL_rect &base_rect, const GL_rect &col_rect ); /* * Bounding box collision test * Checks if the first rect intersects with the second */ bool Col_Box( const SDL_Rect &a, const GL_rect &b ); /* * Bounding box collision test (SDL_Rect) * Checks if the first rect intersects completely with the second */ bool Col_Box_full( const SDL_Rect &a, const SDL_Rect &b ); /* * tests whether 2 circles intersect * * Parameters: * circle1 - center (x1,y1) with radius r1 * circle2 - center (x2,y2) with radius r2 * (allow distance between circles of offset) */ bool Col_Circle( float x1, float y1, float r1, float x2, float y2, float r2, int offset = 1); /* * a circle intersection detection algorithm that will use * the position of the center of the surface as the center of * the circle and approximate the radius using the width and height * of the surface (for example a rect of 4x6 would have r = 2.5). */ bool Col_Circle( cGL_Surface *surface1, SDL_Rect *a, cGL_Surface *surface2, SDL_Rect *b, int offset = 0 ); bool Col_Circle( cGL_Surface *a, float x1, float y1, cGL_Surface *b, float x2, float y2, int offset ); /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ } // namespace SMC #endif
[ [ [ 1, 145 ] ] ]
465a38c29a22f6885c341bc950424c41756399f9
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/graphics/framebuffer.h
a8230196d64490f1efba182b4c62cb01b786e53e
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
742
h
/* * framebuffer.h * * Created on: 3.4.2010 * Author: akin */ #ifndef FRAMEBUFFER_H_ #define FRAMEBUFFER_H_ #include "texture/gtexture.h" namespace ice { class Framebuffer { protected: unsigned int m_width; unsigned int m_height; unsigned int m_id; unsigned int m_depth; public: Framebuffer(); virtual ~Framebuffer(); void attachTexture( GTexture& texture ); void attachTexture( unsigned int width , unsigned int height , unsigned int texture_id ); void attachDepth(); void removeDepth(); unsigned int getDepthId(); void bind(); int getWidth(); int getHeight(); bool invariant(); static void bindDefault(); }; } #endif /* FRAMEBUFFER_H_ */
[ "akin@lich", "akin@localhost" ]
[ [ [ 1, 10 ], [ 12, 44 ] ], [ [ 11, 11 ] ] ]
6d24014c3513398d8fb47e8a7969cfca37c89506
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/ScExec/DRV_BASE.CPP
89c03947437744300cff90b27e513ee2033c2d4a
[]
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
30,411
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #include "sc_defs.h" #define __DRV_BASE_CPP #include "tagobj.h" #include "execlib.h" #include "drv_base.h" #include "dbgmngr.h" //#include "optoff.h" const char* OPC_DLL_Name = "scOPCsrv.dll"; #if WITHDRVMAN #define dbgDriverMan 1 #if dbgDriverMan static CDbgMngr dbgRandomNumbers ("DriverManager", "RandomNumbers"); static CDbgMngr dbgFeedBack ("DriverManager", "FeedBack"); #endif #if WITHDRVDEBUG double CDriver::TimeFromStart() { static DWORD S=0; if (S==0) S=GetTickCount(); return 0.001*(GetTickCount()-S); } #endif //=========================================================================== DrvHstCfg::DrvHstCfg() { iFilterAlg = 0;//HSFA_None; iWinFltCount = 0; dFilterTau = 0.0; dWinFltPeriod = 0.0; dFltDelta = 0.0; iBoxcarAlg = 0;//HSA_None; dDeltaLo = 0.0; dDeltaHi = 0.0; iNoRec = 0; iNoNotRec = 0; dDecrease = 0.0; } DrvArcCfg::DrvArcCfg() { m_iFn=ADBFn_Null; } //=========================================================================== // If these are inline some drivers are not correctly Constructed CDriver::CDriver(const char* Tag) { sTag = Tag; InitializeCriticalSection(&critical_section); hLib = NULL; bConfigIsBusy = 1; pDrvMngr = NULL; bTwoCfgPasses = false; #if DBGDRIVERLOCKS dbgLockTime=0.0; SW.Clear(); SW.Start(); #endif bLclTagSrvrOK=0; } // -------------------------------------------------------------------------- CDriver::~CDriver() { DeleteCriticalSection(&critical_section); } // -------------------------------------------------------------------------- void CDriver::DrvError(CDrvCfgHelper * pCfg, DWORD Flags, char *Drv, char * fmt, ...) { char S[MsgBuffLen]; va_list argptr; va_start(argptr,fmt); vsprintf(S, fmt, argptr); va_end(argptr); Strng Msg; Msg.Set("Item %i: '%s' %s", pCfg->lLineNumber, pCfg->sTag(), S); //LogError((char*)Drv, 0, S()); LogLn(Flags, (char*)Drv, 0, Msg()); pCfg->bErrorFlagged=true; }; //=========================================================================== IMPLEMENT_SPARES(CDelayItem, 5000); CDelayItem::CDelayItem(CDrvSubsConn* pConSlot, PkDataUnion& Dat, DWORD DelayTime) { pCon = pConSlot; pNxt = NULL; pPrev = NULL; Data.Set(Dat); dwDelayTime = DelayTime; dwStartTime = GetTickCount(); static int ANumber=0; dwNumber = ANumber++; } //=========================================================================== IMPLEMENT_SPARES(CDrvSltChange, 5000); CDrvSltChange::CDrvSltChange(CDrvSlot * pSlot, long lDataIndex, double d, byte Typ, CCnvIndex Cnv, LPCTSTR CnvTxt) { m_pSlot = pSlot; m_pCdBlk=NULL; m_pCdBlkVar=NULL; DataIndex = lDataIndex; dVal = d; iTyp = Typ; m_iCnv=Cnv; m_sCnvTxt=CnvTxt; } //=========================================================================== CDrvSltChange::CDrvSltChange(CDrvCodeBlk *pCdBlk, GCVar *pCdBlkVar, long lDataIndex, double d, byte Typ, CCnvIndex Cnv, LPCTSTR CnvTxt) { m_pSlot = NULL; m_pCdBlk = pCdBlk; m_pCdBlkVar = pCdBlkVar; DataIndex = lDataIndex; dVal = d; iTyp = Typ; m_iCnv=Cnv; m_sCnvTxt=CnvTxt; } //=========================================================================== CDrvSubsConn::CDrvSubsConn(pchar pTag, pchar pCnvTxt, flag Get, flag Inv) { m_sTag = pTag; m_sCnvTxt = pCnvTxt; m_iCnv = 0; m_bGet = Get; m_Typ = 0; bInv = Inv; dwDelayTime = 0; dwDelayTime2 = 0; m_nOps=0; for (int i=0; i<DrvSubsConnMaxOps; i++) m_Op[i]=NULL;//CCS_Null; bEdge = 0; bUseDelay2 = 0; bInternal = 0; bDelayLock = 0; iSubsIndex = 0xffff; m_pParentSlot = NULL; m_pSlot = NULL; m_pCdBlk = NULL; m_pCdBlkVar = NULL; m_pNxt = NULL; m_pNxtSubs = NULL; } // -------------------------------------------------------------------------- CDrvSubsConn::~CDrvSubsConn() { for (int i=0; i<DrvSubsConnMaxOps; i++) delete m_Op[i]; }; // -------------------------------------------------------------------------- void CDrvSubsConn::SetDelayTimes(DWORD DelayTime, DWORD DelayTime2, flag UseDelay2) { dwDelayTime = DelayTime; dwDelayTime2 = DelayTime2; bUseDelay2 = UseDelay2; bEdge = (dwDelayTime==InfiniteDelay || (bUseDelay2 && dwDelayTime2==InfiniteDelay)); } // -------------------------------------------------------------------------- CDrvSubsConn * CDrvSubsConn::AddGetConnect(CDrvSubsConn*& pFirst, pchar pTag, flag Inv)//, byte Op, double LclConst) { if (pTag && strlen(pTag)>0) { Strng WrkTag,WrkCnvTxt; TaggedObject::SplitTagCnv(pTag, WrkTag, WrkCnvTxt); TaggedObject::ValidateTag(WrkTag); if (WrkTag.Length()>0) { CDrvSubsConn* pNew = new CDrvSubsConn(WrkTag(), WrkCnvTxt(), True, Inv); //pNew->m_Op[pNew->m_nOps++]=Op; //pNew->m_dLclConst = (float)LclConst; if (pFirst) pNew->m_pNxt = pFirst; pFirst = pNew; return pNew; } } return NULL; } // -------------------------------------------------------------------------- CDrvSubsConn * CDrvSubsConn::AddSetConnect(CDrvSubsConn*& pFirst, pchar pTag, flag Inv, DWORD DelayTime, DWORD DelayTime2, flag UseDelay2)//, byte Op, double LclConst) { if (pTag && strlen(pTag)>0) { Strng WrkTag,WrkCnvTxt; TaggedObject::SplitTagCnv(pTag, WrkTag, WrkCnvTxt); TaggedObject::ValidateTag(WrkTag); if (WrkTag.Length()>0) { CDrvSubsConn* pNew = new CDrvSubsConn(WrkTag(), WrkCnvTxt(), False, Inv); pNew->SetDelayTimes(DelayTime, DelayTime2, UseDelay2); if (pFirst) pNew->m_pNxt = pFirst; pFirst = pNew; return pNew; } } return NULL; } //--------------------------------------------------------------------------- bool CDrvSubsConn::PutSubsValue2Slot(CDriverManagerBase * pMngr, CPkDataItem *pPItem, bool ForcesOn, double DeltaTime, bool AllowNoise) { // m_Typ = pPItem->Type(); // if (pPItem->Contains(PDI_CnvInfo)) // { // m_iCnv=pPItem->CnvIndex(); // long i=(m_iCnv); // if (i!=0 && Cnvs[i]->Find(m_sCnvTxt())==NULL) // LogError("DrvMngr", 0, "Cnv %s not found for %s", m_sCnvTxt(), m_sTag()); // } if (m_bGet) { //value has changed, it must be sent (for trends etc), add it to linked list... double d = pPItem->Value()->GetDouble(m_iCnv, m_sCnvTxt()); for (int op=0; op<m_nOps; op++) { if (AllowNoise || dynamic_cast<CDrvSubsConnOp_Noise*>(m_Op[op])==NULL) d=m_Op[op]->Exec(d, DeltaTime); if (!Valid(d)) { int xxx=0;} } if (ForcesOn && m_pParentSlot->bEnableForces) { PkDataUnion Data(m_pParentSlot->dForceVal); m_pParentSlot->PutTagValue(Data); //send force value to driver... } else { PkDataUnion Data(d); m_pParentSlot->PutTagValue(Data); //send to driver... // pParentSlot->PutTagValue(*(pPItem->Value())); //send to driver... } long DataIndex = m_pParentSlot->SlotNo; pMngr->AddSltChange(DataIndex, d, m_pParentSlot); //send to SysCAD EO objects... return true; } return false; } //=========================================================================== CDrvSubsConnPrf::CDrvSubsConnPrf() { m_Mode=eNULL; }; //--------------------------------------------------------------------------- long CDrvSubsConnPrf::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) { CDrvSubsConnPrfPt 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) { CDrvSubsConnPrfPt 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 CDrvSubsConnPrf::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 CDrvSubsConnPrf::X2Y(double X) { double Y=0; long i0, i1, inc; i0=0; i1=m_Points.GetUpperBound(); inc=1; for (int i=i0; i0!=i1; i+=inc) if (X<m_Points[i].X) break; CDrvSubsConnPrfPt & Pt0=m_Points[i]; CDrvSubsConnPrfPt & Pt1=m_Points[i+1]; Y=Pt0.Y+(Pt1.Y-Pt0.Y)*(X-Pt0.X)/(Pt1.X-Pt0.X); return Y; }; //--------------------------------------------------------------------------- double CDrvSubsConnPrf::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; CDrvSubsConnPrfPt & Pt0=m_Points[i]; CDrvSubsConnPrfPt & Pt1=m_Points[i+inc]; X=Pt0.X+(Pt1.X-Pt0.X)*(Y-Pt0.Y)/NZ(Pt1.Y-Pt0.Y); return X; }; //=========================================================================== IMPLEMENT_SPARES(CProcessConnItem,2000); //=========================================================================== CDrvSlot::CDrvSlot(pchar pTag) { sTag = pTag; iTyp = 0; bChanged = 0; bSetReqd = 0; m_bReqdByExec = 0; bHstCfgd = 0; bArcCfgd = 0; bValInited = 0; bValueWritten = 0; bRecordIt = 0; bIgnoreWrites = 0; bIgnoreReads = 0; bEnableForces = 0; bLocal = 0; m_bHasSet = 0; m_bHasSetAsGet = 0; bHoldOn = 0; bUseInitVal = 0; bHasFarCon = 0; bHasGetConn = 0; dInitVal = 0.0; dForceVal = 0.0; SlotNo = 0; iStatus = 0; chgcount = 0; //iAction = XIO_None; m_iCnv = 0; iCnt = 0; pDrv = NULL; pHstCfg = NULL; pSpan = NULL; pRange = NULL; m_pConnects = NULL; m_pValLst=NULL; m_bProcessConnectsBusy=0; } // -------------------------------------------------------------------------- CDrvSlot::~CDrvSlot() { delete m_pValLst; } // -------------------------------------------------------------------------- flag CDrvSlot::GetTagValue(CPkDataList &List, CPkDataItem * &pPItem, flag Complete) { flag GotIt = False; PkDataUnion PData; #if dbgDriverMan if (dbgRandomNumbers()) GotIt = dbgGetValue(PData); //call virtual method #endif if (!GotIt) GotIt = GetValue(PData); //call virtual method if (Complete) { //supply ranges in SI units !!! DataUnion uMin; DataUnion uMax; if (pRange) { uMin.Set(Cnvs[m_iCnv]->Normal(pRange->RngLo, m_sCnvTxt())); uMax.Set(Cnvs[m_iCnv]->Normal(pRange->RngHi, m_sCnvTxt())); } else { uMin.Set(Cnvs[m_iCnv]->Normal(0.0, m_sCnvTxt())); uMax.Set(Cnvs[m_iCnv]->Normal(1.0, m_sCnvTxt())); } List.SetDataValueAll(/*pPItem,*/ sTag(), "", PData, isDriverTag | ((iAction & XIO_In) ? DDEF_PARAM : 0), uMin, uMax, m_iCnv, m_sCnvTxt(), ""/*sCnvFam()*/, NULL, False, sDescription()); } else List.SetDataValue(/*pPItem,*/ NULL, PData); return True; } // -------------------------------------------------------------------------- flag CDrvSlot::PutTagValue(PkDataUnion& Data) { if ((iAction & XIO_In)!=0) { if (SetValue(Data)) { bValueWritten=1; return True; } } return False; } // -------------------------------------------------------------------------- void CDrvSlot::GetDrvDesc(CString& s) { s = pDrv->sTag(); } // -------------------------------------------------------------------------- void CDrvSlot::GetLongDrvDesc(CString& s) { s = pDrv->sTag(); } // -------------------------------------------------------------------------- void CDrvSlot::GetTagOrAddrDesc(CString& s) { s = pDrv->sTag(); } // -------------------------------------------------------------------------- void TryAddSltChange(CDrvSubsConn* pCon, CDrvSlot * pSetSlt, CDriver * pDrv, double TheVal, long Level) { if (pCon->bInternal) { if (pSetSlt) { if (pSetSlt->m_bReqdByExec) {//only need to send it back if somebody wants it const long DataIndex = pSetSlt->SlotNo; #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK AddSltChg Intern[%5i] %s > %s",(Level*8)+4,"", DataIndex, pCon->m_sTag(), pSetSlt->sTag()); #endif pDrv->pDrvMngr->AddSltChange(DataIndex, TheVal, pCon, Level); } } } else { const long DataIndex = ConIndexStart + pCon->iSubsIndex; #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK AddSltChg [%5i] %s",(Level*8)+4,"", DataIndex, pCon->m_sTag()); #endif pDrv->pDrvMngr->AddSltChange(DataIndex, TheVal, pCon, Level); } }; // -------------------------------------------------------------------------- flag CDrvSlot::AddProcessConnItem(CProcessConnItem * &pItemListHead, CProcessConnItem *&pItemList, flag AsDouble, double rVal, long lVal, flag DoingForceSet, CDrvSubsConn* pCon, CDrvSlot * pSlt, CDriver * pDrv, long Level) { CProcessConnItem * p= new CProcessConnItem; if (pItemListHead==NULL) pItemListHead=p; if (pItemList) { p->m_pNext=p; pItemList=p; } else p->m_pNext=NULL; p->m_bDouble=AsDouble; p->m_rVal=rVal; p->m_lVal=lVal; p->m_bDoingForceSet=DoingForceSet; p->m_pCon=pCon; p->m_pSlt=pSlt; p->m_pDrv=pDrv; p->m_lLevel=Level; return AsDouble ? TestVal(rVal, DoingForceSet) : TestVal(lVal, DoingForceSet); } // -------------------------------------------------------------------------- void CDrvSlot::ApplyProcessConnItems(CProcessConnItem * pItemListHead) { CProcessConnItem * p=pItemListHead; while (pItemListHead) { CProcessConnItem * p=pItemListHead; if (p->m_bDouble) { p->m_pSlt->SetVal(p->m_rVal, p->m_bDoingForceSet); TryAddSltChange(p->m_pCon, p->m_pSlt, p->m_pDrv, p->m_rVal, p->m_lLevel); } else { p->m_pSlt->SetVal(p->m_lVal, p->m_bDoingForceSet); TryAddSltChange(p->m_pCon, p->m_pSlt, p->m_pDrv, p->m_lVal, p->m_lLevel); } pItemListHead=pItemListHead->m_pNext; delete p; } } // -------------------------------------------------------------------------- void CDrvSlot::ProcessConnects(flag Chng, flag WriteThru, flag FromOutput, flag ForceSet, long Level) { CProcessConnItem * pItemListHead=NULL; CProcessConnItem * pItemList=NULL; ProcessConnects(pItemListHead, pItemList, Chng, WriteThru, FromOutput, ForceSet, Level); }; // -------------------------------------------------------------------------- #define DELAYPROCCONNSETS 1 void CDrvSlot::ProcessConnects(CProcessConnItem * &pItemListHead, CProcessConnItem *&pItemList, flag Chng, flag WriteThru, flag FromOutput, flag ForceSet, long Level) { //CProcessConnItem * pItemListHead=NULL; if (m_bProcessConnectsBusy) { LogError("DrvMngr", 0, "Circular Reference to %s", sTag()); } else { m_bProcessConnectsBusy++; #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sProcessConnects %s %s %s",(Level*8),"", m_bHasSet?"Set":" ", m_bHasSetAsGet?"SetG":" ", sTag()); #endif if (m_bHasSet || m_bHasSetAsGet) { CDrvSubsConn* pCon = m_pConnects; while (pCon) { if (!pCon->m_bGet) { #if dbgDriverMan LPTSTR dbgConnTag=pCon->m_sTag(); #endif CDrvSlot *pSetSlt=pCon->m_pSlot; CDrvCodeBlk *pSetCB=pCon->m_pCdBlk; flag FeedBack = 0; flag Done = 0; PkDataUnion Data; #if WITHDRVDEBUG dbgSrcReadTime=CDriver::TimeFromStart(); #endif GetTheVal(Data, FromOutput); flag DoingForceSet = ForceSet;//(!Chng && ForceSet && !pCon->bDelayLock); flag DoingWriteThru = (!Chng && (pDrv->bDoWriteThru||WriteThru) && !pCon->bDelayLock); flag SetDelayZero = (!Chng); if (Chng || DoingForceSet || DoingWriteThru) { ClearFBKChange(); //#if dbgDriverMan //if (dbgTimes()) // dbgpln("AB: chang: %10s %.3f %d", pV->pSlot->sTag(), SW.Secs(), pV->Content); //#endif FeedBack = 1; if (pCon->bInternal) { //internal driver tag must be set, do it now ... dword DlyTime = (SetDelayZero ? 0 : pCon->dwDelayTime); if (pCon->dwDelayTime==InfiniteDelay) DlyTime = pCon->dwDelayTime; if (IsFloatData(iTyp)) { if (DlyTime==0) { double d = Data.GetDouble(); if (pCon->bInv) d = !d; if (pSetCB) { #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK SetGC %g %s > %s", (Level*8)+2,"", d, sTag(), pCon->m_sTag()); #endif // Set the Value pCon->m_pCdBlkVar->set(d); // Execute pgm CGExecContext ECtx(NULL); pSetCB->m_Code.Execute(ECtx); // Update Destination Tags // Update Destination Tags for (int i=0; i<pSetCB->m_GetsFromMe.GetSize(); i++) { CDrvSubsConn *pGetCon=pSetCB->m_GetsFromMe[i]; ASSERT(pGetCon->m_pCdBlk==pSetCB); if (pGetCon->m_pCdBlkVar->WhatAmI()==VarDouble) { double res=pGetCon->m_pCdBlkVar->getD(); CDrvSlot * pSetSlt=pGetCon->m_pParentSlot; #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK GetGC %g %s > %s", (Level*8)+2,"", res, pGetCon->m_sTag(), pSetSlt->sTag()); #endif #if DELAYPROCCONNSETS flag Chng=AddProcessConnItem(pItemListHead, pItemList, true, res, 0, DoingForceSet, pGetCon, pSetSlt, pDrv, Level); #else flag Chng=pSetSlt->SetVal(res, DoingForceSet); TryAddSltChange(pGetCon, pSetSlt, pDrv, res, Level); #endif pSetSlt->ProcessConnects(pItemListHead, pItemList, Chng, WriteThru, FromOutput, ForceSet, Level+1); } else { long res=pGetCon->m_pCdBlkVar->getL(); CDrvSlot * pSetSlt=pGetCon->m_pParentSlot; #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK GetGC %i %s > %s", (Level*8)+2,"", res, pGetCon->m_sTag(), pSetSlt->sTag()); #endif #if DELAYPROCCONNSETS flag Chng=AddProcessConnItem(pItemListHead, pItemList, false, 0, res, DoingForceSet, pGetCon, pSetSlt, pDrv, Level); #else flag Chng=pSetSlt->SetVal(res, DoingForceSet); TryAddSltChange(pGetCon, pSetSlt, pDrv, res, Level); #endif pSetSlt->ProcessConnects(pItemListHead, pItemList, Chng, WriteThru, FromOutput, ForceSet, Level+1); } int xxx=0; } int xxx=0; } else { #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK Set %g %s > %s", (Level*8)+2,"", d, sTag(), dbgConnTag); #endif #if DELAYPROCCONNSETS flag Chng=AddProcessConnItem(pItemListHead, pItemList, true, d, 0, DoingForceSet, pCon, pSetSlt, pDrv, Level); #else pSetSlt->SetVal(d, DoingForceSet); TryAddSltChange(pCon, pSetSlt, pDrv, d, Level); #endif pSetSlt->ProcessConnects(pItemListHead, pItemList, Chng, WriteThru, FromOutput, ForceSet, Level+1); } Done = 1; } } else { long l = Data.GetLong(); if (pCon->bUseDelay2 && l && (!SetDelayZero || pCon->dwDelayTime2==InfiniteDelay)) DlyTime = pCon->dwDelayTime2; if (DlyTime==0) { if (pCon->bInv) l = !l; if (pSetCB) { #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK SetGC %i %s > %s", (Level*8)+2,"", l, sTag(), pCon->m_sTag); #endif // Set the Value pCon->m_pCdBlkVar->set(l); #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK Exec %s [%s]", (Level*8)+2,"", pSetCB->m_sTag(), pSetCB->m_Code.m_DbgMngr.sPgmName()); #endif // Execute pgm CGExecContext ECtx(NULL); pSetCB->m_Code.Execute(ECtx); // Update Destination Tags for (int i=0; i<pSetCB->m_GetsFromMe.GetSize(); i++) { CDrvSubsConn *pGetCon=pSetCB->m_GetsFromMe[i]; ASSERT(pGetCon->m_pCdBlk==pSetCB); if (pGetCon->m_pCdBlkVar->WhatAmI()==VarDouble) { double res=pGetCon->m_pCdBlkVar->getD(); CDrvSlot * pSetSlt=pGetCon->m_pParentSlot; #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK GetGC %g %s > %s", (Level*8)+2,"", res, pGetCon->m_sTag(), pSetSlt->sTag()); #endif #if DELAYPROCCONNSETS flag Chng=AddProcessConnItem(pItemListHead, pItemList, true, res, 0, DoingForceSet, pGetCon, pSetSlt, pDrv, Level); #else flag Chng=pSetSlt->SetVal(res, DoingForceSet); TryAddSltChange(pGetCon, pSetSlt, pDrv, res, Level); #endif pSetSlt->ProcessConnects(pItemListHead, pItemList, Chng, WriteThru, FromOutput, ForceSet, Level+1); } else { long res=pGetCon->m_pCdBlkVar->getL(); CDrvSlot * pSetSlt=pGetCon->m_pParentSlot; #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK GetGC %i %s > %s", (Level*8)+2,"", res, pGetCon->m_sTag(), pSetSlt->sTag()); #endif #if DELAYPROCCONNSETS flag Chng=AddProcessConnItem(pItemListHead, pItemList, false, 0, res, DoingForceSet, pGetCon, pSetSlt, pDrv, Level); #else flag Chng=pSetSlt->SetVal(res, DoingForceSet); TryAddSltChange(pGetCon, pSetSlt, pDrv, res, Level); #endif pSetSlt->ProcessConnects(pItemListHead, pItemList, Chng, WriteThru, FromOutput, ForceSet, Level+1); } int xxx=0; } int xxx=0; } else { #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK Set %i %s > %s", (Level*8)+2,"", l, sTag(), dbgConnTag); #endif #if DELAYPROCCONNSETS flag Chng=AddProcessConnItem(pItemListHead, pItemList, false, 0, l, DoingForceSet, pCon, pSetSlt, pDrv, Level); #else flag Chng=pSetSlt->SetVal(l, DoingForceSet); TryAddSltChange(pCon, pSetSlt, pDrv, l, Level); #endif pSetSlt->ProcessConnects(pItemListHead, pItemList, Chng, WriteThru, FromOutput, ForceSet, Level+1); } Done = 1; } } if (Done) { if (pSetCB) { //ASSERT_ALWAYS(TRUE, "Delays for CodeBlks not yet implemented", __FILE__, __LINE__); } else FeedBack = ((flag)(pSetSlt->m_bReqdByExec) && DlyTime!=InfiniteDelay); } else { FeedBack = 0; if (DlyTime!=InfiniteDelay) { if (pSetCB) { ASSERT_ALWAYS(TRUE, "Delays for CodeBlks not yet implemented", __FILE__, __LINE__); } // pDrv->Lock(); if (pCon->bDelayLock) {//update delay item in linked list... pCDelayItem pDelayItem = pSetSlt->GetDelayItemsForSlot(); while (pDelayItem) { if (pDelayItem->pCon==pCon) { //pDelayItem->dwDelayTime = DlyTime; pDelayItem->Data.Set(Data); break; } pDelayItem = pDelayItem->pNxt; } } else {//add delay item to linked list... #if dbgDriverMan if (dbgFeedBack()) dbgpln("%*sFBK SetDelay %s", (Level*8)+2,"", dbgConnTag); #endif pCon->bDelayLock = 1; pSetSlt->InsertDelayItem(new CDelayItem(pCon, Data, DlyTime)); } // pDrv->UnLock(); } } } else {//check if the external flowsheet tag must be set ... double d = Data.GetDouble(); if (!IsFloatData(iTyp)) { DWORD DlyTime = (SetDelayZero ? 0 : pCon->dwDelayTime); if (pCon->dwDelayTime==InfiniteDelay) DlyTime = pCon->dwDelayTime; long l = Data.GetLong(); if (pCon->bUseDelay2 && l && (!SetDelayZero || pCon->dwDelayTime2==InfiniteDelay)) DlyTime = pCon->dwDelayTime2; if (DlyTime!=InfiniteDelay) TryAddSltChange(pCon, pSetSlt, pDrv, d, Level); } else TryAddSltChange(pCon, pSetSlt, pDrv, d, Level); } } } pCon = pCon->m_pNxt; } } m_bProcessConnectsBusy--; } #if DELAYPROCCONNSETS if (Level==0) ApplyProcessConnItems(pItemListHead); #endif } //=========================================================================== CDriverManagerBase::CDriverManagerBase() { } //=========================================================================== #endif
[ [ [ 1, 14 ], [ 19, 112 ], [ 114, 318 ], [ 320, 320 ], [ 322, 322 ], [ 324, 324 ], [ 326, 893 ], [ 895, 905 ], [ 907, 973 ] ], [ [ 15, 18 ], [ 113, 113 ], [ 319, 319 ], [ 321, 321 ], [ 323, 323 ], [ 325, 325 ], [ 894, 894 ], [ 906, 906 ], [ 974, 975 ] ] ]
453c3929a59ac14cc52269a940b46b73c64761b7
1584e139552d36bbbcc461deb81c22a06d42b713
/shared/shared.h
f65eb0db9ff7e027bb072b6fb8f5c049cad07f7b
[]
no_license
joshmg/battle
fd458da8be387ff0b4f80f0d2029759cd3fabe30
14ab71d903fe0bcf7c3285169026b4f96a186309
refs/heads/master
2020-05-18T17:20:00.768647
2010-09-28T04:34:34
2010-09-28T04:34:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,607
h
// File: shared.h // Written by Joshua Green #ifndef SHARED_H #define SHARED_H #include <string> #undef ERROR // Where is this even defined? // -------------- CONSTANTS -------------- // const int SERVER_PORT = 4444; const std::string SERVER_IP = "192.168.1.201"; // Transmission Variables // Errors const std::string SERVER_ERROR = "!ERROR"; const std::string CHARACTER_TAKEN = "!CHARACTER_TAKEN"; const std::string CHARACTER_NOT_FOUND = "!CHARACTER_NOT_FOUND"; const std::string CHARACTER_CORRUPTED = "!CHARACTER_CORRUPTED"; const std::string INVALID_REQUEST = "!INVALID_REQUEST"; const std::string TIMEBAR_NOT_FULL = "!TIMEBAR_NOT_FULL"; const std::string LOCAL_IS_DEAD = "!LOCAL_TOON_IS_DEAD"; const std::string REMOTE_IS_DEAD = "!REMOTE_TOON_IS_DEAD"; const std::string SPELL_DOES_NOT_EXIST = "!NOSPELL"; const std::string TOON_DOESNT_HAVE_SPELL = "!TOON_MISSING_DMATTER"; const std::string DMATTER_DOES_NOT_EXIST = "!DMATTER_NOT_EXIST"; const std::string DMATTER_NOT_FOR_SALE = "!DMATTER_NOT_FOR_SALE"; const std::string NOT_ENOUGH_EXP = "!LACKING_EXP"; // Data const std::string REQUEST_TOON_DATA = "(CHAR DATA?)"; const std::string TOON_DATA = "(CHAR DATA)"; const std::string NEW_TOON = "(NEW CHARACTER)"; const std::string LOAD_TOON = "(LOAD CHARACTER)"; const std::string CLEAR_TOON_DMATTER = "(CLEAR TOON DMATTER)"; const std::string REQUEST_TOON_DMATTER = "(TOON DMATTER?)"; const std::string TOON_DMATTER = "(TOON DMATTER)"; // Misc const std::string DELIM = std::string(1, (char)128); const std::string DEFN_SERVER_CODE = "(SERVERCODE)"; const std::string DEFN_ID = "(ID::)"; const std::string SERVER_SHUTDOWN = "(SERVER SHUTDOWN)"; const std::string REMOVE_REMOTE_CHAR = "(REMOVE REMOTE)"; const std::string EXECUTE = "!DO"; const std::string DELETE_SAVE_FILE = "!DELETE_SAVE"; const std::string PING = "(PING)"; const std::string PONG = "(PONG)"; const std::string DISCONNECT = "(DISCONNECT)"; const std::string GLOBAL_MESSAGE = "(GLOBAL_MESSAGE)"; // Battle const std::string LOCAL_TOON = "(LOCAL_TOON)"; const std::string REMOTE_TOON = "(REMOTE_TOON)"; const std::string MELEE = "(MELEE)"; const std::string DAMAGE = "(DAMAGE)"; const std::string HEAL = "(HEAL)"; const std::string TARGET_HP = "(->HP)"; const std::string TARGET_MP = "(->MP)"; const std::string DEATH = "(DEATH)"; const std::string GAINED_EXP = "(+EXP)"; const std::string LEVEL_UP = "(+LVL)"; const std::string NOT_ENOUGH_MANA = "(~MANA)"; const std::string SPELL = "(SPELL)"; const std::string NO_AFFECT = "(NO_AFFECT)"; // Shop const std::string SHOP = "(SHOP)"; const std::string BROWSE_DMATTER = "(BROWSE?DMATTER)"; const std::string DMATTER_LIST = "(LIST:DMATTER)"; const std::string END_DMATTER_LIST = "(_LIST:DMATTER)"; const std::string AVAILABLE_DMATTER = "(DMATTER4SALE:)"; const std::string BUY_DMATTER = "(BUY:DMATTER)"; // CTRL const std::string EQUIP_DMATTER = "(EQUIP:DMATTER)"; const std::string GOTO_SERV = "(GOTO:)"; const std::string BATTLE_SERV = "(BATTLE_SERVER)"; const std::string STORE_SERV = "(STORE_SERVER)"; // --------------------------------------- // struct point3d { float x, y, z; point3d() { x = 0.0f; y = 0.0f; z = 0.0f; } point3d(float _x, float _y, float _z) { x = _x; y = _y; z = _z; } point3d operator+(const point3d& p) { return point3d(p.x+x, p.y+y, p.z+z); } point3d operator-(const point3d& p) { return point3d(p.x-x, p.y-y, p.z-z); } point3d operator/(float c) { return point3d(x/c, y/c, z/c); } }; #endif
[ [ [ 1, 102 ] ] ]
9df838298cdd24e2be0985db5dc0ba3f9bbc1f32
bdb1e38df8bf74ac0df4209a77ddea841045349e
/Browser/ImageBrowser/ImageBrowserDoc.h
47f7ac41289573811783c3fe00fee34a647446a1
[]
no_license
Strongc/my001project
e0754f23c7818df964289dc07890e29144393432
07d6e31b9d4708d2ef691d9bedccbb818ea6b121
refs/heads/master
2021-01-19T07:02:29.673281
2010-12-17T03:10:52
2010-12-17T03:10:52
49,062,858
0
1
null
2016-01-05T11:53:07
2016-01-05T11:53:07
null
UTF-8
C++
false
false
842
h
// ImageBrowserDoc.h : interface of the CImageBrowserDoc class // #include "cv.h" #include "cxcore.h" #include "highgui.h" #pragma once class CImageBrowserDoc : public CDocument { protected: // create from serialization only CImageBrowserDoc(); DECLARE_DYNCREATE(CImageBrowserDoc) // Attributes public: // Operations public: // Overrides public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // Implementation public: virtual ~CImageBrowserDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() public: virtual BOOL OnOpenDocument(LPCTSTR lpszPathName); public: IplImage* m_rawImage; public: IplImage* GetImage(void); };
[ "vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e" ]
[ [ [ 1, 48 ] ] ]
d5e572bf9f2b4f8d68d4fbb04cfd03bd80865194
0d8034b26c80aad5d762ecac95beb180c74e16e9
/Billiard/Billiard/EyesTracking.h
cc1340cf2308c267b48e507a277bc3c7b7c798cc
[]
no_license
zinking/3ddesktopgame
c61a20f3812418f032dbf94b5479f3c9306f2f8d
867abd5189b028732e222326e83eed313d7caf83
refs/heads/master
2021-03-12T23:30:28.875389
2009-09-16T10:22:28
2009-09-16T10:22:28
32,133,086
0
0
null
null
null
null
UTF-8
C++
false
false
300
h
#ifndef EYESTRACKING_HEADER #define EYESTRACKING_HEADER namespace EyesTracking { void Initialize(const char* calibFile, const char* glassDef); void Terminate(); bool GetEyesPosition(double& leftx, double& lefty, double& leftz, double& rightx, double& righty, double& rightz); }; #endif
[ "LeoYang01@a4a63562-5fa1-11de-92c7-cf56be1892c0" ]
[ [ [ 1, 11 ] ] ]
029a2c422cc4511edf704a709b9277df3f66b402
1bd75b9c45c3d5d5af3a9c9ba84ab0d4ec1bfd8f
/Learn in Noise/Listener.h
f5c190617947745f4ccce7e0fc27ade1817808bb
[]
no_license
nadernt/whistle-recognizer
168634eda147752fada31d1b4e073971a053b4bf
7f260f7ee38d9445e2f0806566bbc0ceb45d3986
refs/heads/master
2020-04-06T04:26:13.138539
2010-01-12T17:11:08
2017-02-23T12:22:25
82,922,754
1
0
null
null
null
null
UTF-8
C++
false
false
526
h
#pragma once #include "SndCardServices.h" #include "apptools.h" #define FFT_LEN 1024 class Listener { private: AppTools Aptool; CString scrT; int NurlStkWeightState,LrnSynapseWeightState; float NumOfNeg,NumOfPos; public: Listener(void); ~Listener(void); BOOL WhistleListener(int StartPointOfListen,int CUT_OFF_OFFSET,int endofview); void LearningSampleSound(int CUT_OFF_OFFSET,bool InternalLearn); double *WeightLayer; double *InputLayer; void DoEvents(); CString GetResult(); };
[ [ [ 1, 21 ] ] ]
cdf474a87e2cf218d9e6a9154a8a938f4c44ce56
cf579692f2e289563160b6a218fa5f1b6335d813
/XBpatch/Patchers/CUnknownPatcher.h
5b721a56516f4bcfe5b2c607f3f166f69bd0da84
[]
no_license
opcow/XBtool
a7451971de3296e1ce5632b0c9d95430f6d3b223
718a7fbf87e08c12c0c829dd2e2c0d6cee967cbe
refs/heads/master
2021-01-16T21:02:17.759102
2011-03-09T23:36:54
2011-03-09T23:36:54
1,461,420
8
2
null
null
null
null
UTF-8
C++
false
false
1,445
h
////////////////////////////////////////////////////////////////////////////// // CUnknownPatcher.h // XBPatch - Xbox BIOS patch library // Copyright (C) 2003 Mitch Crane // // 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ////////////////////////////////////////////////////////////////////////////// #include "CKernelPatcher.h" class CUnknownPatcher : public CKernelPatcher { public: virtual XBPATCH_API int Read(unsigned char *kernelBuffer, BIOS_Options *BIOSOptions); virtual XBPATCH_API int Write(unsigned char *kernelBuffer, BIOS_Options *BIOSOptions); virtual XBPATCH_API void GetSupportedOptions(BIOS_Supported_Options &SupOpts); void InitPatches() {}; private: int WritePreIDPatches(BIOS_Options *BIOSOptions) { return 0; }; };
[ [ [ 1, 32 ] ] ]
394b1ed4ff82ed27b0ba153cdcee208dd74ddeec
05f4bd87bd001ab38701ff8a71d91b198ef1cb72
/TPTaller/TP3/src/IncLongPad.cpp
3d1c962c3919cbf1ed0664bc02c30affb71c1298
[]
no_license
oscarcp777/tpfontela
ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12
2489442b81dab052cf87b6dedd33cbb51c2a0a04
refs/heads/master
2016-09-01T18:40:21.893393
2011-12-03T04:26:33
2011-12-03T04:26:33
35,110,434
0
0
null
null
null
null
UTF-8
C++
false
false
1,271
cpp
// IncLongPad.cpp: implementation of the IncLongPad class. // ////////////////////////////////////////////////////////////////////// #include "IncLongPad.h" #include "Escenario.h" #include "Define.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// IncLongPad::IncLongPad() { } int IncLongPad::aplicar(){ Escenario* escenario = Escenario::obtenerInstancia(); Pad*pad=NULL; int incUnTercioDeAltura=0; std::string padUltimaColision = escenario->getTejo()->obtenerUltimaColisionPad(); if(padUltimaColision.compare(PAD_CLIENTE1)==0) pad = escenario->getPadCliente1(); else if(padUltimaColision.compare(PAD_CLIENTE2)==0) pad = escenario->getPadCliente2(); int incMax = pad->getAlturaDefault()+ 5*(pad->getAlturaDefault()/3); if(pad==NULL) return -1; incUnTercioDeAltura = pad->getAltura() + pad->getAlturaDefault()/3; if(incUnTercioDeAltura>incMax) return -1; pad->setModificar(true); pad->setAltura(incUnTercioDeAltura); return 0; } IncLongPad::~IncLongPad() { if(DEBUG_DESTRUCTOR==1) std::cout<<" entro al destructor de IncLongPad"<<endl; }
[ "rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b" ]
[ [ [ 1, 50 ] ] ]
7cda4ff34fe6e22663f0f2a82e0f5267cc3725d6
11da90929ba1488c59d25c57a5fb0899396b3bb2
/Src/WindowsCE/Menu.hpp
fffae996c24a03f0e1a5f601d1d7196b3964d06c
[]
no_license
danste/ars-framework
5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6
90f99d43804d3892432acbe622b15ded6066ea5d
refs/heads/master
2022-11-11T15:31:02.271791
2005-10-17T15:37:36
2005-10-17T15:37:36
263,623,421
0
0
null
2020-05-13T12:28:22
2020-05-13T12:28:21
null
UTF-8
C++
false
false
752
hpp
#ifndef GUI_MENU_H__ #define GUI_MENU_H__ #include <Debug.hpp> #include <Utility.hpp> class Menu: private NonCopyable { HMENU menu_; public: #ifndef NDEBUG HMENU handle() const; #else HMENU handle() const {return menu_;} #endif bool valid() const {return NULL != menu_;} enum AutoDestroyOption { autoDestroyNot, autoDestroy }; explicit Menu(AutoDestroyOption ad = autoDestroyNot); explicit Menu(HMENU m, AutoDestroyOption ad = autoDestroyNot); void attach(HMENU m); void detach(); enum MenuType { menuBar, menuPopup }; bool create(MenuType type); void destroy(); virtual ~Menu(); private: AutoDestroyOption autoDestroy_; }; // class Menu #endif // GUI_MENU_H__
[ "andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9" ]
[ [ [ 1, 51 ] ] ]
afb2d7a27abb7689cc1af1a761a23ff21b296ce5
67c2e1ce81b343952e96b09e2eaf1ddc7f3888fc
/Dependencies/LiteSQL/src/generator/ui/ui.cpp
514881e3a14822bc1e7b4ce3fdacb4c4190788bb
[ "BSD-3-Clause" ]
permissive
aclysma/Helium
806c5a3954ecd162a1a7137562bd0f71e084423a
a009248596b2e537ccb8e7c3e587628b8bda8b7a
refs/heads/master
2021-01-18T05:31:57.004647
2011-06-07T04:49:10
2011-06-07T04:49:10
1,301,697
1
0
null
null
null
null
UTF-8
C++
false
false
16,986
cpp
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Apr 16 2008) // http://www.wxformbuilder.org/ // // PLEASE DO LITESQL_L("NOT") EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #include "ui.h" // Using the construction of a static object to ensure that the help provider is set class wxFBContextSensitiveHelpSetter { public: wxFBContextSensitiveHelpSetter() { wxHelpProvider::Set( new wxHelpControllerHelpProvider ); } }; static wxFBContextSensitiveHelpSetter s_wxFBSetTheHelpProvider; /////////////////////////////////////////////////////////////////////////// using namespace ui; ObjectPanel::ObjectPanel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { this->SetMinSize( wxSize( 250,80 ) ); wxFlexGridSizer* gSizer1; gSizer1 = new wxFlexGridSizer( 2, 2, 0, 0 ); gSizer1->AddGrowableCol( 1 ); gSizer1->SetFlexibleDirection( wxBOTH ); gSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); lblName = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Name")), wxDefaultPosition, wxDefaultSize, 0 ); lblName->Wrap( -1 ); gSizer1->Add( lblName, 1, wxALL|wxEXPAND, 5 ); m_textCtrlName = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_textCtrlName, 2, wxALL|wxFIXED_MINSIZE|wxEXPAND, 5 ); lblInherits = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Inherit From")), wxDefaultPosition, wxDefaultSize, 0 ); lblInherits->Wrap( -1 ); gSizer1->Add( lblInherits, 0, wxALL|wxEXPAND, 5 ); wxArrayString m_choiceInheritsFromChoices; m_choiceInheritsFrom = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_choiceInheritsFromChoices, 0 ); m_choiceInheritsFrom->SetSelection( 0 ); m_choiceInheritsFrom->SetMinSize( wxSize( 150,-1 ) ); gSizer1->Add( m_choiceInheritsFrom, 1, wxALL|wxEXPAND, 5 ); this->SetSizer( gSizer1 ); this->Layout(); } ObjectPanel::~ObjectPanel() { } FieldPanel::FieldPanel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { this->SetMinSize( wxSize( 300,120 ) ); wxFlexGridSizer* gSizer1; gSizer1 = new wxFlexGridSizer( 7, 2, 0, 0 ); gSizer1->AddGrowableCol( 1 ); gSizer1->SetFlexibleDirection( wxBOTH ); gSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); lblName = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Name")), wxDefaultPosition, wxDefaultSize, 0 ); lblName->Wrap( -1 ); gSizer1->Add( lblName, 1, wxALL, 5 ); m_textCtrlName = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_textCtrlName, 1, wxALL|wxEXPAND, 5 ); lblFieldtype = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Fieldtype")), wxDefaultPosition, wxDefaultSize, 0 ); lblFieldtype->Wrap( -1 ); gSizer1->Add( lblFieldtype, 1, wxALL, 5 ); wxArrayString m_choiceFieldtypeChoices; m_choiceFieldtype = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_choiceFieldtypeChoices, 0 ); m_choiceFieldtype->SetSelection( 0 ); m_choiceFieldtype->SetMinSize( wxSize( 150,-1 ) ); gSizer1->Add( m_choiceFieldtype, 1, wxALL|wxEXPAND, 5 ); lblDefault = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Default Value:")), wxDefaultPosition, wxDefaultSize, 0 ); lblDefault->Wrap( -1 ); gSizer1->Add( lblDefault, 1, wxALL, 5 ); m_textCtrlDefaultValue = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_textCtrlDefaultValue, 1, wxALL|wxEXPAND, 5 ); lblIndexed = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Indexed")), wxDefaultPosition, wxDefaultSize, 0 ); lblIndexed->Wrap( -1 ); gSizer1->Add( lblIndexed, 1, wxALL, 5 ); m_checkBoxIndexed = new wxCheckBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_checkBoxIndexed, 0, wxALL, 5 ); lblUnique = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Unique")), wxDefaultPosition, wxDefaultSize, 0 ); lblUnique->Wrap( -1 ); gSizer1->Add( lblUnique, 1, wxALL, 5 ); m_checkBoxUnique = new wxCheckBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_checkBoxUnique, 0, wxALL, 5 ); lblValues = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Values")), wxDefaultPosition, wxDefaultSize, 0 ); lblValues->Wrap( -1 ); gSizer1->Add( lblValues, 0, wxALL, 5 ); m_listValues = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_EDIT_LABELS|wxLC_REPORT ); gSizer1->Add( m_listValues, 0, wxALL|wxEXPAND, 5 ); m_staticText20 = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); m_staticText20->Wrap( -1 ); gSizer1->Add( m_staticText20, 1, wxALL, 5 ); wxBoxSizer* bSizer2; bSizer2 = new wxBoxSizer( wxHORIZONTAL ); m_btnAdd = new wxButton( this, wxID_ANY, _(LITESQL_L("+")), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT ); bSizer2->Add( m_btnAdd, 0, wxALL, 5 ); m_btnRemove = new wxButton( this, wxID_ANY, _(LITESQL_L("-")), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT ); bSizer2->Add( m_btnRemove, 0, wxALL, 5 ); gSizer1->Add( bSizer2, 1, wxEXPAND, 5 ); this->SetSizer( gSizer1 ); this->Layout(); // Connect Events m_btnAdd->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FieldPanel::OnAddValue ), NULL, this ); m_btnRemove->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FieldPanel::OnRemoveValue ), NULL, this ); } FieldPanel::~FieldPanel() { // Disconnect Events m_btnAdd->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FieldPanel::OnAddValue ), NULL, this ); m_btnRemove->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FieldPanel::OnRemoveValue ), NULL, this ); } MethodPanel::MethodPanel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { this->SetMinSize( wxSize( 300,120 ) ); wxFlexGridSizer* gSizer1; gSizer1 = new wxFlexGridSizer( 2, 2, 0, 0 ); gSizer1->AddGrowableCol( 1 ); gSizer1->SetFlexibleDirection( wxBOTH ); gSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); lblName = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Name")), wxDefaultPosition, wxDefaultSize, 0 ); lblName->Wrap( -1 ); gSizer1->Add( lblName, 0, wxALL, 5 ); m_textCtrlName = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_textCtrlName, 1, wxALL|wxEXPAND, 5 ); this->SetSizer( gSizer1 ); this->Layout(); } MethodPanel::~MethodPanel() { } RelationPanel::RelationPanel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { this->SetMinSize( wxSize( 300,120 ) ); wxFlexGridSizer* gSizer1; gSizer1 = new wxFlexGridSizer( 3, 2, 0, 0 ); gSizer1->AddGrowableCol( 1 ); gSizer1->SetFlexibleDirection( wxBOTH ); gSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); lblName = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Name")), wxDefaultPosition, wxDefaultSize, 0 ); lblName->Wrap( -1 ); gSizer1->Add( lblName, 0, wxALL|wxEXPAND, 5 ); m_textCtrlName = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); gSizer1->Add( m_textCtrlName, 0, wxALL|wxEXPAND, 5 ); lblObject1 = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Object 1")), wxDefaultPosition, wxDefaultSize, 0 ); lblObject1->Wrap( -1 ); gSizer1->Add( lblObject1, 1, wxALL, 5 ); wxArrayString m_choiceObject1Choices; m_choiceObject1 = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_choiceObject1Choices, 0 ); m_choiceObject1->SetSelection( 0 ); m_choiceObject1->SetMinSize( wxSize( 150,-1 ) ); gSizer1->Add( m_choiceObject1, 0, wxALL|wxEXPAND, 5 ); lblObject2 = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Object 2")), wxDefaultPosition, wxDefaultSize, 0 ); lblObject2->Wrap( -1 ); gSizer1->Add( lblObject2, 1, wxALL, 5 ); wxArrayString m_choiceObject2Choices; m_choiceObject2 = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_choiceObject2Choices, 0 ); m_choiceObject2->SetSelection( 0 ); m_choiceObject2->SetMinSize( wxSize( 150,-1 ) ); gSizer1->Add( m_choiceObject2, 0, wxALL|wxEXPAND, 5 ); this->SetSizer( gSizer1 ); this->Layout(); } RelationPanel::~RelationPanel() { } DatabasePanel::DatabasePanel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { this->SetMinSize( wxSize( 300,120 ) ); wxFlexGridSizer* fgSizer1; fgSizer1 = new wxFlexGridSizer( 3, 2, 0, 0 ); fgSizer1->AddGrowableCol( 1 ); fgSizer1->SetFlexibleDirection( wxBOTH ); fgSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_ALL ); m_staticName = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Name")), wxDefaultPosition, wxDefaultSize, 0 ); m_staticName->Wrap( -1 ); fgSizer1->Add( m_staticName, 0, wxALL, 5 ); m_textName = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); fgSizer1->Add( m_textName, 1, wxALL|wxEXPAND, 5 ); m_staticNamespace = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Namespace")), wxDefaultPosition, wxDefaultSize, 0 ); m_staticNamespace->Wrap( -1 ); fgSizer1->Add( m_staticNamespace, 0, wxALL, 5 ); m_textNamespace = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); fgSizer1->Add( m_textNamespace, 1, wxALL|wxEXPAND, 5 ); m_staticInclude = new wxStaticText( this, wxID_ANY, _(LITESQL_L("additional Include")), wxDefaultPosition, wxDefaultSize, 0 ); m_staticInclude->Wrap( -1 ); fgSizer1->Add( m_staticInclude, 0, wxALL, 5 ); m_textInclude = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); fgSizer1->Add( m_textInclude, 1, wxALL|wxEXPAND, 5 ); this->SetSizer( fgSizer1 ); this->Layout(); } DatabasePanel::~DatabasePanel() { } AboutDialog::AboutDialog( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer4; bSizer4 = new wxBoxSizer( wxVERTICAL ); m_staticText4 = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Visual-Litesql")), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE ); m_staticText4->Wrap( -1 ); bSizer4->Add( m_staticText4, 1, wxALL|wxEXPAND, 5 ); m_staticText5 = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Version")), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE ); m_staticText5->Wrap( -1 ); bSizer4->Add( m_staticText5, 0, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL, 5 ); m_btnClose = new wxButton( this, wxID_OK, _(LITESQL_L("Close")), wxDefaultPosition, wxDefaultSize, 0 ); bSizer4->Add( m_btnClose, 0, wxALL|wxEXPAND, 5 ); this->SetSizer( bSizer4 ); this->Layout(); } AboutDialog::~AboutDialog() { } GeneratePanel::GeneratePanel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { this->SetMinSize( wxSize( 400,210 ) ); wxFlexGridSizer* panelSizer; panelSizer = new wxFlexGridSizer( 4, 2, 0, 0 ); panelSizer->AddGrowableCol( 1 ); panelSizer->SetFlexibleDirection( wxBOTH ); panelSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_ALL ); m_staticOutputDir = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Output Directory")), wxDefaultPosition, wxDefaultSize, 0 ); m_staticOutputDir->Wrap( -1 ); panelSizer->Add( m_staticOutputDir, 0, wxALL, 5 ); m_dirPickerOutputDir = new wxDirPickerCtrl( this, wxID_ANY, wxEmptyString, _(LITESQL_L("Select a folder")), wxDefaultPosition, wxDefaultSize, wxDIRP_DEFAULT_STYLE|wxDIRP_DIR_MUST_EXIST ); panelSizer->Add( m_dirPickerOutputDir, 1, wxALL|wxEXPAND, 5 ); m_staticGenerators = new wxStaticText( this, wxID_ANY, _(LITESQL_L("Select generators")), wxDefaultPosition, wxDefaultSize, 0 ); m_staticGenerators->Wrap( -1 ); panelSizer->Add( m_staticGenerators, 0, wxALL, 5 ); wxArrayString m_checkListGeneratorsChoices; m_checkListGenerators = new wxCheckListBox( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_checkListGeneratorsChoices, wxLB_MULTIPLE ); m_checkListGenerators->SetMinSize( wxSize( -1,120 ) ); panelSizer->Add( m_checkListGenerators, 10, wxALL|wxEXPAND, 5 ); m_buttonRun = new wxButton( this, wxID_ANY, _(LITESQL_L("Run")), wxDefaultPosition, wxDefaultSize, 0 ); panelSizer->Add( m_buttonRun, 0, wxALL, 5 ); m_gaugeRunProgress = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxSize( -1,20 ), wxGA_HORIZONTAL ); m_gaugeRunProgress->SetMinSize( wxSize( 100,20 ) ); m_gaugeRunProgress->SetMaxSize( wxSize( -1,20 ) ); panelSizer->Add( m_gaugeRunProgress, 1, wxALL|wxFIXED_MINSIZE|wxEXPAND, 5 ); this->SetSizer( panelSizer ); this->Layout(); // Connect Events m_buttonRun->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GeneratePanel::OnRunClick ), NULL, this ); } GeneratePanel::~GeneratePanel() { // Disconnect Events m_buttonRun->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GeneratePanel::OnRunClick ), NULL, this ); } ModelTreePanel::ModelTreePanel( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { wxBoxSizer* bMainSizer; bMainSizer = new wxBoxSizer( wxHORIZONTAL ); m_mainSplitter = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_3D ); m_mainSplitter->Connect( wxEVT_IDLE, wxIdleEventHandler( ModelTreePanel::m_mainSplitterOnIdle ), NULL, this ); m_treePanel = new wxPanel( m_mainSplitter, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* btreePanelSizer; btreePanelSizer = new wxBoxSizer( wxVERTICAL ); m_modelTreeCtrl = new wxTreeCtrl( m_treePanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE|wxTR_HIDE_ROOT ); btreePanelSizer->Add( m_modelTreeCtrl, 5, wxALL|wxEXPAND, 5 ); m_treePanel->SetSizer( btreePanelSizer ); m_treePanel->Layout(); btreePanelSizer->Fit( m_treePanel ); m_detailPanel = new wxPanel( m_mainSplitter, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bDetailPanelSizer; bDetailPanelSizer = new wxBoxSizer( wxVERTICAL ); m_detailNotebook = new wxNotebook( m_detailPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 ); bDetailPanelSizer->Add( m_detailNotebook, 1, wxEXPAND | wxALL, 5 ); m_detailPanel->SetSizer( bDetailPanelSizer ); m_detailPanel->Layout(); bDetailPanelSizer->Fit( m_detailPanel ); m_mainSplitter->SplitVertically( m_treePanel, m_detailPanel, 0 ); bMainSizer->Add( m_mainSplitter, 1, wxEXPAND, 5 ); this->SetSizer( bMainSizer ); this->Layout(); // Connect Events m_modelTreeCtrl->Connect( wxEVT_COMMAND_TREE_DELETE_ITEM, wxTreeEventHandler( ModelTreePanel::OnTreeDeleteItem ), NULL, this ); m_modelTreeCtrl->Connect( wxEVT_COMMAND_TREE_ITEM_ACTIVATED, wxTreeEventHandler( ModelTreePanel::OnTreeItemActivated ), NULL, this ); m_modelTreeCtrl->Connect( wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, wxTreeEventHandler( ModelTreePanel::OnTreeItemGetTooltip ), NULL, this ); m_modelTreeCtrl->Connect( wxEVT_COMMAND_TREE_ITEM_MENU, wxTreeEventHandler( ModelTreePanel::OnTreeItemMenu ), NULL, this ); m_modelTreeCtrl->Connect( wxEVT_COMMAND_TREE_SEL_CHANGED, wxTreeEventHandler( ModelTreePanel::OnTreeSelChanged ), NULL, this ); m_modelTreeCtrl->Connect( wxEVT_COMMAND_TREE_SEL_CHANGING, wxTreeEventHandler( ModelTreePanel::OnTreeSelChanging ), NULL, this ); } ModelTreePanel::~ModelTreePanel() { // Disconnect Events m_modelTreeCtrl->Disconnect( wxEVT_COMMAND_TREE_DELETE_ITEM, wxTreeEventHandler( ModelTreePanel::OnTreeDeleteItem ), NULL, this ); m_modelTreeCtrl->Disconnect( wxEVT_COMMAND_TREE_ITEM_ACTIVATED, wxTreeEventHandler( ModelTreePanel::OnTreeItemActivated ), NULL, this ); m_modelTreeCtrl->Disconnect( wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, wxTreeEventHandler( ModelTreePanel::OnTreeItemGetTooltip ), NULL, this ); m_modelTreeCtrl->Disconnect( wxEVT_COMMAND_TREE_ITEM_MENU, wxTreeEventHandler( ModelTreePanel::OnTreeItemMenu ), NULL, this ); m_modelTreeCtrl->Disconnect( wxEVT_COMMAND_TREE_SEL_CHANGED, wxTreeEventHandler( ModelTreePanel::OnTreeSelChanged ), NULL, this ); m_modelTreeCtrl->Disconnect( wxEVT_COMMAND_TREE_SEL_CHANGING, wxTreeEventHandler( ModelTreePanel::OnTreeSelChanging ), NULL, this ); }
[ [ [ 1, 386 ] ] ]
30d70ec1c024f6d3cb4c2a3c9533fc05e19b0bb5
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/audio3/naudiofile.cc
0ccf362eb61b53d4a4584ed204141c0e8f9621a9
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
2,403
cc
//------------------------------------------------------------------------------ // naudiofile.cc // (C) 2005 Radon Labs GmbH //------------------------------------------------------------------------------ #include "audio3/naudiofile.h" //------------------------------------------------------------------------------ /** */ nAudioFile::nAudioFile() : isOpen(false) { // empty } //------------------------------------------------------------------------------ /** */ nAudioFile::~nAudioFile() { n_assert(!this->IsOpen()); } //------------------------------------------------------------------------------ /** Open the file for reading. The method should open the file and read the file's header data. */ bool nAudioFile::Open(const nString& filename) { n_assert(!this->IsOpen()); this->isOpen = true; return true; } //------------------------------------------------------------------------------ /** Close the file. */ void nAudioFile::Close() { n_assert(this->IsOpen()); this->isOpen = false; } //------------------------------------------------------------------------------ /** Read data from file. Returns the number of bytes actually read. If decoding happens inside Read() the number of bytes to read and number of bytes actually read means "decoded data". The method should wrap around if the end of the data is encountered. */ uint nAudioFile::Read(void* buffer, uint bytesToRead) { n_assert(this->IsOpen()); return 0; } //------------------------------------------------------------------------------ /** Reset the object to the beginning of the audio data. */ bool nAudioFile::Reset() { n_assert(this->IsOpen()); return true; } //------------------------------------------------------------------------------ /** This method returns the (decoded) size of audio data in the file in bytes. */ int nAudioFile::GetSize() const { n_assert(this->IsOpen()); return 0; } //------------------------------------------------------------------------------ /** This method returns a pointer to a WAVEFORMATEX structure which describes the format of the audio data in the file. */ WAVEFORMATEX* nAudioFile::GetFormat() const { n_error("nAudioFile::GetFormat(): not implemented!"); return 0; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 94 ] ] ]
5bbfc06d05a5f6c74c562f07671f7dc6050317a5
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/EduNetGames/obsolete/Start/MultiplePursuit.cpp
400ab150ef3acaf95e328e434a58c8486b9409ef
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
9,214
cpp
//----------------------------------------------------------------------------- // // // OpenSteer -- Steering Behaviors for Autonomous Characters // // Copyright (c) 2002-2005, Sony Computer Entertainment America // Original author: Craig Reynolds <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // //----------------------------------------------------------------------------- // // // Multiple pursuit (for testing pursuit) // // 08-22-02 cwr: created // // //----------------------------------------------------------------------------- // 10-30-09 cp/jf: modified for educational purpose #include "OpenSteerUT/CameraPlugin.h" #include "OpenSteerUT/GridPlugin.h" #include "OpenSteer/SimpleVehicle.h" #include "OpenSteer/Color.h" namespace { using namespace OpenSteer; //----------------------------------------------------------------------------- // This Plugin uses two vehicle types: MpWanderer and MpPursuer. They have // a common base class, MpBase, which is a specialization of SimpleVehicle. class MpBase : public SimpleVehicle { public: // constructor MpBase () {reset ();} // reset state void reset (void) { SimpleVehicle::reset (); // reset the vehicle setSpeed (0); // speed along Forward direction. setMaxForce (5.0); // steering force is clipped to this magnitude setMaxSpeed (3.0); // velocity is clipped to this magnitude gaudyPursuitAnnotation = true; // select use of 9-color annotation } // draw into the scene void draw (void) { drawBasic2dCircularVehicle (*this, bodyColor); drawTrail (); } // for draw method Color bodyColor; }; class MpWanderer : public MpBase { public: // constructor MpWanderer () {reset ();} // reset state void reset (void) { MpBase::reset (); bodyColor.set (0.4f, 0.6f, 0.4f); // greenish } // one simulation step void update (const float currentTime, const float elapsedTime) { const Vec3 wander2d = steerForWander (elapsedTime).setYtoZero (); const Vec3 steer = forward() + (wander2d * 3); applySteeringForce (steer, elapsedTime); // for annotation recordTrailVertex (currentTime, position()); } }; class MpPursuer : public MpBase { public: // constructor MpPursuer (MpWanderer* w) {wanderer = w; reset ();} // reset state void reset (void) { MpBase::reset (); bodyColor.set (0.6f, 0.4f, 0.4f); // redish randomizeStartingPositionAndHeading (); } // one simulation step void update (const float currentTime, const float elapsedTime) { // when pursuer touches quarry ("wanderer"), reset its position const float d = Vec3::distance (position(), wanderer->position()); const float r = radius() + wanderer->radius(); if (d < r) reset (); const float maxTime = 20; // xxx hard-to-justify value applySteeringForce (steerForPursuit (*wanderer, maxTime), elapsedTime); // for annotation recordTrailVertex (currentTime, position()); } // reset position void randomizeStartingPositionAndHeading (void) { // randomize position on a ring between inner and outer radii // centered around the home base const float inner = 20; const float outer = 30; const float radius = frandom2 (inner, outer); const Vec3 randomOnRing = RandomUnitVectorOnXZPlane () * radius; setPosition (wanderer->position() + randomOnRing); // randomize 2D heading randomizeHeadingOnXZPlane (); } MpWanderer* wanderer; }; //----------------------------------------------------------------------------- // Plugin for OpenSteerDemo class MpPlugin : public Plugin { public: const char* name (void) const {return "Multiple Pursuit";} float selectionOrderSortKey (void) const {return 0.04f;} virtual ~MpPlugin() {} // be more "nice" to avoid a compiler warning void open (void) { // create the wanderer, saving a pointer to it wanderer = new MpWanderer; allMP.push_back (wanderer); // create the specified number of pursuers, save pointers to them const int pursuerCount = 30; for (int i = 0; i < pursuerCount; i++) allMP.push_back (new MpPursuer (wanderer)); pBegin = allMP.begin() + 1; // iterator pointing to first pursuer pEnd = allMP.end(); // iterator pointing to last pursuer // initialize camera SimpleVehicle::setSelectedVehicle( wanderer ); Camera::accessInstance().mode = Camera::cmStraightDown; Camera::accessInstance().fixedDistDistance = CameraPlugin::cameraTargetDistance; Camera::accessInstance().fixedDistVOffset = CameraPlugin::camera2dElevation; } void update (const float currentTime, const float elapsedTime) { if( false == this->isEnabled() ) { return; } // update the wanderer wanderer->update (currentTime, elapsedTime); // update each pursuer for (iterator i = pBegin; i != pEnd; i++) { ((MpPursuer&) (**i)).update (currentTime, elapsedTime); } } void redraw (const float currentTime, const float elapsedTime) { if( false == this->isVisible() ) { return; } // selected vehicle (user can mouse click to select another) AbstractVehicle& selected = *SimpleVehicle::getSelectedVehicle(); // vehicle nearest mouse (to be highlighted) AbstractVehicle& nearMouse = *SimpleVehicle::getNearestMouseVehicle(); // update camera CameraPlugin::updateCamera (currentTime, elapsedTime, selected); // draw "ground plane" GridPlugin::gridUtility( selected.position() ); // draw each vehicles for (iterator i = allMP.begin(); i != pEnd; i++) (**i).draw (); // highlight vehicle nearest mouse VehicleUtilities::highlightVehicleUtility (nearMouse); VehicleUtilities::circleHighlightVehicleUtility (selected); } void close (void) { // delete wanderer, all pursuers, and clear list delete (wanderer); for (iterator i = pBegin; i != pEnd; i++) delete ((MpPursuer*)*i); allMP.clear(); } void reset (void) { // reset wanderer and pursuers wanderer->reset (); for (iterator i = pBegin; i != pEnd; i++) ((MpPursuer&)(**i)).reset (); // immediately jump to default camera position Camera::accessInstance().doNotSmoothNextMove (); Camera::accessInstance().resetLocalSpace (); } const AVGroup& allVehicles (void) const {return (const AVGroup&) allMP;} AVGroup& allVehicles (void) {return ( AVGroup&) allMP;} // a group (STL vector) of all vehicles std::vector<MpBase*> allMP; typedef std::vector<MpBase*>::const_iterator iterator; iterator pBegin, pEnd; MpWanderer* wanderer; }; MpPlugin gMpPlugin; //----------------------------------------------------------------------------- } // anonymous namespace
[ "janfietz@localhost" ]
[ [ [ 1, 276 ] ] ]
7d1e17b719a02dd3aa041db7233f60a752279ded
fd4f996b64c1994c5e6d8c8ff78a2549255aacb7
/ nicolinorochetaller --username adrianachelotti/trunk/tp3/ClienteUno/Pad.h
88e420691dd4f32eeb47305b13df242f86aa74a0
[]
no_license
adrianachelotti/nicolinorochetaller
026f32476e41cdc5ac5c621c483d70af7b397fb0
d3215dfdfa70b6226b3616c78121f36606135a5f
refs/heads/master
2021-01-10T19:45:15.378823
2009-08-05T14:54:42
2009-08-05T14:54:42
32,193,619
0
0
null
null
null
null
UTF-8
C++
false
false
679
h
// Pad.h: interface for the Pad class. // ////////////////////////////////////////////////////////////////////// #if !defined PAD_H #define PAD_H #include "Rectangulo.h" class Pad { private: Rectangulo* representacionGrafica; Punto posicion; public: /*Constructor sin parametros*/ Pad(); /*Destructor*/ virtual ~Pad(); /*Retorna el rectangulo que representa al pad*/ Rectangulo* getRepresentacionGrafica(); /*Setea el rectangulo que representa al pad*/ void setRepresentacionGrafica(Rectangulo* representacion); /*Devuelve la posicion del vertice inferior izquierdo de la paleta*/ Punto getPosicion(); }; #endif
[ "[email protected]@0b808588-0f27-11de-aab3-ff745001d230" ]
[ [ [ 1, 36 ] ] ]
531f2db6643c9dc010cc06ff96050f10154eee2e
9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab
/demos/采用G.729的语言实时通信/TalkDll/MixOut.cpp
092d3fae614ada8d76b61e3dc8428702a64de021
[]
no_license
zzjs2001702/sfsipua-svn
ca3051b53549066494f6264e8f3bf300b8090d17
e8768338340254aa287bf37cf620e2c68e4ff844
refs/heads/master
2022-01-09T20:02:20.777586
2006-03-29T13:24:02
2006-03-29T13:24:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,452
cpp
#include "stdafx.h" #include "MixOut.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define WND_CLASS_NAME "Wave Output Volume Msg Wnd Class" #define WND_NAME "Wave Output Volume Msg Wnd" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// static CMixOut *g_pThis = NULL; LRESULT CALLBACK CMixOut::MixerWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { if ( uMsg == MM_MIXM_CONTROL_CHANGE ) { if ( g_pThis ) { g_pThis->OnControlChanged( (DWORD)lParam ); } } return ::DefWindowProc( hwnd, uMsg, wParam, lParam); } MMRESULT CMixOut::GetLastMMError() { return m_mmr; } CString CMixOut::GetLastErrorString() { char buffer[256]; memset(buffer,0,256); switch(m_mmr) { case MMSYSERR_NOERROR: sprintf(buffer,"No error."); break; case MIXERR_INVALCONTROL: sprintf(buffer,"Specified device handle is invalid."); break; case MMSYSERR_BADDEVICEID: sprintf(buffer,"The hmxobj parameter specifies an invalid device identifier."); break; case MMSYSERR_INVALFLAG: sprintf(buffer,"One or more flags are invalid."); break; case MMSYSERR_INVALHANDLE: sprintf(buffer,"The hmxobj parameter specifies an invalid handle."); break; case MMSYSERR_INVALPARAM: sprintf(buffer,"One or more parameters are invalid."); break; case MMSYSERR_NODRIVER: sprintf(buffer,"No mixer device is available for the object specified by hmxobj."); break; case MIXERR_INVALLINE: sprintf(buffer,"The audio line reference is invalid.."); break; case MMSYSERR_NOTSUPPORTED: sprintf(buffer,"The mixer device did not process the message."); break; case MMSYSERR_ALLOCATED: sprintf(buffer,"The specified resource is already allocated by the maximum number of clients possible."); break; case MMSYSERR_NOMEM: sprintf(buffer,"Unable to allocate resources."); break; default: sprintf(buffer,"Unknow error,Error code %d",m_mmr); break; } return buffer; } CMixOut::CMixOut(): m_iDevNum(0), m_uiMixerId(0), m_hMixer(0), m_hWnd(NULL), m_bIni(FALSE), m_dwMinimalVolume(0), m_dwMaximalVolume(100) { g_pThis = this; } CMixOut::~CMixOut() { } BOOL CMixOut::Ini() { if (m_bIni) { TRACE("Mix in has alreadly ini.\n"); return FALSE; } if (!OpenMixer()) { TRACE("%s.\n",GetLastErrorString()); return FALSE; }; if (!Initialize()) { TRACE("%s.\n",GetLastErrorString()); return FALSE; } m_bIni = TRUE; return TRUE; } BOOL CMixOut::UnIni() { if (!m_bIni) { TRACE("Mix in hasn't ini.\n"); return FALSE; } ::DestroyWindow( m_hWnd ); CloseMixer(); m_iDevNum = 0; m_uiMixerId = 0; m_hMixer = 0; m_hWnd = NULL; m_bIni = FALSE; m_dwMinimalVolume = 0; m_dwMaximalVolume = 100; m_bIni = FALSE; return TRUE; } BOOL CMixOut::OpenMixer() { m_iDevNum = mixerGetNumDevs(); if (m_iDevNum == 0) { TRACE("There (is) are no device mixer.\n"); return FALSE; } WAVEFORMATEX wfx; memset( &wfx, 0, sizeof(WAVEFORMATEX) ); wfx.wFormatTag = WAVE_FORMAT_PCM; wfx.nChannels = 1; wfx.nSamplesPerSec = 8000; wfx.nAvgBytesPerSec = 1 * 8000 * 16 / 8; wfx.nBlockAlign = 16 * 1 / 8; wfx.wBitsPerSample = 16; wfx.cbSize = 0; HWAVEOUT hwaveOut; m_mmr = waveOutOpen( &hwaveOut, WAVE_MAPPER, &wfx, 0L, 0L, CALLBACK_NULL ); if ( m_mmr != MMSYSERR_NOERROR ) { return false; } else { m_mmr = mixerGetID( (HMIXEROBJ)hwaveOut, &m_uiMixerId, MIXER_OBJECTF_HWAVEOUT ); waveOutClose( hwaveOut ); if (m_mmr != MMSYSERR_NOERROR ) { return false; } } WNDCLASSEX wcx; memset( &wcx, 0, sizeof(WNDCLASSEX) ); wcx.cbSize = sizeof(WNDCLASSEX); wcx.lpszClassName = WND_CLASS_NAME; wcx.lpfnWndProc = (WNDPROC)MixerWndProc; ::RegisterClassEx(&wcx); m_hWnd = CreateWindow( WND_CLASS_NAME, WND_NAME, WS_POPUP | WS_DISABLED, 0, 0, 0, 0, NULL, NULL, NULL, NULL ); if ( !m_hWnd ) { return false; } ::ShowWindow(m_hWnd, SW_HIDE); m_mmr = mixerOpen( (LPHMIXER)&m_hMixer, m_uiMixerId, (DWORD)m_hWnd, 0L, CALLBACK_WINDOW ); if (m_mmr != MMSYSERR_NOERROR ) { ::DestroyWindow( m_hWnd ); return false; } return true; } BOOL CMixOut::CloseMixer() { if (m_hMixer) { m_mmr = mixerClose((HMIXER)m_hMixer); if (m_mmr != MMSYSERR_NOERROR ) { return false; } } return TRUE; } void CMixOut::OnControlChanged(int iValue) { } BOOL CMixOut::Initialize() { if (m_hMixer) { TRACE("You haven't open the mixer.\n"); return FALSE; } MIXERLINE MixerLine; memset( &MixerLine, 0, sizeof(MIXERLINE) ); MixerLine.cbStruct = sizeof(MIXERLINE); MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; m_mmr = mixerGetLineInfo( (HMIXEROBJ)m_hMixer, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); if ( m_mmr != MMSYSERR_NOERROR ) { return false; } MIXERCONTROL Control; memset( &Control, 0, sizeof(MIXERCONTROL) ); Control.cbStruct = sizeof(MIXERCONTROL); MIXERLINECONTROLS LineControls; memset( &LineControls, 0, sizeof(MIXERLINECONTROLS) ); LineControls.cbStruct = sizeof(MIXERLINECONTROLS); LineControls.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; LineControls.dwLineID = MixerLine.dwLineID; LineControls.cControls = 1; LineControls.cbmxctrl = sizeof(MIXERCONTROL); LineControls.pamxctrl = &Control; m_mmr = mixerGetLineControls( (HMIXEROBJ)m_hMixer, &LineControls, MIXER_GETLINECONTROLSF_ONEBYTYPE ); if ( m_mmr == MMSYSERR_NOERROR ) { if ((Control.fdwControl & MIXERCONTROL_CONTROLF_DISABLED) ) { return FALSE; } } else { return FALSE; } m_dwMinimalVolume = Control.Bounds.dwMinimum; m_dwMaximalVolume = Control.Bounds.dwMaximum; return TRUE; } DWORD CMixOut::GetMinimalVolume() { if (!m_bIni) { TRACE("Mix in hasn't ini.\n"); return 0; } return this->m_dwMinimalVolume ; } DWORD CMixOut::GetMaximalVolume() { if (!m_bIni) { TRACE("Mix in hasn't ini.\n"); return 100; } return this->m_dwMaximalVolume ; } DWORD CMixOut::GetCurrentVolume() { if (!m_bIni) { TRACE("Mix in hasn't ini.\n"); return 0; } return 0; } void CMixOut::SetCurrentVolume(DWORD dwValue) { }
[ "yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd" ]
[ [ [ 1, 302 ] ] ]
8a216b749baca49d68513d03838abb5e97a7c77f
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak.Toolkit/TypeInfo.h
5601fd3e9c515b71ef7d3219586622b706c8cd78
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
2,247
h
#pragma once #ifndef __HALAK_TOOLKIT_TYPEINFO_H__ #define __HALAK_TOOLKIT_TYPEINFO_H__ # include <Halak.Toolkit/FWD.h> # include <vector> namespace Halak { namespace Toolkit { class TypeInfo { HKThisIsNoncopyableClass(TypeInfo); public: typedef std::vector<const Attribute*> AttributeCollection; public: void Add(const Attribute* item); bool Remove(const Attribute* item); inline uint32 GetID() const; inline const char* GetNamespace() const; inline const char* GetName() const; inline int GetAllocationSize() const; inline bool IsPrimitive() const; inline bool IsClass() const; inline bool IsEnum() const; inline const AttributeCollection& GetAttributes() const; protected: enum Type { Primitive = (1 << 0), Class = (1 << 1), Enum = (1 << 2), }; protected: TypeInfo(Type type, const int allocationSize); virtual ~TypeInfo(); private: inline void SetID(uint32 value); inline void SetNamespace(const char* value); inline void SetName(const char* value); private: uint32 id; const char* namespace_; const char* name; const int allocationSize; const byte type; AttributeCollection attributes; private: friend class TypeLibrary; friend class PrimitiveRegistrationContext; friend class ClassRegistrationContext; friend class EnumRegistrationContext; }; } } # include <Halak.Toolkit/TypeInfo.inl> #endif
[ [ [ 1, 70 ] ] ]
92ff2c42a8be66a9ca802616868f317c6474b149
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/deeppurple/lwplugins/lwwrapper/Panel/ControlDistance.cpp
b4413d4f9af35f4836bb869544655b76031de0e6
[]
no_license
BackupTheBerlios/lwpp-svn
d2e905641f60a7c9ca296d29169c70762f5a9281
fd6f80cbba14209d4ca639f291b1a28a0ed5404d
refs/heads/master
2021-01-17T17:01:31.802187
2005-10-16T22:12:52
2005-10-16T22:12:52
40,805,554
0
0
null
null
null
null
UTF-8
C++
false
false
467
cpp
#include "StdAfx.h" #include "controldistance.h" ControlDistance::ControlDistance() { } ControlDistance::~ControlDistance(void) { } bool ControlDistance::RegisterWithPanel(LWPanelID pan) { LWPanControlDesc locDesc; locDesc.type=LWT_FLOAT; this->ThisControl=Lightwave3D::panf->addControl(pan,"FloatControl",&locDesc,const_cast<char *>(Name.c_str())); if (this->ThisControl) return true; else return false; }
[ "deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 22 ] ] ]
e74850e039edb09452b8d1622e44823e34fd3007
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/YearsViewSchema.cpp
5fe4c94efcdc246e32cc791edd45ec29efbf9701
[]
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
2,504
cpp
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * 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, 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 GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #include "stdafx.h" #include "YearsViewSchema.h" const TCHAR* const YearsVSString[] = { _T("first(Tracks.Year)"), _T("count(*)"), }; void YearsViewSchema::GetSQL(TCHAR* sql, int len, TracksFilter& Filter, YearsViewSchema::Sorting sorting, BOOL SortDescending) { ASSERT(sql != NULL); ASSERT(len > 200); _tcsncpy(sql, _T("SELECT ") _T("count(*), first(Albums.Year) ") _T("FROM Tracks INNER JOIN Albums ON Tracks.albID = Albums.ID "), len); size_t curLen = _tcslen(sql); ASSERT(curLen); _tcscat(sql, _T(" W"));//Keep some chars for "Where" curLen+=2; size_t newLen = curLen; newLen += GetSQLTracksFilter(&sql[curLen], len - curLen, Filter); if (newLen != curLen) { sql[curLen] = 'H'; sql[curLen+1] = 'E'; sql[curLen+2] = 'R'; sql[curLen+3] = 'E'; curLen = newLen; } else { curLen -= 2; sql[curLen] = 0; } _tcsncat(sql, _T(" GROUP BY albums.year"), len - curLen); curLen = _tcslen(sql); if (sorting > SORT_Disabled && sorting < SORT_Last) { curLen = _tcslen(sql); _sntprintf(&sql[curLen], len - curLen, _T(" ORDER BY %s"), YearsVSString[sorting - 1]); if (SortDescending) { curLen = _tcslen(sql); _tcsncat(sql, _T(" DESC"), len - curLen); } } } INT YearsViewSchema::GetNumTracks() { ASSERT(m_bRecordsetReady); INT val = 0; m_RS->GetFieldValue(0, val); return val; } INT YearsViewSchema::GetYear() { ASSERT(m_bRecordsetReady); INT val = 0; m_RS->GetFieldValue(1, val); return val; }
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 93 ] ] ]
66f18f3973a4a95ad78fc4703401a460a12b1700
2112057af069a78e75adfd244a3f5b224fbab321
/branches/refactor/src_root/src/ireon_client/interface/py_app.cpp
6f5c65cadcc4d5cafb0216073aa464b8f6342535
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,625
cpp
/* Copyright (C) 2005 ireon.org developers council * $Id: py_app.cpp 433 2005-12-20 20:19:15Z zak $ * 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. */ /** * @file py_app.cpp * Export app class to python */ #include "stdafx.h" #include "db/client_char_data.h" #include "ireon_client/net/ws_player_client.h" #define BOOST_PYTHON_STATIC_MODULE #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> using namespace boost::python; class CPythonOutput { public: void write(String arg) {CLog::instance()->log(CLog::msgFlagPython,CLog::msgLvlInfo,arg.c_str());} }; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(CApp_overloads1, getSetting, 1, 1) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(CApp_overloads2, setSetting, 2, 2) BOOST_PYTHON_MODULE(App) { typedef std::vector<ClientOwnCharData> CharVector; class_<CharVector>("CharVector") .def( vector_indexing_suite< std::vector<ClientOwnCharData> >()); typedef std::vector<byte> ByteVector; class_<ByteVector>("ByteVector") .def( vector_indexing_suite< std::vector<byte> >()); class_<StringVector>("StringVector") .def( vector_indexing_suite< std::vector<std::string>, true>()); class_< CPythonOutput > ("Output") .def("write",&CPythonOutput::write); class_< CData > ("Data"); class_< CNetClient, CNetClient*, boost::noncopyable > ("NetClient", no_init ); class_< CPlayerClient, CPlayerClient*, bases<CNetClient> > ("PlayerClient", no_init ); class_< CWSPlayerClient, CWSPlayerClient*, bases<CPlayerClient> > ("WSPlayerClient", no_init) .def("disconnect",&CWSPlayerClient::disconnect) .def("reconnect",&CWSPlayerClient::reconnect) .def("connect",&CWSPlayerClient::connect) .add_property("port",&CWSPlayerClient::getPort) .add_property("host",&CWSPlayerClient::getHost) /// Commands .def("sendChatCmd",&CWSPlayerClient::sendChatCmd); class_< ClientCharData, ClientCharData* > ("ClientCharData") .def_readwrite("velocity",&ClientCharData::m_velocity) .def("serialize",&ClientCharData::serialize); class_< ClientCharPlayerData, ClientCharPlayerData* > ("ClientCharPlayerData") .def_readwrite("id",&ClientCharPlayerData::m_id) .def_readwrite("name",&ClientCharPlayerData::m_name) .def("serialize",&ClientCharPlayerData::serialize); class_< ClientOwnCharData, ClientOwnCharData*, bases<ClientCharPlayerData> > ("ClientOwnCharData") .def_readwrite("id",&ClientOwnCharData::m_id) .def_readwrite("name",&ClientOwnCharData::m_name) .def_readwrite("velocity",&ClientOwnCharData::m_velocity); class_< CClientApp > ("Application",no_init) // .def("rootConn",&CClientApp::getRootConn,return_value_policy<reference_existing_object>()) // .def("worldConn",&CClientApp::getWorldConn,return_value_policy<reference_existing_object>()) .def("shutdown",&CClientApp::shutdown) .add_property("state",&CClientApp::getState,&CClientApp::setState) .def("getSetting",&CClientApp::getSetting,CApp_overloads1()) .def("setSetting",&CClientApp::setSetting,CApp_overloads2()) // .def("connect",&CClientApp::connect) // .def("cancelConnect",&CClientApp::cancelConnect) // .def("createChar",&CClientApp::createChar) // .def("selectChar",&CClientApp::selectChar) // .def("removeChar",&CClientApp::removeChar) .def_readwrite("characters",&CClientApp::m_characters); enum_< CClientApp::State > ("State") .value("MENU",CClientApp::AS_MENU) // .value("CONNECTING_ROOT",CClientApp::AS_CONNECTING_ROOT) // .value("LOGGING_ROOT",CClientApp::AS_LOGGING_ROOT) // .value("CONNECTING_WORLD",CClientApp::AS_CONNECTING_WORLD) // .value("LOGGING_WORLD",CClientApp::AS_LOGGING_WORLD) .value("ROOT",CClientApp::AS_ROOT) .value("PLAY",CClientApp::AS_PLAY); def("get",&CClientApp::instance,return_value_policy<reference_existing_object>()); }; void initAppModule() { initApp(); };
[ [ [ 1, 129 ] ] ]
88e48645c68323c24411aa68e51988f969f22f63
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/Demo/NetSDKDemo.h
5a6c791842fcba891bae391b015fbb6034b0730d
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
5,183
h
// NetSDKDemo.h : main header file for the NETSDKDEMO application // #if !defined(AFX_NETSDKDEMO_H__F984CDA1_DB9B_44E5_ADD8_44A8BB6D6E9D__INCLUDED_) #define AFX_NETSDKDEMO_H__F984CDA1_DB9B_44E5_ADD8_44A8BB6D6E9D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CNetSDKDemoApp: // See NetSDKDemo.cpp for the implementation of this class // //老报警接口 typedef struct { NET_CLIENT_STATE cState; DWORD dError; DWORD dFull; BYTE shelter[16]; BYTE soundalarm[16]; BYTE almDecoder[16]; BYTE PosTicket[1024]; BYTE PosTicketRawData[1024]; }DEV_STATE; /* //新报警接口 typedef struct { BYTE alarmout[16]; BYTE motion[16]; BYTE videolost[16]; BYTE shelter[16]; BYTE soundalarm[16]; BYTE diskfull; BYTE diskerror[32]; }DEV_STATE; */ //设备信息列表结构 typedef struct _DeviceNode { char UserNanme[20]; //登录用户名 char Name[24]; //设备名称 char IP[20]; //设备IP地址字符 LONG LoginID; //设备登录iD NET_DEVICEINFO Info; //设备信息 DEV_STATE State; //设备状态 DWORD TotalKbps; //设备当前总码流 DWORD Max_Kbps; //设置最大网络流量 BOOL bIsOnline; }DeviceNode; //当前画面显示内容的类型 typedef enum _SplitType{ SPLIT_TYPE_NULL = 0, //空白 SPLIT_TYPE_MONITOR, //网络监视 SPLIT_TYPE_NETPLAY, //网络回放 SPLIT_TYPE_MULTIPLAY, //网络预览 SPLIT_TYPE_FILEPLAY, //本地文件播放 SPLIT_TYPE_CYCLEMONITOR, //轮循监视 SPLIT_TYPE_PBBYTIME //通过时间回放 }SplitType; //视频参数结构 typedef union _VideoParam{ BYTE bParam[4]; DWORD dwParam; //视频参数 }VideoParam; //画面分割通道显示信息(可以定义成type/param,param自定义) typedef struct _SplitInfoNode { SplitType Type; //显示类型 空白/监视/网络回放/本地回放等 DWORD iHandle; //用于记录通道id(监视通道ID/播放文件iD等) // DWORD nTimeCount; //时间计数,用于码流统计 // DWORD nKBPS; //码流统计//sdk增加接口后不用应用层统计 int isSaveData; //数据是否保存(直接sdk保存) FILE *SavecbFileRaw; //保存回调原始数据 FILE *SavecbFileStd; //保存回调mp4数据 FILE *SavecbFileYUV; //保存回调yuv数据 FILE *SavecbFilePcm; //保存回调pcm数据 VideoParam nVideoParam; //视频参数 void *Param; //信息参数,对于不同的显示有不同的参数 }SplitInfoNode; class CNetSDKDemoApp : public CWinApp { public: CNetSDKDemoApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CNetSDKDemoApp) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CNetSDKDemoApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; /* class CDeviceListProtector //全局变量保护类 { public: CDeviceListProtector(CPtrList **list):m_ptrdevicelist(list) { *m_ptrdevicelist = new CPtrList(sizeof(DeviceNode)); *list = *m_ptrdevicelist; } ~CDeviceListProtector() { int count = (*m_ptrdevicelist)->GetCount(); for (int i = 0; i < count; i++) { delete (DeviceNode *)((*m_ptrdevicelist)->GetTail()); (*m_ptrdevicelist)->RemoveTail(); } (*m_ptrdevicelist)->RemoveAll(); delete (*m_ptrdevicelist); } private: CPtrList **m_ptrdevicelist; }; class CCSLock { public: CCSLock(CRITICAL_SECTION& cs):m_cs(cs) { EnterCriticalSection(&m_cs); } ~CCSLock() { LeaveCriticalSection(&m_cs); } private: CRITICAL_SECTION& m_cs; }; */ //extern CRITICAL_SECTION g_cs; //全局变量,用于保存程序所在目录的路径名 extern CString g_strWorkDir; //全局变量,用于保存设备列表 //extern CPtrList *g_ptrdevicelist ; //全局函数,将系统时间格式转换为公司定义的网络时间格式 void g_SysTimetoYwtime(SYSTEMTIME *systime , NET_TIME *ywtime); //全局函数,将公司定义的网络时间格式转换为系统时间格式 void g_YwtimetoSystime(NET_TIME *ywtime , SYSTEMTIME *systime); //全局函数,将公司定义的网络时间转换为字符串显示 CString g_TimeOutString(NET_TIME *ywtime ); //全局函数, 计算两时间点之差 DWORD g_IntervalTime(NET_TIME *stime, NET_TIME *etime ); void g_SetWndStaticText(CWnd * pWnd); TCHAR* g_GetIniPath(void); CString ConvertString(CString strText); void ConvertComboBox(CComboBox &stuComboBox); ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_NETSDKDEMO_H__F984CDA1_DB9B_44E5_ADD8_44A8BB6D6E9D__INCLUDED_)
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 190 ] ] ]
c604df29c143c5405c2d787540a58d4cbb973cfa
f2dbe1f26c9ec2af0e7384502558d73ae1626ffd
/big integer/big_integer.h
f08d3e2bfa7db2c14edbfbc2f8b159a86f366c7c
[]
no_license
deckar01/cuda-thrust-extensions
8aea58ed99f36775e0d251e618af9d1d4d52c455
687e1422d898a23029b86b3e32051f0d02eefe69
refs/heads/master
2023-07-21T23:41:19.217232
2010-06-22T21:30:01
2010-06-22T21:30:01
105,018,194
1
1
null
2017-09-27T12:55:38
2017-09-27T12:55:38
null
UTF-8
C++
false
false
6,240
h
/*! \file big_integer.h * \brief Implementation of arbitrary precision integer arithmetic. */ #pragma once #include <iosfwd> #include <stdlib.h> #include <string> #include <string.h> #include <limits> typedef unsigned int uint; namespace thrust { const uint msb = std::numeric_limits<uint>::max() ^ ( std::numeric_limits<uint>::max() >> 1 ); const uint max_uint = std::numeric_limits<uint>::max(); template<uint value_size> struct big_integer { //public: __host__ __device__ inline big_integer(uint value) { set_zero(); data[0] = value; } __host__ __device__ inline big_integer(int value) { set_zero(); data[0] = (uint)value; } __host__ __device__ inline big_integer() { set_zero(); } __host__ __device__ inline big_integer<value_size>& operator=(uint value) { data[0] = value; return *this; } __host__ __device__ inline big_integer<value_size>& operator=(int value) { data[0] = (uint)value; return *this; } __host__ __device__ inline operator uint() { return data[0]; } __host__ __device__ inline operator int() { return (int)data[0]; } __host__ __device__ inline uint size() const { return value_size; } __host__ __device__ inline void set_zero() { // device don't have memset, //memset(data, 0, sizeof(uint) * value_size); for(int i = 0; i < value_size; i++) data[i] = 0; } __host__ __device__ static inline big_integer<value_size> zero() { return m_zero; } __host__ __device__ static inline big_integer<value_size> max() // return max value for a given value size { big_integer<value_size> m; for(int i = 0; i < value_size; i++) m.data[i] = max_uint; return m; } // Shift operators /* big_integer<value_size> operator>>(int shift); big_integer<value_size> operator<<(int shift); big_integer<value_size>& operator>>=(int shift); big_integer<value_size>& operator<<=(int shift); */ // Arithmetic operators __host__ __device__ big_integer<value_size> operator+(const big_integer<value_size>& other) const; /* big_integer<value_size>& operator+=(const big_integer<value_size>& q); big_integer<value_size>& operator++(); // Pre Increment operator -- faster than add big_integer<value_size>& operator++(int); // Post Increment operator -- faster than add big_integer<value_size> operator-(); // Negates a number big_integer<value_size> operator-(const big_integer<value_size>& q) const; big_integer<value_size>& operator-=(const big_integer<value_size>& q); big_integer<value_size>& operator--(); // Pre Decrement operator -- faster than add big_integer<value_size>& operator--(int); // Post Decrement operator -- faster than add //big_integer<value_size> operator*(big_integer<value_size> q); big_integer<value_size> operator*(const big_integer<value_size>& q) const; big_integer<value_size> Divide(big_integer<value_size> dividend, big_integer<value_size> divisor, big_integer<value_size>* remainder); big_integer<value_size> operator/(const big_integer<value_size>& q); big_integer<value_size> operator%(const big_integer<value_size>& q); big_integer<value_size> sqrt(); // returns the square root of this */ // Comparison operators __host__ __device__ int operator<(const big_integer<value_size>& q) const; __host__ __device__ int operator>(const big_integer<value_size>& q) const; __host__ __device__ int operator<=(const big_integer<value_size>& q) const; __host__ __device__ int operator>=(const big_integer<value_size>& q) const; // Bitwise operators /* big_integer<value_size> operator&(const big_integer<value_size>& q); big_integer<value_size> operator|(const big_integer<value_size>& q); big_integer<value_size> operator^(const big_integer<value_size>& q); big_integer<value_size>& operator&=(const big_integer<value_size>& q); big_integer<value_size>& operator|=(const big_integer<value_size>& q); big_integer<value_size>& operator^=(const big_integer<value_size>& q); big_integer<value_size> operator~(); */ // Comparison operators __host__ __device__ int operator==(const big_integer<value_size>& other) const { // device don't have memcmp return memcmp( data, other.data, value_size * sizeof(uint) ) == 0; } /* __host__ __device__ int operator!=(const big_integer<value_size>& other) const { // device don't have memcmp return memcmp( data, other.data, value_size * sizeof(uint) ) != 0; } */ //private: // Storage for values uint data[value_size]; // zero value static big_integer<value_size> m_zero; //template<uint value_size> //friend std::ostream& operator<<(std::ostream& out, const big_integer<value_size>& number); }; } template<uint value_size> thrust::big_integer<value_size> thrust::big_integer<value_size>::m_zero; /* template<uint value_size> std::ostream& operator<<(std::ostream & out, thrust::big_integer<value_size>& num) { thrust::big_integer<value_size> billion = 1000000000; thrust::big_integer<value_size> digit; thrust::big_integer<value_size> q; uint decimaldigit; ldiv_t divideresult; int i; //char tmp; char* p; char* decimal_array = new char[8000]; // Allocate only needed, taking into // account value_size template parameter q = num; p = decimal_array + 3999; *p = 0; p--; if( q == thrust::big_integer<value_size>::zero() ) { *p = '0'; p--; } for(; q > thrust::big_integer<value_size>::zero(); ) { q = q.Divide( q, billion, &digit ); decimaldigit = digit; for( i = 0; i < 9; i++ ) { divideresult = ldiv( decimaldigit, 10 ); *p = (char) divideresult.rem + 0x30; p--; decimaldigit = divideresult.quot; } } for( p++; *p=='0'; p++ ) {} // Strip off leading zeros. if( *p == 0 ) p--; //printf("%s", p); //out << p; out << std::string(p); delete decimal_array; return out; } */ #include "big_integer.inl"
[ "evandermozart@5b3733e1-eabe-a30b-7ceb-694ffea8ce2e" ]
[ [ [ 1, 236 ] ] ]
05d286685b4761460589f1ca8247fb2d307e06f9
18a8014f912f68f9e8c1f5a5ba8ac6b5790f23ce
/src/modules/pokemon/pokemon.cpp
34fcbd33713a6c21bf4dff135e228b9cf3f28ed5
[]
no_license
turtwig/brobot
08c9d9832de14d36b074dd16903003d034fde871
24e00c7940c3468e317139f2a3b687a45271792f
refs/heads/master
2021-01-15T20:03:51.592313
2010-07-16T13:18:53
2010-07-20T15:16:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,963
cpp
#include "modules/pokemon/pokemon.h" PokemonModule::PokemonModule(Brobot* const bro) { channel = bro->stor->get("module.pokemon.channel"); asciidir = bro->stor->get("module.pokemon.asciidir"); stordir = bro->stor->get("module.pokemon.basedir"); }; void PokemonModule::onLoad(Brobot* const bro) { bro->hook("[poke] Test", "OnPRIVMSG", boost::bind(&PokemonModule::testF, this, bro, _1)); }; void PokemonModule::onUnload(Brobot* const bro) { bro->unhook("[poke] Test", "OnPRIVMSG"); }; void PokemonModule::testF(Brobot* const bro, const Args& args) { if (args[4] != channel || args[5].substr(0, 6) != ".poke ") return; Pokemon front(args[5].substr(6, std::string::npos), "cocksucker ", 30, 5); Pokemon back(args[5].substr(6, std::string::npos), "faggot<3 ", 555, 55); front.hp = 10; back.hp = 55; BOOST_FOREACH(std::string s, renderBattle(front, back)) bro->irc->privmsg(channel, s); BOOST_FOREACH(std::string s, renderMessage("I AM SO FUCKING GAY", "THOUGH SERIOUSLY WHAT WILL COCKSUCKER DO", true)) bro->irc->privmsg(channel, s); }; std::vector<std::string> PokemonModule::renderHP(const Pokemon& p) { std::vector<std::string> hpbar; if (p.nickname.size() != 11 || p.hp > p.maxhp || p.level > 999 || p.hp > 99999999 || p.maxhp > 99999999) { return hpbar; } std::string levelstr; if (p.level < 10) { levelstr = "0"+boost::lexical_cast<std::string>(p.level)+"0,0X"; } else if (p.level > 99) { levelstr = boost::lexical_cast<std::string>(p.level)+"0,0"; } else { levelstr = boost::lexical_cast<std::string>(p.level)+"0,0X"; } hpbar.push_back("1,0"+p.nickname+"0,0XXXXX1,0L.0,0X1,00"+levelstr); unsigned short int barcolor; if ((double)p.hp/(double)p.maxhp > 0.6) { barcolor = 9; } else if ((double)p.hp/(double)p.maxhp > 0.3) { barcolor = 8; } else { barcolor = 4; } std::string l = "1,1X"+boost::lexical_cast<std::string>(barcolor)+","+boost::lexical_cast<std::string>(barcolor); unsigned short int i; for (i = 0; i < (int)(((double)p.hp/(double)p.maxhp)*20.0); ++i) { l += "X"; } l += "0,0"; for (; i < 20; ++i) { l += "X"; } l += "1,1X0,0"; hpbar.push_back(l); std::string hpline = "1,1XX0,01"+boost::lexical_cast<std::string>(p.hp)+"1,1"; for (unsigned short int j = 8; j > boost::lexical_cast<std::string>(p.hp).size(); --j) { hpline += "X"; } hpline += "0,1/1,1"; for (unsigned short int j = 8; j > boost::lexical_cast<std::string>(p.maxhp).size(); --j) { hpline += "X"; } hpline += "0,01"+boost::lexical_cast<std::string>(p.maxhp)+"1,1XXX0,0"; hpbar.push_back(hpline); return hpbar; }; std::vector<std::string> PokemonModule::renderBattle(const Pokemon& front, const Pokemon& back) { std::vector<std::string> screen; std::ifstream fsprite, bsprite; fsprite.open((asciidir+front.frontfname).c_str(), std::ios::in); bsprite.open((asciidir+back.backfname).c_str(), std::ios::in); if (!(fsprite && bsprite)) return screen; std::string btoppadding = "0,0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; std::string fbotpadding = "0,0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; unsigned short int i; for (i = 0; i < 3; ++i) { screen.push_back(btoppadding); } BOOST_FOREACH(std::string hpline, renderHP(front)) { hpline = "0,0XXXXXXXXXXXXXXXXXXXXXXX"+hpline+"XXXXXXXXXXXXXXX"; screen.push_back(hpline); } for (; i < 14; ++i) { screen.push_back(btoppadding); } std::string line; while (!bsprite.eof()) { std::getline(bsprite, line); screen.push_back(line); } bsprite.close(); i = 0; while (!fsprite.eof()) { std::getline(fsprite, line); screen[i] += line; ++i; } for (; i < screen.size()-6; ++i) { screen[i] += fbotpadding; } BOOST_FOREACH(std::string hpline, renderHP(back)) { hpline = "0,0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"+hpline+"XXXXXXXXXXXXXXXXXXXXXXX"; screen[i++] += hpline; } for (; i < screen.size(); ++i) { screen[i] += fbotpadding; } return screen; }; std::vector<std::string> PokemonModule::renderMessage(std::string m1, std::string m2, bool actionBox) { std::vector<std::string> msg; if (!actionBox) { if (m1.size() > 90 || m2.size() > 90) return msg; msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XX1,1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX14,14XX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); m1 += "0,0"; for (unsigned short int i = 90; 90 > m1.size(); ++i) m1 += 'X'; msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XX1,1XX0,0XX1,0"+m1+"XX1,1XX14,14XX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); m2 += "0,0"; for (unsigned short int i = 90; 90 > m2.size(); ++i) m2 += 'X'; msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XX1,1XX0,0XX1,0"+m2+"XX1,1XX14,14XX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XX1,1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX14,14XX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } else { if (m1.size() > 70 || m2.size() > 70) return msg; msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0,0XX1,1XXXXXXXXXXXXXXXXXX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1,1XX0,0XX1,1XX0,0XXXXXXXXXXXXXX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XX1,1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX14,14XX1,1XX0,0XX1,1XX0,0X1,0FIGHT0,0XX1,0PKMN0,0XX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); m1 += "0,0"; for (unsigned short int i = 70; 70 > m1.size(); ++i) m1 += 'X'; msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XX1,1XX0,0XX1,0"+m1+"XX1,1XX14,14XX1,1XX0,0XX1,1XX0,0XXXXXXXXXXXXXX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); m2 += "0,0"; for (unsigned short int i = 70; 70 > m2.size(); ++i) m2 += 'X'; msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XX1,1XX0,0XX1,0"+m2+"XX1,1XX14,14XX1,1XX0,0XX1,1XX0,0XX1,0ITEM0,0XXX1,0RUN0,0XX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XX1,1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX14,14XX1,1XX0,0XX1,1XX0,0XXXXXXXXXXXXXX1,1XX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XX14,14XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1,1XX0,0XX1,1XXXXXXXXXXXXXXXXXX0,0XXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXX1,1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0,0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); msg.push_back("0,0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } return msg; };
[ [ [ 1, 161 ] ] ]
138bbb8ab6923325e9fcf6fb1d5e182d1d5e2d4d
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/romtools/rombuild/r_coreimage.cpp
dd2a8f84910fbed3792b64843118f5893b7f4232
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,312
cpp
/* * Copyright (c) 2008-2009 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: * */ #include <e32def.h> #include <e32def_private.h> #include <e32rom.h> #include "h_utl.h" #include "r_rom.h" #include "r_coreimage.h" // CoreRomImage // CoreRomImage::CoreRomImage(const char* aFileName) : iReader(0), iFileName(aFileName), iRomHdr(0), iRootDirectory(0), iNumVariants(0), iVariants(0), iRomAlign(0), iDataRunAddress(0) { } CoreRomImage::~CoreRomImage() { if(iReader) delete iReader; if(iVariants) delete[] iVariants; } TBool CoreRomImage::ProcessImage(const TBool aUseMemMap) { TBool Status = EFalse; TRomRootDirectoryList *rootDirInfo = 0; TInt dirCount = 0; iReader = new CoreRomImageReader(iFileName.c_str(), aUseMemMap); if(!iReader) { return EFalse; } if(iReader->OpenImage()) { Status = iReader->ProcessImage(); } if(Status) { // CoreRomHeader Info iRomHdr = iReader->GetCoreRomHeader(); if(iRomHdr) { // Root Directory Info rootDirInfo = iReader->GetRootDirList(); dirCount = rootDirInfo->iNumRootDirs; if(dirCount) { iNumVariants = dirCount; iVariants = new THardwareVariant[dirCount]; if(iVariants) { while(dirCount--) { iVariants[dirCount] = rootDirInfo->iRootDir[dirCount].iHardwareVariant; } } // RootDirectory Info iRootDirectory = iReader->GetRootDirectory(); } else { Status = EFalse; } } else { Status = EFalse; } } return Status; } TRomNode* CoreRomImage::CopyDirectory(TRomNode*& aSourceDirectory) { return iRootDirectory->CopyDirectory(aSourceDirectory,0); } TUint32 CoreRomImage::RomBase() const { return (iRomHdr->iRomBase); } TUint32 CoreRomImage::RomSize() const { return (iRomHdr->iRomSize); } TVersion CoreRomImage::Version() const { return (iRomHdr->iVersion); } TInt64 CoreRomImage::Time() const { return (iRomHdr->iTime); } TUint32 CoreRomImage::CheckSum() const { return (iRomHdr->iCheckSum); } TUint32 CoreRomImage::CompressionType() const { return (iRomHdr->iCompressionType); } TRomNode* CoreRomImage::RootDirectory() const { return iRootDirectory; } const char* CoreRomImage::RomFileName() const { return iFileName.data(); } TUint32 CoreRomImage::RomAlign() const { return iRomAlign; } TUint32 CoreRomImage::DataRunAddress() const { return iDataRunAddress; } TInt32 CoreRomImage::VariantCount() const { return iNumVariants; } THardwareVariant* CoreRomImage::VariantList() const { return iVariants; } void CoreRomImage::SetRomAlign(const TUint32 aAlign) { iRomAlign = aAlign; } void CoreRomImage::SetDataRunAddress(const TUint32 aRunAddress) { iDataRunAddress = aRunAddress; } void CoreRomImage::DisplayNodes() { iReader->Display(iRootDirectory); return; }
[ "none@none" ]
[ [ [ 1, 175 ] ] ]
5b960071eb2b00f8547deca61f19831cb4bd3f13
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/plugins/GSdx/GS.cpp
4fe4f8f97cf4dcf4bea09959fa546644ecd5112a
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
16,249
cpp
/* * Copyright (C) 2007-2009 Gabest * http://www.gabest.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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 GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include "stdafx.h" #include "GSUtil.h" #include "GSRendererDX9.h" #include "GSRendererDX11.h" #include "GSRendererSW.h" #include "GSRendererNull.h" #include "GSSettingsDlg.h" #define PS2E_LT_GS 0x01 #define PS2E_GS_VERSION 0x0006 #define PS2E_X86 0x01 // 32 bit #define PS2E_X86_64 0x02 // 64 bit static HRESULT s_hr = E_FAIL; static GSRenderer* s_gs = NULL; static void (*s_irq)() = NULL; static uint8* s_basemem = NULL; static int s_renderer = -1; static bool s_framelimit = true; static bool s_vsync = false; static bool s_exclusive = true; static bool s_IsGsOpen2 = false; // boolean to remove some stuff from the config panel in new PCSX2's/ static bool isdx11avail = false; // set on GSinit EXPORT_C_(uint32) PS2EgetLibType() { return PS2E_LT_GS; } EXPORT_C_(char*) PS2EgetLibName() { return GSUtil::GetLibName(); } EXPORT_C_(uint32) PS2EgetLibVersion2(uint32 type) { const uint32 revision = 0; const uint32 build = 1; return (build << 0) | (revision << 8) | (PS2E_GS_VERSION << 16) | (PLUGIN_VERSION << 24); } EXPORT_C_(void) PS2EsetEmuVersion(const char* emuId, uint32 version) { s_IsGsOpen2 = true; } EXPORT_C_(uint32) PS2EgetCpuPlatform() { #if _M_AMD64 return PS2E_X86_64; #else return PS2E_X86; #endif } EXPORT_C GSsetBaseMem(uint8* mem) { s_basemem = mem; if( s_gs ) { s_gs->SetRegsMem( s_basemem ); } } EXPORT_C GSsetSettingsDir(const char* dir) { theApp.SetConfigDir(dir); } EXPORT_C_(INT32) GSinit() { if(!GSUtil::CheckSSE()) { return -1; } #ifdef _WINDOWS //_CrtSetBreakAlloc( 1273 ); s_hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED); if(!GSUtil::CheckDirectX()) { return -1; } isdx11avail = GSUtil::IsDirect3D11Available(); #endif return 0; } EXPORT_C GSshutdown() { delete s_gs; s_gs = NULL; s_renderer = -1; GSUtil::UnloadDynamicLibraries(); #ifdef _WINDOWS if(SUCCEEDED(s_hr)) { ::CoUninitialize(); s_hr = E_FAIL; } #endif } EXPORT_C GSclose() { if( !s_gs ) return; s_gs->ResetDevice(); delete s_gs->m_dev; s_gs->m_dev = NULL; s_gs->m_wnd.Detach(); } static INT32 _GSopen(void* dsp, char* title, int renderer) { GSDevice* dev = NULL; if( renderer == -1 ) { renderer = theApp.GetConfig("renderer", 0); } try { if (s_renderer != renderer) { // Emulator has made a render change request, which requires a completely // new s_gs -- if the emu doesn't save/restore the GS state across this // GSopen call then they'll get corrupted graphics, but that's not my problem. delete s_gs; s_gs = NULL; } switch(renderer) { default: case 0: case 1: case 2: dev = new GSDevice9(); break; case 3: case 4: case 5: dev = new GSDevice11(); break; case 12: case 13: new GSDeviceNull(); break; } if( !dev ) return -1; if( !s_gs ) { switch(renderer) { default: case 0: s_gs = new GSRendererDX9(); break; case 3: s_gs = new GSRendererDX11(); break; case 2: case 5: case 8: case 11: case 13: s_gs = new GSRendererNull(); break; case 1: case 4: case 7: case 10: case 12: s_gs = new GSRendererSW(); break; } s_renderer = renderer; } } catch( std::exception& ex ) { // Allowing std exceptions to escape the scope of the plugin callstack could // be problematic, because of differing typeids between DLL and EXE compilations. // ('new' could throw std::alloc) printf( "GSdx error: Exception caught in GSopen: %s", ex.what() ); return -1; } s_gs->SetRegsMem(s_basemem); s_gs->SetIrqCallback(s_irq); s_gs->SetVsync(s_vsync); s_gs->SetFrameLimit(s_framelimit); if( *(HWND*)dsp == NULL ) { // old-style API expects us to create and manage our own window: int w = theApp.GetConfig("ModeWidth", 0); int h = theApp.GetConfig("ModeHeight", 0); if(!s_gs->CreateWnd(title, w, h)) { GSclose(); return -1; } s_gs->m_wnd.Show(); *(HWND*)dsp = (HWND)s_gs->m_wnd.GetHandle(); } else { s_gs->SetMultithreaded( true ); s_gs->m_wnd.Attach( *(HWND*)dsp, false ); } if( !s_gs->CreateDevice(dev) ) { // This probably means the user has DX11 configured with a video card that is only DX9 // compliant. Cound mean drivr issues of some sort also, but to be sure, that's the most // common cause of device creation errors. :) --air GSclose(); return -1; } // if(mt) _mm_setcsr(MXCSR); return 0; } EXPORT_C_(INT32) GSopen2( void* dsp, INT32 flags ) { int renderer = theApp.GetConfig("renderer", 0); if( flags & 4 ) { if (isdx11avail) renderer = 4; //dx11 sw else renderer = 1; //dx9 sw } INT32 retval = _GSopen( dsp, NULL, renderer ); s_gs->SetAspectRatio(0); // PCSX2 manages the aspect ratios return retval; } EXPORT_C_(INT32) GSopen(void* dsp, char* title, int mt) { int renderer; // Legacy GUI expects to acquire vsync from the configuration files. s_vsync = !!theApp.GetConfig("vsync", 0); if(mt == 2) { // pcsx2 sent a switch renderer request if (isdx11avail) renderer = 4; //dx11 sw else renderer = 1; //dx9 sw mt = 1; } else { // normal init renderer = theApp.GetConfig("renderer", 0); } *(HWND*)dsp = NULL; int retval = _GSopen(dsp, title, renderer); if( retval == 0 && s_gs ) { s_gs->SetMultithreaded( !!mt ); } return retval; } EXPORT_C GSreset() { s_gs->Reset(); } EXPORT_C GSgifSoftReset(uint32 mask) { s_gs->SoftReset(mask); } EXPORT_C GSwriteCSR(uint32 csr) { s_gs->WriteCSR(csr); } EXPORT_C GSreadFIFO(uint8* mem) { s_gs->ReadFIFO(mem, 1); } EXPORT_C GSreadFIFO2(uint8* mem, uint32 size) { s_gs->ReadFIFO(mem, size); } EXPORT_C GSgifTransfer(const uint8* mem, uint32 size) { s_gs->Transfer<3>(mem, size); } EXPORT_C GSgifTransfer1(uint8* mem, uint32 addr) { s_gs->Transfer<0>(const_cast<uint8*>(mem) + addr, (0x4000 - addr) / 16); } EXPORT_C GSgifTransfer2(uint8* mem, uint32 size) { s_gs->Transfer<1>(const_cast<uint8*>(mem), size); } EXPORT_C GSgifTransfer3(uint8* mem, uint32 size) { s_gs->Transfer<2>(const_cast<uint8*>(mem), size); } EXPORT_C GSvsync(int field) { #ifdef _WINDOWS if( s_gs->m_wnd.IsManaged() ) { MSG msg; memset(&msg, 0, sizeof(msg)); while(msg.message != WM_QUIT && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } #endif s_gs->VSync(field); } EXPORT_C_(uint32) GSmakeSnapshot(char* path) { string str = string(path); if (str[str.length() - 1] != '\\') str = str + "\\"; return s_gs->MakeSnapshot(str + "gsdx"); } EXPORT_C GSkeyEvent(GSKeyEventData* e) { s_gs->KeyEvent(e); } EXPORT_C_(int) GSfreeze(int mode, GSFreezeData* data) { if(mode == FREEZE_SAVE) { return s_gs->Freeze(data, false); } else if(mode == FREEZE_SIZE) { return s_gs->Freeze(data, true); } else if(mode == FREEZE_LOAD) { return s_gs->Defrost(data); } return 0; } EXPORT_C GSconfigure() { if( !GSUtil::CheckSSE() ) return; if( GSSettingsDlg( s_IsGsOpen2 ).DoModal() == IDOK ) { if( s_gs != NULL && s_gs->m_wnd.IsManaged() ) { // Legacy apps like gsdxgui expect this... GSshutdown(); } } } EXPORT_C_(INT32) GStest() { if(!GSUtil::CheckSSE()) { return -1; } #ifdef _WINDOWS s_hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED); if(!GSUtil::CheckDirectX()) { if(SUCCEEDED(s_hr)) ::CoUninitialize(); s_hr = E_FAIL; return -1; } if(SUCCEEDED(s_hr)) ::CoUninitialize(); s_hr = E_FAIL; #endif return 0; } EXPORT_C GSabout() { } EXPORT_C GSirqCallback(void (*irq)()) { s_irq = irq; if( s_gs ) { s_gs->SetIrqCallback(s_irq); } } EXPORT_C_(int) GSsetupRecording(int start, void* data) { if(!s_gs) return 0; if(start & 1) s_gs->BeginCapture(); else s_gs->EndCapture(); return 1; } EXPORT_C GSsetGameCRC(uint32 crc, int options) { s_gs->SetGameCRC(crc, options); } EXPORT_C GSgetLastTag(uint32* tag) { s_gs->GetLastTag(tag); } EXPORT_C GSgetTitleInfo(char dest[128]) { //s_gs->GetWindowTitle } EXPORT_C GSsetFrameSkip(int frameskip) { s_gs->SetFrameSkip(frameskip); } EXPORT_C GSsetVsync(int enabled) { s_vsync = !!enabled; if( s_gs ) s_gs->SetVsync(s_vsync); } EXPORT_C GSsetExclusive(int enabled) { s_exclusive = !!enabled; if( s_gs ) s_gs->SetVsync(s_vsync); } EXPORT_C GSsetFrameLimit(int limit) { s_framelimit = !!limit; if( s_gs ) s_gs->SetFrameLimit(s_framelimit); } #ifdef _WINDOWS // Returns false if the window's been closed or an invalid packet was encountered. static __forceinline bool LoopDatPacket_Thingamajig(HWND hWnd, uint8 (&regs)[0x2000], vector<uint8>& buff, FILE* fp, long start) { switch(fgetc(fp)) { case EOF: fseek(fp, start, 0); return !!IsWindowVisible(hWnd); case 0: { uint32 index = fgetc(fp); uint32 size; fread(&size, 4, 1, fp); switch(index) { case 0: { if(buff.size() < 0x4000) buff.resize(0x4000); uint32 addr = 0x4000 - size; fread(&buff[0] + addr, size, 1, fp); GSgifTransfer1(&buff[0], addr); } break; case 1: if(buff.size() < size) buff.resize(size); fread(&buff[0], size, 1, fp); GSgifTransfer2(&buff[0], size / 16); break; case 2: if(buff.size() < size) buff.resize(size); fread(&buff[0], size, 1, fp); GSgifTransfer3(&buff[0], size / 16); break; } } break; case 1: GSvsync(fgetc(fp)); return !!IsWindowVisible(hWnd); case 2: { uint32 size; fread(&size, 4, 1, fp); if(buff.size() < size) buff.resize(size); GSreadFIFO2(&buff[0], size / 16); } break; case 3: fread(regs, 0x2000, 1, fp); break; default: return false; } return true; } // lpszCmdLine: // First parameter is the renderer. // Second parameter is the gs file to load and run. EXPORT_C GSReplay(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) { int renderer = -1; { char* start = lpszCmdLine; char* end = NULL; long n = strtol(lpszCmdLine, &end, 10); if(end > start) {renderer = n; lpszCmdLine = end;} } while(*lpszCmdLine == ' ') lpszCmdLine++; ::SetPriorityClass(::GetCurrentProcess(), HIGH_PRIORITY_CLASS); vector<uint8> buff; if(FILE* fp = fopen(lpszCmdLine, "rb")) { GSinit(); uint8 regs[0x2000]; GSsetBaseMem(regs); s_vsync = !!theApp.GetConfig("vsync", 0); HWND hWnd = NULL; _GSopen(&hWnd, "", renderer); uint32 crc; fread(&crc, 4, 1, fp); GSsetGameCRC(crc, 0); GSFreezeData fd; fread(&fd.size, 4, 1, fp); fd.data = new uint8[fd.size]; fread(fd.data, fd.size, 1, fp); GSfreeze(FREEZE_LOAD, &fd); delete [] fd.data; fread(regs, 0x2000, 1, fp); long start = ftell(fp); GSvsync(1); while( LoopDatPacket_Thingamajig(hWnd, regs, buff, fp, start) ) ; GSclose(); GSshutdown(); fclose(fp); } } EXPORT_C GSBenchmark(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) { ::SetPriorityClass(::GetCurrentProcess(), HIGH_PRIORITY_CLASS); FILE* file = fopen("c:\\log.txt", "a"); fprintf(file, "-------------------------\n\n"); if(1) { GSLocalMemory mem; static struct {int psm; const char* name;} s_format[] = { {PSM_PSMCT32, "32"}, {PSM_PSMCT24, "24"}, {PSM_PSMCT16, "16"}, {PSM_PSMCT16S, "16S"}, {PSM_PSMT8, "8"}, {PSM_PSMT4, "4"}, {PSM_PSMT8H, "8H"}, {PSM_PSMT4HL, "4HL"}, {PSM_PSMT4HH, "4HH"}, {PSM_PSMZ32, "32Z"}, {PSM_PSMZ24, "24Z"}, {PSM_PSMZ16, "16Z"}, {PSM_PSMZ16S, "16ZS"}, }; uint8* ptr = (uint8*)_aligned_malloc(1024 * 1024 * 4, 16); for(int i = 0; i < 1024 * 1024 * 4; i++) ptr[i] = (uint8)i; // for(int tbw = 5; tbw <= 10; tbw++) { int n = 256 << ((10 - tbw) * 2); int w = 1 << tbw; int h = 1 << tbw; fprintf(file, "%d x %d\n\n", w, h); for(int i = 0; i < countof(s_format); i++) { const GSLocalMemory::psm_t& psm = GSLocalMemory::m_psm[s_format[i].psm]; GSLocalMemory::writeImage wi = psm.wi; GSLocalMemory::readImage ri = psm.ri; GSLocalMemory::readTexture rtx = psm.rtx; GSLocalMemory::readTexture rtxP = psm.rtxP; GIFRegBITBLTBUF BITBLTBUF; BITBLTBUF.SBP = 0; BITBLTBUF.SBW = w / 64; BITBLTBUF.SPSM = s_format[i].psm; BITBLTBUF.DBP = 0; BITBLTBUF.DBW = w / 64; BITBLTBUF.DPSM = s_format[i].psm; GIFRegTRXPOS TRXPOS; TRXPOS.SSAX = 0; TRXPOS.SSAY = 0; TRXPOS.DSAX = 0; TRXPOS.DSAY = 0; GIFRegTRXREG TRXREG; TRXREG.RRW = w; TRXREG.RRH = h; GSVector4i r(0, 0, w, h); GIFRegTEX0 TEX0; TEX0.TBP0 = 0; TEX0.TBW = w / 64; GIFRegTEXA TEXA; TEXA.TA0 = 0; TEXA.TA1 = 0x80; TEXA.AEM = 0; int trlen = w * h * psm.trbpp / 8; int len = w * h * psm.bpp / 8; clock_t start, end; _ftprintf(file, _T("[%4s] "), s_format[i].name); start = clock(); for(int j = 0; j < n; j++) { int x = 0; int y = 0; (mem.*wi)(x, y, ptr, trlen, BITBLTBUF, TRXPOS, TRXREG); } end = clock(); fprintf(file, "%6d %6d | ", (int)((float)trlen * n / (end - start) / 1000), (int)((float)(w * h) * n / (end - start) / 1000)); start = clock(); for(int j = 0; j < n; j++) { int x = 0; int y = 0; (mem.*ri)(x, y, ptr, trlen, BITBLTBUF, TRXPOS, TRXREG); } end = clock(); fprintf(file, "%6d %6d | ", (int)((float)trlen * n / (end - start) / 1000), (int)((float)(w * h) * n / (end - start) / 1000)); const GSOffset* o = mem.GetOffset(TEX0.TBP0, TEX0.TBW, TEX0.PSM); start = clock(); for(int j = 0; j < n; j++) { (mem.*rtx)(o, r, ptr, w * 4, TEXA); } end = clock(); fprintf(file, "%6d %6d ", (int)((float)len * n / (end - start) / 1000), (int)((float)(w * h) * n / (end - start) / 1000)); if(psm.pal > 0) { start = clock(); for(int j = 0; j < n; j++) { (mem.*rtxP)(o, r, ptr, w, TEXA); } end = clock(); fprintf(file, "| %6d %6d ", (int)((float)len * n / (end - start) / 1000), (int)((float)(w * h) * n / (end - start) / 1000)); } fprintf(file, "\n"); fflush(file); } fprintf(file, "\n"); } _aligned_free(ptr); } // if(0) { GSLocalMemory mem; uint8* ptr = (uint8*)_aligned_malloc(1024 * 1024 * 4, 16); for(int i = 0; i < 1024 * 1024 * 4; i++) ptr[i] = (uint8)i; const GSLocalMemory::psm_t& psm = GSLocalMemory::m_psm[PSM_PSMCT32]; GSLocalMemory::writeImage wi = psm.wi; GIFRegBITBLTBUF BITBLTBUF; BITBLTBUF.DBP = 0; BITBLTBUF.DBW = 32; BITBLTBUF.DPSM = PSM_PSMCT32; GIFRegTRXPOS TRXPOS; TRXPOS.DSAX = 0; TRXPOS.DSAY = 1; GIFRegTRXREG TRXREG; TRXREG.RRW = 256; TRXREG.RRH = 256; int trlen = 256 * 256 * psm.trbpp / 8; int x = 0; int y = 0; (mem.*wi)(x, y, ptr, trlen, BITBLTBUF, TRXPOS, TRXREG); } // fclose(file); PostQuitMessage(0); } #endif
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 836 ] ] ]
9055c5f7cfe7fbfa90f45482c332f4c788a67794
7dd2dbb15df45024e4c3f555da6d9ca6fc2c4d8b
/content_exporters/texture/default_texture_exporters/bmp_exporter.cpp
a5cb45528d3684908c89731082d16354a6ca29c6
[]
no_license
wangscript/maelstrom-editor
c9f761e1f9e5f4e64d7e37834a7a63e04f57ae31
5bfab31bf444f44b9f8209f4deaed8715c305426
refs/heads/master
2021-01-10T01:37:00.619456
2011-11-21T23:17:08
2011-11-21T23:17:08
50,160,495
0
0
null
null
null
null
UTF-8
C++
false
false
6,749
cpp
#define EXPORTER_NAME "Bmp Texture Exporter" #include <iostream> #include <fstream> #include <list> #include <texturebmpexporter.h> #include <stdlib.h> #include <cmath> #include <cstring> #include <algorithm> #define BUFFER_SIZE 512 #define BITMAPSIGNATURE 19778 #define BITMAPCOREHEADER_SIZE 12 #define BITMAPCOREHEADER2_SIZE 64 #define BITMAPINFOHEADER_SIZE 40 #define BITMAPV2INFOHEADER_SIZE 52 #define BITMAPV3INFOHEADER_SIZE 56 #define BITMAPV4HEADER_SIZE 108 #define BITMAPV5HEADER_SIZE 124 #if defined(WIN32) #include <Windows.h> #define EXPORT __declspec(dllexport) #endif #if defined(__linux) #define EXPORT #endif extern "C" { BmpExporter::BmpExporter() { this->last_error = NULL; } IContent *BmpExporter::process(char *path) { std::ifstream input(path, std::ifstream::binary); if(!input.good()) { std::string msg("Could not open file for processing."); msg.append(path); ContentPlugin::set_last_error_msg(msg); return NULL; } Content *texture = new Content; BITMAP_FILEHEADER header; input.read(reinterpret_cast<char*>(&header), sizeof(BITMAP_FILEHEADER)); if(header.bfType != BITMAPSIGNATURE) { input.close(); std::string msg("Input is not a valid Bitmap Image File."); ContentPlugin::set_last_error_msg(msg); return NULL; } I32 dib_header_size; input.read(reinterpret_cast<char*>(&dib_header_size), sizeof(I32)); input.seekg(-4, std::ios_base::cur); if(dib_header_size == BITMAPINFOHEADER_SIZE) { BITMAP_INFOHEADER dib_header; if(this->parse_dib_bitmapinfoheader(input, dib_header) != 0) { input.close(); return NULL; } texture->set_int_value("WIDTH", new int(dib_header.biWidth)); texture->set_int_value("HEIGHT", new int(dib_header.biHeight)); if(dib_header.biBitCount <= 8) { int* palette = new int[dib_header.biClrUsed]; input.read(reinterpret_cast<char*>(palette), sizeof(palette)); } int stride = ceil((dib_header.biBitCount * dib_header.biWidth) / 32.0f) * 4; int stride_padding = stride - ((dib_header.biBitCount / 8) * dib_header.biWidth); char *pixel_data = new char[dib_header.biSizeImage]; input.seekg(header.bfOffBits, std::ios_base::beg); input.read(pixel_data, dib_header.biSizeImage); // When height is non-negavite, its scan lines are flipped vertically so we must flip them. if(dib_header.biHeight > 0) { this->flip_scanlines(pixel_data, dib_header.biSizeImage, stride); } // Every texture exporter must export texture data in 32BPP, so we need to transform the bitmap data if it is not 32BPP. char *transformed_pixel_data; U32 transformed_length; switch(dib_header.biBitCount) { case 24: this->transform_24BPP(pixel_data, stride, stride_padding, dib_header.biHeight, &transformed_pixel_data, &transformed_length); //this->transform_24BPP(pixel_data, dib_header.biSizeImage, dib_header.biSizeImage / row_size, &transformed_pixel_data, &transformed_length); delete[] pixel_data; pixel_data = transformed_pixel_data; break; default: transformed_length = dib_header.biSizeImage; break; } texture->set_pchar_value("PIXELDATA", pixel_data); texture->set_int_value("PIXELDATA_LEN", new int(transformed_length)); } else if(dib_header_size == BITMAPV3INFOHEADER_SIZE) { BITMAP_V3HEADER dib_header; input.read(reinterpret_cast<char*>(&dib_header), sizeof(dib_header)); char *pixel_data = new char[dib_header.bV4SizeImage]; input.seekg(header.bfOffBits, std::ios_base::beg); input.read(pixel_data, dib_header.bV4SizeImage); texture->set_pchar_value("PIXELDATA", pixel_data); texture->set_int_value("PIXELDATA_LEN", new int(dib_header.bV4SizeImage)); } else { input.close(); std::string msg("Unkown DIB header size."); ContentPlugin::set_last_error_msg(msg); return NULL; } input.close(); char *pdat = texture->get_pchar_value("PIXELDATA"); return texture; } void BmpExporter::flip_scanlines(char *data, U32 size, U32 stride) { char *pixel_data_temp = new char[size]; int rows = size / stride; // Copy all scanline rows into temp buffer in reverse order for(int y = 0; y < rows; y++) memcpy( static_cast<void*>(&pixel_data_temp[y * stride]), static_cast<void*>(&data[(rows - y - 1) * stride]), stride); // Copy entire temp buffer content into main buffer. memcpy( static_cast<void*>(data), static_cast<void*>(pixel_data_temp), size); delete[] pixel_data_temp; } void BmpExporter::transform_24BPP(char *data, U32 stride, U32 stride_padding, U32 scanlines, char **transformed_data, U32 *transformed_length) { U32 pixels_per_scanline = (stride - stride_padding) / 3; U32 total_pixels = pixels_per_scanline * scanlines; U32 new_stride = pixels_per_scanline * 4; *transformed_length = total_pixels * 4; *transformed_data = new char[*transformed_length]; for(int y = 0; y < scanlines; y++) { for(int x = 0; x < pixels_per_scanline; x++) { int source_x = x*3; int source_y = stride*y; int dest_x = x*4; int dest_y = new_stride*y; char a = 0xFF; char b = data[(source_y) + (source_x)]; char g = data[(source_y) + (source_x) + 1]; char r = data[(source_y) + (source_x) + 2]; (*transformed_data)[(dest_y) + (dest_x) + 0] = b; // Fully opaque (*transformed_data)[(dest_y) + (dest_x) + 1] = g; (*transformed_data)[(dest_y) + (dest_x) + 2] = r; (*transformed_data)[(dest_y) + (dest_x) + 3] = a; } } } int BmpExporter::parse_dib_bitmapinfoheader(std::ifstream &input, BITMAP_INFOHEADER &header) { input.read(reinterpret_cast<char*>(&header), sizeof(header)); if(header.biCompression != CMP_RGB) { std::string msg("Bitmap compression is not supported."); ContentPlugin::set_last_error_msg(msg); return -1; } return 0; } void BmpExporter::destroy(IContent *data) { } class BmpExporterFactory : public ContentExporterFactory { public: BmpExporterFactory() : ContentExporterFactory("Bmp Texture Exporter", "") { } BmpExporter *create(void) { return new BmpExporter; } void destroy(ContentExporter *exporter) { delete exporter; } }; EXPORT ContentExporterFactory *create_exporter_factory(void) { return new BmpExporterFactory; } } #if defined(WIN32) BOOL WINAPI DllMain( __in HINSTANCE hinstDLL, __in DWORD fdwReason, __in LPVOID lpvReserved ) { return TRUE; } #endif //extern "C" __declspec(dllexport) register_plugin
[ [ [ 1, 247 ] ] ]
6c4e21b6791af31c1a4d96f4e9bb233dd008a692
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/Algorithm/BitStreamHolder.cpp
e9603bd8ee333fb951135d7e46ff5e41e19a3a48
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
4,272
cpp
#include "StdAfx.h" #include "BitStreamHolder.h" BitStreamHolder::BitStreamHolder(void) { m_count = -1; } BitStreamHolder::~BitStreamHolder(void) { } void BitStreamHolder::AddAttributeID(int _att_id) { m_attribute_no.push_back(_att_id); } void BitStreamHolder::Print() { cout << "Printing Bit Holder" << endl; typedef vector<int>::const_iterator vect_iter; cout << "Print attribute No " << endl; for (vect_iter iter = m_attribute_no.begin(); iter != m_attribute_no.end(); iter++) { cout <<*(iter); } cout << endl; cout << "Print Unique Streams " << endl; for (vect_iter iter = m_bit_stream_no.begin(); iter != m_bit_stream_no.end(); iter++) { cout <<*(iter); } cout << endl; } void BitStreamHolder::AddStreamNo(int _stream_no) { m_bit_stream_no.push_back(_stream_no); } bool BitStreamHolder::Contains(int _value, std::vector<int> &_container) { sort(_container.begin(),_container.end()); return binary_search(_container.begin(),_container.end(),_value); } int BitStreamHolder::Count() { // if (m_count == -1) // { // m_count = m_bit_stream->Count(); // } return m_bit_stream->Count(); } //Handle when vector<int> is not set (or throw an exeption) int BitStreamHolder::Hash() { int factor = 1; int hash = 0; typedef vector<int>::const_iterator int_iter; for (int_iter start = m_bit_stream_no.begin(); start != m_bit_stream_no.end() ; start++) { hash += ((*(start) + 1) * factor); factor *= MULTIPLICATIVE_UNIT; } return hash; } // void BitStreamHolder:: vector<BitStreamHolder *> BitStreamHolder::Difference(BitStreamHolder * _holder,map<int,int> & _index_attribute_map) { vector<int> left_op = _holder->Bit_stream_no(); vector<int> right_op = this->m_bit_stream_no; sort(left_op.begin(),left_op.end()); sort(right_op.begin(),right_op.end()); vector<int> intermediate; back_insert_iterator< std::vector<int> > output_iter( intermediate ); set_difference(left_op.begin(),left_op.end(),right_op.begin(),right_op.end(),output_iter); vector<BitStreamHolder *> holder; BitStreamHolder * hld = NULL; typedef vector<int>::const_iterator holder_iter; for (holder_iter start = intermediate.begin(); start != intermediate.end(); start++) { hld = new BitStreamHolder(); hld->AddStreamNo(*(start)); hld->AddAttributeID(_index_attribute_map[*(start)]); holder.push_back(hld); } return holder; } BitStreamHolder * BitStreamHolder::Merge(BitStreamHolder * _holder,map<int,int> & _index_attribute_map,vector<BitStreamHolder *> & _index_holder) { BitStreamHolder * hld; size_t right_holder_index = _holder->Bit_stream_no().at(0); int att_no = _index_attribute_map[right_holder_index]; if (this->ContainsAttID(att_no) && !(this->ContainsStreamNo(right_holder_index))) { hld = NULL; }else { hld = new BitStreamHolder(); vector<int> left_vector = this->m_bit_stream_no; vector<int> right_vector = _holder->Bit_stream_no(); sort(left_vector.begin(),left_vector.end()); sort(right_vector.begin(),right_vector.end()); vector<int> result_vector; back_insert_iterator< std::vector<int> > output_iter( result_vector ); set_union(left_vector.begin(),left_vector.end(),right_vector.begin(),right_vector.end(),output_iter); hld->Bit_stream_no(result_vector); BitStreamInfo * left_op = m_bit_stream; BitStreamInfo * right_op = _index_holder.at(_holder->Bit_stream_no().at(0))->Bit_stream(); BitStreamInfo * result_str = *(left_op) & *(right_op); hld->Bit_stream(result_str); vector<int> result_att_vector; if (!this->ContainsAttID(att_no)) { vector<int> result_att_vector = m_attribute_no; result_att_vector.push_back(att_no) ; hld->Attribute_no(result_att_vector); } } return hld; } void BitStreamHolder::DeleteBitStream() { delete m_bit_stream; m_bit_stream = NULL; } bool BitStreamHolder::ContainsAttID(int _att_id) { return Contains(_att_id,m_attribute_no); } bool BitStreamHolder::ContainsStreamNo(int _stream_no) { return Contains(_stream_no,m_bit_stream_no); }
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 152 ] ] ]
82d52080d6f047918fd20a118c875b1846640fbf
d4b316c5dfe18916d6747e564a6bb8e814d4413a
/date_checker/kupjak/graphic_proj3/graphic_proj3/main.cpp
9ff02b7eb82b23987dfce1afbb55e9a8536cfe2f
[]
no_license
artemshynkarenko/ilsdev
3c8b485beb66cd9d33c9b844758bf2e79c5ea94f
e6cc62f14aae409cc1e462ba03b8dcb2c1a6aa02
refs/heads/master
2016-09-06T08:30:25.052724
2009-06-19T16:35:14
2009-06-19T16:35:14
32,579,868
0
0
null
null
null
null
UTF-8
C++
false
false
6,280
cpp
#include <windows.h> #include <stdlib.h> #include <string.h> #include <tchar.h> #include <time.h> #include "grmanager.h" #define VK_0 0x30 #define VK_1 0x31 #define VK_2 0x32 #define VK_3 0x33 #define VK_4 0x34 #define VK_5 0x35 #define VK_6 0x36 #define VK_7 0x37 #define VK_8 0x38 #define VK_9 0x39 /////// #define VK_A 0x041 #define VK_B 0x042 #define VK_C 0x043 #define VK_D 0x044 #define VK_E 0x045 #define VK_F 0x046 #define VK_G 0x047 #define VK_H 0x048 #define VK_I 0x049 #define VK_J 0x04A #define VK_K 0x04B #define VK_L 0x04C #define VK_M 0x04D #define VK_N 0x04E #define VK_O 0x04F #define VK_P 0x050 #define VK_Q 0x051 #define VK_R 0x052 #define VK_S 0x053 #define VK_T 0x054 #define VK_U 0x055 #define VK_V 0x056 #define VK_W 0x057 #define VK_X 0x058 #define VK_Y 0x059 #define VK_Z 0x05A static TCHAR szWindowClass[] = _T("win32app"); // The main window class name. static TCHAR szTitle[] = _T("Win32 Guided Tour Application"); // The string that appears in the application's title bar. LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Forward declarations of functions included in this code module Grmanager gr; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); if (!RegisterClassEx(&wcex)) { MessageBox(NULL, _T("Call to RegisterClassEx failed!"), _T("Win32 Guided Tour"), NULL); return 1; } // The parameters to CreateWindow explained: // szWindowClass: the name of the application // szTitle: the text that appears in the title bar // WS_OVERLAPPEDWINDOW: the type of window to create // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y) // 500, 100: initial size (width, length) // NULL: the parent of this window // NULL: this application dows not have a menu bar // hInstance: the first parameter from WinMain // NULL: not used in this application HWND hWnd = CreateWindow( szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, hInstance, NULL ); //hwnd_main = hWnd; if (!hWnd) { MessageBox(NULL, _T("Call to CreateWindow failed!"), _T("Win32 Guided Tour"), NULL); return 1; } gr.set(hWnd, 800, 600); ShowWindow(hWnd,nCmdShow); // The parameters to ShowWindow explained: hWnd: the value returned from CreateWindow; nCmdShow: the fourth parameter from WinMain; UpdateWindow(hWnd); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) // Main message loop { TranslateMessage(&msg); DispatchMessage(&msg); } return (int) msg.wParam; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // WCHAR to_wchar(char c){ if (c == '0') return L'0'; if (c == '1') return L'1'; if (c == '2') return L'2'; if (c == '3') return L'3'; if (c == '4') return L'4'; if (c == '5') return L'5'; if (c == '6') return L'6'; if (c == '7') return L'7'; if (c == '8') return L'8'; if (c == '9') return L'9'; if (c == '.') return L'.'; return L' '; } wstring to_wstring(double n){ char s[100]; sprintf(s, "%lf", n); wstring res; for (int i=0; s[i]!=0; ++i) res.push_back(to_wchar(s[i])); return res; } int old_x=0, old_y=0; bool lb_pressed = false; bool rb_pressed = false; int old_time; LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { TCHAR greeting[] = _T("Hello, World!"); int x, y; wstring s; switch (message) { case WM_CREATE: SetTimer(hWnd, IDTIMEOUT, gr.get_msec_per_frame(), NULL); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_TIMER: s = to_wstring(1.0/(double(old_time-clock())/CLOCKS_PER_SEC)); old_time = clock(); SetWindowText(hWnd, (LPCWSTR)s.c_str()); gr.display_frame(); break; case WM_KEYDOWN: switch (wParam){ case VK_UP: gr.move_up(); //gr.mouse_vertical(1); break; case VK_DOWN: //gr.mouse_vertical(-1); gr.move_down(); break; case VK_LEFT: gr.move_left(); //gr.mouse_horizontal(1); break; case VK_RIGHT: gr.move_right(); //gr.mouse_horizontal(-1); break; case VK_SPACE: gr.change_pause(); break; case VK_DELETE: gr.inc_function(+0.02); break; case VK_INSERT: gr.inc_function(-0.02); break; case VK_Z: gr.change_line_style(); break; case VK_L: gr.change_light(); break; } break; case WM_MOUSEMOVE: x = LOWORD(lParam); y = HIWORD(lParam); if (lb_pressed){ gr.mouse_horizontal(x-old_x); gr.mouse_vertical(y-old_y); } if (rb_pressed){ /*if (abs(x-old_x) > abs(y-old_y)) gr.scaled(x-old_x); else gr.scaled(y-old_y); */ gr.scaled(y-old_y); } old_x = x; old_y = y; break; case WM_LBUTTONDOWN: lb_pressed = true; break; case WM_LBUTTONUP: lb_pressed = false; break; case WM_RBUTTONDOWN: rb_pressed = true; break; case WM_RBUTTONUP: rb_pressed = false; break; default: return DefWindowProc(hWnd, message, wParam, lParam); break; } return 0; }
[ "kupjak@0d0ad13b-7e51-0410-977d-d3f3eabcdc60" ]
[ [ [ 1, 280 ] ] ]
c7f0e12327a6665cdfe2969f14e8191a1e24f04a
af96c6474835be2cc34ef21b0c2a45e950bb9148
/media/libdrm/mobile2/include/util/crypto/DrmCrypto.h
10e7bc1ff19b1fcbd04ab3a6ee61b4a9d827d0d3
[ "Apache-2.0", "LicenseRef-scancode-unicode" ]
permissive
zsol/android_frameworks_base
86abe37fcd4136923cab2d6677e558826f087cf9
8d18426076382edaaea68392a0298d2c32cfa52e
refs/heads/donut
2021-07-04T17:24:05.847586
2010-01-13T19:24:55
2010-01-13T19:24:55
469,422
14
12
NOASSERTION
2020-10-01T18:05:31
2010-01-12T21:20:20
Java
UTF-8
C++
false
false
6,328
h
/* * Copyright (C) 2007 The Android Open Source Project * * 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. */ #ifndef _DRMCRYPTO_H_ #define _DRMCRYPTO_H_ #include <Drm2CommonTypes.h> #include <openssl/aes.h> #include <openssl/hmac.h> #include <openssl/sha.h> #include <openssl/rsa.h> // AES encrypt mode typedef enum {AES_128_CBC = 0x01,AES_128_CTR = 0x02}AesMode; // aes crypto for decrypt class AesAgent { public: AesAgent(const AesMode method,const unsigned char* decryptedKey) :mode(method),AesKey(decryptedKey){}; /** * decrypt data using AES, now only support 128 bits CBC * \param iv 128 bits initialization vector/counter * prefixing the ciphertext * \param encData encrypted data * \param encLen the length of encData * \param decData the buffer to store decrypted data * \param decLen the actual length of decrypted data * \return * >= succeed, the padding length * < 0 failed */ int32_t decContent( unsigned char* iv, const unsigned char* encData, const unsigned long encLen, unsigned char* decData); static const int32_t AES_DEC_FAILED = -1; PRIVATE: static const uint32_t AES_KEY_BITS = 128; const AesMode mode; const unsigned char* AesKey; PRIVATE: // get the actual length of decrypt data void discardPaddingByte(unsigned char* decryptedBuf,unsigned long* decryptedBufLen); }; // Sha1 crypto for hash class Sha1Agent { public: /** * compute hash using Sha1 * \param inData the data to be hashed * \param inLen the length of inData * \param outHash the hash of inData * \return none */ void computeHash( const unsigned char* inData, unsigned long inLen, unsigned char* outHash) const; /** * get the length of SHA1 hash * \param none * \return * the length of SHA1 hash */ unsigned long getShaLen(void) const { return SHA_DIGEST_LENGTH; } }; // Hmac-Sha1 crypto for MAC class HmacSha1Agent { public: HmacSha1Agent(const unsigned char* Key, int key_len) :macKey(Key),keyLen(key_len){}; /** * compute MAC using Hmac-Sha1 * \param inData the data to be MAC * \param inLen the length of inData * \param outMac the MAC of inData * \return none */ void computeMac( const unsigned char* inData, unsigned long inLen, unsigned char* outMac) const; /** * get the length of HMAC-SHA1 MAC * \param none * \return * the length of HMAC-SHA1 MAC */ unsigned long getHmacLen(void) const { return SHA_DIGEST_LENGTH; } PRIVATE: const unsigned char* macKey; const int keyLen; }; // Rsa crypto for signature,verify signature and key transport class RsaAgent { public: RsaAgent(RSA& Key):rsaKey(Key) { rsaSize = (unsigned int)RSA_size(&Key); }; // signature algorithm typedef enum {RSA_PSS,RSA_SHA1}RsaAlg; /** * Do signature using RSA-PSS * \param rawData the data to be signature * \param rawLen the length of inData * \param sigData the buffer to store the signature of rawData * \param sigAlg signature algorithm * \return * true succeed * false failed */ bool signature( const unsigned char* rawData, const unsigned long rawLen, unsigned char* sigData, const RsaAlg sigAlg); /** * get the length of signature * \param none * \return * the length of signature */ unsigned int getSigLen(void) const { return rsaSize; } /** * Verify signature using RSA-PSS * \param sigData the data to be verify * \param sigLen the length of sigData * \param rawData the data from which the sigData generated * \param rawLen the length of rawData * \param sigAlg signature algorithm * \return * true succeed * false failed */ bool sigVerify(unsigned char* sigData, unsigned long sigLen, const unsigned char* rawData, const unsigned long rawLen, const RsaAlg sigAlg); /** * Decrypt data using RSA * \param encData encrypted data * \param encLen the length of encData * \param decData the buffer to store decrypted data * \return * -1 decrypted failed * >0 the actual length of decrypted data */ int decrypt( const unsigned char* encData, const unsigned long encLen, unsigned char* decData); /** * get the length of decrypted data * \param none * \return * the length of decrypted data */ unsigned int getDecLen(void) const { return rsaSize; } PRIVATE: RSA& rsaKey; unsigned int rsaSize; }; #endif /* _DRMCRYPTO_H_ */
[ [ [ 1, 211 ] ] ]
cd12437bb31e3239405959e28ce6724ece2c0903
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/Externs/ParticleUniverseVortexExtern.h
bad24e8432883b3a8de09c0f0098a2a17f0a9eb7
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
2,366
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. 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. ----------------------------------------------------------------------------- */ #ifndef __PU_VORTEX_EXTERN_H__ #define __PU_VORTEX_EXTERN_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleAffectors/ParticleUniverseVortexAffector.h" #include "ParticleUniverseAttachable.h" namespace ParticleUniverse { /** The VortexExtern is a wrapper of the VortexAffector, adding the functionality of a MovableObject. The VortexExtern can be attached to another SceneNode than the one where the ParticleSystem at which the VortexExtern is registered, is attached. This makes it possible to affect the particles in the Particle System, while both SceneNodes moves different from each other. This approach makes it possible to simulate something like a helicopter (SceneNode to which the VortexExtern is attached) that flies over a certain area and rotates the leaves on the ground (Particle System attached to another SceneNode). */ class _ParticleUniverseExport VortexExtern : public Attachable, public VortexAffector { public: VortexExtern(void) : Attachable(), VortexAffector(){}; virtual ~VortexExtern(void) {}; /** The _preProcessParticles() function sets the position and mDerivedPosition attributes to the actual world position of the node to which it is attached. */ virtual void _preProcessParticles(ParticleTechnique* technique, Ogre::Real timeElapsed); /** Processes a particle. */ virtual void _interface(ParticleTechnique* technique, Particle* particle, Ogre::Real timeElapsed); /** Copy both the Extern and the derived VortexAffector properties. */ virtual void copyAttributesTo (Extern* externObject); }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 59 ] ] ]
cd58ef124d5022efa8f9996ae6a10d6885ae3f15
f96efcf47a7b6a617b5b08f83924c7384dcf98eb
/tags/mucc_v1058/FontList.h
2e0076e765ef939caa939fe51caab5b300e42d31
[]
no_license
BackupTheBerlios/mtlen-svn
0b4e7c53842914416ed3f6b1fa02c3f1623cac44
f0ea6f0cec85e9ed537b89f7d28f75b1dc108554
refs/heads/master
2020-12-03T19:37:37.828462
2011-12-07T20:02:16
2011-12-07T20:02:16
40,800,938
0
0
null
null
null
null
UTF-8
C++
false
false
2,178
h
/* MUCC Group Chat GUI Plugin for Miranda IM Copyright (C) 2004 Piotr Piastucki 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef FONTLIST_INCLUDED #define FONTLIST_INCLUDED #include "mucc.h" class Font { private: COLORREF color; char * face; char * name; int size; int style; int charSet; public: enum STYLES { BOLD = 1, ITALIC = 2, UNDERLINE = 4, STROKE = 8, UNDERWAVE = 16 }; Font(); Font(const char *name, const char *face, int charSet, int size, int style, COLORREF color); void setColor(COLORREF c); COLORREF getColor(); void setSize(int s); int getSize(); void setStyle(int s); int getStyle(); void setFace(const char *s); const char *getFace(); void setName(const char *s); const char *getName(); void setCharSet(int s); int getCharSet(); }; class FontList { private: static Font *fonts; static Font *fontsSettings; public: enum FONTIDEX { FONT_TIMESTAMP = 0, // FONT_COLON = 1, FONT_OTHERSNAMES = 1, FONT_MYNAME = 2, FONT_INMESSAGE = 3, FONT_OUTMESSAGE = 4, FONT_JOINED = 5, FONT_LEFT = 6, FONT_TOPIC = 7, // FONT_NOTIFICATION = 9, FONT_ERROR = 8, FONT_TYPING = 9, FONT_USERLIST = 10, FONT_USERLISTGROUP = 11 }; static Font *getFont(int index); static Font *getFontSettings(int index); static void release(); static void init(); static int getFontNum(); static void loadSettings(); static void saveSettings(); }; #endif
[ "the_leech@3f195757-89ef-0310-a553-cc0e5972f89c" ]
[ [ [ 1, 90 ] ] ]
8db171038cf98ba82a671816a88fdc925e239f39
b3b0c727bbafdb33619dedb0b61b6419692e03d3
/Source/RSSPlugin/gTestRSS/stdafx.cpp
163b4a57f97dd0d44568c1abc747dba404c9edf6
[]
no_license
testzzzz/hwccnet
5b8fb8be799a42ef84d261e74ee6f91ecba96b1d
4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113
refs/heads/master
2021-01-10T02:59:32.527961
2009-11-04T03:39:39
2009-11-04T03:39:39
45,688,112
0
1
null
null
null
null
GB18030
C++
false
false
268
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // gTestRSS.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ [ [ 1, 8 ] ] ]
4e9218dd49343bd5c740db098d96430365af9786
07c0d53e7cc80e1ef07b2ed57509d712f2134adf
/PrimeFactors_fast.cpp
06014ab55490e1c4094fdeab2a1ec66fd29ea737
[]
no_license
hector1618/Prime-factorisation
299125d4cfd2cf16cbafc7ed0cbd443555df0d38
f25411823acfea12a3c02989975882de7ed839b3
refs/heads/master
2021-01-10T01:01:00.665176
2011-03-04T13:50:49
2011-03-04T13:50:49
1,439,481
0
0
null
null
null
null
UTF-8
C++
false
false
3,500
cpp
/* Name: PrimeFactors Copyright: Author: TALE PRAFULLKUMAR P. 072074 Date: 15/03/10 14:14 Description: This program will be used to factorize a given number. It will display all the distinct prime factors of the given number. The concept of trees is being used. */ #include<iostream> #include <cmath> #include "LinkedList.h" #include "GetDown.h" using namespace std; static LinkedList PF;// To store the prime factors static GetDown GD; int Check_BasicPrimes(int n) //This function is to check whether the given number //is divisible by basic primes i.e. {2,3,5,7,11,13} //and to reduce the no if it is divisible. { int P_basic[6]={2,3,5,7,11,13}; for(int i=0;i<6;i++) { if(n%P_basic[i]==0) { PF.push(P_basic[i]); } while(n%P_basic[i]==0) { n=n/P_basic[i]; } } return n; } int LeftChild(int n) //Here is the function LeftChild(n) which will return //the left child of given number. //Finding the LeftChild is fasten using class GetDown.h { int a; float n1=n; a = int (sqrt(n1)); //We can write a = 30030*q + r int q = a/30030; int r = a%30030; int i=-1; i = GD.Search(r); a = GD.display(i); while(n%a !=0) { a=GD.GoDown(a,i); i=i-1; if(i==-1) { q=q-1; i=3248; } }; return a; } int SquareCheck(int n) // Since the prime factors of n^2 and n are same,this // function will convert any square to its root (if the // root is interger) { int j=0; int a; while (j==0) { float n1=n; a = (int) sqrt(n1); if(n==a*a) { n=a; } else { j=1; }; } return n; } int main() { int n; cout<<"Enter the number "<<endl; cin>>n; LinkedList S;//Will be used as a stack int nl,nr;//nl=leftchild ,nr=rightchild int e;//flag veriable int k=0; n = Check_BasicPrimes(n); if(n==1) { cout<<"Prime factors are "<<endl; PF.print(); system("pause"); return 0; } while (k!=1) { if (n==1) { while(n==1) { n=S.pop(); n=PF.traverse_and_check(n); } }; n = SquareCheck(n); nl=LeftChild(n); if (nl==1) { PF.push(n); e=S.isempty(); if(e==1) { break; } n=S.pop(); n=PF.traverse_and_check(n); } else { nr=n/nl; S.push(nr); n = nl; }; k=S.isempty();//checking whether the stack //is empty or not //This is a check for the last element if (k==1) { nl = LeftChild(n); if(nl!=1) { k=0; } else { PF.push(n); } } } //This is to remove 1 if present k=PF.pop(); if(k!=1) { PF.push(k); }; cout<<"The prime factors are "<<endl; PF.print(); system ("pause"); return 0; }
[ [ [ 1, 168 ] ] ]
5b298774bc512f10ac76d43004d207a4e93aaa87
b91c59623f28031d0255684adffcaa5e54528777
/demo.h
aa36075b539dc05f0642fe3de272d975d4e963d5
[]
no_license
ninhoabrantes/fop3d
dbe03ba3f3b2ca5073ed6dc8f03e2c7cbdd9b1ad
7c099f5720fca1a673fdc238bc95e6ceadb4488c
refs/heads/master
2021-01-10T06:26:56.752957
2010-01-27T08:35:43
2010-01-27T08:35:43
51,085,749
0
0
null
null
null
null
UTF-8
C++
false
false
1,717
h
// demo.h : main header file for the DEMO application // #if !defined(AFX_DEMO_H__78802C02_E99A_4E84_876C_8D3F5BC0734B__INCLUDED_) #define AFX_DEMO_H__78802C02_E99A_4E84_876C_8D3F5BC0734B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols //#pragma comment(lib, "opengl32") //#pragma comment(lib, "glu32") //#pragma comment(lib, "glut32") #include <gl/glu.h> #include <gl/gl.h> #include <gl/glaux.h> #include "glut.h" #include "LoginDlg.h" const int MESSAGE_STEPPRO = WM_USER + 102; const int MEASURETIMES = 30000; ///////////////////////////////////////////////////////////////////////////// // CDemoApp: // See demo.cpp for the implementation of this class // class CDemoApp : public CWinApp { public: _ConnectionPtr m_pConnection; CLoginDlg dlgLogin; CDemoApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDemoApp) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CDemoApp) afx_msg void OnAppAbout(); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DEMO_H__78802C02_E99A_4E84_876C_8D3F5BC0734B__INCLUDED_)
[ "chaoyu.bupter@6deafb92-e873-11de-91d6-89caad0352f8", "emilyaimeihsu@6deafb92-e873-11de-91d6-89caad0352f8" ]
[ [ [ 1, 22 ], [ 25, 26 ], [ 28, 39 ], [ 42, 68 ] ], [ [ 23, 24 ], [ 27, 27 ], [ 40, 41 ] ] ]
c46c752ed14607f386f93b23801b887c0b796b8a
c6f4fe2766815616b37beccf07db82c0da27e6c1
/VisualVertexArraySphere.h
b41cf9761a38915d3c21ae121fc542d2ec8d9448
[]
no_license
fragoulis/gpm-sem1-spacegame
c600f300046c054f7ab3cbf7193ccaad1503ca09
85bdfb5b62e2964588f41d03a295b2431ff9689f
refs/heads/master
2023-06-09T03:43:53.175249
2007-12-13T03:03:30
2007-12-13T03:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,089
h
#pragma once #include "VisualVertexArray.h" namespace tlib { /** * Code for this class and the sphere is taken from the tutorials */ class OCVisualVertexArraySphere : public OCVisualVertexArray { private: // Sphere's radius float m_fRadius; // Sphere attributes int m_iStacks, m_iSlices; public: /** * Constructor */ OCVisualVertexArraySphere( float fRadius, int iStacks, int iSlices ); /** * Returns the unique component ID */ const string componentID() const { return string("vertexarraysphere"); } /** * Accessors */ float getRadius() const { return m_fRadius; } /** * Renders the sphere */ void render() const; /** * Creates the sphere */ bool create(); }; // end of OCVisualVertexArraySphere class } // end of namespace tlib
[ "john.fragkoulis@201bd241-053d-0410-948a-418211174e54" ]
[ [ [ 1, 50 ] ] ]
69236043dcf47c39a543528f95af3b6a2fb6c387
1f8c4298e80a2da0f78424152d0db18837bb6254
/source/Box2D/Collision/b2Shape.h
b54ab2578ff685228635281cb349160768d1d717
[]
no_license
benbaker76/TriballDS
68822bd2760f927a9950d8061ee416d07f3d2e4c
80dabc161227c564940912672f4b643dd401dcd8
refs/heads/master
2022-11-28T03:34:09.460898
2010-01-10T22:51:34
2010-01-10T22:51:34
241,390,317
1
0
null
null
null
null
UTF-8
C++
false
false
6,727
h
/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * 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. */ #ifndef B2_SHAPE_H #define B2_SHAPE_H #include "../Common/b2Math.h" #include "b2Collision.h" class b2Body; class b2BroadPhase; struct b2MassData { Fixed mass; b2Vec2 center; Fixed I; }; enum b2ShapeType { e_unknownShape = -1, e_circleShape, e_boxShape, e_polyShape, e_meshShape, e_shapeTypeCount, }; struct b2ShapeDef { b2ShapeDef() { type = e_unknownShape; userData = NULL; localPosition.Set(0.0f, 0.0f); localRotation = 0.0f; friction = 0.2f; restitution = 0.0f; density = 0.0f; categoryBits = 0x0001; maskBits = 0xFFFF; groupIndex = 0; } virtual ~b2ShapeDef() {} void ComputeMass(b2MassData* massData) const; b2ShapeType type; void* userData; b2Vec2 localPosition; Fixed localRotation; Fixed friction; Fixed restitution; Fixed density; // The collision category bits. Normally you would just set one bit. uint16 categoryBits; // The collision mask bits. This states the categories that this // shape would accept for collision. uint16 maskBits; // Collision groups allow a certain group of objects to never collide (negative) // or always collide (positive). Zero means no collision group. Non-zero group // filtering always wins against the mask bits. int16 groupIndex; }; struct b2CircleDef : public b2ShapeDef { b2CircleDef() { type = e_circleShape; radius = 1.0f; } Fixed radius; }; struct b2BoxDef : public b2ShapeDef { b2BoxDef() { type = e_boxShape; extents.Set(1.0f, 1.0f); } b2Vec2 extents; }; // Convex polygon, vertices must be in CCW order. struct b2PolyDef : public b2ShapeDef { b2PolyDef() { type = e_polyShape; vertexCount = 0; } b2Vec2 vertices[b2_maxPolyVertices]; int32 vertexCount; }; // Shapes are created automatically when a body is created. // Client code does not normally interact with shapes. class b2Shape { public: virtual bool TestPoint(const b2Vec2& p) = 0; void* GetUserData(); b2ShapeType GetType() const; // Get the parent body of this shape. b2Body* GetBody(); // Get the world position. const b2Vec2& GetPosition() const; // Get the world rotation. const b2Mat22& GetRotationMatrix() const; // Remove and then add proxy from the broad-phase. // This is used to refresh the collision filters. virtual void ResetProxy(b2BroadPhase* broadPhase) = 0; // Get the next shape in the parent body's shape list. b2Shape* GetNext(); //--------------- Internals Below ------------------- static b2Shape* Create( const b2ShapeDef* def, b2Body* body, const b2Vec2& newOrigin); static void Destroy(b2Shape*& shape); b2Shape(const b2ShapeDef* def, b2Body* body); virtual ~b2Shape(); virtual void Synchronize( const b2Vec2& position1, const b2Mat22& R1, const b2Vec2& position2, const b2Mat22& R2) = 0; virtual void QuickSync(const b2Vec2& position, const b2Mat22& R) = 0; virtual b2Vec2 Support(const b2Vec2& d) const = 0; Fixed GetMaxRadius() const; void DestroyProxy(); b2Shape* m_next; b2Mat22 m_R; b2Vec2 m_position; b2ShapeType m_type; void* m_userData; b2Body* m_body; Fixed m_friction; Fixed m_restitution; Fixed m_maxRadius; uint16 m_proxyId; uint16 m_categoryBits; uint16 m_maskBits; int16 m_groupIndex; }; class b2CircleShape : public b2Shape { public: bool TestPoint(const b2Vec2& p); void ResetProxy(b2BroadPhase* broadPhase); //--------------- Internals Below ------------------- b2CircleShape(const b2ShapeDef* def, b2Body* body, const b2Vec2& newOrigin); void Synchronize( const b2Vec2& position1, const b2Mat22& R1, const b2Vec2& position2, const b2Mat22& R2); void QuickSync(const b2Vec2& position, const b2Mat22& R); b2Vec2 Support(const b2Vec2& d) const; // Local position in parent body b2Vec2 m_localPosition; Fixed m_radius; }; // A convex polygon. The position of the polygon (m_position) is the // position of the centroid. The vertices of the incoming polygon are pre-rotated // according to the local rotation. The vertices are also shifted to be centered // on the centroid. Since the local rotation is absorbed into the vertex // coordinates, the polygon rotation is equal to the body rotation. However, // the polygon position is centered on the polygon centroid. This simplifies // some collision algorithms. class b2PolyShape : public b2Shape { public: bool TestPoint(const b2Vec2& p); void ResetProxy(b2BroadPhase* broadPhase); //--------------- Internals Below ------------------- b2PolyShape(const b2ShapeDef* def, b2Body* body, const b2Vec2& newOrigin); void Synchronize( const b2Vec2& position1, const b2Mat22& R1, const b2Vec2& position2, const b2Mat22& R2); void QuickSync(const b2Vec2& position, const b2Mat22& R); b2Vec2 Support(const b2Vec2& d) const; // Local position of the shape centroid in parent body frame. b2Vec2 m_localCentroid; // Local position oriented bounding box. The OBB center is relative to // shape centroid. b2OBB m_localOBB; b2Vec2 m_vertices[b2_maxPolyVertices]; b2Vec2 m_coreVertices[b2_maxPolyVertices]; int32 m_vertexCount; b2Vec2 m_normals[b2_maxPolyVertices]; }; inline b2ShapeType b2Shape::GetType() const { return m_type; } inline void* b2Shape::GetUserData() { return m_userData; } inline b2Body* b2Shape::GetBody() { return m_body; } inline b2Shape* b2Shape::GetNext() { return m_next; } inline const b2Vec2& b2Shape::GetPosition() const { return m_position; } inline const b2Mat22& b2Shape::GetRotationMatrix() const { return m_R; } inline Fixed b2Shape::GetMaxRadius() const { return m_maxRadius; } #endif
[ [ [ 1, 284 ] ] ]
5c8e057e9b656aead598ec96d07f353d087008b2
d504537dae74273428d3aacd03b89357215f3d11
/src/Script/ScriptJS.cpp
b09ca1176bb59fdcf158bf63f2e576525cd01e29
[]
no_license
h0MER247/e6
1026bf9aabd5c11b84e358222d103aee829f62d7
f92546fd1fc53ba783d84e9edf5660fe19b739cc
refs/heads/master
2020-12-23T05:42:42.373786
2011-02-18T16:16:24
2011-02-18T16:16:24
237,055,477
1
0
null
2020-01-29T18:39:15
2020-01-29T18:39:14
null
UTF-8
C++
false
false
11,992
cpp
#include "../e6/e6_impl.h" #include "Script.h" #include <stdarg.h> #include <map> #include "jsapi.h" // // this is the function to wrap: // ////static JSBool //// doit(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) //// { //// /* //// * Look in argv for argc actual parameters, set *rval to return a //// * value to the caller. //// */ //// ... //// } // global: e6::Engine * engine = 0; JSObject * currentProto = 0; std::map<int,JSClass> classes; std::map<int,JSObject*> protos; std::map<const char*,JSObject*> supers; JSFunctionSpec specs[512]; JSFunctionSpec *theSpec = 0; int _n_specs = 0; //! params to 'doit' in a struct //! i need them in a single chunk, so i can sell //! a reference to it to the stackmachine-templytes. struct JSVM { JSContext *cx; JSObject *obj; uintN argc; jsval *argv; jsval *rval; JSObject *global; }; typedef JSVM & VM; typedef JSBool RetType; typedef RetType (*SCRIPT_CALLBACK)(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval); //! js args start at 0: const int freeFunctionOffset = 0; //! 'this' is not on the stack: const int classMemberOffset = 0; #include "StackMachine.h" namespace StackMachine { JSBool retValue( int r ) { return 1; //(r?1:0); // make it bool } template < class Func, Func ptr > static RetType Function (JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { JSVM vm = {cx,obj,argc,argv,rval,0}; return StackMachine::function( vm, ptr ); } template <class T> JSBool Constructor_prohibited( JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { return 0; //sq_throwerror(vm, "you cannot create an instance of this!" ); } template <class T> JSBool Constructor(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { int i=0; JSVM vm = {cx,obj,argc,argv,rval,0}; const char * modName = getString(vm,i); const char * interfaceName = getString(vm,i); T * t = (T*)engine->createInterface( modName, interfaceName ); return putObject(vm, t, 1); } void Dtor(JSContext *cx, JSObject *obj) { e6::Base * ptr = static_cast< e6::Base * >( JS_GetPrivate( cx, obj ) ); E_RELEASE(ptr); JS_SetPrivate( cx, obj, 0 ); } ////! returns prototype //JSBool getProp(JSContext *cx, JSObject *obj, jsval id, jsval *rval) //{ // int x = JSVAL_TO_INT(id); // if (! JSVAL_IS_INT(id)) return JS_FALSE; // switch (x) // { // case 0: // { // JSObject *proto = JS_GetPrototype(cx, obj); // *(rval) = OBJECT_TO_JSVAL(proto); // } // break; // default: return JS_FALSE; // } // return JS_TRUE; //} // //! handle float3, float4 as arrays: // void put_arr( VM vm, const float*f, int n ) { JSObject *arr = JS_NewArrayObject( vm.cx, n, 0 ); for ( int i=0; i<n; i++ ) { jsval vp; JS_NewDoubleValue(vm.cx, f[i], &vp); JS_SetElement(vm.cx, arr, i, &vp); } *(vm.rval) = OBJECT_TO_JSVAL(arr); } template <> RetType put<const float3& >(VM vm, const float3 & f) { put_arr( vm, &(f.x), 3 ); return 1; } template <> RetType put<float3>(VM vm, float3 f) { put_arr( vm, &(f.x), 3 ); return 1; } template <> float3 get(VM vm, int &i) { float3 f; f[0] = getFloat( vm, i ); f[1] = getFloat( vm, i ); f[2] = getFloat( vm, i ); return f; } template <> const float3 & get(VM vm, int &i) { static float3 f; ///PPP uuuuuuuuuuaaaaaaaaa f[0] = getFloat( vm, i ); f[1] = getFloat( vm, i ); f[2] = getFloat( vm, i ); return f; } template <> RetType put<const float4& >(VM vm, const float4 & f) { put_arr( vm, &(f.x), 4 ); return 1; } template <> RetType put<float4>(VM vm, float4 f) { put_arr( vm, &(f.x), 4 ); return 1; } template <> float4 get(VM vm, int &i) { float4 f; f[0] = getFloat( vm, i ); f[1] = getFloat( vm, i ); f[2] = getFloat( vm, i ); f[3] = getFloat( vm, i ); return f; } template <> const float4 & get(VM vm, int &i) { static float4 f; ///PPP uuuuuuuuuuaaaaaaaaa f[0] = getFloat( vm, i ); f[1] = getFloat( vm, i ); f[2] = getFloat( vm, i ); f[3] = getFloat( vm, i ); return f; } } #include "ScriptBind.h" namespace StackMachine { int error(VM vm, const char *e ) { return 0; } template < class X > bool getObject( VM vm, X**pptarget, int &index ) { JSObject * obj = 0; bool ok = JS_ValueToObject( vm.cx, vm.argv[index], &obj ); if ( ok ) { *pptarget = static_cast< X* >( JS_GetPrivate( vm.cx, obj ) ); } index ++; return ok; } template < class X > X * getThis( VM vm, int &index ) { return static_cast< X* >( JS_GetPrivate( vm.cx, vm.obj ) ); } template < class X > int putObject( VM vm, X * x, int pos ) { if ( ! x ) { // we have to return 'null' at least, since it is a valid answer. *(vm.rval) = JSVAL_VOID; return 1; } int clsID = getClassID<X>(); JSObject * obj = JS_NewObject( vm.cx, &classes[clsID], protos[clsID], vm.obj ); JS_SetPrivate( vm.cx, obj, x ); *(vm.rval) = OBJECT_TO_JSVAL(obj); return 1; } float getFloat( VM vm, int & index ) { jsdouble target=0; JS_ValueToNumber(vm.cx, vm.argv[index], &target); index ++; return target; } int putFloat( VM vm, float f ) { return JS_NewDoubleValue(vm.cx, f, vm.rval); } int getInt( VM vm, int & index ) { int32 target=0; JS_ValueToInt32(vm.cx, vm.argv[index], &target); index ++; return target; } int putInt( VM vm, int t ) { return JS_NewNumberValue( vm.cx, t, vm.rval ); } const char * getString( VM vm, int & index ) { JSString * str = JS_ValueToString(vm.cx, vm.argv[index]); const char * target = JS_GetStringBytes( str ); index ++; return target; } int putString( VM vm, const char * str ) { JSString * jstr = JS_NewString( vm.cx, (char*)str, strlen(str) ); *(vm.rval) = STRING_TO_JSVAL(jstr); return (1 ); } void module_start(VM v, const char * modName) { } void class_start(VM vm, const char * clsName, const char * superName, int classID, SCRIPT_CALLBACK ctor) { JSClass my_class = { clsName, JSCLASS_HAS_PRIVATE, JS_PropertyStub,JS_PropertyStub,/*StackMachine::getProp*/JS_PropertyStub,JS_PropertyStub, JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub, StackMachine::Dtor // JS_FinalizeStub };; classes[ classID ]= my_class; // setup inheritance: JSObject * parent = 0; if ( ! supers.empty() ) { std::map<const char*,JSObject*>::iterator it = supers.find( superName ); if ( it!=supers.end() ) { parent = it->second; } } theSpec = &specs[_n_specs]; //static JSPropertySpec e6_properties[] = { // {"prototype", 0, JSPROP_EXPORTED, StackMachine::getProp}, // {0} //}; currentProto = JS_InitClass( vm.cx, vm.global, parent, &classes[ classID ], // native constructor function and min arg count ctor, 2, // prototype object properties and methods 0, theSpec, // static properties and methods 0/*e6_properties*/, 0 ); supers[ clsName ] = currentProto; protos[ classID ] = currentProto; } void push_variable(VM v, const char * vName, int i) { } void push_method(VM v, const char * fuName, SCRIPT_CALLBACK func, bool isStatic) { if ( isStatic ) { JS_DefineFunction(v.cx, v.global, fuName, func, 7, 0); } else { JSFunctionSpec spec = {fuName,func,7,0}; specs[_n_specs++] = spec; } } void class_end(VM vm) { // terminate spec list: static JSFunctionSpec zero = {0,0,0,0}; specs[_n_specs++] = zero; JS_DefineFunctions(vm.cx, currentProto, theSpec); currentProto = 0; } void module_end(VM v) { } bool eval_code(VM v, const char * code ) { return 0; } } namespace ScriptJS { struct DefLogger : e6::Logger { virtual bool printLog( const char * s ) { fprintf( stdout, s ); return 1; } } _defLog; e6::Logger * l_err = &_defLog; e6::Logger * l_out = &_defLog; //! The error reporter callback. void reportError(JSContext *cx, const char *message, JSErrorReport *report) { char buf[2048]; sprintf(buf, "%s:%u:%s\r\n", report->filename ? report->filename : "<no filename>", (unsigned int) report->lineno, message); l_err->printLog( buf ); } //! print to e6::Logger JSBool print(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { for ( uintN i=0; i<argc; i++ ) { JSString * str = JS_ValueToString(cx, argv[i]); if (!str) return JS_FALSE; l_out->printLog( JS_GetStringBytes(str) ); if ( i < argc-1 ) l_out->printLog(" "); } return 1; } struct CInterpreter : e6::CName< Script::Interpreter , CInterpreter > { JSVM vm; JSRuntime * rt ; CInterpreter() : rt(0) { $1("CInterpreter()"); setName( "e6_JS" ); classes.clear(); protos.clear(); supers.clear(); _n_specs = 0; } ~CInterpreter() { $1("~CInterpreter()"); JS_DestroyContext(this->vm.cx); JS_DestroyRuntime(this->rt); JS_ShutDown(); E_RELEASE( engine ); } virtual bool setup( e6::Engine * ngin ) { E_ADDREF( ngin ); E_RELEASE( engine ); engine = ngin; static JSClass global_class = { "global",0, JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub, JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,JS_FinalizeStub }; this->rt = JS_NewRuntime(0x100000L); if ( ! this->rt ) { printf("no rt !\n"); return 0; } this->vm.cx = JS_NewContext(rt, 0x1000); if ( ! this->vm.cx ) { printf("no cx !\n"); return 0; } this->vm.global = JS_NewObject(this->vm.cx, &global_class, NULL, NULL); //JS_GetGlobalObject(cx); if ( ! this->vm.global ) { printf("no global !\n"); return 0; } JS_SetErrorReporter(this->vm.cx, reportError); JS_InitStandardClasses(this->vm.cx, this->vm.global); // overwrite builtin 'print' JS_DefineFunction(this->vm.cx, this->vm.global, "print", print, 7, 0); int ok = Script::addModules( this->vm ); return ok; } // load & run virtual bool exec( const char *code, const char * marker ) { uint nBytes = strlen(code); jsval rval; int ok = JS_EvaluateScript( this->vm.cx, this->vm.global, code, nBytes, marker, 13, &rval ); // trigger gc on every 2000 bytes of input code: static uint gcBytes = 0; gcBytes += nBytes; if ( gcBytes > 2000 ) { JS_GC( this->vm.cx ); gcBytes = 0; } return ok; } // run function in compiled code virtual bool call( const char *function, const char *marker ) { return 0; //NOT_IMPL } // run function in compiled code virtual bool call( const char *function, float f, const char *marker ) { return 0; //NOT_IMPL } virtual void setOutlog( e6::Logger & lg ) { l_out = &lg ; } virtual void setErrlog( e6::Logger & lg ) { l_err = &lg ; } virtual const char * getFileExtension() const { return "js"; } }; // CInterpreter } // ScriptJS extern "C" uint getClassInfo( e6::ClassInfo ** ptr ) { const static e6::ClassInfo _ci[] = { { "Script.Interpreter", "ScriptJS", ScriptJS::CInterpreter::createSingleton, ScriptJS::CInterpreter::classRef }, { 0, 0, 0 } }; *ptr = (e6::ClassInfo *)_ci; return 1; // classses } #include "../e6/version.h" extern "C" uint getVersion( e6::ModVersion * mv ) { mv->modVersion = ("ScriptJS 00.000.0061 (" __DATE__ ")"); mv->e6Version = e6::e6_version; return 1; }
[ [ [ 1, 553 ] ] ]
70059c9277e5a8d322b513f367ac812aafb59f2a
23b2ab84309de65b42333c87e0de088503e2cb36
/src/engine/tasks.cpp
34b836061f0d8f5cce81d40fb8a4ee09f25ad4b0
[]
no_license
fyrestone/simple-pms
74a771d83979690eac231a82f1c457d7b6c55f41
1917d5c4e14bf7829707bacb9cc2452b49d6cc2b
refs/heads/master
2021-01-10T20:36:39.403902
2011-04-16T15:38:12
2011-04-16T15:38:12
32,192,134
0
0
null
null
null
null
UTF-8
C++
false
false
30,898
cpp
/*! \file task.cpp \author Liubao \version 1.0 \date 2011/4/4 \brief 所有业务逻辑实现 \warning 由于业务逻辑可能同步执行也可能异步执行,所有需要使用指针的业务逻辑,都需要: 1、使用安全指针如QPointer、QWeakPointer 2、即使使用安全指针,该指针也不可在异步线程中解引用 3、必须使用信号-槽传递该指针(使用自动信号-槽捆绑),并在槽中对其解引用 4、在使用该指针槽中,必须解引用前使用RETURN_IF_FAIL来测试该指针 */ #include "tasks.h" #include "../context/context.h" #include <QSqlDatabase> #include <QSqlQuery> #include <QSqlError> #include <QStandardItemModel> using namespace DataEngine; /*! 测试target,若为假,打印信息并退出 \param target 测试的逻辑值 */ #define RETURN_IF_FAIL(target) \ if(!(target)) \ { \ qDebug("%s:%d Info: " #target " failed", __PRETTY_FUNCTION__, __LINE__);\ return; \ } /*! 打印函数运行线程信息 */ #define PRINT_RUN_THREAD() \ qDebug() << __PRETTY_FUNCTION__ << "run in Thread" << QThread::currentThreadId() /* 注册信号/槽参数类型 */ int i1 = qRegisterMetaType<QSqlRecord>("QSqlRecord"); int i2 = qRegisterMetaType< QPointer<QStandardItemModel> >("QPointer<QStandardItemModel>"); int i3 = qRegisterMetaType< QPointer<QAbstractTableModel> >("QPointer<QAbstractTableModel>"); int i4 = qRegisterMetaType< QPointer<QTreeWidget> >("QPointer<QTreeWidget>"); int i5 = qRegisterMetaType< QList<QSqlRecord> >("QList<QSqlRecord>"); /* 注册QVariant支持类型 */ Q_DECLARE_METATYPE(QList<QSqlRecord>); InitializeDBTask::InitializeDBTask(QObject *parent) : AbstractTask<InitializeDBTask, InitializeDB, bool>(parent) { setRunEntry(&InitializeDBTask::run); } bool InitializeDBTask::run(const QString &dbPath) { PRINT_RUN_THREAD(); return createConnection(dbPath) && createTable() && fillInitialData(); } bool InitializeDBTask::createConnection(const QString &dbPath) { bool success = false; QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); if(db.isValid()) { db.setDatabaseName(dbPath); success = db.open(); } return success; } bool InitializeDBTask::createTable() { static const QString createClassTypeTable = tr( "CREATE TABLE IF NOT EXISTS ClassType (" "class_type_id INTEGER PRIMARY KEY NOT NULL," "name NVARCHAR(20))" ); static const QString createGradeClassTable = tr( "CREATE TABLE IF NOT EXISTS GradeClass (" "grade INTEGER NOT NULL," "class INTEGER NOT NULL," "class_type_id INTEGER NOT NULL DEFAULT 0," "PRIMARY KEY(grade, class)," "FOREIGN KEY(class_type_id) REFERENCES ClassType(class_type_id) ON DELETE SET DEFAULT ON UPDATE CASCADE)" ); static const QString createStudentsTable = tr( "CREATE TABLE IF NOT EXISTS Students (" "student_id INTEGER PRIMARY KEY NOT NULL," "id NVARCHAR(20)," "sex NCHAR(1)," "name NVARCHAR(15)," "grade INTEGER," "class INTEGER," "in_school INTEGER NOT NULL DEFAULT 1," "FOREIGN KEY(grade, class) REFERENCES GradeClass(grade, class) ON DELETE SET NULL ON UPDATE CASCADE," "CHECK(sex IN ('男', '女')))" ); static const QString createExamsTable = tr( "CREATE TABLE IF NOT EXISTS Exams (" "exam_id INTEGER NOT NULL," "name NVARCHAR(20)," "date DATE NOT NULL DEFAULT CURRENT_DATE," "PRIMARY KEY(exam_id))" ); static const QString createCoursesTable = tr( "CREATE TABLE IF NOT EXISTS Courses (" "course_id INTEGER PRIMARY KEY NOT NULL," "exam_id INTEGER NOT NULL," "name NVARCHAR(10)," "FOREIGN KEY(exam_id) REFERENCES Exams(exam_id) ON DELETE CASCADE ON UPDATE CASCADE)" ); static const QString createNormalCoursesTable = tr( "CREATE TABLE IF NOT EXISTS NormalCourses (" "course_id INTEGER NOT NULL," "full_mark DECIMAL(10,2) DEFAULT 100," "pass_rate FLOAT(2) DEFAULT 0.6 CHECK(pass_rate >=0 and pass_rate <= 1)," "good_rate FLOAT(2) DEFAULT 0.8 CHECK(good_rate >=0 and good_rate <= 1)," "excellent_rate FLOAT(2) DEFAULT 0.9 CHECK(excellent_rate >=0 and excellent_rate <= 1)," "PRIMARY KEY(course_id)," "FOREIGN KEY(course_id) REFERENCES Courses(course_id) ON DELETE CASCADE ON UPDATE CASCADE)" ); static const QString createSpecialCoursesTable = tr( "CREATE TABLE IF NOT EXISTS SpecialCourses (" "course_id INTEGER NOT NULL," "command NVARCHAR(100)," "PRIMARY KEY(course_id)," "FOREIGN KEY(course_id) REFERENCES Courses(course_id) ON DELETE CASCADE ON UPDATE CASCADE)" ); static const QString createScoresTable = tr( "CREATE TABLE IF NOT EXISTS Scores (" "student_id INTEGER NOT NULL," "course_id INTEGER NOT NULL," "exam_id INTEGER NOT NULL," "score DECIMAL(10,2)," "PRIMARY KEY(student_id, course_id, exam_id)," "FOREIGN KEY(student_id) REFERENCES Students(student_id) ON DELETE CASCADE ON UPDATE CASCADE," "FOREIGN KEY(course_id) REFERENCES Courses(Course_id) ON DELETE CASCADE ON UPDATE CASCADE," "FOREIGN KEY(exam_id) REFERENCES Exams(exam_id) ON DELETE CASCADE ON UPDATE CASCADE)" ); static const QString createCourseSetTable = tr( "CREATE TABLE IF NOT EXISTS CourseNameSet (" "name NVARCHAR(10))" ); static const QString createAccountsTable = tr( "CREATE TABLE IF NOT EXISTS Accounts (" "account_id NVARCHAR(10) UNIQUE NOT NULL," "account_pwd NVARCHAR(10)," "name NVARCHAR(10)," "save_password INTEGER NOT NULL DEFAULT 0," "permission BLOB NOT NULL," "login_time DATETIME DEFAULT (datetime(current_timestamp,'localtime')))" ); static const QString createVersionTable = tr( "CREATE TABLE IF NOT EXISTS Version (" "major_version INTEGER UNIQUE NOT NULL," "minor_version INTEGER UNIQUE NOT NULL)" ); bool success = false; QSqlDatabase db = QSqlDatabase::database(); if(db.transaction()) { QSqlQuery sql(db); success = sql.exec(createClassTypeTable); if(success) success = sql.exec(createGradeClassTable); if(success) success = sql.exec(createStudentsTable); if(success) success = sql.exec(createExamsTable); if(success) success = sql.exec(createCoursesTable); if(success) success = sql.exec(createNormalCoursesTable); if(success) success = sql.exec(createSpecialCoursesTable); if(success) success = sql.exec(createScoresTable); if(success) success = sql.exec(createCourseSetTable); if(success) success = sql.exec(createAccountsTable); if(success) success = sql.exec(createVersionTable); if(success) success = db.commit(); else (void)db.rollback(); } return success; } bool InitializeDBTask::fillInitialData() { static const QString fillDefaultClassType = tr( "INSERT OR REPLACE INTO ClassType" "(class_type_id, name)" "VALUES" "(0, \"普通班\")" ); static const QString fillVersionNumber = tr( "INSERT OR REPLACE INTO Version" "(major_version, minor_version)" "VALUES" "(2, 0)" ); static const QString fillAccount = tr( "INSERT OR IGNORE INTO Accounts" "(account_id, account_pwd, name, permission)" "VALUES" "(:id, :password, :username, :permission)" ); bool success = false; QSqlDatabase db = QSqlDatabase::database(); if(db.transaction()) { QSqlQuery sql(db); QByteArray byteArray; //Permission序列化的字节流 Permission permission; success = sql.exec(fillDefaultClassType); if(success) success = sql.exec(fillVersionNumber); if(success) success = sql.prepare(fillAccount); if(success) { /* 设置管理员权限到permission */ permission.setCreateAccount(true); permission.setCreateClass(false); permission.setCreateExam(true); permission.setEditScore(false); /* 序列化permission到字节流 */ QDataStream ds(&byteArray, QIODevice::WriteOnly); ds << permission; sql.bindValue(":id", "Admin"); sql.bindValue(":password", "123456"); sql.bindValue(":username", tr("管理员")); sql.bindValue(":permission", byteArray); /* 把字节流保存到数据库 */ success = !byteArray.isEmpty() && sql.exec(); } if(success) { byteArray.clear(); /* 设置游客权限到permission */ permission.setCreateAccount(false); permission.setCreateClass(false); permission.setCreateExam(false); permission.setEditScore(false); /* 序列化permission到字节流 */ QDataStream ds(&byteArray, QIODevice::WriteOnly); ds << permission; sql.bindValue(":id", "Guest"); sql.bindValue(":password", "123456"); sql.bindValue(":username", tr("游客")); sql.bindValue(":permission", byteArray); /* 把字节流保存到数据库 */ success = !byteArray.isEmpty() && sql.exec(); } if(success) success = db.commit(); else (void)db.rollback(); } return success; } LoginTask::LoginTask(QObject *parent) : AbstractTask<LoginTask, Login, bool>(parent) { setRunEntry(&LoginTask::run); } bool LoginTask::run(const QString &id, const QString &pwd, bool save) { static const QString login = tr( "SELECT permission FROM Accounts WHERE " "account_id = :id and account_pwd = :pwd" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.prepare(login)) { sql.bindValue(":id", id); sql.bindValue(":pwd", pwd); if(sql.exec() && sql.next()) { QVariant result = sql.value(0); if(result.isValid()) { success = updateSaveStateAndLoginTime(id, save); if(success) { QByteArray byteArray = result.toByteArray(); QDataStream ds(&byteArray, QIODevice::ReadOnly); ds >> Context::instance()->curAccountPermission(); } } } } PRINT_RUN_THREAD(); return success; } bool LoginTask::updateSaveStateAndLoginTime(const QString &id, bool save) { static const QString updateSaveState = tr( "UPDATE Accounts SET save_password = :save, login_time = datetime(current_timestamp,'localtime') " "WHERE account_id = :id" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.prepare(updateSaveState)) { sql.bindValue(":save", save ? 1 : 0); sql.bindValue(":id", id); success = sql.exec(); } return success; } InsertOrUpdateClassTask::InsertOrUpdateClassTask(QObject *parent) : AbstractTask<InsertOrUpdateClassTask, InsertOrUpdateClass, bool>(parent) { setRunEntry(&InsertOrUpdateClassTask::run); } bool InsertOrUpdateClassTask::run(int gradeNum, int classNum, int classTypeID) { static const QString insertGradeClass = tr( "INSERT OR REPLACE INTO GradeClass(grade, class, class_type_id) " "VALUES (:grade, :class, :class_type_id)" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.prepare(insertGradeClass)) { sql.bindValue(":grade", gradeNum); sql.bindValue(":class", classNum); sql.bindValue(":class_type_id", classTypeID); success = sql.exec(); } PRINT_RUN_THREAD(); return success; } DeleteClassTask::DeleteClassTask(QObject *parent) : AbstractTask<DeleteClassTask, DeleteClass, bool>(parent) { setRunEntry(&DeleteClassTask::run); } bool DeleteClassTask::run(int gradeNum, int classNum) { static const QString deleteGradeClass = tr( "DELETE FROM GradeClass WHERE grade = :grade and class = :class" ); static const QString deleteGrade = tr( "DELETE FROM GradeClass WHERE grade = :grade" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(classNum == INVALID_CLASS_NUM) { if(sql.prepare(deleteGrade)) { sql.bindValue(":grade", gradeNum); success = sql.exec(); } } else if(sql.prepare(deleteGradeClass)) { sql.bindValue(":grade", gradeNum); sql.bindValue(":class", classNum); success = sql.exec(); } PRINT_RUN_THREAD(); return success; } FillAccountsListModelTask::FillAccountsListModelTask(QObject *parent) : AbstractTask<FillAccountsListModelTask, FillAccountsListModel, bool>(parent) { setRunEntry(&FillAccountsListModelTask::run); connect(this, SIGNAL(querySuccess(QPointer<QStandardItemModel>)), this, SLOT(initModel(QPointer<QStandardItemModel>))); connect(this, SIGNAL(sendData(QPointer<QStandardItemModel>,QSqlRecord)), this, SLOT(recvData(QPointer<QStandardItemModel>,QSqlRecord))); } bool FillAccountsListModelTask::run(QPointer<QStandardItemModel> model, int max) { static const QString listAccounts = tr( "SELECT account_id, name," "CASE WHEN save_password = 0 " "THEN '' " "ELSE account_pwd " "END AS account_pwd , save_password " "FROM Accounts " "ORDER BY login_time DESC LIMIT :max" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.prepare(listAccounts)) { sql.bindValue(":max", QString::number(max)); if(sql.exec()) { emit querySuccess(model); while(sql.next()) emit sendData(model, sql.record()); success = true; } } PRINT_RUN_THREAD(); return success; } void FillAccountsListModelTask::initModel(QPointer<QStandardItemModel> model) { RETURN_IF_FAIL(model); model->clear(); } void FillAccountsListModelTask::recvData(QPointer<QStandardItemModel> model, const QSqlRecord &record) { RETURN_IF_FAIL(model); QList<QStandardItem *> row; row.append(new QStandardItem(record.value(0).toString())); //账号 row.append(new QStandardItem(record.value(1).toString())); //姓名 row.append(new QStandardItem(record.value(2).toString())); //密码 QStandardItem *savePWD = new QStandardItem(); savePWD->setData(record.value(3), Qt::DisplayRole); row.append(savePWD); //是否记住密码 QStandardItem *autoLogin = new QStandardItem(); autoLogin->setData(0, Qt::DisplayRole); row.append(autoLogin); //是否自动登陆 model->appendRow(row); } FillNavigationTreeTask::FillNavigationTreeTask(QObject *parent) : AbstractTask<FillNavigationTreeTask, FillNavigationTree, bool>(parent) { setRunEntry(&FillNavigationTreeTask::run); connect(this, SIGNAL(querySuccess(QPointer<QTreeWidget>,QString)), this, SLOT(initWidget(QPointer<QTreeWidget>,QString))); connect(this, SIGNAL(sendData(QPointer<QTreeWidget>,QList<QSqlRecord>)), this, SLOT(recvData(QPointer<QTreeWidget>,QList<QSqlRecord>))); } bool FillNavigationTreeTask::run(QPointer<QTreeWidget> widget, const QString &rootName) { static const QString gradeClassQuery = tr( "SELECT grade, class from GradeClass order by grade DESC, class ASC" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.exec(gradeClassQuery)) { QList<QSqlRecord> recordSet; emit querySuccess(widget, rootName); while(sql.next()) recordSet.push_back(sql.record()); emit sendData(widget, recordSet); success = true; } PRINT_RUN_THREAD(); return success; } void FillNavigationTreeTask::initWidget(QPointer<QTreeWidget> widget, const QString &rootName) { RETURN_IF_FAIL(widget); widget->clear(); QTreeWidgetItem *root = new QTreeWidgetItem(Root); root->setText(0, rootName); widget->addTopLevelItem(root); } void FillNavigationTreeTask::recvData(QPointer<QTreeWidget> widget, const QList<QSqlRecord> &data) { RETURN_IF_FAIL(widget); QTreeWidgetItem *lastGradeItem = NULL; int lastGradeNum = -1; for(int i = 0; i < data.count(); ++i) { int currGradeNum = data.at(i).value(0).toInt(); int currClassNum = data.at(i).value(1).toInt(); if(currGradeNum != lastGradeNum) { lastGradeNum = currGradeNum; lastGradeItem = new QTreeWidgetItem(widget->topLevelItem(0), Grade); lastGradeItem->setText(0, QString::number(currGradeNum) + tr("级")); lastGradeItem->setData(0, Qt::UserRole, currGradeNum); } QTreeWidgetItem *classItem = new QTreeWidgetItem(lastGradeItem, Class); classItem->setText(0, QString::number(currClassNum) + tr("班")); classItem->setData(0, Qt::UserRole, currClassNum); } widget->expandAll(); } FillGradeListTask::FillGradeListTask(QObject *parent) : AbstractTask<FillGradeListTask, FillGradeList, bool>(parent) { setRunEntry(&FillGradeListTask::run); connect(this, SIGNAL(querySuccess(QPointer<QTreeWidget>,QString)), this, SLOT(initWidget(QPointer<QTreeWidget>,QString))); connect(this, SIGNAL(sendData(QPointer<QTreeWidget>,QVariant)), this, SLOT(recvData(QPointer<QTreeWidget>,QVariant))); } bool FillGradeListTask::run(QPointer<QTreeWidget> widget, const QString &headName) { static const QString gradeQuery = tr( "SELECT DISTINCT grade from GradeClass order by grade ASC" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.exec(gradeQuery)) { emit querySuccess(widget, headName); while(sql.next()) emit sendData(widget, sql.value(0)); success = true; } PRINT_RUN_THREAD(); return success; } void FillGradeListTask::initWidget(QPointer<QTreeWidget> widget, const QString &headName) { RETURN_IF_FAIL(widget); widget->clear(); QTreeWidgetItem *header = widget->headerItem(); if(header) { header->setText(0, headName); header->setTextAlignment(0, Qt::AlignCenter); } } void FillGradeListTask::recvData(QPointer<QTreeWidget> widget, const QVariant &data) { RETURN_IF_FAIL(widget); QTreeWidgetItem *gradeItem = new QTreeWidgetItem(widget); gradeItem->setData(0, Qt::DisplayRole, data); gradeItem->setTextAlignment(0, Qt::AlignCenter); widget->addTopLevelItem(gradeItem); } FillClassListTask::FillClassListTask(QObject *parent) : AbstractTask<FillClassListTask, FillClassList, bool>(parent) { setRunEntry(&FillClassListTask::run); connect(this, SIGNAL(querySuccess(QPointer<QTreeWidget>,QString)), this, SLOT(initWidget(QPointer<QTreeWidget>,QString))); connect(this, SIGNAL(sendData(QPointer<QTreeWidget>,QVariant)), this, SLOT(recvData(QPointer<QTreeWidget>,QVariant))); } bool FillClassListTask::run(QPointer<QTreeWidget> widget, const QString &headName, int gradeNum) { static const QString classQuery = tr( "SELECT DISTINCT class from GradeClass WHERE grade = :gradeNum order by class ASC" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.prepare(classQuery)) { sql.bindValue(":gradeNum", gradeNum); if(sql.exec()) { emit querySuccess(widget, headName); while(sql.next()) emit sendData(widget, sql.value(0)); success = true; } } PRINT_RUN_THREAD(); return success; } void FillClassListTask::initWidget(QPointer<QTreeWidget> widget, const QString &headName) { RETURN_IF_FAIL(widget); widget->clear(); QTreeWidgetItem *header = widget->headerItem(); if(header) { header->setText(0, headName); header->setTextAlignment(0, Qt::AlignCenter); } } void FillClassListTask::recvData(QPointer<QTreeWidget> widget, const QVariant &data) { RETURN_IF_FAIL(widget); QTreeWidgetItem *classItem = new QTreeWidgetItem(widget); classItem->setData(0, Qt::DisplayRole, data); classItem->setTextAlignment(0, Qt::AlignCenter); widget->addTopLevelItem(classItem); } FillClassTypeListModelTask::FillClassTypeListModelTask(QObject *parent) : AbstractTask<FillClassTypeListModelTask, FillClassTypeListModel, bool>(parent) { setRunEntry(&FillClassTypeListModelTask::run); connect(this, SIGNAL(querySuccess(QPointer<QStandardItemModel>)), this, SLOT(initModel(QPointer<QStandardItemModel>))); connect(this, SIGNAL(sendData(QPointer<QStandardItemModel>,QSqlRecord)), this, SLOT(recvData(QPointer<QStandardItemModel>,QSqlRecord))); } bool FillClassTypeListModelTask::run(QPointer<QStandardItemModel> model) { static const QString classTypeQuery = tr( "SELECT class_type_id, name from ClassType order by class_type_id ASC" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.exec(classTypeQuery)) { emit querySuccess(model); while(sql.next()) sendData(model, sql.record()); success = true; } PRINT_RUN_THREAD(); return success; } void FillClassTypeListModelTask::initModel(QPointer<QStandardItemModel> model) { RETURN_IF_FAIL(model); model->clear(); } void FillClassTypeListModelTask::recvData(QPointer<QStandardItemModel> model, const QSqlRecord &record) { RETURN_IF_FAIL(model); QList<QStandardItem *> row; row.append(new QStandardItem(record.value(1).toString())); //班级类型名 row.append(new QStandardItem(record.value(0).toString())); //班级类型序号 model->appendRow(row); } FillStudentMgmtModelTask::FillStudentMgmtModelTask(QObject *parent) : AbstractTask<FillStudentMgmtModelTask, FillStudentMgmtModel, bool>(parent) { setRunEntry(&FillStudentMgmtModelTask::run); connect(this, SIGNAL(querySuccess(QPointer<QAbstractTableModel>)), this, SLOT(initModel(QPointer<QAbstractTableModel>))); connect(this, SIGNAL(sendData(QPointer<QAbstractTableModel>,QVariant)), this, SLOT(recvData(QPointer<QAbstractTableModel>,QVariant))); connect(this, SIGNAL(queryComplete(QPointer<QAbstractTableModel>)), this, SLOT(fillHeader(QPointer<QAbstractTableModel>))); } bool FillStudentMgmtModelTask::run(QPointer<QAbstractTableModel> model, int gradeNum, int classNum) { static const QString studentInfoQuery = tr( "SELECT student_id, id, sex, name FROM Students WHERE grade = :grade and class = :class" ); int success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.prepare(studentInfoQuery)) { sql.bindValue(":grade", gradeNum); sql.bindValue(":class", classNum); if(sql.exec()) { QList<QSqlRecord> tableRecord; emit querySuccess(model); while(sql.next()) tableRecord.push_back(sql.record()); emit sendData(model, QVariant::fromValue(tableRecord)); emit queryComplete(model); success = true; } } PRINT_RUN_THREAD(); return success; } void FillStudentMgmtModelTask::initModel(QPointer<QAbstractTableModel> model) { RETURN_IF_FAIL(model); model->setData(QModelIndex(), QVariant(), Qt::UserRole); //重置模型 model->setData(QModelIndex(), 4, Qt::UserRole); //初始化列标为4列 } void FillStudentMgmtModelTask::recvData(QPointer<QAbstractTableModel> model, const QVariant &tableRecord) { RETURN_IF_FAIL(model); model->setData(QModelIndex(), tableRecord, Qt::UserRole); //更新模型 } void FillStudentMgmtModelTask::fillHeader(QPointer<QAbstractTableModel> model) { RETURN_IF_FAIL(model); model->setHeaderData(0, Qt::Horizontal, tr("编号")); model->setHeaderData(1, Qt::Horizontal, tr("学号")); model->setHeaderData(2, Qt::Horizontal, tr("性别")); model->setHeaderData(3, Qt::Horizontal, tr("姓名")); } InsertRowStudentMgmtModelTask::InsertRowStudentMgmtModelTask(QObject *parent) : AbstractTask<InsertRowStudentMgmtModelTask, InsertRowStudentMgmtModel, bool>(parent) { setRunEntry(&InsertRowStudentMgmtModelTask::run); connect(this, SIGNAL(sendData(QPointer<QAbstractTableModel>,int,QVariant)), this, SLOT(recvData(QPointer<QAbstractTableModel>,int,QVariant))); } bool InsertRowStudentMgmtModelTask::run(QPointer<QAbstractTableModel> model, int gradeNum, int classNum, int row) { static const QString insertNULLStudentInfo = tr( "INSERT INTO Students(student_id, id, sex, name, grade, class, in_school)" "VALUES (NULL, NULL, NULL, NULL, :gradeNum, :classNum, 1)" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.prepare(insertNULLStudentInfo)) { sql.bindValue(":gradeNum", gradeNum); sql.bindValue(":classNum", classNum); if(sql.exec()) { QVariant id = sql.lastInsertId(); if(id.type() == QVariant::LongLong) { emit sendData(model, row, id); success = true; } } } return success; } void InsertRowStudentMgmtModelTask::recvData(QPointer<QAbstractTableModel> model, int row, const QVariant &id) { RETURN_IF_FAIL(model); model->insertRows(row, 1); model->setData(model->index(row, 0), id); } DeleteRowStudentMgmtModelTask::DeleteRowStudentMgmtModelTask(QObject *parent) : AbstractTask<DeleteRowStudentMgmtModelTask, DeleteRowStudentMgmtModel, bool>(parent) { setRunEntry(&DeleteRowStudentMgmtModelTask::run); connect(this, SIGNAL(sendData(QPointer<QAbstractTableModel>,int)), this, SLOT(recvData(QPointer<QAbstractTableModel>,int))); } bool DeleteRowStudentMgmtModelTask::run(QPointer<QAbstractTableModel> model, int row) { static const QString deleteStudentInfo = tr( "DELETE FROM Students WHERE student_id = :student_id" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(sql.prepare(deleteStudentInfo)) { QVariant id = model->data(model->index(row, 0)); if(id.isValid() && id.type() == QVariant::LongLong) { sql.bindValue(":student_id", id); if(sql.exec()) { sendData(model, row); success = true; } } } return success; } void DeleteRowStudentMgmtModelTask::recvData(QPointer<QAbstractTableModel> model, int row) { RETURN_IF_FAIL(model); model->removeRows(row, 1); } UpdateStudentMgmtModelTask::UpdateStudentMgmtModelTask(QObject *parent) : AbstractTask<UpdateStudentMgmtModelTask, UpdateStudentMgmtModel, bool>(parent) { //不提供异步调用 } bool UpdateStudentMgmtModelTask::run(QPointer<QAbstractTableModel> model, const QModelIndex &index, const QVariant &value) { static const QStringList column= (QStringList() << "student_id" << "id" << "sex" << "name"); static const QString updateStudentInfo = tr( "UPDATE Students SET %1 = :updateValue " "WHERE student_id = :student_id" ); bool success = false; QSqlQuery sql(QSqlDatabase::database()); if(index.isValid() && sql.prepare(updateStudentInfo.arg(column[index.column()]))) { QVariant id = model->data(model->index(index.row(), 0)); if(id.isValid() && id.type() == QVariant::LongLong) { sql.bindValue(":updateValue", value); sql.bindValue(":student_id", id); success = sql.exec(); } } return success; }
[ "[email protected]@95127988-2b6b-df20-625d-5ecc0e46e2bb", "zihongdelei@95127988-2b6b-df20-625d-5ecc0e46e2bb" ]
[ [ [ 1, 406 ], [ 418, 420 ], [ 426, 435 ], [ 448, 981 ] ], [ [ 407, 417 ], [ 421, 425 ], [ 436, 447 ] ] ]
b6bd68e2b64ef56ab6ce90c220f8417da63d3196
bbcd9d87dfc5b475763174dc00ba6fef76aca82d
/wiNstaller/src/iPhone.h
cec979778ed6e7e901c0ee98b746c17a26ea33ca
[]
no_license
wwxxyx/winstaller
8cec98422fb18de2e65846e0562d3038a34ac14b
722bda5b6687d50caa377ceedca7a222d5b04763
refs/heads/master
2020-05-24T07:50:29.060316
2007-09-13T05:43:05
2007-09-13T05:43:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,169
h
#ifndef _IPHONE_H_ #define _IPHONE_H_ #include <string> #include "MobileDevice.h" using namespace std; struct am_device; struct am_device_notification_callback_info; struct am_recovery_device; class IPhoneComm { public: enum Notifications { NotifyConnected, NotifyDisconnected, NotifyJailbreakFailed, NotifyJailbreakSucceeded, NotifyReturnToJailFailed, NotifyReturnToJailSucceeded, NotifyApplicationInstallFailed, NotifyApplicationInstallSucceeded, NotifyActivateFailed, NotifyActivateSucceeded }; enum LogLevel { None, Info, Verbose }; public: ~IPhoneComm(); static IPhoneComm* Instance(); bool initialize(); bool activate(); bool deactivate(); void setNotificationCallback( void (*notificationCallback)( enum IPhoneComm::Notifications notification ) ); bool installApplication( string applicationPath ); bool jailbreak(); bool returnToJail(); bool sendFileToDevice( string sourcePath, string destinationPath ); bool sendFileToDevice( const unsigned char* data, int len, string destinationPath ); bool setRamdiskAndKernelCache( string ramdiskPath, string kernelCachePath ); bool isConnected(); bool isJailbroken(); bool isActivated(); protected: IPhoneComm(); IPhoneComm(const IPhoneComm&); IPhoneComm& operator= (const IPhoneComm&); private: enum DeviceState { Idle, EnteringRecovery, EnteringRestore, ExitingRestore, ReturnToJail }; struct iTunesDllPatch { unsigned long performRestoreOffset; unsigned long sendCommandOffset; unsigned long sendFileOffset; unsigned long socketForPortOffset; unsigned long performOperationOffset; unsigned long sendCommandCrc; unsigned long sendFileCrc; unsigned long socketForPortCrc; unsigned long performOperationsCrc; }; static IPhoneComm* instance; am_device *iPhone; am_recovery_device *iPhoneRecovery; afc_connection *afcConnection; enum DeviceState state; bool connected; bool jailbroken; bool activated; string ramdiskPath; string kernelCachePath; string applicationPath; string applicationName; struct iTunesDllPatch patches[2]; void (*notificationCallback)(enum IPhoneComm::Notifications notification); bool matchFunctionCrc( FILE *f, unsigned long offset, unsigned long crc ); bool loadItunesDLL(); void resetConnection(); bool establishConnection(); bool enterRecovery( bool noRestore ); void exitRecovery(); void enterRestoreMode(); void doRestoreMode(); void doFinalStep(); bool createDirectoryOnDevice(const char *dir); void putDirRecursively(const char * remoteBasePath, const char *basePath, bool exeOnly); void transferApplicationFakingExesRecursively( struct am_restore_device *rdev, const char* destBasePath, const char* srcBasePath, const char* localBasePath ); void sendNotification(enum IPhoneComm::Notifications notification); CFStringRef StringtoCFString(string input); string CFStringtoString(CFStringRef input); void handleRestoreNotification(am_recovery_device *rdev); void handleDeviceNotification(am_device_notification_callback_info *info); void handleRecoveryDisconnect(struct am_recovery_device *rdev); void handleRecoveryConnect(struct am_recovery_device *rdev); static void _handleDeviceNotification(am_device_notification_callback_info *info); static void _handleRecoveryDisconnect(struct am_recovery_device *rdev); static void _handleRecoveryConnect(struct am_recovery_device *rdev); void * VsendCommandToDevice; void * VsendFileToDevice; void * VsocketForPort; void * VperformOperation; unsigned int sendCommandToDevice(am_recovery_device *rdev, CFStringRef cfs); unsigned int sendFileToDevice(am_recovery_device * rdev, CFStringRef fname); unsigned int socketForPort(struct am_restore_device * rdev, unsigned int port); unsigned int performOperation(am_restore_device * rdev, CFDictionaryRef cfdr); static const char *rwFstab; static const char *modifiedServicesPlist; static const char *roFstab; static const char *originalServicesPlist; }; #endif
[ [ [ 1, 158 ] ] ]
c699ba2d78eeef603fab45201d2a96354d92377e
43626054205d6048ec98c76db5641ce8e42b8237
/source/CPlayer.h
c4e3cf12742200558da709bbfcdebae2283a3584
[]
no_license
Wazoobi/whitewings
b700da98b855a64442ad7b7c4b0be23427b0ee23
a53fdb832cfb1ce8605209c9af47f36b01c44727
refs/heads/master
2021-01-10T19:33:22.924792
2009-08-05T18:30:07
2009-08-05T18:30:07
32,119,981
0
0
null
null
null
null
UTF-8
C++
false
false
2,336
h
#pragma once #include "CBase.h" class CSGD_DirectInput; class CEnemy; #define SHOT_DELAY 3.0f class CPlayer : public CBase { float m_fStunGunTimer; bool m_bStunGunReady; bool m_bEnemyHacked; float m_fDashTimer; bool m_bIsDashing; bool m_bIsJumping; bool m_bIsHackingTerminal; bool m_bTouchingTerminal; bool m_bIsHacking; CEnemy *m_pCurrentlyHackedEnemy; int m_nHealth; int m_nHackOrbs; int m_nDirection; // 0 is Left. 1 is Right. int m_nImageID; int m_nHackableImageID; bool m_bDrawHackableImage; float m_fGravity; float m_fGravityTimer; int m_nCollisionType; // 0 = no collision, 1 = collision on right, 2 = collision on left, 3 = collision from above, 4 = collision from below float m_fInvulnerableTimer; bool m_bIsInvulnerable; CPlayer(); ~CPlayer(); CPlayer(const CPlayer&); CPlayer& operator=(const CPlayer&); public: static CPlayer* GetInstance(); inline int GetDirection() const {return m_nDirection;} inline int GetHackOrbs() const {return m_nHackOrbs;} inline int GetHealth() const {return m_nHealth;} inline bool GetInvulnerable() const {return m_bIsInvulnerable;} inline bool GetIsJumping() const {return m_bIsJumping;} void SetHackOrbs(int nHackOrbs) {m_nHackOrbs = nHackOrbs;} void SetHealth(int nHealth) {m_nHealth = nHealth;} void SetInvulnerable(bool bInvulnerable) {m_bIsInvulnerable = bInvulnerable;} void SetIsJumping(bool bIsJumping) {m_bIsJumping = bIsJumping;} void ResetPlayer(); ////////////////////////////////////////////////////////////////////////// // Function : Checks for collision // // Purpose : Returns true if there is a collision ////////////////////////////////////////////////////////////////////////// bool CheckCollision(CBase* pBase); ////////////////////////////////////////////////////////////////////////// // Function : Updates // // Purpose : Updates data members based on time. ////////////////////////////////////////////////////////////////////////// void Update(float fElapsedTime); ////////////////////////////////////////////////////////////////////////// // Function : Render // // Purpose : Draws to the screen. ////////////////////////////////////////////////////////////////////////// void Render(void); };
[ "Juno05@1cfc0206-7002-11de-8585-3f51e31374b7" ]
[ [ [ 1, 85 ] ] ]
65e587f6df30f7a10ce6be584aca75f2fa0f9dd2
16d8b25d0d1c0f957c92f8b0d967f71abff1896d
/OblivionOnline/cegui/RendererModules/directx9GUIRenderer/d3d9renderer.h
f8744563935d7edb4346e302b4987ecb14ad193b
[]
no_license
wlasser/oonline
51973b5ffec0b60407b63b010d0e4e1622cf69b6
fd37ee6985f1de082cbc9f8625d1d9307e8801a6
refs/heads/master
2021-05-28T23:39:16.792763
2010-05-12T22:35:20
2010-05-12T22:35:20
null
0
0
null
null
null
null
ISO-8859-2
C++
false
false
10,891
h
/*********************************************************************** filename: d3d9renderer.h created: 17/7/2004 author: Paul D Turner with D3D 9 Updates by Magnus Österlind purpose: Interface for DirectX 9.0 Renderer class *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ /************************************************************************* This file contains code that is specific to Win32 and DirectX *************************************************************************/ #ifndef _d3d9renderer_h_ #define _d3d9renderer_h_ #include "../../CEGUIBase.h" #include "../../CEGUIRenderer.h" #include "../../CEGUITexture.h" #include <d3d9.h> #include <list> #include <set> #if !defined(CEGUI_STATIC) #ifdef DIRECTX9_GUIRENDERER_EXPORTS #define DIRECTX9_GUIRENDERER_API __declspec(dllexport) #else #define DIRECTX9_GUIRENDERER_API __declspec(dllimport) #endif #else #define DIRECTX9_GUIRENDERER_API #endif #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) #endif // Start of CEGUI namespace section namespace CEGUI { /************************************************************************* Forward refs *************************************************************************/ class DirectX9Texture; /*! \brief Renderer class to interface with Microsoft DirectX 9.0 */ class DIRECTX9_GUIRENDERER_API DirectX9Renderer : public Renderer { public: /*! \brief Constructor for Direct3D 9.0 Renderer object \param device Pointer to the IDirect3DDevice9 interface object that will be used for all rendering \param max_quads Obsolete. Set to 0. */ DirectX9Renderer(LPDIRECT3DDEVICE9 device, uint max_quads); /*! \brief Destructor for DirectX9Renderer objects */ virtual ~DirectX9Renderer(void); // add's a quad to the list to be rendered virtual void addQuad(const Rect& dest_rect, float z, const Texture* tex, const Rect& texture_rect, const ColourRect& colours, QuadSplitMode quad_split_mode); // perform final rendering for all queued renderable quads. virtual void doRender(void); // clear the queue virtual void clearRenderList(void); /*! \brief Enable or disable the queueing of quads from this point on. This only affects queueing. If queueing is turned off, any calls to addQuad will cause the quad to be rendered directly. Note that disabling queueing will not cause currently queued quads to be rendered, nor is the queue cleared - at any time the queue can still be drawn by calling doRender, and the list can be cleared by calling clearRenderList. Re-enabling the queue causes subsequent quads to be added as if queueing had never been disabled. \param setting true to enable queueing, or false to disable queueing (see notes above). \return Nothing */ virtual void setQueueingEnabled(bool setting) {d_queueing = setting;} // create an empty texture virtual Texture* createTexture(void); // create a texture and load it with the specified file. virtual Texture* createTexture(const String& filename, const String& resourceGroup); // create a texture and set it to the specified size virtual Texture* createTexture(float size); // destroy the given texture virtual void destroyTexture(Texture* texture); // destroy all textures still active virtual void destroyAllTextures(void); // return ptr to device LPDIRECT3DDEVICE9 getDevice(void) const {return d_device;} /*! \brief Return whether queueing is enabled. \return true if queueing is enabled, false if queueing is disabled. */ virtual bool isQueueingEnabled(void) const {return d_queueing;} /*! \brief Return the current width of the display in pixels \return float value equal to the current width of the display in pixels. */ virtual float getWidth(void) const {return d_display_area.getWidth();} /*! \brief Return the current height of the display in pixels \return float value equal to the current height of the display in pixels. */ virtual float getHeight(void) const {return d_display_area.getHeight();} /*! \brief Return the size of the display in pixels \return Size object describing the dimensions of the current display. */ virtual Size getSize(void) const {return d_display_area.getSize();} /*! \brief Return a Rect describing the screen \return A Rect object that describes the screen area. Typically, the top-left values are always 0, and the size of the area described is equal to the screen resolution. */ virtual Rect getRect(void) const {return d_display_area;} /*! \brief Return the maximum texture size available \return Size of the maximum supported texture in pixels (textures are always assumed to be square) */ virtual uint getMaxTextureSize(void) const {return d_maxTextureSize;} /*! \brief Return the horizontal display resolution dpi \return horizontal resolution of the display in dpi. */ virtual uint getHorzScreenDPI(void) const {return 96;} /*! \brief Return the vertical display resolution dpi \return vertical resolution of the display in dpi. */ virtual uint getVertScreenDPI(void) const {return 96;} /*! \brief Direct3D support method that must be called prior to a Reset call on the Direct3DDevice; this is required so that the GUI renderer can release any unmanaged D3D resources as needed for the device reset to succeed. */ virtual void preD3DReset(void); /*! \brief Direct3D support method that must be called after a Reset call on the Direct3DDevice; this is required so that the GUI renderer can rebuild any unmanaged D3D resources after the device has been reset. */ virtual void postD3DReset(void); /*! \brief Set the size of the display in pixels. You do not have to call this method under normal operation as the system will automatically extract the size from the current view port. \note This method will cause the EventDisplaySizeChanged event to fire if the display size has changed. \param sz Size object describing the size of the display. \return Nothing. */ void setDisplaySize(const Size& sz); private: /************************************************************************ Implementation Constants ************************************************************************/ static const int VERTEX_PER_QUAD; //!< number of vertices per quad static const int VERTEX_PER_TRIANGLE; //!< number of vertices for a triangle static const int VERTEXBUFFER_CAPACITY; //!< capacity of the allocated vertex buffer static const ulong VERTEX_FVF; //!< FVF specifier constant /************************************************************************* Implementation Structs & classes *************************************************************************/ /*! \brief FVF structure used for all vertices. */ struct QuadVertex { FLOAT x, y, z, rhw; //!< The transformed position for the vertex. DWORD diffuse; //!< colour of the vertex float tu1, tv1; //!< texture coordinates }; /*! \brief structure holding details about a quad to be drawn */ struct QuadInfo { LPDIRECT3DTEXTURE9 texture; Rect position; float z; Rect texPosition; ulong topLeftCol; ulong topRightCol; ulong bottomLeftCol; ulong bottomRightCol; QuadSplitMode splitMode; bool operator<(const QuadInfo& other) const { // this is intentionally reversed. return z > other.z; } }; /************************************************************************* Implementation Methods *************************************************************************/ // setup states etc void initPerFrameStates(void); // renders whatever is in the vertex buffer void renderVBuffer(void); // sort quads list according to texture void sortQuads(void); // render a quad directly to the display void renderQuadDirect(const Rect& dest_rect, float z, const Texture* tex, const Rect& texture_rect, const ColourRect& colours, QuadSplitMode quad_split_mode); // return size of device view port (if possible) Size getViewportSize(void); // method to do work of constructor void constructor_impl(LPDIRECT3DDEVICE9 device, const Size& display_size); /************************************************************************* Implementation Data *************************************************************************/ Rect d_display_area; typedef std::multiset<QuadInfo> QuadList; QuadList d_quadlist; bool d_queueing; //!< setting for queueing control. LPDIRECT3DDEVICE9 d_device; //!< Base Direct3DDevice9 interface that we use for rendering LPDIRECT3DTEXTURE9 d_currTexture; //!< currently set texture; LPDIRECT3DVERTEXBUFFER9 d_buffer; //!< vertex buffer to queue sprite rendering int d_bufferPos; //!< index into buffer where next vertex should be put. std::list<DirectX9Texture*> d_texturelist; //!< List used to track textures. uint d_maxTextureSize; //!< Holds maximum supported texture size (in pixels). }; } // End of CEGUI namespace section #if defined(_MSC_VER) # pragma warning(pop) #endif #endif // end of guard _d3d9renderer_h_
[ "masterfreek64@2644d07b-d655-0410-af38-4bee65694944" ]
[ [ [ 1, 353 ] ] ]
98bde86494c40f29e387e479336aff314bb3bd74
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Game/GameObject/GameObjectDiamondTree.h
5f22af7d427a8d00cc77dca5d7c7c876e9c91830
[]
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
6,251
h
#ifndef GameObjectDiamondTreeH_H #define GameObjectDiamondTreeH_H #include "GameObject.h" #include "../../Graphics/RenderComponent/RenderComponentEntity.h" #include "../../Graphics/RenderComponent/RenderComponentInitial.h" #include "../../Graphics/RenderComponent/RenderComponentPositional.h" #include "../../Physics/PhysicsComponent/PhysicsComponentSimpleBox.h" #include "../../Logic/LogicComponent/LogicComponentProp.h" namespace OUAN { //State names const std::string DT_STATE_IDLE="DT_STATE_IDLE"; const std::string DT_STATE_HIT="DT_STATE_HIT"; const std::string DT_STATE_MAY_HIT="DT_STATE_MAY_HIT"; const std::string DT_STATE_DEPLETED="DT_STATE_DEPLETED"; //Animation names const std::string DT_ANIM_IDLE="static_pose"; const std::string DT_ANIM_HIT="hit"; const double DT_ANIMATION_TIME=1; //Sounds const std::string DT_SOUND_TREE="tree"; const std::string DT_SOUND_DIAMOND="diamond"; /// Class to hold DiamondTree information class GameObjectDiamondTree : public GameObject, public boost::enable_shared_from_this<GameObjectDiamondTree> { private: /// Visual component RenderComponentEntityPtr mRenderComponentEntity; /// Position information RenderComponentInitialPtr mRenderComponentInitial; RenderComponentPositionalPtr mRenderComponentPositional; /// Particle Systems RenderComponentParticleSystemPtr mRenderComponentParticleSystemStars; /// Physics information PhysicsComponentSimpleBoxPtr mPhysicsComponentSimpleBox; /// Logic component: it'll represent the 'brains' of the game object /// containing information on its current state, its life and health(if applicable), /// or the world(s) the object belongs to LogicComponentPropPtr mLogicComponent; /// Length of the time period since Any hits the tree double mTotalHitTime; /// Audio component AudioComponentPtr mAudioComponent; public: //Constructor GameObjectDiamondTree(const std::string& name); //Destructor ~GameObjectDiamondTree(); /// Set logic component void setLogicComponent(LogicComponentPropPtr logicComponent); /// return logic component LogicComponentPropPtr getLogicComponent(); /// Set audio component /// @param pRenderComponentEntity AudioComponentPtr getAudioComponent() const; void setAudioComponent(AudioComponentPtr audioComponent); /// Return render component entity /// @return render component entity RenderComponentEntityPtr getRenderComponentEntity() const; /// Set render component /// @param pRenderComponentEntity void setRenderComponentEntity(RenderComponentEntityPtr pRenderComponentEntity); /// Set positional component /// @param pRenderComponentPositional the component containing the positional information void setRenderComponentPositional(RenderComponentPositionalPtr pRenderComponentPositional); /// Set initial component void setRenderComponentInitial(RenderComponentInitialPtr pRenderComponentInitial); /// Set Particle Systems void setRenderComponentParticleSystemStars(RenderComponentParticleSystemPtr mRenderComponentParticleSystemStars); /// Get Particle Systems RenderComponentParticleSystemPtr getRenderComponentParticleSystemStars() const; void setVisible(bool visible); /// Return positional component /// @return positional component RenderComponentPositionalPtr getRenderComponentPositional() const; /// Return initial component /// @return initial component RenderComponentInitialPtr getRenderComponentInitial() const; //PhysicsComponentSimpleBoxPtr getPhysicsComponentSimpleBox() const; //void setPhysicsComponentSimpleBox(PhysicsComponentSimpleBoxPtr physicsComponentSimpleBox); //PhysicsComponentVolumeBoxPtr getPhysicsComponentVolumeBox() const; //void setPhysicsComponentVolumeBox(PhysicsComponentVolumeBoxPtr physicsComponentVolumeBox); PhysicsComponentSimpleBoxPtr getPhysicsComponentSimpleBox() const; void setPhysicsComponentSimpleBox(PhysicsComponentSimpleBoxPtr physicsComponentSimpleBox); /// React to a world change to the one given as a parameter /// @param world world to change to void changeToWorld(int newWorld, double perc); void changeWorldFinished(int newWorld); void changeWorldStarted(int newWorld); void calculateChangeWorldTotalTime(double changeWorldTotalTime); void calculateChangeWorldDelay(double totalElapsedTime,double totalTime,int newWorld,double delay_factor,double intersection); /// Reset object virtual void reset(); bool hasPositionalComponent() const; RenderComponentPositionalPtr getPositionalComponent() const; bool hasPhysicsComponent() const; PhysicsComponentPtr getPhysicsComponent() const; void updatePhysicsComponents(double elapsedSeconds); bool hasRenderComponentEntity() const; RenderComponentEntityPtr getEntityComponent() const; /// Process collision event /// @param gameObject which has collision with void processCollision(GameObjectPtr pGameObject, Ogre::Vector3 pNormal); /// Process collision event /// @param gameObject which has collision with void processEnterTrigger(GameObjectPtr pGameObject); /// Process collision event /// @param gameObject which has collision with void processExitTrigger(GameObjectPtr pGameObject); void processAnimationEnded(const std::string& animationName); void update(double elapsedSeconds); bool hasLogicComponent() const; LogicComponentPtr getLogicComponent() const; }; class TGameObjectDiamondTreeParameters: public TGameObjectParameters { public: TGameObjectDiamondTreeParameters(); ~TGameObjectDiamondTreeParameters(); ///Parameters specific to an Ogre Entity TRenderComponentEntityParameters tRenderComponentEntityParameters; ///Positional parameters TRenderComponentPositionalParameters tRenderComponentPositionalParameters; ///Physics parameters TPhysicsComponentSimpleBoxParameters tPhysicsComponentSimpleBoxParameters; /// Audio component params TAudioComponentMap tAudioComponentParameters; ///Logic parameters TLogicComponentPropParameters tLogicComponentParameters; }; } #endif
[ "wyern1@1610d384-d83c-11de-a027-019ae363d039", "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039", "ithiliel@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 5 ], [ 7, 7 ], [ 11, 12 ], [ 23, 24 ], [ 26, 27 ], [ 29, 37 ], [ 39, 39 ], [ 42, 43 ], [ 45, 47 ], [ 50, 50 ], [ 52, 60 ], [ 62, 63 ], [ 65, 83 ], [ 93, 98 ], [ 109, 119 ], [ 125, 128 ], [ 134, 135 ], [ 137, 144 ], [ 151, 151 ], [ 153, 174 ], [ 176, 178 ] ], [ [ 6, 6 ], [ 10, 10 ], [ 38, 38 ], [ 40, 41 ], [ 84, 92 ], [ 99, 107 ], [ 120, 122 ], [ 136, 136 ] ], [ [ 8, 9 ], [ 13, 22 ], [ 25, 25 ], [ 28, 28 ], [ 44, 44 ], [ 48, 49 ], [ 51, 51 ], [ 61, 61 ], [ 64, 64 ], [ 108, 108 ], [ 123, 124 ], [ 129, 133 ], [ 145, 150 ], [ 152, 152 ], [ 175, 175 ] ] ]
32c341d1ec0c0607eb99e9ad2c70663e1be24bed
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/uavobjects/telemetrysettings.h
a649e73e79e0f2fdd6eb7a2fbe48e2d0b6fa0199
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,573
h
/** ****************************************************************************** * * @file telemetrysettings.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @see The GNU Public License (GPL) Version 3 * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup UAVObjectsPlugin UAVObjects Plugin * @{ * * @note Object definition file: telemetrysettings.xml. * This is an automatically generated file. * DO NOT modify manually. * * @brief The UAVUObjects GCS plugin *****************************************************************************/ /* * 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 3 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., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef TELEMETRYSETTINGS_H #define TELEMETRYSETTINGS_H #include "uavdataobject.h" #include "uavobjectmanager.h" class UAVOBJECTS_EXPORT TelemetrySettings: public UAVDataObject { Q_OBJECT public: // Field structure typedef struct { quint8 Speed; } __attribute__((packed)) DataFields; // Field information // Field Speed information /* Enumeration options for field Speed */ typedef enum { SPEED_9600=0, SPEED_38400=1, SPEED_57600=2, SPEED_115200=3 } SpeedOptions; // Constants static const quint32 OBJID = 2785592614U; static const QString NAME; static const bool ISSINGLEINST = 1; static const bool ISSETTINGS = 1; static const quint32 NUMBYTES = sizeof(DataFields); // Functions TelemetrySettings(); DataFields getData(); void setData(const DataFields& data); Metadata getDefaultMetadata(); UAVDataObject* clone(quint32 instID); static TelemetrySettings* GetInstance(UAVObjectManager* objMngr, quint32 instID = 0); private: DataFields data; void setDefaultFieldValues(); }; #endif // TELEMETRYSETTINGS_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 80 ] ] ]
9766f55c5201e7196468ec50af9a887eafa30802
82e8d2fca1858c076ea1593ed0364583356789dd
/atask/Factory.cpp
990a6043e0e06a247ff64b36c8bffbbfffc1f888
[]
no_license
slogic/E323AI
1ddbf179d1edaf49c460a2726f21794ceb39f141
dfd540283198b12b3d70907e279df33843c1ac99
refs/heads/master
2021-01-18T12:20:39.082252
2011-01-09T18:37:11
2011-01-09T18:37:11
489,916
0
0
null
null
null
null
UTF-8
C++
false
false
3,482
cpp
#include "Factory.h" #include "../CGroup.h" #include "../CWishList.h" #include "../CUnit.h" #include "../CUnitTable.h" #include "../CConfigParser.h" FactoryTask::FactoryTask(AIClasses *_ai, CGroup& group): ATask(_ai) { t = TASK_FACTORY; // NOTE: currently if factories are joined into one group then assisters // will assist the first factory only //factoryTask->pos = group.pos(); pos = group.firstUnit()->pos(); validateInterval = 10 * 30; addGroup(group); } bool FactoryTask::assistable(CGroup& assister) { CGroup *group = firstGroup(); if (!group->firstUnit()->def->canBeAssisted) return false; // there is no physical ability if ((assister.firstUnit()->type->cats&COMMANDER).any()) return true; // commander must stay at the base int maxAssisters; switch(ai->difficulty) { case DIFFICULTY_EASY: maxAssisters = FACTORY_ASSISTERS / 3; break; case DIFFICULTY_NORMAL: maxAssisters = FACTORY_ASSISTERS / 2; break; case DIFFICULTY_HARD: maxAssisters = FACTORY_ASSISTERS; break; } if (assisters.size() >= std::min(ai->cfgparser->getState() * 2, maxAssisters)) { if ((assister.cats&AIR).any()) { // try replacing existing assisters (except commander) with // aircraft assisters to free factory exit... std::list<ATask*>::iterator it; for (it = assisters.begin(); it != assisters.end(); ++it) { ATask *task = *it; if ((task->firstGroup()->cats&(AIR|COMMANDER)).none()) { task->remove(); return true; } } } return false; } return true; } bool FactoryTask::onValidate() { int numUnits = ai->cb->GetFriendlyUnits(&ai->unitIDs[0], pos, 16.0f); if (numUnits > 0) { int factoryID = firstGroup()->firstUnit()->key; for (int i = 0; i < numUnits; i++) { int uid = ai->unitIDs[i]; if (factoryID == uid) continue; if (!ai->cb->UnitBeingBuilt(uid)) { CUnit *unit = ai->unittable->getUnit(uid); if (unit) { if (unit->canPerformTasks()) // our unit stalled a factory return false; } else // some stupid allied unit stalled out factory return false; } } } return true; } void FactoryTask::onUpdate() { std::map<int, CUnit*>::iterator i; CGroup *group = firstGroup(); CUnit *factory; for(i = group->units.begin(); i != group->units.end(); ++i) { factory = i->second; if (ai->unittable->idle[factory->key] && !ai->wishlist->empty(factory->key)) { Wish w = ai->wishlist->top(factory->key); ai->wishlist->pop(factory->key); if (factory->factoryBuild(w.ut)) { ai->unittable->unitsBuilding[factory->key] = w; } } } } void FactoryTask::setWait(bool on) { std::map<int, CUnit*>::iterator itUnit; std::list<ATask*>::iterator itTask; CGroup *group = firstGroup(); CUnit *factory; for (itUnit = group->units.begin(); itUnit != group->units.end(); ++itUnit) { factory = itUnit->second; if(on) factory->wait(); else factory->unwait(); } for (itTask = assisters.begin(); itTask != assisters.end(); ++itTask) { if ((*itTask)->isMoving) continue; if(on) (*itTask)->firstGroup()->wait(); else (*itTask)->firstGroup()->unwait(); } } void FactoryTask::toStream(std::ostream& out) const { out << "FactoryTask(" << key << ") "; CGroup *group = firstGroup(); if (group) out << (*group); }
[ [ [ 1, 131 ] ] ]
2e086e0feed0122e957688f3e4cc6edfebae8afe
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/AffirmDeleteDlg.cpp
bb473f378c66155f7afb24eb706c5e6656bd393a
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
GB18030
C++
false
false
1,498
cpp
// AffirmDeleteDlg.cpp : 实现文件 // #include "stdafx.h" #include "emule.h" #include "AffirmDeleteDlg.h" #include ".\affirmdeletedlg.h" // CAffirmDeleteDlg 对话框 IMPLEMENT_DYNAMIC(CAffirmDeleteDlg, CDialog) CAffirmDeleteDlg::CAffirmDeleteDlg(CWnd* pParent /*=NULL*/) : CDialog(CAffirmDeleteDlg::IDD, pParent) { } CAffirmDeleteDlg::~CAffirmDeleteDlg() { } void CAffirmDeleteDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_CHECK1, IsChecked); } BEGIN_MESSAGE_MAP(CAffirmDeleteDlg, CDialog) ON_BN_CLICKED(IDOK, OnBnClickedOk) END_MESSAGE_MAP() // CAffirmDeleteDlg 消息处理程序 BOOL CAffirmDeleteDlg::OnInitDialog() { CDialog::OnInitDialog(); this->SetWindowText(GetResString(IDS_DELETE_FILE)); GetDlgItem(IDC_STATIC)->SetWindowText(GetResString(IDS_DELETE_TASK)); GetDlgItem(IDC_CHECK1)->SetWindowText(GetResString(IDS_DELETE_DISKFILE)); GetDlgItem(IDOK)->SetWindowText(GetResString(IDS_OK)); GetDlgItem(IDCANCEL)->SetWindowText(GetResString(IDS_CANCEL)); HICON hicon = ::LoadIcon(NULL, IDI_QUESTION); if(!hicon) return false; CStatic *pStatic = (CStatic *)GetDlgItem(IDC_IMAGE); if(pStatic) pStatic->SetIcon(hicon); return TRUE; } void CAffirmDeleteDlg::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 if(IsChecked.GetCheck() == 1) bIsDeleteFile = true; else bIsDeleteFile = false; OnOK(); }
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 59 ] ] ]
086c32abc8e7e1f94aff00841bd431cd547fa7a8
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/include/Ngl/IVideoPlayer.h
627d682281f11051325013583f41b3e7c9bb18ef
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,100
h
/*******************************************************************************/ /** * @file IVideoPlayer.h. * * @brief ビデオプレイヤーインターフェース定義. * * @date 2008/07/30. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _NGL_IVIDEOPLAYER_H_ #define _NGL_IVIDEOPLAYER_H_ namespace Ngl{ static const unsigned int VIDEO_VOLUME_MIN = 0; /**< ボリュームの最小値 */ static const unsigned int VIDEO_VOLUME_MAX = 100; /**< ボリュームの最大値 */ /** * @interface IVideoPlayer. * @brief ビデオプレイヤーインターフェース. */ class IVideoPlayer { public: /*=========================================================================*/ /** * @brief デストラクタ * * @param[in] なし. */ virtual ~IVideoPlayer() {} /*=========================================================================*/ /** * @brief ムービーの高さを取得 * * @param[in] なし. * @return ムービーの高さ. */ virtual int getImageHeight() const = 0; /*=========================================================================*/ /** * @brief ムービーの幅を取得 * * @param[in] なし. * @return ムービーの幅. */ virtual int getImageWidth() const = 0; /*=========================================================================*/ /** * @brief ムービーのイメージをロックする * * @param[in] なし. * @return ロックしたビデオメモリ. */ virtual void* lockImage() = 0; /*=========================================================================*/ /** * @brief ムービーのイメージをアンロックする * * @param[in] なし. * @return なし. */ virtual void unlockImage() = 0; /*=========================================================================*/ /** * @brief ムービーの再生 * * @param[in] なし. * @return なし. */ virtual void play() = 0; /*=========================================================================*/ /** * @brief ムービーの停止 * * @param[in] なし. * @return なし. */ virtual void stop() = 0; /*=========================================================================*/ /** * @brief 再生スピードの変更 * * @param[in] time 設定するスピード. * @return なし. */ virtual void setSpeed( float time ) = 0; /*=========================================================================*/ /** * @brief 現在の再生位置を指定位置にセット * * @param[in] time 設定する再生位置時間. * @return なし. */ virtual void setTime( float time ) = 0; /*=========================================================================*/ /** * @brief 再生終了時間を取得する * * @param[in] なし. * @return 終了時間. */ virtual float getStopTime() const = 0; /*=========================================================================*/ /** * @brief ストリームの時間幅の取得 * * @param[in] なし. * @return 時間幅. */ virtual float getDuration() const = 0; /*=========================================================================*/ /** * @brief 現在の再生位置の取得 * * @param[in] なし. * @return 現在の再生位置. */ virtual float getCurrentPosition() const = 0; /*=========================================================================*/ /** * @brief ボリュームの設定 * * 最大値 100( SOUND_VOLUME_MAX ) * 最小値 0 ( SOUND_VOLUME_MIN ) * * @param[in] volume 設定するボリューム. * @return なし. */ virtual void setVolume( unsigned int volume ) = 0; }; } // namespace Ngl #endif /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 170 ] ] ]
d68d828692ee95fb00f307200d6295b4d6190d2e
cbdc078b00041668dd740917e1e781f74b6ea9f4
/GiftFactory/src/model_obj.h
2c17dba928de04233b511dd59bebcf4696fc065d
[]
no_license
mireidril/gift-factory
f30d8075575af6a00a42d54bfdd4ad4c953f1936
4888b59b1ee25a107715742d0495e40b81752051
refs/heads/master
2020-04-13T07:19:09.351853
2011-12-16T11:36:05
2011-12-16T11:36:05
32,514,347
0
0
null
null
null
null
UTF-8
C++
false
false
7,841
h
//----------------------------------------------------------------------------- // Copyright (c) 2007 dhpoware. All Rights Reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #if !defined(MODEL_OBJ_H) #define MODEL_OBJ_H #include <cstdio> #include <iostream> #include <map> #include <string> #include <vector> #include "TextureManager.hpp" //----------------------------------------------------------------------------- // Alias|Wavefront OBJ file loader. // // This OBJ file loader contains the following restrictions: // 1. Group information is ignored. Faces are grouped based on the material // that each face uses. // 2. Object information is ignored. This loader will merge everything into a // single object. // 3. The MTL file must be located in the same directory as the OBJ file. If // it isn't then the MTL file will fail to load and a default material is // used instead. // 4. This loader triangulates all polygonal faces during importing. //----------------------------------------------------------------------------- class ModelOBJ { public: struct Material { float ambient[4]; float diffuse[4]; float specular[4]; float shininess; // [0 = min shininess, 1 = max shininess] float alpha; // [0 = fully transparent, 1 = fully opaque] std::string name; std::string colorMapFilename; std::string bumpMapFilename; std::string shaderName; std::vector<TextureManager::Texture*> textures; }; struct Vertex { float position[3]; float texCoord[2]; float normal[3]; float tangent[4]; float bitangent[3]; }; struct Mesh { int startIndex; int triangleCount; const Material *pMaterial; }; ModelOBJ(); ~ModelOBJ(); void destroy(); bool import(const char *pszFilename, bool rebuildNormals = false); void normalize(float scaleTo = 1.0f, bool center = true); void reverseWinding(); // Getter methods. void getCenter(float &x, float &y, float &z) const; float getWidth() const; float getHeight() const; float getLength() const; float getRadius() const; const int *getIndexBuffer() const; int getIndexSize() const; const Material &getMaterial(int i) const; const Mesh &getMesh(int i) const; int getNumberOfIndices() const; int getNumberOfMaterials() const; int getNumberOfMeshes() const; int getNumberOfTriangles() const; int getNumberOfVertices() const; const std::string &getPath() const; const Vertex &getVertex(int i) const; const Vertex *getVertexBuffer() const; int getVertexSize() const; bool hasNormals() const; bool hasPositions() const; bool hasTangents() const; bool hasTextureCoords() const; private: void addTrianglePos(int index, int material, int v0, int v1, int v2); void addTrianglePosNormal(int index, int material, int v0, int v1, int v2, int vn0, int vn1, int vn2); void addTrianglePosTexCoord(int index, int material, int v0, int v1, int v2, int vt0, int vt1, int vt2); void addTrianglePosTexCoordNormal(int index, int material, int v0, int v1, int v2, int vt0, int vt1, int vt2, int vn0, int vn1, int vn2); int addVertex(int hash, const Vertex *pVertex); void bounds(float center[3], float &width, float &height, float &length, float &radius) const; void buildMeshes(); void generateNormals(); void generateTangents(); void importGeometryFirstPass(FILE *pFile); void importGeometrySecondPass(FILE *pFile); bool importMaterials(const char *pszFilename); void scale(float scaleFactor, float offset[3]); bool m_hasPositions; bool m_hasTextureCoords; bool m_hasNormals; bool m_hasTangents; int m_numberOfVertexCoords; int m_numberOfTextureCoords; int m_numberOfNormals; int m_numberOfTriangles; int m_numberOfMaterials; int m_numberOfMeshes; float m_center[3]; float m_width; float m_height; float m_length; float m_radius; std::string m_directoryPath; std::vector<Mesh> m_meshes; std::vector<Material> m_materials; std::vector<Vertex> m_vertexBuffer; std::vector<int> m_indexBuffer; std::vector<int> m_attributeBuffer; std::vector<float> m_vertexCoords; std::vector<float> m_textureCoords; std::vector<float> m_normals; std::map<std::string, int> m_materialCache; std::map<int, std::vector<int> > m_vertexCache; }; //----------------------------------------------------------------------------- inline void ModelOBJ::getCenter(float &x, float &y, float &z) const { x = m_center[0]; y = m_center[1]; z = m_center[2]; } inline float ModelOBJ::getWidth() const { return m_width; } inline float ModelOBJ::getHeight() const { return m_height; } inline float ModelOBJ::getLength() const { return m_length; } inline float ModelOBJ::getRadius() const { return m_radius; } inline const int *ModelOBJ::getIndexBuffer() const { return &m_indexBuffer[0]; } inline int ModelOBJ::getIndexSize() const { return static_cast<int>(sizeof(int)); } inline const ModelOBJ::Material &ModelOBJ::getMaterial(int i) const { return m_materials[i]; } inline const ModelOBJ::Mesh &ModelOBJ::getMesh(int i) const { return m_meshes[i]; } inline int ModelOBJ::getNumberOfIndices() const { return m_numberOfTriangles * 3; } inline int ModelOBJ::getNumberOfMaterials() const { return m_numberOfMaterials; } inline int ModelOBJ::getNumberOfMeshes() const { return m_numberOfMeshes; } inline int ModelOBJ::getNumberOfTriangles() const { return m_numberOfTriangles; } inline int ModelOBJ::getNumberOfVertices() const { return static_cast<int>(m_vertexBuffer.size()); } inline const std::string &ModelOBJ::getPath() const { return m_directoryPath; } inline const ModelOBJ::Vertex &ModelOBJ::getVertex(int i) const { return m_vertexBuffer[i]; } inline const ModelOBJ::Vertex *ModelOBJ::getVertexBuffer() const { return &m_vertexBuffer[0]; } inline int ModelOBJ::getVertexSize() const { return static_cast<int>(sizeof(Vertex)); } inline bool ModelOBJ::hasNormals() const { return m_hasNormals; } inline bool ModelOBJ::hasPositions() const { return m_hasPositions; } inline bool ModelOBJ::hasTangents() const { return m_hasTangents; } inline bool ModelOBJ::hasTextureCoords() const { return m_hasTextureCoords; } #endif
[ "delau.eleonore@369dbe5e-add6-1733-379f-dc396ee97aaa" ]
[ [ [ 1, 245 ] ] ]
84ae05d62666393b0b2c5b2b750fbb8c17c5c8e2
8d3bc2c1c82dee5806c4503dd0fd32908c78a3a9
/wwscript/src/angelscript/as_compiler.h
aea2b83dcbdb3446c2fb62d842a8cb7a40fa92ff
[]
no_license
ryzom/werewolf2
2645d169381294788bab9a152c4071061063a152
a868205216973cf4d1c7d2a96f65f88360177b69
refs/heads/master
2020-03-22T20:08:32.123283
2010-03-05T21:43:32
2010-03-05T21:43:32
140,575,749
0
0
null
null
null
null
UTF-8
C++
false
false
12,618
h
/* AngelCode Scripting Library Copyright (c) 2003-2009 Andreas Jonsson 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. The original version of this library can be located at: http://www.angelcode.com/angelscript/ Andreas Jonsson [email protected] */ // // as_compiler.h // // The class that does the actual compilation of the functions // #ifndef AS_COMPILER_H #define AS_COMPILER_H #include "as_config.h" #include "as_builder.h" #include "as_scriptfunction.h" #include "as_variablescope.h" #include "as_bytecode.h" #include "as_array.h" #include "as_datatype.h" #include "as_typeinfo.h" BEGIN_AS_NAMESPACE struct asSExprContext; struct asSDeferredParam { asSDeferredParam() {argNode = 0; origExpr = 0;} asCScriptNode *argNode; asCTypeInfo argType; int argInOutFlags; asSExprContext *origExpr; }; struct asSExprContext { asSExprContext(asCScriptEngine *engine) : bc(engine) {exprNode = 0; origExpr = 0; property_get = 0; property_set = 0;} asCByteCode bc; asCTypeInfo type; int property_get; int property_set; bool property_const; // If the object that is being accessed through property accessor is read-only asCArray<asSDeferredParam> deferredParams; asCScriptNode *exprNode; asSExprContext *origExpr; }; enum EImplicitConv { asIC_IMPLICIT_CONV, asIC_EXPLICIT_REF_CAST, asIC_EXPLICIT_VAL_CAST }; class asCCompiler { public: asCCompiler(asCScriptEngine *engine); ~asCCompiler(); int CompileFunction(asCBuilder *builder, asCScriptCode *script, asCScriptNode *func, asCScriptFunction *outFunc); int CompileDefaultConstructor(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc); int CompileFactory(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc); int CompileTemplateFactoryStub(asCBuilder *builder, int trueFactoryId, asCObjectType *objType, asCScriptFunction *outFunc); int CompileGlobalVariable(asCBuilder *builder, asCScriptCode *script, asCScriptNode *expr, sGlobalVariableDescription *gvar); asCByteCode byteCode; asCArray<asCObjectType*> objVariableTypes; asCArray<int> objVariablePos; protected: friend class asCBuilder; void Reset(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc); // Statements void CompileStatementBlock(asCScriptNode *block, bool ownVariableScope, bool *hasReturn, asCByteCode *bc); void CompileDeclaration(asCScriptNode *decl, asCByteCode *bc); void CompileStatement(asCScriptNode *statement, bool *hasReturn, asCByteCode *bc); void CompileIfStatement(asCScriptNode *node, bool *hasReturn, asCByteCode *bc); void CompileSwitchStatement(asCScriptNode *node, bool *hasReturn, asCByteCode *bc); void CompileCase(asCScriptNode *node, asCByteCode *bc); void CompileForStatement(asCScriptNode *node, asCByteCode *bc); void CompileWhileStatement(asCScriptNode *node, asCByteCode *bc); void CompileDoWhileStatement(asCScriptNode *node, asCByteCode *bc); void CompileBreakStatement(asCScriptNode *node, asCByteCode *bc); void CompileContinueStatement(asCScriptNode *node, asCByteCode *bc); void CompileReturnStatement(asCScriptNode *node, asCByteCode *bc); void CompileExpressionStatement(asCScriptNode *node, asCByteCode *bc); // Expressions int CompileAssignment(asCScriptNode *expr, asSExprContext *out); int CompileCondition(asCScriptNode *expr, asSExprContext *out); int CompileExpression(asCScriptNode *expr, asSExprContext *out); int CompilePostFixExpression(asCArray<asCScriptNode *> *postfix, asSExprContext *out); int CompileExpressionTerm(asCScriptNode *node, asSExprContext *out); int CompileExpressionPreOp(asCScriptNode *node, asSExprContext *out); int CompileExpressionPostOp(asCScriptNode *node, asSExprContext *out); int CompileExpressionValue(asCScriptNode *node, asSExprContext *out); void CompileFunctionCall(asCScriptNode *node, asSExprContext *out, asCObjectType *objectType, bool objIsConst, const asCString &scope = ""); void CompileConstructCall(asCScriptNode *node, asSExprContext *out); void CompileConversion(asCScriptNode *node, asSExprContext *out); int CompileOperator(asCScriptNode *node, asSExprContext *l, asSExprContext *r, asSExprContext *out); void CompileOperatorOnHandles(asCScriptNode *node, asSExprContext *l, asSExprContext *r, asSExprContext *out); void CompileMathOperator(asCScriptNode *node, asSExprContext *l, asSExprContext *r, asSExprContext *out); void CompileBitwiseOperator(asCScriptNode *node, asSExprContext *l, asSExprContext *r, asSExprContext *out); void CompileComparisonOperator(asCScriptNode *node, asSExprContext *l, asSExprContext *r, asSExprContext *out); void CompileBooleanOperator(asCScriptNode *node, asSExprContext *l, asSExprContext *r, asSExprContext *out); bool CompileOverloadedDualOperator(asCScriptNode *node, asSExprContext *l, asSExprContext *r, asSExprContext *out); int CompileOverloadedDualOperator2(asCScriptNode *node, const char *methodName, asSExprContext *l, asSExprContext *r, asSExprContext *out, bool specificReturn = false, const asCDataType &returnType = asCDataType::CreatePrimitive(ttVoid, false)); void CompileInitList(asCTypeInfo *var, asCScriptNode *node, asCByteCode *bc); int CallDefaultConstructor(asCDataType &type, int offset, asCByteCode *bc, asCScriptNode *node, bool isGlobalVar = false); void CallDestructor(asCDataType &type, int offset, asCByteCode *bc); int CompileArgumentList(asCScriptNode *node, asCArray<asSExprContext *> &args); void MatchFunctions(asCArray<int> &funcs, asCArray<asSExprContext*> &args, asCScriptNode *node, const char *name, asCObjectType *objectType = NULL, bool isConstMethod = false, bool silent = false, bool allowObjectConstruct = true, const asCString &scope = ""); // Helper functions void ProcessPropertyGetAccessor(asSExprContext *ctx, asCScriptNode *node); int ProcessPropertySetAccessor(asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node); int FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asCScriptNode *node); void SwapPostFixOperands(asCArray<asCScriptNode *> &postfix, asCArray<asCScriptNode *> &target); void PrepareTemporaryObject(asCScriptNode *node, asSExprContext *ctx, asCArray<int> *reservedVars); void PrepareOperand(asSExprContext *ctx, asCScriptNode *node); void PrepareForAssignment(asCDataType *lvalue, asSExprContext *rvalue, asCScriptNode *node, asSExprContext *lvalueExpr = 0); void PerformAssignment(asCTypeInfo *lvalue, asCTypeInfo *rvalue, asCByteCode *bc, asCScriptNode *node); bool IsVariableInitialized(asCTypeInfo *type, asCScriptNode *node); void Dereference(asSExprContext *ctx, bool generateCode); bool CompileRefCast(asSExprContext *ctx, const asCDataType &to, bool isExplicit, asCScriptNode *node, bool generateCode = true); int MatchArgument(asCArray<int> &funcs, asCArray<int> &matches, const asCTypeInfo *argType, int paramNum, bool allowObjectConstruct = true); void PerformFunctionCall(int funcId, asSExprContext *out, bool isConstructor = false, asCArray<asSExprContext*> *args = 0, asCObjectType *objTypeForConstruct = 0, bool useVariable = false, int varOffset = 0); void MoveArgsToStack(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args, bool addOneToOffset); void MakeFunctionCall(asSExprContext *ctx, int funcId, asCObjectType *objectType, asCArray<asSExprContext*> &args, asCScriptNode *node, bool useVariable = false, int stackOffset = 0); void PrepareFunctionCall(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args); void AfterFunctionCall(int funcId, asCArray<asSExprContext*> &args, asSExprContext *ctx, bool deferAll); void ProcessDeferredParams(asSExprContext *ctx); void PrepareArgument(asCDataType *paramType, asSExprContext *ctx, asCScriptNode *node, bool isFunction = false, int refType = 0, asCArray<int> *reservedVars = 0); void PrepareArgument2(asSExprContext *ctx, asSExprContext *arg, asCDataType *paramType, bool isFunction = false, int refType = 0, asCArray<int> *reservedVars = 0); bool IsLValue(asCTypeInfo &type); int DoAssignment(asSExprContext *out, asSExprContext *lctx, asSExprContext *rctx, asCScriptNode *lexpr, asCScriptNode *rexpr, int op, asCScriptNode *opNode); void MergeExprContexts(asSExprContext *before, asSExprContext *after); void FilterConst(asCArray<int> &funcs); void ConvertToVariable(asSExprContext *ctx); void ConvertToVariableNotIn(asSExprContext *ctx, asSExprContext *exclude); void ConvertToVariableNotIn(asSExprContext *ctx, asCArray<int> *reservedVars); void ConvertToTempVariable(asSExprContext *ctx); void ConvertToTempVariableNotIn(asSExprContext *ctx, asSExprContext *exclude); void ConvertToTempVariableNotIn(asSExprContext *ctx, asCArray<int> *reservedVars); void ConvertToReference(asSExprContext *ctx); void PushVariableOnStack(asSExprContext *ctx, bool asReference); #ifdef AS_DEPRECATED // deprecated since 2009-07-20, 2.17.0 int TokenToBehaviour(int token); #endif asCString GetScopeFromNode(asCScriptNode *node); void ImplicitConversion(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode = true, asCArray<int> *reservedVars = 0, bool allowObjectConstruct = true); void ImplicitConvPrimitiveToPrimitive(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode = true, asCArray<int> *reservedVars = 0); void ImplicitConvObjectToPrimitive(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode = true, asCArray<int> *reservedVars = 0); void ImplicitConvPrimitiveToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode = true, asCArray<int> *reservedVars = 0, bool allowObjectConstruct = true); void ImplicitConvObjectToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode = true, asCArray<int> *reservedVars = 0, bool allowObjectConstruct = true); void ImplicitConversionConstant(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType); void LineInstr(asCByteCode *bc, size_t pos); asUINT ProcessStringConstant(asCString &str, asCScriptNode *node); void ProcessHeredocStringConstant(asCString &str); int GetPrecedence(asCScriptNode *op); void Error(const char *msg, asCScriptNode *node); void Warning(const char *msg, asCScriptNode *node); void PrintMatchingFuncs(asCArray<int> &funcs, asCScriptNode *node); void AddVariableScope(bool isBreakScope = false, bool isContinueScope = false); void RemoveVariableScope(); bool hasCompileErrors; int nextLabel; asCVariableScope *variables; asCBuilder *builder; asCScriptEngine *engine; asCScriptCode *script; asCScriptFunction *outFunc; bool m_isConstructor; bool m_isConstructorCalled; asCArray<int> breakLabels; asCArray<int> continueLabels; int AllocateVariable(const asCDataType &type, bool isTemporary); int AllocateVariableNotIn(const asCDataType &type, bool isTemporary, asCArray<int> *vars); int GetVariableOffset(int varIndex); int GetVariableSlot(int varOffset); void DeallocateVariable(int pos); void ReleaseTemporaryVariable(asCTypeInfo &t, asCByteCode *bc); void ReleaseTemporaryVariable(int offset, asCByteCode *bc); asCArray<asCDataType> variableAllocations; asCArray<bool> variableIsTemporary; asCArray<int> freeVariables; asCArray<int> tempVariables; bool globalExpression; bool isProcessingDeferredParams; int noCodeOutput; }; END_AS_NAMESPACE #endif
[ [ [ 1, 247 ] ] ]
590cc5aec993532e8cb228f02135857dd28dd762
1142a252973904e5ac5b8b0763af75e42095119b
/common/peb.cpp
63a8c59a5968d0b102e1b6e05014024e838f4c12
[]
no_license
somma/spinjector
19b57557aefc8556003c779179c76962b62e398a
c9b3634e79ff651b338d6bb718b0fcae2d772dc3
refs/heads/master
2021-01-01T18:17:56.005514
2009-04-20T08:31:13
2009-04-20T08:31:13
32,852,425
0
0
null
null
null
null
UHC
C++
false
false
6,803
cpp
/*----------------------------------------------------------------------------- * peb.cpp *----------------------------------------------------------------------------- * *----------------------------------------------------------------------------- * All rights reserved by somma ([email protected], [email protected]) **---------------------------------------------------------------------------*/ #include "stdafx.h" #include "peb.h" #include <crtdbg.h> //kd> dt _NT_TIB // +0x000 ExceptionList : Ptr32 _EXCEPTION_REGISTRATION_RECORD // +0x004 StackBase : Ptr32 Void // +0x008 StackLimit : Ptr32 Void // +0x00c SubSystemTib : Ptr32 Void // +0x010 FiberData : Ptr32 Void // +0x010 Version : Uint4B // +0x014 ArbitraryUserPointer : Ptr32 Void // +0x018 Self : Ptr32 _NT_TIB <<== #define XPSP2_NT_TIB_SELF_OFFSET 0x018 //kd> dt _TEB // +0x000 NtTib : _NT_TIB // +0x01c EnvironmentPointer : Ptr32 Void // +0x020 ClientId : _CLIENT_ID // +0x028 ActiveRpcHandle : Ptr32 Void // +0x02c ThreadLocalStoragePointer : Ptr32 Void // +0x030 ProcessEnvironmentBlock : Ptr32 _PEB <<== // +0x034 LastErrorValue : Uint4B // +0x038 CountOfOwnedCriticalSections : Uint4B //..... #define XPSP2_NT_TEB_PEB_OFFSET 0x030 //kd> dt _PEB // +0x000 InheritedAddressSpace : UChar // +0x001 ReadImageFileExecOptions : UChar // +0x002 BeingDebugged : UChar // +0x003 SpareBool : UChar // +0x004 Mutant : Ptr32 Void // +0x008 ImageBaseAddress : Ptr32 Void // +0x00c Ldr : Ptr32 _PEB_LDR_DATA <<== // +0x010 ProcessParameters : Ptr32 _RTL_USER_PROCESS_PARAMETERS // +0x014 SubSystemData : Ptr32 Void //..... #define XPSP2_PEB_LDR_OFFSET 0x00C /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ CPeb::CPeb() : m_init(FALSE), m_pPeb(NULL), m_pPebLdrData(NULL) { }; /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ CPeb::~CPeb() { if (TRUE == initialized()) terminate(); }; // ntdll.dll, kernel32.dll 등의 문자열을 미리 해쉬해 두고, Ldr 을 뒤져서 // Hash 값을 비교해서 모듈의 베이스 주소를 추출하려 했으나 Ldr 의 DllBaseName // 등의 UNICODE_STRING 을 변환하면서 문자열이 발견되기 더 쉽다. // // 따라서 해당 DllBaseName 의 특정 오프셋의 문자 몇개만 비교하는 방식을 사용한다. // ///** --------------------------------------------------------------------------- // \brief 문자열 해시를 구하는 함수 // this hash function is described in "The C Programming Language" // by Brian Kernighan and Donald Ritchie, Prentice Hall // // \param // \return // \code // \endcode //-----------------------------------------------------------------------------*/ //DWORD CPeb::HashBKDR(int buffer_length, const char *modname_buf) //{ // int i = 0; // DWORD ret = 0; // // if (0 >= buffer_length) // { // _ASSERTE(!"invalid buffer length"); // return 0; // } // if (TRUE == IsBadReadPtr(modname_buf, buffer_length)) // { // _ASSERTE(!"BadReadPtr()"); // return 0; // } // // // for (i = 0; i < buffer_length; i ++) // { // ret = (ret * 31) + modname_buf[i]; // } // return ret; //} /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ BOOL CPeb::init() { // _PEB 주소 계산 // PBYTE pPeb = NULL; __asm { mov eax, FS:XPSP2_NT_TIB_SELF_OFFSET // _NT_TIB.Self mov eax, dword ptr[eax + XPSP2_NT_TEB_PEB_OFFSET] // _TEB.ProcessEnvironmentBlock (_PEB) mov pPeb, eax } m_pPeb = pPeb; // // 잊지 말자 요 코드 만드는데 한 두시간 거렸다. -_-;; 아 ~ 띠바 // 오늘 더이상 코딩하지 말아야 겠다... // //DWORD_PTR ldr; //memmove(&ldr, m_pPeb + XPSP2_PEB_LDR_OFFSET, sizeof(DWORD_PTR)); // m_pPebLdrData = (PPEB_LDR_DATA)*(DWORD_PTR *)(m_pPeb + XPSP2_PEB_LDR_OFFSET ); m_init = TRUE; return TRUE; } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ BOOL CPeb::terminate() { m_init = FALSE; return TRUE; } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PBYTE CPeb::getPeb() { if (TRUE == initialized()) return m_pPeb; else { _ASSERTE(!"not initialized"); return NULL; } }; /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PPEB_LDR_DATA CPeb::getPebLdr() { if (TRUE == initialized()) return m_pPebLdrData; else { _ASSERTE(!"not initialized"); return NULL; } } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLIST_ENTRY CPeb::getmodule_by_loadorder() { if (TRUE != initialized()) { _ASSERTE(!"not initialized"); return NULL; } return &m_pPebLdrData->InLoadOrderModuleList; } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLIST_ENTRY CPeb::getmodule_by_memorder() { if (TRUE != initialized()) { _ASSERTE(!"not initialized"); return NULL; } return &m_pPebLdrData->InMemoryOrderModuleList; } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLIST_ENTRY CPeb::getmodule_by_initorder() { if (TRUE != initialized()) { _ASSERTE(!"not initialized"); return NULL; } return &m_pPebLdrData->InInitializationOrderModuleList; }
[ "fixBrain@71c39c02-2d83-11de-bfb9-e98281094dd5" ]
[ [ [ 1, 268 ] ] ]
5d01b708c7784175609710c9f78f3ec0e405e7f2
a36fcac2b8224325125203475fedea5e8ee8af7d
/KnihaJazd/AutoDlg.h
03a04588af212502b2de03aaee005fa5a49aab77
[]
no_license
mareqq/knihajazd
e000a04dbed8417e32f8a1ba3dce59e35892e3bb
e99958dd9bed7cfda6b7e8c50c86ea798c4e754e
refs/heads/master
2021-01-19T08:25:50.761893
2008-05-26T09:11:56
2008-05-26T09:11:56
32,898,594
0
0
null
null
null
null
UTF-8
C++
false
false
808
h
#pragma once #include "FirmaRecordset.h" #include "AutoRecordset.h" class CAutoDlg : public CDialog { DECLARE_DYNAMIC(CAutoDlg) public: CString m_Spz; CString m_Typ; double m_KmSadzba; double m_PriemernaSpotreba; long m_Rok; CAutoDlg(CWnd* pParent = NULL); virtual ~CAutoDlg(); enum { IDD = IDD_AUTODLG }; void SetParams(long idFirmy, long idAuta = 0); long GetIdAuta() { return m_IdAuta; } protected: virtual void DoDataExchange(CDataExchange* pDX); virtual BOOL OnInitDialog(); virtual void OnOK(); DECLARE_MESSAGE_MAP() CAutoRecordset m_rsAuto; long m_IdFirmy; //Id firmy, s ktorou pracujeme a v ktorej sa auto nachadza long m_IdAuta; // Id auta, s ktorym pracujeme. // Ak je 0, tak sa bude pridavat nove auto. };
[ "[email protected]@d4c424c1-354d-0410-9d05-3f146b4bb521" ]
[ [ [ 1, 37 ] ] ]
f3d030adca66d9b36153b9d0234601e751097eae
198faaa66e25fb612798ee7eecd1996f77f56cf8
/Console/DlgSettingsAppearance.h
8dbfaf7a800edfcd150f4ba1328d17b44b56c80d
[]
no_license
atsuoishimoto/console2-ime-old
bb83043d942d91b1835acefa94ce7e1f679a9e41
85e7909761fde64e4de3687e49b1e1457d1571dd
refs/heads/master
2021-01-17T17:21:35.221688
2011-05-27T04:06:14
2011-05-27T04:06:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,737
h
#pragma once #include "DlgSettingsBase.h" ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// class DlgSettingsAppearance : public DlgSettingsBase { public: DlgSettingsAppearance(CComPtr<IXMLDOMElement>& pOptionsRoot); BEGIN_DDX_MAP(DlgSettingsAppearance) DDX_TEXT(IDC_WINDOW_TITLE, m_strWindowTitle) DDX_CHECK(IDC_CHECK_USE_TAB_TITLE, m_nUseTabTitle) DDX_CHECK(IDC_CHECK_USE_CONSOLE_TITLE, m_nUseConsoleTitle) DDX_CHECK(IDC_CHECK_SHOW_COMMAND, m_nShowCommand) DDX_CHECK(IDC_CHECK_SHOW_COMMAND_TABS, m_nShowCommandTabs) DDX_CHECK(IDC_CHECK_TRIM_TAB_TITLES, m_nTrimTabTitles) DDX_UINT(IDC_TRIM_TAB_TITLES, m_windowSettings.dwTrimTabTitles) DDX_UINT(IDC_TRIM_TAB_TITLES_RIGHT, m_windowSettings.dwTrimTabTitlesRight) DDX_TEXT(IDC_WINDOW_ICON, m_strWindowIcon) DDX_CHECK(IDC_CHECK_USE_TAB_ICON, m_nUseTabIcon) DDX_TEXT(IDC_FONT, m_strFontName) DDX_UINT(IDC_FONT_SIZE, m_fontSettings.dwSize) DDX_CHECK(IDC_CHECK_BOLD, m_nFontBold) DDX_CHECK(IDC_CHECK_ITALIC, m_nFontItalic) DDX_CHECK(IDC_CHECK_USE_COLOR, m_nUseFontColor) DDX_CHECK(IDC_CHECK_POSITION, m_nUsePosition) DDX_INT(IDC_POS_X, m_nX) DDX_INT(IDC_POS_Y, m_nY) DDX_CHECK(IDC_CHECK_SAVE_POSITION, m_nSavePosition) DDX_CHECK(IDC_CHECK_SNAP, m_nSnapToEdges) DDX_INT(IDC_SNAP, m_positionSettings.nSnapDistance) END_DDX_MAP() BEGIN_MSG_MAP(DlgSettingsAppearance) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnCtlColorStatic) COMMAND_ID_HANDLER(IDOK, OnCloseCmd) COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) COMMAND_HANDLER(IDC_CHECK_USE_TAB_TITLE, BN_CLICKED, OnClickedCheckbox) COMMAND_HANDLER(IDC_CHECK_USE_TAB_ICON, BN_CLICKED, OnClickedCheckbox) COMMAND_HANDLER(IDC_BTN_BROWSE_ICON, BN_CLICKED, OnClickedBtnBrowseIcon) COMMAND_HANDLER(IDC_BTN_BROWSE_FONT, BN_CLICKED, OnClickedBtnBrowseFont) COMMAND_HANDLER(IDC_CHECK_USE_CONSOLE_TITLE, BN_CLICKED, OnClickedCheckbox) COMMAND_HANDLER(IDC_CHECK_TRIM_TAB_TITLES, BN_CLICKED, OnClickedCheckbox) COMMAND_HANDLER(IDC_CHECK_USE_COLOR, BN_CLICKED, OnClickedCheckbox) COMMAND_HANDLER(IDC_CHECK_POSITION, BN_CLICKED, OnClickedCheckbox) COMMAND_HANDLER(IDC_CHECK_SNAP, BN_CLICKED, OnClickedCheckbox) COMMAND_HANDLER(IDC_FONT_COLOR, BN_CLICKED, OnClickedFontColor) END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnCtlColorStatic(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnHScroll(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/); LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnClickedBtnBrowseIcon(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnClickedBtnBrowseFont(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnClickedCheckbox(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnClickedFontColor(WORD /*wNotifyCode*/, WORD /*wID*/, HWND hWndCtl, BOOL& /*bHandled*/); private: void EnableControls(); private: WindowSettings m_windowSettings; FontSettings m_fontSettings; PositionSettings m_positionSettings; CString m_strWindowTitle; int m_nUseTabTitle; int m_nUseConsoleTitle; int m_nShowCommand; int m_nShowCommandTabs; int m_nTrimTabTitles; CString m_strWindowIcon; int m_nUseTabIcon; CString m_strFontName; int m_nFontBold; int m_nFontItalic; int m_nUseFontColor; int m_nUsePosition; int m_nX; int m_nY; int m_nSavePosition; int m_nSnapToEdges; CComboBox m_comboFontSmoothing; CComboBox m_comboDocking; CComboBox m_comboZOrder; }; //////////////////////////////////////////////////////////////////////////////
[ [ [ 1, 114 ] ] ]
b466dea199fede6c6f49264468047f747e0e4e5e
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkDistanceRepresentation2D.h
bb41a8dd5afbae6901708a46431de414d6199221
[]
no_license
tack1/Casam
ad0a98febdb566c411adfe6983fcf63442b5eed5
3914de9d34c830d4a23a785768579bea80342f41
refs/heads/master
2020-04-06T03:45:40.734355
2009-06-10T14:54:07
2009-06-10T14:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,175
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkDistanceRepresentation2D.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkDistanceRepresentation2D - represent the vtkDistanceWidget // .SECTION Description // The vtkDistanceRepresentation2D is a representation for the // vtkDistanceWidget. This representation consists of a measuring line (axis) // and two vtkHandleWidgets to place the end points of the line. Note that // this particular widget draws its representation in the overlay plane. // .SECTION See Also // vtkDistanceWidget vtkDistanceRepresentation #ifndef __vtkDistanceRepresentation2D_h #define __vtkDistanceRepresentation2D_h #include "vtkDistanceRepresentation.h" class vtkAxisActor2D; class vtkProperty2D; class VTK_WIDGETS_EXPORT vtkDistanceRepresentation2D : public vtkDistanceRepresentation { public: // Description: // Instantiate class. static vtkDistanceRepresentation2D *New(); // Description: // Standard VTK methods. vtkTypeRevisionMacro(vtkDistanceRepresentation2D,vtkDistanceRepresentation); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Satisfy the superclasses API. virtual double GetDistance() {return this->Distance;} // Description: // Methods to Set/Get the coordinates of the two points defining // this representation. Note that methods are available for both // display and world coordinates. void GetPoint1WorldPosition(double pos[3]); void GetPoint2WorldPosition(double pos[3]); void SetPoint1DisplayPosition(double pos[3]); void SetPoint2DisplayPosition(double pos[3]); void GetPoint1DisplayPosition(double pos[3]); void GetPoint2DisplayPosition(double pos[3]); // Description: // Retrieve the vtkAxisActor2D used to draw the measurement axis. With this // properties can be set and so on. vtkAxisActor2D *GetAxis(); // Description: // Method to satisfy superclasses' API. virtual void BuildRepresentation(); // Description: // Methods required by vtkProp superclass. virtual void ReleaseGraphicsResources(vtkWindow *w); virtual int RenderOverlay(vtkViewport *viewport); virtual int RenderOpaqueGeometry(vtkViewport *viewport); protected: vtkDistanceRepresentation2D(); ~vtkDistanceRepresentation2D(); // Add a line to the mix vtkAxisActor2D *AxisActor; vtkProperty2D *AxisProperty; // The distance between the two points double Distance; private: vtkDistanceRepresentation2D(const vtkDistanceRepresentation2D&); //Not implemented void operator=(const vtkDistanceRepresentation2D&); //Not implemented }; #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 94 ] ] ]
99db831da6bfc7a94e1ffa5f59f3490f76e0b673
5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd
/EngineSource/dpslim/dpslim/Random/wnchyppr.cpp
c8fc541e964b4a17a78fd0f4230aadc0dcc46a9c
[]
no_license
karakots/dpresurrection
1a6f3fca00edd24455f1c8ae50764142bb4106e7
46725077006571cec1511f31d314ccd7f5a5eeef
refs/heads/master
2016-09-05T09:26:26.091623
2010-02-01T11:24:41
2010-02-01T11:24:41
32,189,181
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
75,762
cpp
/************************** WNCHYPPR.CPP ********************** 2002-10-20 AF * * * Calculation of univariate and multivariate Wallenius noncentral * hypergeometric probability distribution. * * This file contains source code for the class CWalleniusNCHypergeometric * and CMultiWalleniusNCHypergeometricMoments defined in stocc.h. * * Documentation: * ============== * The file stocc.h contains class definitions. * The file stocc.htm contains further instructions. * The file nchyp.pdf, available from www.agner.org/random/theory * describes the theory of the calculation methods. * *******************************************************************************/ #include <string.h> // memcpy function #include "stocc.h" // class definition #include "erfres.cpp" // table of error function residues (Don't precompile this as a header file) /*********************************************************************** constants ***********************************************************************/ static const double LN2 = 0.693147180559945309417; // log(2) /*********************************************************************** Log and Exp functions with special care for small x ***********************************************************************/ // These are functions that involve expressions of the types log(1+x) // and exp(x)-1. Use library functions log1p and expm1 if available, // otherwise, use Taylor expansions #if defined(__GNUC__) || defined (__INTEL_COMPILER) || defined(HAVE_EXPM1) // Functions log1p(x) = log(1+x) and expm1(x) = exp(x)-1 are available // in the math libraries of Gnu and Intel compilers // and in R.DLL (www.r-project.org). double pow2_1(double q, double * y0 = 0) { // calculate 2^q and (1-2^q) without loss of precision. // return value is (1-2^q). 2^q is returned in *y0 double y, y1; q *= LN2; if (fabs(q) > 0.1) { y = exp(q); // 2^q y1 = 1. - y; // 1-2^q } else { // Use expm1 y1 = expm1(q); // 2^q-1 y = y1 + 1; // 2^q y1 = -y1; // 1-2^q } if (y0) *y0 = y; // Return y if not void pointer return y1; // Return y1 } double log1mx(double x, double x1) { // Calculate log(1-x) without loss of precision when x is small. // Parameter x1 must be = 1-x. if (fabs(x) > 0.03) { return log(x1); } else { // use log1p(x) = log(1+x) return log1p(-x); } } double log1pow(double q, double x) { // calculate log((1-e^q)^x) without loss of precision. // Combines the methods of the above two functions. double y, y1; if (fabs(q) > 0.1) { y = exp(q); // e^q y1 = 1. - y; // 1-e^q } else { // Use expm1 y1 = expm1(q); // e^q-1 y = y1 + 1; // e^q y1 = -y1; // 1-e^q } if (y > 0.1) { // (1-y)^x calculated without problem return x * log(y1); } else { // Use log1p return x * log1p(-y); } } #else // (3) // Functions log1p and expm1 are not available in MS and Borland compiler // libraries. Use explicit Taylor expansion when needed. double pow2_1(double q, double * y0 = 0) { // calculate 2^q and (1-2^q) without loss of precision. // return value is (1-2^q). 2^q is returned in *y0 double y, y1, y2, qn, i, ifac; q *= LN2; if (fabs(q) > 0.1) { y = exp(q); y1 = 1. - y; } else { // expand 1-e^q = -summa(q^n/n!) to avoid loss of precision y1 = 0; qn = i = ifac = 1; do { y2 = y1; qn *= q; ifac *= i++; y1 -= qn / ifac; } while (y1 != y2); y = 1.-y1; } if (y0) *y0 = y; return y1; } double log1mx(double x, double x1) { // Calculate log(1-x) without loss of precision when x is small. // Parameter x1 must be = 1-x. if (fabs(x) > 0.03) { return log(x1); } else { // expand ln(1-x) = -summa(x^n/n) double y, z1, z2, i; y = i = 1.; z1 = 0; do { z2 = z1; y *= x; z1 -= y / i++; } while (z1 != z2); return z1; } } double log1pow(double q, double x) { // calculate log((1-e^q)^x) without loss of precision // Uses various Taylor expansions to avoid loss of precision double y, y1, y2, z1, z2, qn, i, ifac; if (fabs(q) > 0.1) { y = exp(q); y1 = 1. - y; } else { // expand 1-e^q = -summa(q^n/n!) to avoid loss of precision y1 = 0; qn = i = ifac = 1; do { y2 = y1; qn *= q; ifac *= i++; y1 -= qn / ifac; } while (y1 != y2); y = 1. - y1; } if (y > 0.1) { // (1-y)^x calculated without problem return x * log(y1); } else { // expand ln(1-y) = -summa(y^n/n) y1 = i = 1.; z1 = 0; do { z2 = z1; y1 *= y; z1 -= y1 / i++; } while (z1 != z2); return x * z1; } } #endif /*********************************************************************** Other shared functions ***********************************************************************/ double LnFacr(double x) { // log factorial of non-integer x int32 ix = (int32)(x); if (x == ix) return LnFac(ix); // x is integer double r, r2, D = 1., f; static const double C0 = 0.918938533204672722, // ln(sqrt(2*pi)) C1 = 1./12., C3 = -1./360., C5 = 1./1260., C7 = -1./1680.; if (x < 6.) { if (x == 0 || x == 1) return 0; while (x < 6) D *= ++x; } r = 1. / x; r2 = r*r; f = (x + 0.5)*log(x) - x + C0 + r*(C1 + r2*(C3 + r2*(C5 + r2*C7))); if (D != 1.) f -= log(D); return f; } double FallingFactorial(double a, double b) { // calculates ln(a*(a-1)*(a-2)* ... * (a-b+1)) if (b < 30 && int(b) == b && a < 1E10) { // direct calculation double f = 1.; for (int i = 0; i < b; i++) f *= a--; return log(f); } if (a > 100.*b && b > 1.) { // combine Stirling formulas for a and (a-b) to avoid loss of precision double ar = 1./a; double cr = 1./(a-b); // calculate -log(1-b/a) by Taylor expansion double s = 0., lasts, n = 1., ba = b*ar, f = ba; do { lasts = s; s += f/n; f *= ba; n++; } while (s != lasts); return (a+0.5)*s + b*log(a-b) - b + (1./12.)*(ar-cr) //- (1./360.)*(ar*ar*ar-cr*cr*cr) ; } // use LnFacr function return LnFacr(a)-LnFacr(a-b); } double Erf (double x) { // Calculates the error function erf(x) as a series expansion or // continued fraction expansion. // This function may be available in math libraries as erf(x) static const double rsqrtpi = 0.564189583547756286948; // 1/sqrt(pi) static const double rsqrtpi2 = 1.12837916709551257390; // 2/sqrt(pi) if (x < 0.) return -Erf(-x); if (x > 6.) return 1.; if (x < 2.4) { // use series expansion double term; // term in summation double j21; // 2j+1 double sum = 0; // summation double xx2 = x*x*2.; // 2x^2 int j; term = x; j21 = 1.; for (j=0; j<=50; j++) { // summation loop sum += term; if (term <= 1.E-13) break; j21 += 2.; term *= xx2 / j21; } return exp(-x*x) * sum * rsqrtpi2; } else { // use continued fraction expansion double a, f; int n = int(2.25f*x*x - 23.4f*x + 60.84f); // predict expansion degree if (n < 1) n = 1; a = 0.5 * n; f = x; for (; n > 0; n--) { // continued fraction loop f = x + a / f; a -= 0.5; } return 1. - exp(-x*x) * rsqrtpi / f; } } int32 FloorLog2(float x) { // This function calculates floor(log2(x)) for positive x. // The return value is <= -127 for x <= 0. #if defined(_M_IX86) || defined(__INTEL__) || defined(_M_X64) || defined(__IA64__) || defined(__POWERPC__) // Running on a platform known to use IEEE-754 floating point format int32 n = *(int32*)&x; return (n >> 23) - 0x7F; #else // Check if floating point format is IEEE-754 static const float one = 1.0f; if (*(int32*)&one == 0x3F800000) { // We have the standard IEEE floating point format int32 n = *(int32*)&x; return (n >> 23) - 0x7F; } else { // Unknown floating point format if (x <= 0.f) return -127; return (int32)floor(log(x)*(1./LN2)); } #endif } int NumSD (double accuracy) { // Gives the length of the integration interval necessary to achieve // the desired accuracy when integrating/summating a probability // function, relative to the standard deviation // Returns an integer approximation to 2*NormalDistrFractile(accuracy/2) static const double fract[] = { 2.699796e-03, 4.652582e-04, 6.334248e-05, 6.795346e-06, 5.733031e-07, 3.797912e-08, 1.973175e-09, 8.032001e-11, 2.559625e-12, 6.381783e-14}; int i; for (i = 0; i < (int)(sizeof(fract)/sizeof(*fract)); i++) { if (accuracy >= fract[i]) break; } return i + 6; } /*********************************************************************** Methods for class CWalleniusNCHypergeometric ***********************************************************************/ CWalleniusNCHypergeometric::CWalleniusNCHypergeometric(int32 n_, int32 m_, int32 N_, double odds_, double accuracy_) { // constructor accuracy = accuracy_; SetParameters(n_, m_, N_, odds_);} void CWalleniusNCHypergeometric::SetParameters(int32 n_, int32 m_, int32 N_, double odds) { // change parameters if (n_ < 0 || n_ > N_ || m_ < 0 || m_ > N_ || odds < 0) FatalError("Parameter out of range in CWalleniusNCHypergeometric"); n = n_; m = m_; N = N_; omega = odds; // set parameters xmin = m + n - N; if (xmin < 0) xmin = 0; // calculate xmin xmax = n; if (xmax > m) xmax = m; // calculate xmax xLastBico = xLastFindpars = -99; // indicate last x is invalid r = 1.; // initialize } double CWalleniusNCHypergeometric::mean(void) { // find approximate mean int iter; // number of iterations double a, b; // temporaries in calculation of first guess double mean, mean1; // iteration value of mean double m1r, m2r; // 1/m, 1/m2 double e1, e2; // temporaries double g; // function to find root of double gd; // derivative of g double omegar; // 1/omega if (omega == 1.) { // simple hypergeometric return double(m)*n/N; } // calculate Cornfield mean of Fisher noncentral hypergeometric distribution as first guess a = (m+n)*omega + (N-m-n); b = a*a - 4.*omega*(omega-1.)*m*n; b = b > 0. ? sqrt(b) : 0.; mean = (a-b)/(2.*(omega-1.)); if (mean < xmin) mean = xmin; if (mean > xmax) mean = xmax; m1r = 1./m; m2r = 1./(N-m); iter = 0; if (omega > 1.) { do { // Newton Raphson iteration mean1 = mean; e1 = 1.-(n-mean)*m2r; if (e1 < 1E-14) { e2 = 0.; // avoid underflow } else { e2 = pow(e1,omega-1.); } g = e2*e1 + (mean-m)*m1r; gd = e2*omega*m2r + m1r; mean -= g / gd; if (mean < xmin) mean = xmin; if (mean > xmax) mean = xmax; if (++iter > 40) { FatalError("Search for mean failed in function CWalleniusNCHypergeometric::mean"); } } while (fabs(mean1 - mean) > 2E-6); } else { // omega < 1 omegar = 1./omega; do { // Newton Raphson iteration mean1 = mean; e1 = 1.-mean*m1r; if (e1 < 1E-14) { e2 = 0.; // avoid underflow } else { e2 = pow(e1,omegar-1.); } g = 1.-(n-mean)*m2r-e2*e1; gd = e2*omegar*m1r + m2r; mean -= g / gd; if (mean < xmin) mean = xmin; if (mean > xmax) mean = xmax; if (++iter > 40) { FatalError("Search for mean failed in function CWalleniusNCHypergeometric::mean"); } } while (fabs(mean1 - mean) > 2E-6); } return mean; } double CWalleniusNCHypergeometric::variance(void) { // find approximate variance (poor approximation) double my = mean(); // approximate mean // find approximate variance from Fisher's noncentral hypergeometric approximation double r1 = my * (m-my); double r2 = (n-my)*(my+N-n-m); double var = N*r1*r2/((N-1)*(m*r2+(N-m)*r1)); if (var < 0.) var = 0.; return var; } double CWalleniusNCHypergeometric::moments(double * mean_, double * var_) { // calculate exact mean and variance // return value = sum of f(x), expected = 1. double y, sy=0, sxy=0, sxxy=0, me1; int32 x, xm, x1; const double accuracy = 1E-10f; // accuracy of calculation xm = (int32)mean(); // approximation to mean for (x=xm; x<=xmax; x++) { y = probability(x); x1 = x - xm; // subtract approximate mean to avoid loss of precision in sums sy += y; sxy += x1 * y; sxxy += x1 * x1 * y; if (y < accuracy) break; } for (x=xm-1; x>=xmin; x--) { y = probability(x); x1 = x - xm; // subtract approximate mean to avoid loss of precision in sums sy += y; sxy += x1 * y; sxxy += x1 * x1 * y; if (y < accuracy) break; } me1 = sxy / sy; *mean_ = me1 + xm; y = sxxy / sy - me1 * me1; if (y < 0) y=0; *var_ = y; return sy; } int32 CWalleniusNCHypergeometric::mode(void) { // find mode int32 Mode; // mode if (omega == 1.) { // simple hypergeometric int32 L = m + n - N; int32 m1 = m + 1, n1 = n + 1; Mode = int32((double)m1*n1*omega/((m1+n1)*omega-L)); } else { // find mode double f, f2 = 0.; int32 xi, x2; int32 xmin = m + n - N; if (xmin < 0) xmin = 0; // calculate xmin int32 xmax = n; if (xmax > m) xmax = m; // calculate xmax Mode = (int32)mean(); // floor(mean) if (omega < 1.) { if (Mode < xmax) Mode++; // ceil(mean) x2 = xmin; // lower limit if (omega > 0.294 && N <= 10000000) { x2 = Mode - 1;} // search for mode can be limited for (xi = Mode; xi >= x2; xi--) { f = probability(xi); if (f <= f2) break; Mode = xi; f2 = f; } } else { if (Mode < xmin) Mode++; x2 = xmax; // upper limit if (omega < 3.4 && N <= 10000000) { x2 = Mode + 1;} // search for mode can be limited for (xi = Mode; xi <= x2; xi++) { f = probability(xi); if (f <= f2) break; Mode = xi; f2 = f; } } } return Mode; } double CWalleniusNCHypergeometric::lnbico() { // natural log of binomial coefficients. // returns lambda = log(m!*x!/(m-x)!*m2!*x2!/(m2-x2)!) int32 x2 = n-x, m2 = N-m; if (xLastBico < 0) { // m, n, N have changed mFac = LnFac(m) + LnFac(m2); } if (m < FAK_LEN && m2 < FAK_LEN) goto DEFLT; switch (x - xLastBico) { case 0: // x unchanged break; case 1: // x incremented. calculate from previous value xFac += log (double(x) * (m2-x2) / (double(x2+1)*(m-x+1))); break; case -1: // x decremented. calculate from previous value xFac += log (double(x2) * (m-x) / (double(x+1)*(m2-x2+1))); break; default: DEFLT: // calculate all xFac = LnFac(x) + LnFac(x2) + LnFac(m-x) + LnFac(m2-x2); } xLastBico = x; return bico = mFac - xFac; } void CWalleniusNCHypergeometric::findpars() { // calculate d, E, r, w if (x == xLastFindpars) { return; // all values are unchanged since last call } // find r to center peak of integrand at 0.5 double dd, d1, z, zd, rr, lastr, rrc, rt, r2, r21, a, b, dummy; double oo[2]; double xx[2] = {x, n-x}; int i, j = 0; if (omega > 1.) { // make both omegas <= 1 to avoid overflow oo[0] = 1.; oo[1] = 1./omega; } else { oo[0] = omega; oo[1] = 1.; } dd = oo[0]*(m-x) + oo[1]*(N-m-xx[1]); d1 = 1./dd; E = (oo[0]*m + oo[1]*(N-m)) * d1; rr = r; if (rr <= d1) rr = 1.2*d1; // initial guess // Newton-Raphson iteration to find r do { lastr = rr; rrc = 1. / rr; z = dd - rrc; zd = rrc * rrc; for (i=0; i<2; i++) { rt = rr * oo[i]; if (rt < 100.) { // avoid overflow if rt big r21 = pow2_1(rt, &r2); // r2=2^r, r21=1.-2^r a = oo[i] / r21; // omegai/(1.-2^r) b = xx[i] * a; // x*omegai/(1.-2^r) z += b; zd += b * a * LN2 * r2; } } if (zd == 0) FatalError("can't find r in function CWalleniusNCHypergeometric::findpars"); rr -= z / zd; if (rr <= d1) rr = lastr * 0.125 + d1*0.875; if (++j == 70) FatalError("convergence problem searching for r in function CWalleniusNCHypergeometric::findpars"); } while (fabs(rr-lastr) > rr * 1.E-6); if (omega > 1) { dd *= omega; rr *= oo[1]; } r = rr; rd = rr * dd; // find peak width double ro, k1, k2; ro = r * omega; if (ro < 300) { // avoid overflow k1 = pow2_1(ro, &dummy); k1 = -1. / k1; k1 = omega*omega*(k1+k1*k1); } else k1 = 0.; if (r < 300) { // avoid overflow k2 = pow2_1(r, &dummy); k2 = -1. / k2; k2 = (k2+k2*k2); } else k2 = 0.; phi2d = -4.*r*r*(x*k1 + (n-x)*k2); if (phi2d >= 0.) { FatalError("peak width undefined in function CWalleniusNCHypergeometric::findpars"); /* wr = r = 0.; */ } else { wr = sqrt(-phi2d); w = 1./wr; } xLastFindpars = x; } int CWalleniusNCHypergeometric::BernouilliH(int32 x_, double h, double rh, StochasticLib1 *sto) { // This function generates a Bernouilli variate with probability proportional // to the univariate Wallenius' noncentral hypergeometric distribution. // The return value will be 1 with probability f(x_)/h and 0 with probability // 1-f(x_)/h. // This is equivalent to calling sto->Bernouilli(probability(x_)/h), // but this method is faster. The method used here avoids calculating the // Wallenius probability by sampling in the t-domain. // rh is a uniform random number in the interval 0 <= rh < h. The function // uses additional random numbers generated from sto. // This function is intended for use in rejection methods for sampling from // the Wallenius distribution. It is called from // StochasticLib3::WalleniusNCHypRatioOfUnifoms in the file stoc3.cpp double f0; // Lambda*Phi(½) double phideri0; // phi(½)/rd double qi; // 2^(-r*omega[i]) double qi1; // 1-qi double omegai[2] = {omega,1.}; // weights for each color double romegi; // r*omega[i] double xi[2] = {x_, n-x_}; // number of each color sampled double k; // adjusted width for majorizing function Ypsilon(t) double erfk; // erf correction double rdm1; // rd - 1 double G_integral; // integral of majorizing function Ypsilon(t) double ts; // t sampled from Ypsilon(t) distribution double logts; // log(ts) double rlogts; // r*log(ts) double fts; // Phi(ts)/rd double rgts; // 1/(Ypsilon(ts)/rd) double t2; // temporary in calculation of Ypsilon(ts) int i, j; // loop counters static const double rsqrt8 = 0.3535533905932737622; // 1/sqrt(8) static const double sqrt2pi = 2.506628274631000454; // sqrt(2*pi) x = x_; // save x in class object lnbico(); // calculate bico = log(Lambda) findpars(); // calculate r, d, rd, w, E if (E > 0.) { k = log(E); // correction for majorizing function k = 1. + 0.0271 * (k * sqrt(k)); } else k = 1.; k *= w; // w * k rdm1 = rd - 1.; // calculate phi(½)/rd phideri0 = -LN2 * rdm1; for (i=0; i<2; i++) { romegi = r * omegai[i]; if (romegi > 40.) { qi=0.; qi1 = 1.; // avoid underflow } else { qi1 = pow2_1(-romegi, &qi); } phideri0 += xi[i] * log1mx(qi, qi1); } erfk = Erf(rsqrt8 / k); f0 = rd * exp(phideri0 + bico); G_integral = f0 * sqrt2pi * k * erfk; if (G_integral <= h) { // G fits under h-hat do { ts = sto->Normal(0,k); // sample ts from normal distribution } while (fabs(ts) >= 0.5); // reject values outside interval, and avoid ts = 0 ts += 0.5; // ts = normal distributed in interval (0,1) for (fts=0., j=0; j<2; j++) { // calculate (Phi(ts)+Phi(1-ts))/2 logts = log(ts); rlogts = r * logts; // (ts = 0 avoided above) fts += exp(log1pow(rlogts*omega,xi[0]) + log1pow(rlogts,xi[1]) + rdm1*logts + bico); ts = 1. - ts; } fts *= 0.5; t2 = (ts-0.5) / k; // calculate 1/Ypsilon(ts) rgts = exp(-(phideri0 + bico - 0.5 * t2*t2)); return rh < G_integral * fts * rgts; // Bernouilli variate } else { // G > h: can't use sampling in t-domain return rh < probability(x); } } /*********************************************************************** methods for calculating probability in class CWalleniusNCHypergeometric ***********************************************************************/ double CWalleniusNCHypergeometric::recursive() { // recursive calculation // Wallenius noncentral hypergeometric distribution by recursion formula // Approximate by ignoring probabilities < accuracy and minimize storage requirement const int BUFSIZE = 512; // buffer size double p[BUFSIZE+2]; // probabilities double * p1, * p2; // offset into p double mxo; // (m-x)*omega double Nmnx; // N-m-nu+x double y, y1; // save old p[x] before it is overwritten double d1, d2, dcom; // divisors in probability formula double accuracya; // absolute accuracy int32 xi, nu; // xi, nu = recursion values of x, n int32 x1, x2; // xi_min, xi_max accuracya = 0.005f * accuracy; // absolute accuracy p1 = p2 = p + 1; // make space for p1[-1] p1[-1] = 0.; p1[0] = 1.; // initialize for recursion x1 = x2 = 0; for (nu=1; nu<=n; nu++) { if (n - nu < x - x1 || p1[x1] < accuracya) { x1++; // increase lower limit when breakpoint passed or probability negligible p2--; // compensate buffer offset in order to reduce storage space } if (x2 < x && p1[x2] >= accuracya) { x2++; y1 = 0.; // increase upper limit until x has been reached } else { y1 = p1[x2]; } if (x1 > x2) return 0.; if (p2+x2-p > BUFSIZE) FatalError("buffer overrun in function CWalleniusNCHypergeometric::recursive"); mxo = (m-x2)*omega; Nmnx = N-m-nu+x2+1; for (xi = x2; xi >= x1; xi--) { // backwards loop d2 = mxo + Nmnx; mxo += omega; Nmnx--; d1 = mxo + Nmnx; dcom = 1. / (d1 * d2); // save a division by making common divisor y = p1[xi-1]*mxo*d2*dcom + y1*(Nmnx+1)*d1*dcom; y1 = p1[xi-1]; // (warning: pointer alias, can't swap instruction order) p2[xi] = y; } p1 = p2; } if (x < x1 || x > x2) return 0.; return p1[x]; } double CWalleniusNCHypergeometric::binoexpand() { // calculate by binomial expansion of integrand // only for x < 2 or n-x < 2 (not implemented for higher x because of loss of precision) int32 x1, m1, m2; double o; if (x > n/2) { // invert x1 = n-x; m1 = N-m; m2 = m; o = 1./omega; } else { x1 = x; m1 = m; m2 = N-m; o = omega; } if (x1 == 0) { return exp(FallingFactorial(m2,n) - FallingFactorial(m2+o*m1,n)); } if (x1 == 1) { double d, e, q, q0, q1; q = FallingFactorial(m2,n-1); e = o*m1+m2; q1 = q - FallingFactorial(e,n); e -= o; q0 = q - FallingFactorial(e,n); d = e - (n-1); return m1*d*(exp(q0) - exp(q1)); } FatalError("x > 1 not supported by function CWalleniusNCHypergeometric::binoexpand"); return 0; } double CWalleniusNCHypergeometric::laplace() { // Laplace's method with narrow integration interval, // using error function residues table, defined in erfres.cpp // Note that this function can only be used when the integrand peak is narrow. // findpars() must be called before this function. const int COLORS = 2; // number of colors const int MAXDEG = 40; // arraysize, maximum expansion degree int degree; // max expansion degree double accur; // stop expansion when terms below this threshold double omegai[COLORS] = {omega, 1.}; // weights for each color double xi[COLORS] = {x, n-x}; // number of each color sampled double f0; // factor outside integral double rho[COLORS]; // r*omegai double qi; // 2^(-rho) double qi1; // 1-qi double qq[COLORS]; // qi / qi1 double eta[COLORS+1][MAXDEG+1]; // eta coefficients double phideri[MAXDEG+1]; // derivatives of phi double PSIderi[MAXDEG+1]; // derivatives of PSI double * erfresp; // pointer to table of error function residues // variables in asymptotic summation static const double sqrt8 = 2.828427124746190098; // sqrt(8) double qqpow; // qq^j double pow2k; // 2^k double bino; // binomial coefficient double vr; // 1/v, v = integration interval double v2m2; // (2*v)^(-2) double v2mk1; // (2*v)^(-k-1) double s; // summation term double sum; // Taylor sum int i; // loop counter for color int j; // loop counter for derivative int k; // loop counter for expansion degree int ll; // k/2 int converg = 0; // number of consequtive terms below accuracy int PrecisionIndex; // index into ErfRes table according to desired precision // initialize for (k = 0; k <= 2; k++) phideri[k] = PSIderi[k] = 0; // find rho[i], qq[i], first eta coefficients, and zero'th derivative of phi for (i = 0; i < COLORS; i++) { rho[i] = r * omegai[i]; if (rho[i] > 40.) { qi=0.; qi1 = 1.;} // avoid underflow else { qi1 = pow2_1(-rho[i], &qi);} // qi=2^(-rho), qi1=1.-2^(-rho) qq[i] = qi / qi1; // 2^(-r*omegai)/(1.-2^(-r*omegai)) // peak = zero'th derivative phideri[0] += xi[i] * log1mx(qi, qi1); // eta coefficients eta[i][0] = 0.; eta[i][1] = eta[i][2] = rho[i]*rho[i]; } // r, rd, and w must be calculated by findpars() // zero'th derivative phideri[0] -= (rd - 1.) * LN2; // scaled factor outside integral f0 = rd * exp(phideri[0] + lnbico()); vr = sqrt8 * w; phideri[2] = phi2d; // get table according to desired precision PrecisionIndex = (-FloorLog2((float)accuracy) - ERFRES_B + ERFRES_S - 1) / ERFRES_S; if (PrecisionIndex < 0) PrecisionIndex = 0; if (PrecisionIndex > ERFRES_N-1) PrecisionIndex = ERFRES_N-1; while (w * NumSDev[PrecisionIndex] > 0.3) { // check if integration interval is too wide if (PrecisionIndex == 0) { FatalError("Laplace method failed. Peak width too high in function CWalleniusNCHypergeometric::laplace"); break;} PrecisionIndex--; // reduce precision to keep integration interval narrow } erfresp = ErfRes[PrecisionIndex]; // choose desired table degree = MAXDEG; // max expansion degree if (degree >= ERFRES_L*2) degree = ERFRES_L*2-2; // set up for starting loop at k=3 v2m2 = 0.25 * vr * vr; // (2*v)^(-2) PSIderi[0] = 1.; pow2k = 8.; sum = 0.5 * vr * erfresp[0]; v2mk1 = 0.5 * vr * v2m2 * v2m2; accur = accuracy * sum; // summation loop for (k = 3; k <= degree; k++) { phideri[k] = 0.; // loop for all (2) colors for (i = 0; i < COLORS; i++) { eta[i][k] = 0.; // backward loop for all powers for (j = k; j > 0; j--) { // find coefficients recursively from previous coefficients eta[i][j] = eta[i][j]*(j*rho[i]-(k-2)) + eta[i][j-1]*rho[i]*(j-1); } qqpow = 1.; // forward loop for all powers for (j=1; j<=k; j++) { qqpow *= qq[i]; // qq^j // contribution to derivative phideri[k] += xi[i] * eta[i][j] * qqpow; } } // finish calculation of derivatives phideri[k] = -pow2k*phideri[k] + 2*(1-k)*phideri[k-1]; pow2k *= 2.; // 2^k // loop to calculate derivatives of PSI from derivatives of psi. // terms # 0, 1, 2, k-2, and k-1 are zero and not included in loop. // The j'th derivatives of psi are identical to the derivatives of phi for j>2, and // zero for j=1,2. Hence we are using phideri[j] for j>2 here. PSIderi[k] = phideri[k]; // this is term # k bino = 0.5 * (k-1) * (k-2); // binomial coefficient for term # 3 for (j = 3; j < k-2; j++) { // loop for remaining nonzero terms (if k>5) PSIderi[k] += PSIderi[k-j] * phideri[j] * bino; bino *= double(k-j)/double(j); } if ((k & 1) == 0) { // only for even k ll = k/2; s = PSIderi[k] * v2mk1 * erfresp[ll]; sum += s; // check for convergence of Taylor expansion if (fabs(s) < accur) converg++; else converg = 0; if (converg > 1) break; // update recursive expressions v2mk1 *= v2m2; } } // multiply by terms outside integral return f0 * sum; } double CWalleniusNCHypergeometric::integrate() { // Wallenius non-central hypergeometric distribution function // calculation by numerical integration with variable-length steps // NOTE: findpars() must be called before this function. double s; // result of integration step double sum; // integral double ta, tb; // subinterval for integration step lnbico(); // compute log of binomial coefficients // choose method: if (w < 0.02 || w < 0.1 && (x==m || n-x==N-m) && accuracy > 1E-6) { // normal method. Step length determined by peak width w double delta, s1; s1 = accuracy < 1E-9 ? 0.5 : 1.; delta = s1 * w; // integration steplength ta = 0.5 + 0.5 * delta; sum = integrate_step(1.-ta, ta); // first integration step around center peak do { tb = ta + delta; if (tb > 1.) tb = 1.; s = integrate_step(ta, tb); // integration step to the right of peak s += integrate_step(1.-tb,1.-ta);// integration step to the left of peak sum += s; if (s < accuracy * sum) break; // stop before interval finished if accuracy reached ta = tb; if (tb > 0.5 + w) delta *= 2.; // increase step length far from peak } while (tb < 1.); } else { // difficult situation. Step length determined by inflection points double t1, t2, tinf, delta, delta1; sum = 0.; // do left and right half of integration interval separately: for (t1=0., t2=0.5; t1 < 1.; t1+=0.5, t2+=0.5) { // integrate from 0 to 0.5 or from 0.5 to 1 tinf = search_inflect(t1, t2); // find inflection point delta = tinf - t1; if (delta > t2 - tinf) delta = t2 - tinf; // distance to nearest endpoint delta *= 1./7.; // 1/7 will give 3 steps to nearest endpoint if (delta < 1E-4) delta = 1E-4; delta1 = delta; // integrate from tinf forwards to t2 ta = tinf; do { tb = ta + delta1; if (tb > t2 - 0.25*delta1) tb = t2; // last step of this subinterval s = integrate_step(ta, tb); // integration step sum += s; delta1 *= 2; // double steplength if (s < sum * 1E-4) delta1 *= 8.; // large step when s small ta = tb; } while (tb < t2); if (tinf) { // integrate from tinf backwards to t1 tb = tinf; do { ta = tb - delta; if (ta < t1 + 0.25*delta) ta = t1; // last step of this subinterval s = integrate_step(ta, tb); // integration step sum += s; delta *= 2; // double steplength if (s < sum * 1E-4) delta *= 8.; // large step when s small tb = ta;} while (ta > t1); } } } return sum * rd; } double CWalleniusNCHypergeometric::integrate_step(double ta, double tb) { // integration subprocedure used by integrate() // makes one integration step from ta to tb using Gauss-Legendre method. // result is scaled by multiplication with exp(bico) double ab, delta, tau, ltau, y, sum, taur, rdm1; int i; // define constants for Gauss-Legendre integration with IPOINTS points #define IPOINTS 8 // number of points in each integration step #if IPOINTS == 3 static const double xval[3] = {-.774596669241,0,0.774596668241}; static const double weights[3] = {.5555555555555555,.88888888888888888,.55555555555555}; #elif IPOINTS == 4 static const double xval[4] = {-0.861136311594,-0.339981043585,0.339981043585,0.861136311594}, static const double weights[4] = {0.347854845137,0.652145154863,0.652145154863,0.347854845137}; #elif IPOINTS == 5 static const double xval[5] = {-0.906179845939,-0.538469310106,0,0.538469310106,0.906179845939}; static const double weights[5] = {0.236926885056,0.478628670499,0.568888888889,0.478628670499,0.236926885056}; #elif IPOINTS == 6 static const double xval[6] = {-0.932469514203,-0.661209386466,-0.238619186083,0.238619186083,0.661209386466,0.932469514203}; static const double weights[6] = {0.171324492379,0.360761573048,0.467913934573,0.467913934573,0.360761573048,0.171324492379}; #elif IPOINTS == 8 static const double xval[8] = {-0.960289856498,-0.796666477414,-0.525532409916,-0.183434642496,0.183434642496,0.525532409916,0.796666477414,0.960289856498}; static const double weights[8] = {0.10122853629,0.222381034453,0.313706645878,0.362683783378,0.362683783378,0.313706645878,0.222381034453,0.10122853629}; #elif IPOINTS == 12 static const double xval[12] = {-0.981560634247,-0.90411725637,-0.769902674194,-0.587317954287,-0.367831498998,-0.125233408511,0.125233408511,0.367831498998,0.587317954287,0.769902674194,0.90411725637,0.981560634247}; static const double weights[12]= {0.0471753363866,0.106939325995,0.160078328543,0.203167426723,0.233492536538,0.249147045813,0.249147045813,0.233492536538,0.203167426723,0.160078328543,0.106939325995,0.0471753363866}; #elif IPOINTS == 16 static const double xval[16] = {-0.989400934992,-0.944575023073,-0.865631202388,-0.755404408355,-0.617876244403,-0.458016777657,-0.281603550779,-0.0950125098376,0.0950125098376,0.281603550779,0.458016777657,0.617876244403,0.755404408355,0.865631202388,0.944575023073,0.989400934992}; static const double weights[16]= {0.027152459411,0.0622535239372,0.0951585116838,0.124628971256,0.149595988817,0.169156519395,0.182603415045,0.189450610455,0.189450610455,0.182603415045,0.169156519395,0.149595988817,0.124628971256,0.0951585116838,0.0622535239372,0.027152459411}; #else #error // IPOINTS must be a value for which the tables are defined #endif delta = 0.5 * (tb - ta); ab = 0.5 * (ta + tb); rdm1 = rd - 1.; sum = 0; for (i = 0; i < IPOINTS; i++) { tau = ab + delta * xval[i]; ltau = log(tau); taur = r * ltau; // possible loss of precision due to subtraction here: y = log1pow(taur*omega,x) + log1pow(taur,n-x) + rdm1*ltau + bico; if (y > -50.) sum += weights[i] * exp(y); } return delta * sum; } double CWalleniusNCHypergeometric::search_inflect(double t_from, double t_to) { // search for an inflection point of the integrand PHI(t) in the interval // t_from < t < t_to const int COLORS = 2; // number of colors double t, t1; // independent variable double rho[COLORS]; // r*omega[i] double q; // t^rho[i] / (1-t^rho[i]) double q1; // 1-t^rho[i] double xx[COLORS]; // x[i] double zeta[COLORS][4][4]; // zeta[i,j,k] coefficients double phi[4]; // derivatives of phi(t) = log PHI(t) double Z2; // PHI''(t)/PHI(t) double Zd; // derivative in Newton Raphson iteration double rdm1; // r * d - 1 double tr; // 1/t double log2t; // log2(t) double method; // 0 for z2'(t) method, 1 for z3(t) method int i; // color int iter; // count iterations rdm1 = rd - 1.; if (t_from == 0 && rdm1 <= 1.) return 0.; //no inflection point rho[0] = r*omega; rho[1] = r; xx[0] = x; xx[1] = n - x; t = 0.5 * (t_from + t_to); for (i = 0; i < COLORS; i++) { // calculate zeta coefficients zeta[i][1][1] = rho[i]; zeta[i][1][2] = rho[i] * (rho[i] - 1.); zeta[i][2][2] = rho[i] * rho[i]; zeta[i][1][3] = zeta[i][1][2] * (rho[i] - 2.); zeta[i][2][3] = zeta[i][1][2] * rho[i] * 3.; zeta[i][3][3] = zeta[i][2][2] * rho[i] * 2.; } iter = 0; do { t1 = t; tr = 1. / t; log2t = log(t)*(1./LN2); phi[1] = phi[2] = phi[3] = 0.; for (i=0; i<COLORS; i++) { // calculate first 3 derivatives of phi(t) q1 = pow2_1(rho[i]*log2t,&q); q /= q1; phi[1] -= xx[i] * zeta[i][1][1] * q; phi[2] -= xx[i] * q * (zeta[i][1][2] + q * zeta[i][2][2]); phi[3] -= xx[i] * q * (zeta[i][1][3] + q * (zeta[i][2][3] + q * zeta[i][3][3])); } phi[1] += rdm1; phi[2] -= rdm1; phi[3] += 2. * rdm1; phi[1] *= tr; phi[2] *= tr * tr; phi[3] *= tr * tr * tr; method = (iter & 2) >> 1; // alternate between the two methods Z2 = phi[1]*phi[1] + phi[2]; Zd = method*phi[1]*phi[1]*phi[1] + (2.+method)*phi[1]*phi[2] + phi[3]; if (t < 0.5) { if (Z2 > 0) { t_from = t; } else { t_to = t; } if (Zd >= 0) { // use binary search if Newton-Raphson iteration makes problems t = (t_from ? 0.5 : 0.2) * (t_from + t_to); } else { // Newton-Raphson iteration t -= Z2 / Zd; } } else { if (Z2 < 0) { t_from = t; } else { t_to = t; } if (Zd <= 0) { // use binary search if Newton-Raphson iteration makes problems t = 0.5 * (t_from + t_to); } else { // Newton-Raphson iteration t -= Z2 / Zd; } } if (t >= t_to) t = (t1 + t_to) * 0.5; if (t <= t_from) t = (t1 + t_from) * 0.5; if (++iter > 20) FatalError("Search for inflection point failed in function CWalleniusNCHypergeometric::search_inflect"); } while (fabs(t - t1) > 1E-5); return t; } double CWalleniusNCHypergeometric::probability(int32 x_) { // calculate probability function. choosing best method x = x_; if (x < xmin || x > xmax) return 0.; if (xmin == xmax) return 1.; if (omega == 1.) { // hypergeometric return exp(lnbico() + LnFac(n) + LnFac(N-n) - LnFac(N)); } int32 x2 = n - x; int32 x0 = x < x2 ? x : x2; int em = (x == m || x2 == N-m); if (x0 == 0 && n > 500) { return binoexpand(); } if (double(n)*x0 < 1000 || double(n)*x0 < 10000 && (N > 1000.*n || em)) { return recursive(); } if (x0 <= 1 && N-n <= 1) { return binoexpand(); } findpars(); if (w < 0.04 && E < 10 && (!em || w > 0.004)) { return laplace(); } return integrate(); } int32 CWalleniusNCHypergeometric::MakeTable(double * table, int32 MaxLength, int32 * xfirst, int32 * xlast, double cutoff) { // Makes a table of Wallenius noncentral hypergeometric probabilities // table must point to an array of length MaxLength. // The function returns 1 if table is long enough. Otherwise it fills // the table with as many correct values as possible and returns 0. // The tails are cut off where the values are < cutoff, so that // *xfirst may be > xmin and *xlast may be < xmax. // The value of cutoff will be 0.01 * accuracy if not specified. // The first and last x value represented in the table are returned in // *xfirst and *xlast. The resulting probability values are returned in // the first (*xfirst - *xlast + 1) positions of table. Any unused part // of table may be overwritten with garbage. // // The function will return the following information when MaxLength = 0: // The return value is the desired length of table. // *xfirst is 1 if it will be more efficient to call MakeTable than to call // probability repeatedly, even if only some of the table values are needed. // *xfirst is 0 if it is more efficient to call probability repeatedly. double * p1, * p2; // offset into p double mxo; // (m-x)*omega double Nmnx; // N-m-nu+x double y, y1; // probability. Save old p[x] before it is overwritten double d1, d2, dcom; // divisors in probability formula double area; // estimate of area needed for recursion method int32 xi, nu; // xi, nu = recursion values of x, n int32 x1, x2; // lowest and highest x or xi int32 i1, i2; // index into table int32 UseTable; // 1 if table method used int32 LengthNeeded; // Necessary table length if (cutoff <= 0. || cutoff > 0.1) cutoff = 0.01 * accuracy; LengthNeeded = N - m; // m2 if (m < LengthNeeded) LengthNeeded = m; if (n < LengthNeeded) LengthNeeded = n; // LengthNeeded = min(m1,m2,n) area = double(n)*LengthNeeded; // Estimate calculation time for table method UseTable = area < 5000. || area < 10000. && N > 1000. * n; if (MaxLength <= 0) { // Return UseTable and LengthNeeded if (xfirst) *xfirst = UseTable; i1 = LengthNeeded + 2; // Necessary table length if (!UseTable && i1 > 200) { // Calculate necessary table length from standard deviation double sd = sqrt(variance()); // calculate approximate standard deviation // estimate number of standard deviations to include from normal distribution i2 = (int32)(NumSD(accuracy) * sd + 0.5); if (i1 > i2) i1 = i2; } return i1; } if (UseTable && MaxLength > LengthNeeded) { // use recursion table method p1 = p2 = table + 1; // make space for p1[-1] p1[-1] = 0.; p1[0] = 1.; // initialize for recursion x1 = x2 = 0; for (nu = 1; nu <= n; nu++) { if (n - nu < xmin - x1 || p1[x1] < cutoff) { x1++; // increase lower limit when breakpoint passed or probability negligible p2--; // compensate buffer offset in order to reduce storage space } if (x2 < xmax && p1[x2] >= cutoff) { x2++; y1 = 0.; // increase upper limit until x has been reached } else { y1 = p1[x2]; } if (p2 - table + x2 >= MaxLength || x1 > x2) { goto ONE_BY_ONE; // Error: table length exceeded. Use other method } mxo = (m-x2)*omega; Nmnx = N-m-nu+x2+1; for (xi = x2; xi >= x1; xi--) { // backwards loop d2 = mxo + Nmnx; mxo += omega; Nmnx--; d1 = mxo + Nmnx; dcom = 1. / (d1 * d2); // save a division by making common divisor y = p1[xi-1]*mxo*d2*dcom + y1*(Nmnx+1)*d1*dcom; y1 = p1[xi-1]; // (warning: pointer alias, can't swap instruction order) p2[xi] = y; } p1 = p2; } // return results i1 = i2 = x2 - x1 + 1; // desired table length if (i2 > MaxLength) i2 = MaxLength; // limit table length *xfirst = x1; *xlast = x1 + i2 - 1; if (i2 > 0) memcpy(table, table+1, i2*sizeof(table[0]));// copy to start of table return i1 == i2; // true if table size not reduced } else { // Recursion method would take too much time // Calculate values one by one ONE_BY_ONE: // Start to fill table from the end and down. start with x = floor(mean) x2 = (int32)mean(); x1 = x2 + 1; i1 = MaxLength; while (x1 > xmin) { // loop for left tail x1--; i1--; y = probability(x1); table[i1] = y; if (y < cutoff) break; if (i1 == 0) break; } *xfirst = x1; i2 = x2 - x1 + 1; if (i1 > 0 && i2 > 0) { // move numbers down to beginning of table memcpy(table, table+i1, i2*sizeof(table[0])); } // Fill rest of table from mean and up i2--; while (x2 < xmax) { // loop for right tail if (i2 == MaxLength-1) { *xlast = x2; return 0; // table full } x2++; i2++; y = probability(x2); table[i2] = y; if (y < cutoff) break; } *xlast = x2; return 1; } } /*********************************************************************** calculation methods in class CMultiWalleniusNCHypergeometric ***********************************************************************/ CMultiWalleniusNCHypergeometric::CMultiWalleniusNCHypergeometric(int32 n_, int32 * m_, double * odds_, int colors_, double accuracy_) { // constructor accuracy = accuracy_; SetParameters(n_, m_, odds_, colors_); } void CMultiWalleniusNCHypergeometric::SetParameters(int32 n_, int32 * m_, double * odds_, int colors_) { // change parameters int32 N1; int i; n = n_; m = m_; omega = odds_; colors = colors_; r = 1.; for (N=N1=0, i=0; i < colors; i++) { if (m[i] < 0 || omega[i] < 0) FatalError("Parameter negative in constructor for CMultiWalleniusNCHypergeometric"); N += m[i]; if (omega[i]) N1 += m[i]; } if (N < n) FatalError("Not enough items in constructor for CMultiWalleniusNCHypergeometric"); if (N1< n) FatalError("Not enough items with nonzero weight in constructor for CMultiWalleniusNCHypergeometric"); } void CMultiWalleniusNCHypergeometric::mean(double * mu) { // calculate approximate mean of multivariate Wallenius noncentral hypergeometric // distribution. Result is returned in mu[0..colors-1] double omeg[MAXCOLORS]; // scaled weights double omr; // reciprocal mean weight double t, t1; // independent variable in iteration double To, To1; // exp(t*omega[i]), 1-exp(t*omega[i]) double H; // function to find root of double HD; // derivative of H double dummy; // unused return int i; // color index int iter; // number of iterations // calculate mean weight for (omr=0., i=0; i < colors; i++) omr += omega[i]*m[i]; omr = N / omr; // scale weights to make mean = 1 for (i = 0; i < colors; i++) omeg[i] = omega[i] * omr; // Newton Raphson iteration iter = 0; t = -1.; // first guess do { t1 = t; H = HD = 0.; // calculate H and HD for (i = 0; i < colors; i++) { if (omeg[i] != 0.) { To1 = pow2_1(t * (1./LN2) * omeg[i], &To); H += m[i] * To1; HD -= m[i] * omeg[i] * To; } } t -= (H-n) / HD; if (t >= 0) t = 0.5 * t1; if (++iter > 20) { FatalError("Search for mean failed in function CMultiWalleniusNCHypergeometric::mean"); } } while (fabs(H - n) > 1E-3); // finished iteration. Get all mu[i] for (i = 0; i < colors; i++) { if (omeg[i] != 0.) { To1 = pow2_1(t * (1./LN2) * omeg[i], &dummy); mu[i] = m[i] * To1; } else { mu[i] = 0.; } } } // implementations of different calculation methods double CMultiWalleniusNCHypergeometric::binoexpand(void) { // binomial expansion of integrand // only implemented for x[i] = 0 for all but one i int i, j, k; double W = 0.; // total weight for (i=j=k=0; i<colors; i++) { W += omega[i] * m[i]; if (x[i]) { j=i; k++; // find the nonzero x[i] } } if (k > 1) FatalError("More than one x[i] nonzero in CMultiWalleniusNCHypergeometric::binoexpand"); return exp(FallingFactorial(m[j],n) - FallingFactorial(W/omega[j],n)); } double CMultiWalleniusNCHypergeometric::lnbico(void) { // natural log of binomial coefficients bico = 0.; int i; for (i=0; i<colors; i++) { if (x[i] < m[i] && omega[i]) { bico += LnFac(m[i]) - LnFac(x[i]) - LnFac(m[i]-x[i]); } } return bico; } void CMultiWalleniusNCHypergeometric::findpars(void) { // calculate r, w, E // calculate d, E, r, w // find r to center peak of integrand at 0.5 double dd; // scaled d double dr; // 1/d double z, zd, rr, lastr, rrc, rt, r2, r21, a, b, ro, k1, dummy; double omax; // highest omega double omaxr; // 1/omax double omeg[MAXCOLORS]; // scaled weights int i, j = 0; // find highest omega for (omax=0., i=0; i < colors; i++) { if (omega[i] > omax) omax = omega[i]; } omaxr = 1. / omax; dd = E = 0.; for (i = 0; i < colors; i++) { // scale weights to make max = 1 omeg[i] = omega[i] * omaxr; // calculate d and E dd += omeg[i] * (m[i]-x[i]); E += omeg[i] * m[i]; } dr = 1. / dd; E *= dr; rr = r * omax; if (rr <= dr) rr = 1.2 * dr; // initial guess // Newton-Raphson iteration to find r do { lastr = rr; rrc = 1. / rr; z = dd - rrc; // z(r) zd = rrc * rrc; // z'(r) for (i=0; i<colors; i++) { rt = rr * omeg[i]; if (rt < 100. && rt > 0.) { // avoid overflow and division by 0 r21 = pow2_1(rt, &r2); // r2=2^r, r21=1.-2^r a = omeg[i] / r21; // omegai/(1.-2^r) b = x[i] * a; // x*omegai/(1.-2^r) z += b; zd += b * a * r2 * LN2; } } if (zd == 0) FatalError("can't find r in function CMultiWalleniusNCHypergeometric::findpars"); rr -= z / zd; // next r if (rr <= dr) rr = lastr * 0.125 + dr * 0.875; if (++j == 70) FatalError("convergence problem searching for r in function CMultiWalleniusNCHypergeometric::findpars"); } while (fabs(rr-lastr) > rr * 1.E-5); rd = rr * dd; r = rr * omaxr; // find peak width phi2d = 0.; for (i=0; i<colors; i++) { ro = rr * omeg[i]; if (ro < 300 && ro > 0.) { // avoid overflow and division by 0 k1 = pow2_1(ro, &dummy); k1 = -1. / k1; k1 = omeg[i] * omeg[i] * (k1 + k1*k1); } else k1 = 0.; phi2d += x[i] * k1; } phi2d *= -4. * rr * rr; if (phi2d > 0.) FatalError("peak width undefined in function CMultiWalleniusNCHypergeometric::findpars"); wr = sqrt(-phi2d); w = 1. / wr; } double CMultiWalleniusNCHypergeometric::laplace(void) { // Laplace's method with narrow integration interval, // using error function residues table, defined in erfres.cpp // Note that this function can only be used when the integrand peak is narrow. // findpars() must be called before this function. const int MAXDEG = 40; // arraysize int degree; // max expansion degree double accur; // stop expansion when terms below this threshold double f0; // factor outside integral double rho[MAXCOLORS]; // r*omegai double qi; // 2^(-rho) double qi1; // 1-qi double qq[MAXCOLORS]; // qi / qi1 double eta[MAXCOLORS+1][MAXDEG+1]; // eta coefficients double phideri[MAXDEG+1]; // derivatives of phi double PSIderi[MAXDEG+1]; // derivatives of PSI double * erfresp; // pointer to table of error function residues // variables in asymptotic summation static const double sqrt8 = 2.828427124746190098; // sqrt(8) double qqpow; // qq^j double pow2k; // 2^k double bino; // binomial coefficient double vr; // 1/v, v = integration interval double v2m2; // (2*v)^(-2) double v2mk1; // (2*v)^(-k-1) double s; // summation term double sum; // Taylor sum int i; // loop counter for color int j; // loop counter for derivative int k; // loop counter for expansion degree int ll; // k/2 int converg = 0; // number of consequtive terms below accuracy int PrecisionIndex; // index into ErfRes table according to desired precision // initialize for (k = 0; k <= 2; k++) phideri[k] = PSIderi[k] = 0; // find rho[i], qq[i], first eta coefficients, and zero'th derivative of phi for (i = 0; i < colors; i++) { rho[i] = r * omega[i]; if (rho[i] == 0.) continue; if (rho[i] > 40.) { qi=0.; qi1 = 1.; // avoid underflow } else { qi1 = pow2_1(-rho[i], &qi); // qi=2^(-rho), qi1=1.-2^(-rho) } qq[i] = qi / qi1; // 2^(-r*omegai)/(1.-2^(-r*omegai)) // peak = zero'th derivative phideri[0] += x[i] * log1mx(qi, qi1); // eta coefficients eta[i][0] = 0.; eta[i][1] = eta[i][2] = rho[i]*rho[i]; } // d, r, and w must be calculated by findpars() // zero'th derivative phideri[0] -= (rd - 1.) * LN2; // scaled factor outside integral f0 = rd * exp(phideri[0] + lnbico()); // calculate narrowed integration interval vr = sqrt8 * w; phideri[2] = phi2d; // get table according to desired precision PrecisionIndex = (-FloorLog2((float)accuracy) - ERFRES_B + ERFRES_S - 1) / ERFRES_S; if (PrecisionIndex < 0) PrecisionIndex = 0; if (PrecisionIndex > ERFRES_N-1) PrecisionIndex = ERFRES_N-1; while (w * NumSDev[PrecisionIndex] > 0.3) { // check if integration interval is too wide if (PrecisionIndex == 0) { FatalError("Laplace method failed. Peak width too high in function CWalleniusNCHypergeometric::laplace"); break; } PrecisionIndex--; // reduce precision to keep integration interval narrow } erfresp = ErfRes[PrecisionIndex]; // choose desired table degree = MAXDEG; // max expansion degree if (degree >= ERFRES_L*2) degree = ERFRES_L*2-2; // set up for starting loop at k=3 v2m2 = 0.25 * vr * vr; // (2*v)^(-2) PSIderi[0] = 1.; pow2k = 8.; sum = 0.5 * vr * erfresp[0]; v2mk1 = 0.5 * vr * v2m2 * v2m2; accur = accuracy * sum; // summation loop for (k = 3; k <= degree; k++) { phideri[k] = 0.; // loop for all colors for (i = 0; i < colors; i++) { if (rho[i] == 0.) continue; eta[i][k] = 0.; // backward loop for all powers for (j = k; j > 0; j--) { // find coefficients recursively from previous coefficients eta[i][j] = eta[i][j]*(j*rho[i]-(k-2)) + eta[i][j-1]*rho[i]*(j-1); } qqpow = 1.; // forward loop for all powers for (j = 1; j <= k; j++) { qqpow *= qq[i]; // qq^j // contribution to derivative phideri[k] += x[i] * eta[i][j] * qqpow; } } // finish calculation of derivatives phideri[k] = -pow2k * phideri[k] + 2*(1-k)*phideri[k-1]; pow2k *= 2.; // 2^k // loop to calculate derivatives of PSI from derivatives of psi. // terms # 0, 1, 2, k-2, and k-1 are zero and not included in loop. // The j'th derivatives of psi are identical to the derivatives of phi for j>2, and // zero for j=1,2. Hence we are using phideri[j] for j>2 here. PSIderi[k] = phideri[k]; // this is term # k bino = 0.5 * (k-1) * (k-2); // binomial coefficient for term # 3 for (j=3; j < k-2; j++) { // loop for remaining nonzero terms (if k>5) PSIderi[k] += PSIderi[k-j] * phideri[j] * bino; bino *= double(k-j)/double(j); } if ((k & 1) == 0) { // only for even k ll = k/2; s = PSIderi[k] * v2mk1 * erfresp[ll]; sum += s; // check for convergence of Taylor expansion if (fabs(s) < accur) converg++; else converg = 0; if (converg > 1) break; // update recursive expressions v2mk1 *= v2m2; } } // multiply by terms outside integral return f0 * sum; } double CMultiWalleniusNCHypergeometric::integrate(void) { // Wallenius non-central hypergeometric distribution function // calculation by numerical integration with variable-length steps // NOTE: findpars() must be called before this function. double s; // result of integration step double sum; // integral double ta, tb; // subinterval for integration step lnbico(); // compute log of binomial coefficients // choose method: if (w < 0.02) { // normal method. Step length determined by peak width w double delta, s1; s1 = accuracy < 1E-9 ? 0.5 : 1.; delta = s1 * w; // integration steplength ta = 0.5 + 0.5 * delta; sum = integrate_step(1.-ta, ta); // first integration step around center peak do { tb = ta + delta; if (tb > 1.) tb = 1.; s = integrate_step(ta, tb); // integration step to the right of peak s += integrate_step(1.-tb,1.-ta);// integration step to the left of peak sum += s; if (s < accuracy * sum) break; // stop before interval finished if accuracy reached ta = tb; if (tb > 0.5 + w) delta *= 2.; // increase step length far from peak } while (tb < 1.); } else { // difficult situation. Step length determined by inflection points double t1, t2, tinf, delta, delta1; sum = 0.; // do left and right half of integration interval separately: for (t1=0., t2=0.5; t1 < 1.; t1+=0.5, t2+=0.5) { // integrate from 0 to 0.5 or from 0.5 to 1 tinf = search_inflect(t1, t2); // find inflection point delta = tinf - t1; if (delta > t2 - tinf) delta = t2 - tinf; // distance to nearest endpoint delta *= 1./7.; // 1/7 will give 3 steps to nearest endpoint if (delta < 1E-4) delta = 1E-4; delta1 = delta; // integrate from tinf forwards to t2 ta = tinf; do { tb = ta + delta1; if (tb > t2 - 0.25*delta1) tb = t2; // last step of this subinterval s = integrate_step(ta, tb); // integration step sum += s; delta1 *= 2; // double steplength if (s < sum * 1E-4) delta1 *= 8.; // large step when s small ta = tb; } while (tb < t2); if (tinf) { // integrate from tinf backwards to t1 tb = tinf; do { ta = tb - delta; if (ta < t1 + 0.25*delta) ta = t1; // last step of this subinterval s = integrate_step(ta, tb); // integration step sum += s; delta *= 2; // double steplength if (s < sum * 1E-4) delta *= 8.; // large step when s small tb = ta; } while (ta > t1); } } } return sum * rd; } double CMultiWalleniusNCHypergeometric::integrate_step(double ta, double tb) { // integration subprocedure used by integrate() // makes one integration step from ta to tb using Gauss-Legendre method. // result is scaled by multiplication with exp(bico) double ab, delta, tau, ltau, y, sum, taur, rdm1; int i, j; // define constants for Gauss-Legendre integration with IPOINTS points #define IPOINTS 8 // number of points in each integration step #if IPOINTS == 3 static const double xval[3] = {-.774596669241,0,0.774596668241}; static const double weights[3] = {.5555555555555555,.88888888888888888,.55555555555555}; #elif IPOINTS == 4 static const double xval[4] = {-0.861136311594,-0.339981043585,0.339981043585,0.861136311594}, static const double weights[4] = {0.347854845137,0.652145154863,0.652145154863,0.347854845137}; #elif IPOINTS == 5 static const double xval[5] = {-0.906179845939,-0.538469310106,0,0.538469310106,0.906179845939}; static const double weights[5] = {0.236926885056,0.478628670499,0.568888888889,0.478628670499,0.236926885056}; #elif IPOINTS == 6 static const double xval[6] = {-0.932469514203,-0.661209386466,-0.238619186083,0.238619186083,0.661209386466,0.932469514203}; static const double weights[6] = {0.171324492379,0.360761573048,0.467913934573,0.467913934573,0.360761573048,0.171324492379}; #elif IPOINTS == 8 static const double xval[8] = {-0.960289856498,-0.796666477414,-0.525532409916,-0.183434642496,0.183434642496,0.525532409916,0.796666477414,0.960289856498}; static const double weights[8] = {0.10122853629,0.222381034453,0.313706645878,0.362683783378,0.362683783378,0.313706645878,0.222381034453,0.10122853629}; #elif IPOINTS == 12 static const double xval[12] = {-0.981560634247,-0.90411725637,-0.769902674194,-0.587317954287,-0.367831498998,-0.125233408511,0.125233408511,0.367831498998,0.587317954287,0.769902674194,0.90411725637,0.981560634247}; static const double weights[12]= {0.0471753363866,0.106939325995,0.160078328543,0.203167426723,0.233492536538,0.249147045813,0.249147045813,0.233492536538,0.203167426723,0.160078328543,0.106939325995,0.0471753363866}; #elif IPOINTS == 16 static const double xval[16] = {-0.989400934992,-0.944575023073,-0.865631202388,-0.755404408355,-0.617876244403,-0.458016777657,-0.281603550779,-0.0950125098376,0.0950125098376,0.281603550779,0.458016777657,0.617876244403,0.755404408355,0.865631202388,0.944575023073,0.989400934992}; static const double weights[16]= {0.027152459411,0.0622535239372,0.0951585116838,0.124628971256,0.149595988817,0.169156519395,0.182603415045,0.189450610455,0.189450610455,0.182603415045,0.169156519395,0.149595988817,0.124628971256,0.0951585116838,0.0622535239372,0.027152459411}; #else #error // IPOINTS must be a value for which the tables are defined #endif delta = 0.5 * (tb - ta); ab = 0.5 * (ta + tb); rdm1 = rd - 1.; sum = 0; for (j = 0; j < IPOINTS; j++) { tau = ab + delta * xval[j]; ltau = log(tau); taur = r * ltau; y = 0.; for (i = 0; i < colors; i++) { // possible loss of precision due to subtraction here: if (omega[i]) { y += log1pow(taur*omega[i],x[i]); // ln((1-e^taur*omegai)^xi) } } y += rdm1*ltau + bico; if (y > -50.) sum += weights[j] * exp(y); } return delta * sum; } double CMultiWalleniusNCHypergeometric::search_inflect(double t_from, double t_to) { // search for an inflection point of the integrand PHI(t) in the interval // t_from < t < t_to double t, t1; // independent variable double rho[MAXCOLORS]; // r*omega[i] double q; // t^rho[i] / (1-t^rho[i]) double q1; // 1-t^rho[i] double zeta[MAXCOLORS][4][4]; // zeta[i,j,k] coefficients double phi[4]; // derivatives of phi(t) = log PHI(t) double Z2; // PHI''(t)/PHI(t) double Zd; // derivative in Newton Raphson iteration double rdm1; // r * d - 1 double tr; // 1/t double log2t; // log2(t) double method; // 0 for z2'(t) method, 1 for z3(t) method int i; // color int iter; // count iterations rdm1 = rd - 1.; if (t_from == 0 && rdm1 <= 1.) return 0.; //no inflection point t = 0.5 * (t_from + t_to); for (i = 0; i < colors; i++) { // calculate zeta coefficients rho[i] = r * omega[i]; zeta[i][1][1] = rho[i]; zeta[i][1][2] = rho[i] * (rho[i] - 1.); zeta[i][2][2] = rho[i] * rho[i]; zeta[i][1][3] = zeta[i][1][2] * (rho[i] - 2.); zeta[i][2][3] = zeta[i][1][2] * rho[i] * 3.; zeta[i][3][3] = zeta[i][2][2] * rho[i] * 2.; } iter = 0; do { t1 = t; tr = 1. / t; log2t = log(t)*(1./LN2); phi[1] = phi[2] = phi[3] = 0.; for (i=0; i<colors; i++) { // calculate first 3 derivatives of phi(t) if (rho[i] == 0.) continue; q1 = pow2_1(rho[i]*log2t,&q); q /= q1; phi[1] -= x[i] * zeta[i][1][1] * q; phi[2] -= x[i] * q * (zeta[i][1][2] + q * zeta[i][2][2]); phi[3] -= x[i] * q * (zeta[i][1][3] + q * (zeta[i][2][3] + q * zeta[i][3][3])); } phi[1] += rdm1; phi[2] -= rdm1; phi[3] += 2. * rdm1; phi[1] *= tr; phi[2] *= tr * tr; phi[3] *= tr * tr * tr; method = (iter & 2) >> 1; // alternate between the two methods Z2 = phi[1]*phi[1] + phi[2]; Zd = method*phi[1]*phi[1]*phi[1] + (2.+method)*phi[1]*phi[2] + phi[3]; if (t < 0.5) { if (Z2 > 0) { t_from = t; } else { t_to = t; } if (Zd >= 0) { // use binary search if Newton-Raphson iteration makes problems t = (t_from ? 0.5 : 0.2) * (t_from + t_to); } else { // Newton-Raphson iteration t -= Z2 / Zd; } } else { if (Z2 < 0) { t_from = t; } else { t_to = t; } if (Zd <= 0) { // use binary search if Newton-Raphson iteration makes problems t = 0.5 * (t_from + t_to); } else { // Newton-Raphson iteration t -= Z2 / Zd; } } if (t >= t_to) t = (t1 + t_to) * 0.5; if (t <= t_from) t = (t1 + t_from) * 0.5; if (++iter > 20) FatalError("Search for inflection point failed in function CMultiWalleniusNCHypergeometric::search_inflect"); } while (fabs(t - t1) > 1E-5); return t; } double CMultiWalleniusNCHypergeometric::probability(int32 * x_) { // calculate probability function. choosing best method int i, j, em; int32 xsum; x = x_; for (xsum = i = 0; i < colors; i++) xsum += x[i]; if (xsum != n) { FatalError("sum of x values not equal to n in function CMultiWalleniusNCHypergeometric::probability"); } if (colors < 3) { if (colors <= 0) return 1.; if (colors == 1) return x[0] == m[0]; // colors = 2 if (omega[1] == 0.) return x[0] == m[0]; return CWalleniusNCHypergeometric(n,m[0],N,omega[0]/omega[1],accuracy).probability(x[0]); } for (i = j = em = 0; i < colors; i++) { if (x[i] > m[i] || x[i] < 0 || x[i] < n - N + m[i]) return 0.; if (x[i] > 0) j++; if (omega[i] == 0. && x[i]) return 0.; if (x[i] == m[i] || omega[i] == 0.) em++; } if (n == 0 || em == colors) return 1.; if (j == 1) { return binoexpand(); } findpars(); if (w < 0.04 && E < 10 && (!em || w > 0.004)) { return laplace(); } return integrate(); } /*********************************************************************** Methods for CMultiWalleniusNCHypergeometricMoments ***********************************************************************/ double CMultiWalleniusNCHypergeometricMoments::moments(double * mu, double * variance, int32 * combinations) { // calculates mean and variance of multivariate Wallenius noncentral // hypergeometric distribution by calculating all combinations of x-values. // Return value = sum of all probabilities. The deviation of this value // from 1 is a measure of the accuracy. // Returns the mean to mean[0...colors-1] // Returns the variance to variance[0...colors-1] double sumf; // sum of all f(x) values int32 msum; // temporary sum int i; // loop counter // get approximate mean mean(sx); // round mean to integers for (i=0; i < colors; i++) { xm[i] = (int32)(sx[i]+0.4999999); } // set up for recursive loops for (i=colors-1, msum=0; i >= 0; i--) { remaining[i] = msum; msum += m[i]; } for (i=0; i<colors; i++) sx[i] = sxx[i] = 0.; sn = 0; // recursive loops to calculate sums sumf = loop(n, 0); // calculate mean and variance for (i = 0; i < colors; i++) { mu[i] = sx[i]/sumf; variance[i] = sxx[i]/sumf - sx[i]*sx[i]/(sumf*sumf); } // return combinations and sum if (combinations) *combinations = sn; return sumf; } double CMultiWalleniusNCHypergeometricMoments::loop(int32 n, int c) { // recursive function to loop through all combinations of x-values. // used by moments() int32 x, x0; // x of color c int32 xmin, xmax; // min and max of x[c] double s1, s2, sum = 0.; // sum of f(x) values int i; // loop counter if (c < colors-1) { // not the last color // calculate min and max of x[c] for given x[0]..x[c-1] xmin = n - remaining[c]; if (xmin < 0) xmin = 0; xmax = m[c]; if (xmax > n) xmax = n; x0 = xm[c]; if (x0 < xmin) x0 = xmin; if (x0 > xmax) x0 = xmax; // loop for all x[c] from mean and up for (x = x0, s2 = 0.; x <= xmax; x++) { xi[c] = x; sum += s1 = loop(n-x, c+1); // recursive loop for remaining colors if (s1 < accuracy && s1 < s2) break; // stop when values become negligible s2 = s1; } // loop for all x[c] from mean and down for (x = x0-1; x >= xmin; x--) { xi[c] = x; sum += s1 = loop(n-x, c+1); // recursive loop for remaining colors if (s1 < accuracy && s1 < s2) break; // stop when values become negligible s2 = s1; } } else { // last color xi[c] = n; s1 = probability(xi); for (i=0; i < colors; i++) { sx[i] += s1 * xi[i]; sxx[i] += s1 * xi[i] * xi[i]; } sn++; sum = s1; } return sum; }
[ "Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c" ]
[ [ [ 1, 1984 ] ] ]
4c95d51b7a67e90afbec6051e27477c51943c6b3
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/DOMParser.cpp
062fe752a8a1fc934fb8c8e5096e2c3da05d260b
[ "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
45,475
cpp
/* * Copyright 1999-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. */ /** * This file contains code to build the DOM tree. It registers a document * handler with the scanner. In these handler methods, appropriate DOM nodes * are created and added to the DOM tree. * * $Id: DOMParser.cpp,v 1.33 2004/09/08 13:55:42 peiyongz Exp $ * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/internal/XMLScannerResolver.hpp> #include <xercesc/sax/EntityResolver.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/sax/ErrorHandler.hpp> #include <xercesc/sax/SAXParseException.hpp> #include <xercesc/framework/XMLNotationDecl.hpp> #include <xercesc/util/IOException.hpp> #include <xercesc/framework/XMLValidator.hpp> #include <xercesc/validators/common/GrammarResolver.hpp> #include <xercesc/framework/XMLGrammarPool.hpp> #include <xercesc/framework/XMLSchemaDescription.hpp> #include <xercesc/util/Janitor.hpp> #include "DOMParser.hpp" #include "ElementImpl.hpp" #include "AttrImpl.hpp" #include "AttrNSImpl.hpp" #include "TextImpl.hpp" #include "DocumentImpl.hpp" #include "DocumentTypeImpl.hpp" #include "EntityImpl.hpp" #include "NotationImpl.hpp" #include "NamedNodeMapImpl.hpp" #include "NodeIDMap.hpp" #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/DTD/DTDAttDefList.hpp> #include <xercesc/util/OutOfMemoryException.hpp> #include <xercesc/util/XMLEntityResolver.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // DOMParser: Constructors and Destructor // --------------------------------------------------------------------------- DOMParser::DOMParser( XMLValidator* const valToAdopt , MemoryManager* const manager , XMLGrammarPool* const gramPool) : fToCreateXMLDeclTypeNode(false) , fCreateEntityReferenceNodes(true) , fIncludeIgnorableWhitespace(true) , fParseInProgress(false) , fWithinElement(false) , fEntityResolver(0) , fXMLEntityResolver(0) , fErrorHandler(0) , fPSVIHandler(0) , fNodeStack(0) , fScanner(0) , fDocumentType(0) , fGrammarResolver(0) , fURIStringPool(0) , fValidator(valToAdopt) , fMemoryManager(manager) , fGrammarPool(gramPool) { try { initialize(); } catch(const OutOfMemoryException&) { throw; } catch(...) { cleanUp(); throw; } } DOMParser::~DOMParser() { cleanUp(); } // --------------------------------------------------------------------------- // DOMParser: Initialize/CleanUp methods // --------------------------------------------------------------------------- void DOMParser::initialize() { // Create grammar resolver and URI string pool to pass to the scanner fGrammarResolver = new (fMemoryManager) GrammarResolver(fGrammarPool, fMemoryManager); fURIStringPool = fGrammarResolver->getStringPool(); // Create a scanner and tell it what validator to use. Then set us // as the document event handler so we can fill the DOM document. fScanner = XMLScannerResolver::getDefaultScanner(fValidator, fGrammarResolver, fMemoryManager); fScanner->setDocHandler(this); fScanner->setDocTypeHandler(this); fScanner->setURIStringPool(fURIStringPool); fNodeStack = new (fMemoryManager) ValueStackOf<DOM_Node>(64, fMemoryManager, true); this->reset(); } void DOMParser::cleanUp() { delete fNodeStack; delete fScanner; delete fGrammarResolver; // grammar pool must do this //delete fURIStringPool; if (fValidator) delete fValidator; } void DOMParser::reset() { // // Note: DOM Documents are reference counted. Doing this assignment // will cause the old one to go away unless application code is also // holding a reference to it. // fDocument = DOM_Document::createDocument(fMemoryManager); resetDocType(); fCurrentParent = 0; fCurrentNode = 0; fParseInProgress = false; fWithinElement = false; fNodeStack->removeAllElements(); }; // --------------------------------------------------------------------------- // DOMParser: Getter methods // --------------------------------------------------------------------------- const XMLValidator& DOMParser::getValidator() const { return *fScanner->getValidator(); } bool DOMParser::getDoNamespaces() const { return fScanner->getDoNamespaces(); } bool DOMParser::getExitOnFirstFatalError() const { return fScanner->getExitOnFirstFatal(); } bool DOMParser::getValidationConstraintFatal() const { return fScanner->getValidationConstraintFatal(); } DOMParser::ValSchemes DOMParser::getValidationScheme() const { const XMLScanner::ValSchemes scheme = fScanner->getValidationScheme(); if (scheme == XMLScanner::Val_Always) return Val_Always; else if (scheme == XMLScanner::Val_Never) return Val_Never; return Val_Auto; } bool DOMParser::getDoSchema() const { return fScanner->getDoSchema(); } bool DOMParser::getValidationSchemaFullChecking() const { return fScanner->getValidationSchemaFullChecking(); } bool DOMParser::getIdentityConstraintChecking() const { return fScanner->getIdentityConstraintChecking(); } int DOMParser::getErrorCount() const { return fScanner->getErrorCount(); } XMLCh* DOMParser::getExternalSchemaLocation() const { return fScanner->getExternalSchemaLocation(); } XMLCh* DOMParser::getExternalNoNamespaceSchemaLocation() const { return fScanner->getExternalNoNamespaceSchemaLocation(); } bool DOMParser::isCachingGrammarFromParse() const { return fScanner->isCachingGrammarFromParse(); } bool DOMParser::isUsingCachedGrammarInParse() const { return fScanner->isUsingCachedGrammarInParse(); } Grammar* DOMParser::getGrammar(const XMLCh* const nameSpaceKey) { return fGrammarResolver->getGrammar(nameSpaceKey); } Grammar* DOMParser::getRootGrammar() { return fScanner->getRootGrammar(); } const XMLCh* DOMParser::getURIText(unsigned int uriId) const { return fScanner->getURIText(uriId); } bool DOMParser::getCalculateSrcOfs() const { return fScanner->getCalculateSrcOfs(); } bool DOMParser::getStandardUriConformant() const { return fScanner->getStandardUriConformant(); } unsigned int DOMParser::getSrcOffset() const { return fScanner->getSrcOffset(); } // --------------------------------------------------------------------------- // DOMParser: Setter methods // --------------------------------------------------------------------------- void DOMParser::setDoNamespaces(const bool newState) { fScanner->setDoNamespaces(newState); } void DOMParser::setErrorHandler(ErrorHandler* const handler) { fErrorHandler = handler; if (fErrorHandler) { fScanner->setErrorReporter(this); fScanner->setErrorHandler(fErrorHandler); } else { fScanner->setErrorReporter(0); fScanner->setErrorHandler(0); } } void DOMParser::setPSVIHandler(PSVIHandler* const handler) { fPSVIHandler = handler; if (fPSVIHandler) { fScanner->setPSVIHandler(fPSVIHandler); } else { fScanner->setPSVIHandler(0); } } void DOMParser::setEntityResolver(EntityResolver* const handler) { fEntityResolver = handler; if (fEntityResolver) { fScanner->setEntityHandler(this); fXMLEntityResolver = 0; } else { fScanner->setEntityHandler(0); } } void DOMParser::setXMLEntityResolver(XMLEntityResolver* const handler) { fXMLEntityResolver = handler; if (fXMLEntityResolver) { fEntityResolver = 0; fScanner->setEntityHandler(this); } else { fScanner->setEntityHandler(0); } } void DOMParser::setExitOnFirstFatalError(const bool newState) { fScanner->setExitOnFirstFatal(newState); } void DOMParser::setValidationConstraintFatal(const bool newState) { fScanner->setValidationConstraintFatal(newState); } void DOMParser::setValidationScheme(const ValSchemes newScheme) { if (newScheme == Val_Never) fScanner->setValidationScheme(XMLScanner::Val_Never); else if (newScheme == Val_Always) fScanner->setValidationScheme(XMLScanner::Val_Always); else fScanner->setValidationScheme(XMLScanner::Val_Auto); } void DOMParser::setDoSchema(const bool newState) { fScanner->setDoSchema(newState); } void DOMParser::setValidationSchemaFullChecking(const bool schemaFullChecking) { fScanner->setValidationSchemaFullChecking(schemaFullChecking); } void DOMParser::setIdentityConstraintChecking(const bool identityConstraintChecking) { fScanner->setIdentityConstraintChecking(identityConstraintChecking); } void DOMParser::setExternalSchemaLocation(const XMLCh* const schemaLocation) { fScanner->setExternalSchemaLocation(schemaLocation); } void DOMParser::setExternalNoNamespaceSchemaLocation(const XMLCh* const noNamespaceSchemaLocation) { fScanner->setExternalNoNamespaceSchemaLocation(noNamespaceSchemaLocation); } void DOMParser::setExternalSchemaLocation(const char* const schemaLocation) { fScanner->setExternalSchemaLocation(schemaLocation); } void DOMParser::setExternalNoNamespaceSchemaLocation(const char* const noNamespaceSchemaLocation) { fScanner->setExternalNoNamespaceSchemaLocation(noNamespaceSchemaLocation); } void DOMParser::cacheGrammarFromParse(const bool newState) { fScanner->cacheGrammarFromParse(newState); if (newState) fScanner->useCachedGrammarInParse(newState); } void DOMParser::useCachedGrammarInParse(const bool newState) { if (newState || !fScanner->isCachingGrammarFromParse()) fScanner->useCachedGrammarInParse(newState); } void DOMParser::setCalculateSrcOfs(const bool newState) { fScanner->setCalculateSrcOfs(newState); } void DOMParser::setStandardUriConformant(const bool newState) { fScanner->setStandardUriConformant(newState); } void DOMParser::useScanner(const XMLCh* const scannerName) { XMLScanner* tempScanner = XMLScannerResolver::resolveScanner ( scannerName , fValidator , fGrammarResolver , fMemoryManager ); if (tempScanner) { tempScanner->setParseSettings(fScanner); tempScanner->setURIStringPool(fURIStringPool); delete fScanner; fScanner = tempScanner; } } // --------------------------------------------------------------------------- // DOMParser: Parsing methods // --------------------------------------------------------------------------- void DOMParser::parse(const InputSource& source) { // Avoid multiple entrance if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); try { fParseInProgress = true; fScanner->scanDocument(source); fParseInProgress = false; } catch(const OutOfMemoryException&) { throw; } catch(...) { fParseInProgress = false; throw; } } void DOMParser::parse(const XMLCh* const systemId) { // Avoid multiple entrance if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); try { fParseInProgress = true; fScanner->scanDocument(systemId); fParseInProgress = false; } catch(const OutOfMemoryException&) { throw; } catch(...) { fParseInProgress = false; throw; } } void DOMParser::parse(const char* const systemId) { // Avoid multiple entrance if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); try { fParseInProgress = true; fScanner->scanDocument(systemId); fParseInProgress = false; } catch(const OutOfMemoryException&) { throw; } catch(...) { fParseInProgress = false; throw; } } // --------------------------------------------------------------------------- // DOMParser: Progressive parse methods // --------------------------------------------------------------------------- bool DOMParser::parseFirst( const XMLCh* const systemId , XMLPScanToken& toFill) { // // Avoid multiple entrance. We cannot enter here while a regular parse // is in progress. // if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); return fScanner->scanFirst(systemId, toFill); } bool DOMParser::parseFirst( const char* const systemId , XMLPScanToken& toFill) { // // Avoid multiple entrance. We cannot enter here while a regular parse // is in progress. // if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); return fScanner->scanFirst(systemId, toFill); } bool DOMParser::parseFirst( const InputSource& source , XMLPScanToken& toFill) { // // Avoid multiple entrance. We cannot enter here while a regular parse // is in progress. // if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); return fScanner->scanFirst(source, toFill); } bool DOMParser::parseNext(XMLPScanToken& token) { return fScanner->scanNext(token); } void DOMParser::parseReset(XMLPScanToken& token) { // Reset the scanner, and then reset the parser fScanner->scanReset(token); reset(); } // --------------------------------------------------------------------------- // DOMParser: Implementation of the XMLErrorReporter interface // --------------------------------------------------------------------------- void DOMParser::error( const unsigned int code , const XMLCh* const msgDomain , const XMLErrorReporter::ErrTypes errType , const XMLCh* const errorText , const XMLCh* const systemId , const XMLCh* const publicId , const XMLSSize_t lineNum , const XMLSSize_t colNum) { SAXParseException toThrow = SAXParseException ( errorText , publicId , systemId , lineNum , colNum , fMemoryManager ); // // If there is an error handler registered, call it, otherwise ignore // all but the fatal errors. // if (!fErrorHandler) { if (errType == XMLErrorReporter::ErrType_Fatal) throw toThrow; return; } if (errType == XMLErrorReporter::ErrType_Warning) fErrorHandler->warning(toThrow); else if (errType >= XMLErrorReporter::ErrType_Fatal) fErrorHandler->fatalError(toThrow); else fErrorHandler->error(toThrow); } void DOMParser::resetErrors() { } // --------------------------------------------------------------------------- // DOMParser: Implementation of XMLEntityHandler interface // --------------------------------------------------------------------------- InputSource* DOMParser::resolveEntity(const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI) { // // Just map it to the SAX entity resolver. If there is not one installed, // return a null pointer to cause the default resolution. // if (fEntityResolver) return fEntityResolver->resolveEntity(publicId, systemId); return 0; } InputSource* DOMParser::resolveEntity(XMLResourceIdentifier* resourceIdentifier) { // // Just map it to the SAX entity resolver. If there is not one installed, // return a null pointer to cause the default resolution. // if (fEntityResolver) return fEntityResolver->resolveEntity(resourceIdentifier->getPublicId(), resourceIdentifier->getSystemId()); if (fXMLEntityResolver) return fXMLEntityResolver->resolveEntity(resourceIdentifier); return 0; } // --------------------------------------------------------------------------- // DOMParser: Implementation of XMLDocumentHandler interface // --------------------------------------------------------------------------- void DOMParser::docCharacters( const XMLCh* const chars , const unsigned int length , const bool cdataSection) { // Ignore chars outside of content if (!fWithinElement) return; if (cdataSection == true) { DOM_CDATASection node = fDocument.createCDATASection ( DOMString(chars, length) ); fCurrentParent.appendChild(node); fCurrentNode = node; } else { if (fCurrentNode.getNodeType() == DOM_Node::TEXT_NODE) { DOM_Text node = (DOM_Text&)fCurrentNode; node.appendData(DOMString(chars, length)); } else { DOM_Text node = fDocument.createTextNode(DOMString(chars, length)); fCurrentParent.appendChild(node); fCurrentNode = node; } } } void DOMParser::docComment(const XMLCh* const comment) { DOM_Comment dcom = fDocument.createComment(comment); fCurrentParent.appendChild(dcom); fCurrentNode = dcom; } void DOMParser::docPI( const XMLCh* const target , const XMLCh* const data) { DOM_ProcessingInstruction pi = fDocument.createProcessingInstruction ( target , data ); fCurrentParent.appendChild(pi); fCurrentNode = pi; } void DOMParser::endEntityReference(const XMLEntityDecl& entDecl) { if (fCreateEntityReferenceNodes == true) { if (fCurrentParent.getNodeType() == DOM_Node::ENTITY_REFERENCE_NODE) { ((DOM_EntityReference&)fCurrentParent).fImpl->setReadOnly(true, true); } fCurrentParent = fNodeStack->pop(); fCurrentNode = fCurrentParent; } } void DOMParser::endElement( const XMLElementDecl& elemDecl , const unsigned int urlId , const bool isRoot , const XMLCh* const elemPrefix) { fCurrentNode = fCurrentParent; fCurrentParent = fNodeStack->pop(); // If we've hit the end of content, clear the flag if (fNodeStack->empty()) fWithinElement = false; } void DOMParser::ignorableWhitespace(const XMLCh* const chars , const unsigned int length , const bool cdataSection) { // Ignore chars before the root element if (!fWithinElement || !fIncludeIgnorableWhitespace) return; if (fCurrentNode.getNodeType() == DOM_Node::TEXT_NODE) { DOM_Text node = (DOM_Text&)fCurrentNode; node.appendData(DOMString(chars, length)); } else { DOM_Text node = fDocument.createTextNode(DOMString(chars, length)); TextImpl *text = (TextImpl *) node.fImpl; text -> setIgnorableWhitespace(true); fCurrentParent.appendChild(node); fCurrentNode = node; } } void DOMParser::resetDocument() { // // The reset methods are called before a new parse event occurs. // Reset this parsers state to clear out anything that may be left // from a previous use, in particular the DOM document itself. // this->reset(); } void DOMParser::startDocument() { // Just set the document as the current parent and current node fCurrentParent = fDocument; fCurrentNode = fDocument; // set DOM error checking off fDocument.setErrorChecking(false); } void DOMParser::endDocument() { // set DOM error checking back on fDocument.setErrorChecking(true); } void DOMParser::startElement(const XMLElementDecl& elemDecl , const unsigned int urlId , const XMLCh* const elemPrefix , const RefVectorOf<XMLAttr>& attrList , const unsigned int attrCount , const bool isEmpty , const bool isRoot) { DOM_Element elem; DocumentImpl *docImpl = (DocumentImpl *)fDocument.fImpl; if (fScanner -> getDoNamespaces()) { //DOM Level 2, doNamespaces on XMLBuffer buf(1023, fMemoryManager); DOMString namespaceURI = 0; DOMString elemQName = 0; if (urlId != fScanner->getEmptyNamespaceId()) { //TagName has a prefix fScanner->getURIText(urlId, buf); //get namespaceURI namespaceURI = DOMString(buf.getRawBuffer()); if (elemPrefix && *elemPrefix) { elemQName.appendData(elemPrefix); elemQName.appendData(chColon); } } elemQName.appendData(elemDecl.getBaseName()); elem = fDocument.createElementNS(namespaceURI, elemQName); ElementImpl *elemImpl = (ElementImpl *) elem.fImpl; for (unsigned int index = 0; index < attrCount; ++index) { static const XMLCh XMLNS[] = { chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chNull }; const XMLAttr* oneAttrib = attrList.elementAt(index); unsigned int attrURIId = oneAttrib -> getURIId(); namespaceURI = 0; if (!XMLString::compareString(oneAttrib -> getName(), XMLNS)) //for xmlns=... attrURIId = fScanner->getXMLNSNamespaceId(); if (attrURIId != fScanner->getEmptyNamespaceId()) { //TagName has a prefix fScanner->getURIText(attrURIId, buf); //get namespaceURI namespaceURI = DOMString(buf.getRawBuffer()); } AttrImpl *attr = elemImpl->setAttributeNS(namespaceURI, oneAttrib -> getQName(), oneAttrib -> getValue()); // Attributes of type ID. If this is one, add it to the hashtable of IDs // that is constructed for use by GetElementByID(). // if (oneAttrib->getType()==XMLAttDef::ID) { if (docImpl->fNodeIDMap == 0) docImpl->fNodeIDMap = new (fMemoryManager) NodeIDMap(500, fMemoryManager); docImpl->fNodeIDMap->add(attr); attr->isIdAttr(true); } attr->setSpecified(oneAttrib->getSpecified()); } } else { //DOM Level 1 elem = fDocument.createElement(elemDecl.getFullName()); ElementImpl *elemImpl = (ElementImpl *) elem.fImpl; for (unsigned int index = 0; index < attrCount; ++index) { const XMLAttr* oneAttrib = attrList.elementAt(index); AttrImpl *attr = elemImpl->setAttribute(oneAttrib->getName(), oneAttrib->getValue()); attr->setSpecified(oneAttrib->getSpecified()); // Attributes of type ID. If this is one, add it to the hashtable of IDs // that is constructed for use by GetElementByID(). // if (oneAttrib->getType()==XMLAttDef::ID) { if (docImpl->fNodeIDMap == 0) docImpl->fNodeIDMap = new (fMemoryManager) NodeIDMap(500, fMemoryManager); docImpl->fNodeIDMap->add(attr); attr->isIdAttr(true); } } } fCurrentParent.appendChild(elem); fNodeStack->push(fCurrentParent); fCurrentParent = elem; fCurrentNode = elem; fWithinElement = true; // If an empty element, do end right now (no endElement() will be called) if (isEmpty) endElement(elemDecl, urlId, isRoot, elemPrefix); } void DOMParser::startEntityReference(const XMLEntityDecl& entDecl) { if (fCreateEntityReferenceNodes == true) { DOMString entName(entDecl.getName()); DOM_EntityReference er = fDocument.createEntityReference(entName); //set the readOnly flag to false before appending node, will be reset in endEntityReference er.fImpl->setReadOnly(false, true); fCurrentParent.appendChild(er); fNodeStack->push(fCurrentParent); fCurrentParent = er; fCurrentNode = er; // this entityRef needs to be stored in Entity map too. // We'd decide later whether the entity nodes should be created by a // separated method in parser or not. For now just stick it in if // the ref nodes are created EntityImpl* entity = (EntityImpl*)fDocumentType->entities->getNamedItem(entName); entity->setEntityRef((EntityReferenceImpl*)er.fImpl); } } void DOMParser::XMLDecl(const XMLCh* const version , const XMLCh* const encoding , const XMLCh* const standalone , const XMLCh* const actualEncStr) { //This is a non-standard extension to creating XMLDecl type nodes and attching to DOM Tree // currently this flag it set to false unless user explicitly asks for it // Needs to be revisited after W3C specs are laid out on this issue. if (fToCreateXMLDeclTypeNode) { DOMString ver(version); DOMString enc(encoding); DOMString isStd(standalone); DOM_XMLDecl xmlDecl = fDocument.createXMLDecl(ver, enc, isStd); fCurrentParent.appendChild(xmlDecl); } } // --------------------------------------------------------------------------- // DOMParser: Deprecated methods // --------------------------------------------------------------------------- bool DOMParser::getDoValidation() const { // // We don't want to tie the public parser classes to the enum used // by the scanner, so we use a separate one and map. // // DON'T mix the new and old methods!! // const XMLScanner::ValSchemes scheme = fScanner->getValidationScheme(); if (scheme == XMLScanner::Val_Always) return true; return false; } void DOMParser::setDoValidation(const bool newState) { fScanner->setDoValidation ( newState ? XMLScanner::Val_Always : XMLScanner::Val_Never ); } //doctypehandler interfaces void DOMParser::attDef ( const DTDElementDecl& elemDecl , const DTDAttDef& attDef , const bool ignoring ) { if (fDocumentType->isIntSubsetReading()) { DOMString attString; if (elemDecl.hasAttDefs()) { attString.appendData(chOpenAngle); attString.appendData(chBang); attString.appendData(XMLUni::fgAttListString); attString.appendData(chSpace); attString.appendData(elemDecl.getFullName()); attString.appendData(chSpace); attString.appendData(attDef.getFullName()); // Get the type and display it const XMLAttDef::AttTypes type = attDef.getType(); switch(type) { case XMLAttDef::CData : attString.appendData(chSpace); attString.appendData(XMLUni::fgCDATAString); break; case XMLAttDef::ID : attString.appendData(chSpace); attString.appendData(XMLUni::fgIDString); break; case XMLAttDef::IDRef : attString.appendData(chSpace); attString.appendData(XMLUni::fgIDRefString); break; case XMLAttDef::IDRefs : attString.appendData(chSpace); attString.appendData(XMLUni::fgIDRefsString); break; case XMLAttDef::Entity : attString.appendData(chSpace); attString.appendData(XMLUni::fgEntityString); break; case XMLAttDef::Entities : attString.appendData(chSpace); attString.appendData(XMLUni::fgEntitiesString); break; case XMLAttDef::NmToken : attString.appendData(chSpace); attString.appendData(XMLUni::fgNmTokenString); break; case XMLAttDef::NmTokens : attString.appendData(chSpace); attString.appendData(XMLUni::fgNmTokensString); break; case XMLAttDef::Notation : attString.appendData(chSpace); attString.appendData(XMLUni::fgNotationString); break; case XMLAttDef::Enumeration : attString.appendData(chSpace); // attString.appendData(XMLUni::fgEnumerationString); const XMLCh* enumString = attDef.getEnumeration(); int length = XMLString::stringLen(enumString); if (length > 0) { DOMString anotherEnumString; anotherEnumString.appendData(chOpenParen ); for(int i=0; i<length; i++) { if (enumString[i] == chSpace) anotherEnumString.appendData(chPipe); else anotherEnumString.appendData(enumString[i]); } anotherEnumString.appendData(chCloseParen); attString.appendData(anotherEnumString); } break; } //get te default types of the attlist const XMLAttDef::DefAttTypes def = attDef.getDefaultType(); switch(def) { case XMLAttDef::Required : attString.appendData(chSpace); attString.appendData(XMLUni::fgRequiredString); break; case XMLAttDef::Implied : attString.appendData(chSpace); attString.appendData(XMLUni::fgImpliedString); break; case XMLAttDef::Fixed : attString.appendData(chSpace); attString.appendData(XMLUni::fgFixedString); break; } const XMLCh* defaultValue = attDef.getValue(); if (defaultValue != 0) { attString.appendData(chSpace); attString.appendData(chDoubleQuote); attString.appendData(defaultValue); attString.appendData(chDoubleQuote); } attString.appendData(chCloseAngle); fDocumentType->internalSubset.appendData(attString); } } } void DOMParser::doctypeComment ( const XMLCh* const comment ) { if (fDocumentType->isIntSubsetReading()) { if (comment != 0) { DOMString comString; comString.appendData(XMLUni::fgCommentString); comString.appendData(chSpace); comString.appendData(comment); comString.appendData(chSpace); comString.appendData(chDash); comString.appendData(chDash); comString.appendData(chCloseAngle); fDocumentType->internalSubset.appendData(comString); } } } void DOMParser::doctypeDecl ( const DTDElementDecl& elemDecl , const XMLCh* const publicId , const XMLCh* const systemId , const bool hasIntSubset , const bool hasExtSubset ) { DOM_DocumentType dt; dt = fDocument.getImplementation().createDocumentType(elemDecl.getFullName(), publicId, systemId); fDocumentType = (DocumentTypeImpl*)dt.fImpl; ((DocumentImpl*)fDocument.fImpl)->setDocumentType(fDocumentType); } void DOMParser::doctypePI ( const XMLCh* const target , const XMLCh* const data ) { if (fDocumentType->isIntSubsetReading()) { //add these chars to internalSubset variable DOMString pi; pi.appendData(chOpenAngle); pi.appendData(chQuestion); pi.appendData(target); pi.appendData(chSpace); pi.appendData(data); pi.appendData(chQuestion); pi.appendData(chCloseAngle); fDocumentType->internalSubset.appendData(pi); } } void DOMParser::doctypeWhitespace ( const XMLCh* const chars , const unsigned int length ) { if (fDocumentType->isIntSubsetReading()) fDocumentType->internalSubset.appendData(chars); } void DOMParser::elementDecl ( const DTDElementDecl& decl , const bool isIgnored ) { if (fDocumentType->isIntSubsetReading()) { DOMString elemDecl; elemDecl.appendData(chOpenAngle); elemDecl.appendData(chBang); elemDecl.appendData(XMLUni::fgElemString); elemDecl.appendData(chSpace); elemDecl.appendData(decl.getFullName()); //get the ContentSpec information const XMLCh* contentModel = decl.getFormattedContentModel(); if (contentModel != 0) { elemDecl.appendData(chSpace); elemDecl.appendData(contentModel); } elemDecl.appendData(chCloseAngle); fDocumentType->internalSubset.appendData(elemDecl); } } void DOMParser::endAttList ( const DTDElementDecl& elemDecl ) { // this section sets up default attributes. // default attribute nodes are stored in a NamedNodeMap DocumentTypeImpl::elements // default attribute data attached to the document is used to conform to the // DOM spec regarding creating element nodes & removing attributes with default values // see DocumentTypeImpl if (elemDecl.hasAttDefs()) { XMLAttDefList* defAttrs = &elemDecl.getAttDefList(); XMLAttDef* attr = 0; AttrImpl* insertAttr = 0; DOM_Element dom_elem = fDocument.createElement(elemDecl.getFullName()); ElementImpl* elem = (ElementImpl*)(dom_elem.fImpl); for(unsigned int i=0; i<defAttrs->getAttDefCount(); i++) { attr = &defAttrs->getAttDef(i); if (attr->getValue() != null) { if (fScanner->getDoNamespaces()) { // DOM Level 2 wants all namespace declaration attributes // to be bound to "http://www.w3.org/2000/xmlns/" // So as long as the XML parser doesn't do it, it needs to // done here. DOMString qualifiedName = attr->getFullName(); int index = DocumentImpl::indexofQualifiedName(qualifiedName); XMLBuffer buf(1023, fMemoryManager); static const XMLCh XMLNS[] = { chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chNull}; if (index > 0) { // there is prefix // map to XML URI for all cases except when prefix == "xmlns" DOMString prefix = qualifiedName.substringData(0, index); if (prefix.equals(XMLNS)) buf.append(XMLUni::fgXMLNSURIName); else buf.append(XMLUni::fgXMLURIName); } else { // No prefix if (qualifiedName.equals(XMLNS)) buf.append(XMLUni::fgXMLNSURIName); } insertAttr = new (fMemoryManager) AttrNSImpl((DocumentImpl*)fDocument.fImpl, DOMString(buf.getRawBuffer()), // NameSpaceURI qualifiedName); // qualified name } else { // Namespaces is turned off... insertAttr = new (fMemoryManager) AttrImpl((DocumentImpl*)fDocument.fImpl, attr->getFullName()); } insertAttr->setValue(attr->getValue()); // memory leak here AttrImpl * previousAttr = elem->setAttributeNode(insertAttr); if ( previousAttr != 0 && previousAttr->nodeRefCount ==0) NodeImpl::deleteIf(previousAttr); insertAttr->setSpecified(false); } } ElementImpl *previousElem = (ElementImpl *) fDocumentType->getElements()->setNamedItem( elem ); // // If this new element is replacing an element node that was already // in the element named node map, we need to delete the original // element node, assuming no-one else was referencing it. // if (previousElem != 0 && previousElem->nodeRefCount == 0) NodeImpl::deleteIf(previousElem); } } void DOMParser::endIntSubset() { fDocumentType->intSubsetReading = false; } void DOMParser::endExtSubset() { } void DOMParser::entityDecl ( const DTDEntityDecl& entityDecl , const bool isPEDecl , const bool isIgnored ) { EntityImpl* entity = ((DocumentImpl*)fDocument.fImpl)->createEntity(entityDecl.getName()); entity->setPublicId(entityDecl.getPublicId()); entity->setSystemId(entityDecl.getSystemId()); entity->setNotationName(entityDecl.getNotationName()); EntityImpl *previousDef = (EntityImpl *) fDocumentType->entities->setNamedItem( entity ); // // If this new entity node is replacing an entity node that was already // in the entities named node map (happens if documents redefine the // predefined entited such as lt), we need to delete the original // entitiy node, assuming no-one else was referencing it. // if (previousDef != 0 && previousDef->nodeRefCount == 0) NodeImpl::deleteIf(previousDef); if (fDocumentType->isIntSubsetReading()) { //add thes chars to internalSubset variable DOMString entityName; entityName.appendData(chOpenAngle); entityName.appendData(chBang); entityName.appendData(XMLUni::fgEntityString); entityName.appendData(chSpace); entityName.appendData(entityDecl.getName()); DOMString id = entity->getPublicId(); if (id != 0) { entityName.appendData(chSpace); entityName.appendData(XMLUni::fgPubIDString); entityName.appendData(chSpace); entityName.appendData(chDoubleQuote); entityName.appendData(id); entityName.appendData(chDoubleQuote); } id = entity->getSystemId(); if (id != 0) { entityName.appendData(chSpace); entityName.appendData(XMLUni::fgSysIDString); entityName.appendData(chSpace); entityName.appendData(chDoubleQuote); entityName.appendData(id); entityName.appendData(chDoubleQuote); } id = entity->getNotationName(); if (id != 0) { entityName.appendData(chSpace); entityName.appendData(XMLUni::fgNDATAString); entityName.appendData(chSpace); entityName.appendData(chDoubleQuote); entityName.appendData(id); entityName.appendData(chDoubleQuote); } id = entityDecl.getValue(); if (id !=0) { entityName.appendData(chSpace); entityName.appendData(chDoubleQuote); entityName.appendData(id); entityName.appendData(chDoubleQuote); } entityName.appendData(chCloseAngle); fDocumentType->internalSubset.appendData(entityName); } } void DOMParser::resetDocType() { fDocumentType = null; } void DOMParser::notationDecl ( const XMLNotationDecl& notDecl , const bool isIgnored ) { NotationImpl* notation = ((DocumentImpl*)fDocument.fImpl)->createNotation(notDecl.getName()); notation->setPublicId(notDecl.getPublicId()); notation->setSystemId(notDecl.getSystemId()); NotationImpl *previousNot = (NotationImpl *) fDocumentType->notations->setNamedItem( notation ); // // If this new notation is replacing a notation node that was already // in the notation named node map, we need to delete the original // notation node, assuming no-one else was referencing it. // if (previousNot != 0 && previousNot->nodeRefCount == 0) NodeImpl::deleteIf(previousNot); } void DOMParser::startAttList ( const DTDElementDecl& elemDecl ) { } void DOMParser::startIntSubset() { fDocumentType->intSubsetReading = true; } void DOMParser::startExtSubset() { } void DOMParser::TextDecl ( const XMLCh* const versionStr , const XMLCh* const encodingStr ) { } // --------------------------------------------------------------------------- // DOMParser: Grammar preparsing methods // --------------------------------------------------------------------------- Grammar* DOMParser::loadGrammar(const char* const systemId, const short grammarType, const bool toCache) { // Avoid multiple entrance if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); Grammar* grammar = 0; try { fParseInProgress = true; grammar = fScanner->loadGrammar(systemId, grammarType, toCache); fParseInProgress = false; } catch(const OutOfMemoryException&) { throw; } catch(...) { fParseInProgress = false; throw; } return grammar; } Grammar* DOMParser::loadGrammar(const XMLCh* const systemId, const short grammarType, const bool toCache) { // Avoid multiple entrance if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); Grammar* grammar = 0; try { fParseInProgress = true; grammar = fScanner->loadGrammar(systemId, grammarType, toCache); fParseInProgress = false; } catch(const OutOfMemoryException&) { throw; } catch(...) { fParseInProgress = false; throw; } return grammar; } Grammar* DOMParser::loadGrammar(const InputSource& source, const short grammarType, const bool toCache) { // Avoid multiple entrance if (fParseInProgress) ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager); Grammar* grammar = 0; try { fParseInProgress = true; grammar = fScanner->loadGrammar(source, grammarType, toCache); fParseInProgress = false; } catch(const OutOfMemoryException&) { throw; } catch(...) { fParseInProgress = false; throw; } return grammar; } void DOMParser::resetCachedGrammarPool() { fGrammarResolver->resetCachedGrammar(); } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 1463 ] ] ]
d8c42306e5217ea5d53677ca7212f348962f169b
7b4d4c1d7bf7a2a145c2a5e2bd2b955eab97b0d2
/bfw/render_ogl/font_ft.cpp
4f853e280a440750c877efe7010fc852bb9d003c
[]
no_license
wangscript/bluefire
dd3eeb41443f93105e11d9ea74c017a08ed4bb80
71ba4125b30eb16ea01e1f0aaf09df749312a38e
refs/heads/master
2021-01-10T01:36:59.743592
2010-07-09T07:02:39
2010-07-09T07:02:39
50,160,614
0
0
null
null
null
null
UTF-8
C++
false
false
15,010
cpp
/* Bluefire: OpenGL Rendering Extention: FreeType2 Font Routines (c) Copyright 2006 Jacob Hipps Bluefire MDL Core: Winchester */ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../bluefire.h" #include "ogl.h" #include <freetype/freetype.h> #include <freetype/ftglyph.h> #include <freetype/ftoutln.h> #include <freetype/fttrigon.h> struct { float h; // Holds The Height Of The Font. GLuint ft_textures[128]; // Holds The Texture Id's GLuint list_base; // Holds The First Display List Id } ft_font; FT_Library library; // exported int bf_ft_init(); void bf_ft_kill(); void bf_ft_addfont(const char * fname, unsigned int h); void bf_ft_print(int font_id, float x, float y, const char *fmt, ...); void bf_ft_font_remove(); extern int atr_bfstate; // render state attribute index extern short bfstate; // render state bitmask // 1 = Lighting enabled // 2 = Texturing enabled #define update_state glVertexAttrib1sARB(atr_bfstate,bfstate) // local utility functions (private) void ft_make_dlist ( FT_Face face, char ch, GLuint list_base, GLuint * tex_base ); inline void pushScreenCoordinateMatrix(); inline void pop_projection_matrix(); inline int next_p2 (int a); int bf_ft_init() { BEGIN_FUNC("bf_ft_init") if(FT_Init_FreeType(&library)) { zlogthis("bf_ft_init: Error initializing FreeType. Type rasterization unavailable.\n"); return -1; } int vmaj, vmin, vpat; FT_Library_Version(library, &vmaj, &vmin, &vpat); zlogthis("bf_ft_init: FreeType %i.%i.%i initialized succesfully.\n",vmaj,vmin,vpat); END_FUNC return 0; } /* int bf_ft_open(char* filename, BF_FT_FONT* font_ptr) { BEGIN_FUNC("bf_ft_open") if(FT_New_Face(library, filename, 0, &font_ptr->face)) { zlogthis("bf_ttf_open: Error loading font from file \"%s\".\n",filename); } zlogthis("bf_ttf_open: Font \"%s\" opened.\n",filename); END_FUNC return 0; } */ /* int bf_ft_rasterize(BF_FT_FONT* font_ptr, int sz) { BEGIN_FUNC("bf_ft_rasterize") zlogthis("bf_ft_rasterize: Rasterizing font to %i pixels square.\n",sz); if(FT_Set_Pixel_Sizes(font_ptr->face, 0, sz)) { zlogthis("bf_ft_rasterize: Error setting font pixel parameters.\n"); } int i, chdex; font_ptr->sz = sz; font_ptr->glyph_sz = font_ptr->sz * font_ptr->sz; if((font_ptr->facedex = (char*)malloc(font_ptr->glyph_sz * 256)) == NULL) { zlogthis("bf_ft_rasterize: Memory allocation error!\n"); return -1; } memset(font_ptr->facedex, 0, font_ptr->glyph_sz * 256); int row, col; int xcz; int desty; FT_BBox bbox; for(i = 0; i < 256; i++) { chdex = FT_Get_Char_Index(font_ptr->face, i); FT_Load_Glyph(font_ptr->face, chdex, FT_LOAD_RENDER); font_ptr->kern[i] = font_ptr->face->glyph->metrics.width >> 6; //font_ptr->kern[i] = font_ptr->face->glyph->advance.x >> 6; //font_ptr->kern[i] = (font_ptr->face->glyph->metrics.horiAdvance >> 6) + (font_ptr->face->glyph->metrics.horiBearingX >> 6); //font_ptr->ybear[i] = font_ptr->face->glyph->metrics.horiBearingY >> 6; font_ptr->ybear[i] = font_ptr->face->glyph->bitmap_top - font_ptr->face->glyph->bitmap.rows; //font_ptr->face->glyph->bitmap.width + 3; // blit type two (16x16 glyph square block) row = (i / 16); col = (i % 16); zlogthis("%i '%c': (%i,%i) buffer = 0x%08x, size = %i x %i pixels, kern=%i, bmtop=%i\n",i,i,row,col,font_ptr->face->glyph->bitmap.buffer,font_ptr->face->glyph->bitmap.width,font_ptr->face->glyph->bitmap.rows,font_ptr->kern[i],font_ptr->ybear[i]); desty = font_ptr->sz - font_ptr->face->glyph->bitmap.rows; if(font_ptr->face->glyph->bitmap.buffer != 0) { for(xcz = 0; xcz < font_ptr->face->glyph->bitmap.rows; xcz++) { //memcpy(font_ptr->facedex + (row * 16 * font_ptr->glyph_sz) + (col * font_ptr->glyph_sz) + (xcz * 16 * font_ptr->sz), font_ptr->face->glyph->bitmap.buffer + (font_ptr->face->glyph->bitmap.width * xcz),font_ptr->face->glyph->bitmap.width); memcpy(font_ptr->facedex + (row * 16 * font_ptr->glyph_sz) + (font_ptr->sz * col) + (font_ptr->sz * 16 * desty), font_ptr->face->glyph->bitmap.buffer + (font_ptr->face->glyph->bitmap.width * xcz),font_ptr->face->glyph->bitmap.width); desty++; } } } // DUMPFILE for DEBUG <-----------------<---------<---------------------- DEBUG FILE *lizzy; if((lizzy = fopen("fdump.raw","wb")) == NULL) { zlogthis("could not open \"fdump.raw\" for writing!\n"); } else { fwrite(font_ptr->facedex,font_ptr->glyph_sz,256,lizzy); fclose(lizzy); } // DUMPFILE for DEBUG <-----------------<---------<---------------------- DEBUG // release the face FT_Done_Face(font_ptr->face); END_FUNC return 0; } */ /* void bf_ft_kill_font(BF_FT_FONT *font_ptr) { BEGIN_FUNC("bf_ft_kill_font") free(font_ptr->facedex); font_ptr->sz = 0; END_FUNC return; } */ void bf_ft_kill() { BEGIN_FUNC("bf_ft_kill") FT_Done_FreeType(library); END_FUNC return; } ////// new vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv NEHE void bf_ft_addfont(const char * fname, unsigned int h) { // Allocate Some Memory To Store The Texture Ids. //ft_font.ft_textures = new GLuint[128]; ft_font.h = h; // The Object In Which FreeType Holds Information On A Given // Font Is Called A "face". FT_Face face; // This Is Where We Load In The Font Information From The File. // Of All The Places Where The Code Might Die, This Is The Most Likely, // As FT_New_Face Will Fail If The Font File Does Not Exist Or Is Somehow Broken. if (FT_New_Face( library, fname, 0, &face )) { zlogthis("FT_New_Face failed (there is probably a problem with your font file)\n"); } // For Some Twisted Reason, FreeType Measures Font Size // In Terms Of 1/64ths Of Pixels. Thus, To Make A Font // h Pixels High, We Need To Request A Size Of h*64. // (h << 6 Is Just A Prettier Way Of Writing h*64) FT_Set_Char_Size( face, ft_font.h * 64.0f, ft_font.h * 64.0f, 96, 96); // Here We Ask OpenGL To Allocate Resources For // All The Textures And Display Lists Which We // Are About To Create. ft_font.list_base = glGenLists(128); glGenTextures( 128, ft_font.ft_textures ); // This Is Where We Actually Create Each Of The Fonts Display Lists. bfr_set_blending(BF_AMODE_LUMA); for(unsigned char i=0;i<128;i++) { ft_make_dlist(face,i,ft_font.list_base,ft_font.ft_textures); } bfr_set_blending(BF_AMODE_NORMAL); // We Don't Need The Face Information Now That The Display // Lists Have Been Created, So We Free The Assosiated Resources. FT_Done_Face(face); } void bf_ft_font_remove() { glDeleteLists(ft_font.list_base,128); glDeleteTextures(128,ft_font.ft_textures); //delete [] textures; } // Create A Display List Corresponding To The Given Character. void ft_make_dlist ( FT_Face face, char ch, GLuint list_base, GLuint * tex_base ) { // The First Thing We Do Is Get FreeType To Render Our Character // Into A Bitmap. This Actually Requires A Couple Of FreeType Commands: // Load The Glyph For Our Character. if(FT_Load_Glyph( face, FT_Get_Char_Index( face, ch ), FT_LOAD_DEFAULT )) { zlogthis("FT_Load_Glyph failed\n"); } // Move The Face's Glyph Into A Glyph Object. FT_Glyph glyph; if(FT_Get_Glyph( face->glyph, &glyph )) { zlogthis("FT_Get_Glyph failed\n"); } // Convert The Glyph To A Bitmap. FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1 ); FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph; // This Reference Will Make Accessing The Bitmap Easier. FT_Bitmap& bitmap=bitmap_glyph->bitmap; // Use Our Helper Function To Get The Widths Of // The Bitmap Data That We Will Need In Order To Create // Our Texture. //zlogthis("PRE width = %i, height(rows) = %i\n",bitmap.width,bitmap.rows); int width = next_p2( bitmap.width ); int height = next_p2( bitmap.rows ); // Allocate Memory For The Texture Data. GLubyte* expanded_data; if((expanded_data = (GLubyte*)malloc(2*width*height)) == NULL) { zlogthis("Memory allocation error in ft_make_dlist!!\n"); go_down(); } // Here We Fill In The Data For The Expanded Bitmap. // Notice That We Are Using A Two Channel Bitmap (One For // Channel Luminosity And One For Alpha), But We Assign // Both Luminosity And Alpha To The Value That We // Find In The FreeType Bitmap. // We Use The ?: Operator To Say That Value Which We Use // Will Be 0 If We Are In The Padding Zone, And Whatever // Is The FreeType Bitmap Otherwise. for(int j=0; j <height;j++) { for(int i=0; i < width; i++){ expanded_data[2*(i+j*width)]= expanded_data[2*(i+j*width)+1] = (i>=bitmap.width || j>=bitmap.rows) ? 0 : bitmap.buffer[i + bitmap.width*j]; } } //zlogthis("ch = %i, width = %i, height = %i\n",ch,width,height); // Now We Just Setup Some Texture Parameters. glBindTexture(GL_TEXTURE_2D, tex_base[ch]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //zlogthis("tex_base[ch] = %i\n",tex_base[ch]); // Here We Actually Create The Texture Itself, Notice // That We Are Using GL_LUMINANCE_ALPHA To Indicate That // We Are Using 2 Channel Data. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expanded_data ); // With The Texture Created, We Don't Need The Expanded Data Anymore. //delete [] expanded_data; free(expanded_data); glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); // Now We Create The Display List glNewList(ft_font.list_base+ch,GL_COMPILE); glBindTexture(GL_TEXTURE_2D,tex_base[ch]); //glBindTexture(GL_TEXTURE_2D,0); glPushMatrix(); // First We Need To Move Over A Little So That // The Character Has The Right Amount Of Space // Between It And The One Before It. glTranslatef(bitmap_glyph->left,0,0); // Now We Move Down A Little In The Case That The // Bitmap Extends Past The Bottom Of The Line // This Is Only True For Characters Like 'g' Or 'y'. glTranslatef(0,bitmap_glyph->top-bitmap.rows,0); // Now We Need To Account For The Fact That Many Of // Our Textures Are Filled With Empty Padding Space. // We Figure What Portion Of The Texture Is Used By // The Actual Character And Store That Information In // The x And y Variables, Then When We Draw The // Quad, We Will Only Reference The Parts Of The Texture // That Contains The Character Itself. float x=(float)bitmap.width / (float)width, y = (float)bitmap.rows / (float)height; // Here We Draw The Texturemapped Quads. // The Bitmap That We Got From FreeType Was Not // Oriented Quite Like We Would Like It To Be, // But We Link The Texture To The Quad // In Such A Way That The Result Will Be Properly Aligned. glBegin(GL_QUADS); update_state; glTexCoord2d(0,0); glVertex2f(0,bitmap.rows); glTexCoord2d(0,y); glVertex2f(0,0); glTexCoord2d(x,y); glVertex2f(bitmap.width,0); glTexCoord2d(x,0); glVertex2f(bitmap.width,bitmap.rows); glEnd(); glPopMatrix(); glTranslatef(face->glyph->advance.x >> 6 ,0,0); // Increment The Raster Position As If We Were A Bitmap Font. // (Only Needed If You Want To Calculate Text Length) // glBitmap(0,0,0,0,face->glyph->advance.x >> 6,0,NULL); // Finish The Display List glEndList(); } // Much Like NeHe's glPrint Function, But Modified To Work // With FreeType Fonts. void bf_ft_print(int font_id, float x, float y, const char *fmt, ...) { // We Want A Coordinate System Where Distance Is Measured In Window Pixels. pushScreenCoordinateMatrix(); GLuint font=ft_font.list_base; // We Make The Height A Little Bigger. There Will Be Some Space Between Lines. float h=ft_font.h/.63f; char text[512]; // Holds Our String va_list ap; // Pointer To List Of Arguments if (fmt == NULL) // If There's No Text *text=0; // Do Nothing else { va_start(ap, fmt); // Parses The String For Variables vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers va_end(ap); // Results Are Stored In Text } glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT); glMatrixMode(GL_MODELVIEW); bf_disable_lighting(); bf_enable_textures(); glDisable(GL_DEPTH_TEST); //glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); bfr_set_blending(BF_AMODE_LUMA); glListBase(font); float modelview_matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, modelview_matrix); // This Is Where The Text Display Actually Happens. // For Each Line Of Text We Reset The Modelview Matrix // So That The Line's Text Will Start In The Correct Position. // Notice That We Need To Reset The Matrix, Rather Than Just Translating // Down By h. This Is Because When Each Character Is // Drawn It Modifies The Current Matrix So That The Next Character // Will Be Drawn Immediately After It. //for(int i=0;i<lines.size();i++) { glPushMatrix(); glLoadIdentity(); glTranslatef(x,y,0); //glRasterPos2d(x, y); // set the position glMultMatrixf(modelview_matrix); // The Commented Out Raster Position Stuff Can Be Useful If You Need To // Know The Length Of The Text That You Are Creating. // If You Decide To Use It Make Sure To Also Uncomment The glBitmap Command // In make_dlist(). // glRasterPos2f(0,0); //glCallLists(lines[i].length(), GL_UNSIGNED_BYTE, lines[i].c_str()); glCallLists(strlen(text), GL_UNSIGNED_BYTE, text); // float rpos[4]; // glGetFloatv(GL_CURRENT_RASTER_POSITION ,rpos); // float len=x-rpos[0]; (Assuming No Rotations Have Happend) glPopMatrix(); //} glPopAttrib(); pop_projection_matrix(); bfr_set_blending(BF_AMODE_NORMAL); } // This Function Gets The First Power Of 2 >= The // Int That We Pass It. inline int next_p2 (int a ) { int rval=1; // rval<<=1 Is A Prettier Way Of Writing rval*=2; while(rval<a) rval<<=1; return rval; } // A Fairly Straightforward Function That Pushes // A Projection Matrix That Will Make Object World // Coordinates Identical To Window Coordinates. inline void pushScreenCoordinateMatrix() { glPushAttrib(GL_TRANSFORM_BIT); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(viewport[0],viewport[2],viewport[1],viewport[3]); glPopAttrib(); } // Pops The Projection Matrix Without Changing The Current // MatrixMode. inline void pop_projection_matrix() { glPushAttrib(GL_TRANSFORM_BIT); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); }
[ "tetrisfrog@989b7fda-6ebe-11de-b5d2-8dea7b56f9cf" ]
[ [ [ 1, 482 ] ] ]
4251dc49876ef3a3d3f9e4b49684272491534633
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/TeCom/src/TdkLayout/Source Files/TdkSelectedFeaturesProperty.cpp
32ab07af957a46d5496af356f690794160ff697f
[]
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
ISO-8859-2
C++
false
false
4,000
cpp
#include<TdkLayoutTypes.h> #include <TdkSelectedFeaturesProperty.h> /////////////////////////////////////////////////////////////////////////////// // Constructor //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// TdkSelectedFeaturesProperty::TdkSelectedFeaturesProperty(bool *necessaryRedraw, const std::string &value) { _propertyName="SelectedFeatures_Property"; _type=PText; _value=value; _necessaryRedraw=necessaryRedraw; } /////////////////////////////////////////////////////////////////////////////// // Destructor //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// TdkSelectedFeaturesProperty::~TdkSelectedFeaturesProperty() { } /////////////////////////////////////////////////////////////////////////////// // setValue //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// void TdkSelectedFeaturesProperty::setValue(const std::string &newVal) { _value=newVal; *_necessaryRedraw=true; } /////////////////////////////////////////////////////////////////////////////// // getValue //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// std::string TdkSelectedFeaturesProperty::getValue() { return _value; } /////////////////////////////////////////////////////////////////////////////// // getValue by reference //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// void TdkSelectedFeaturesProperty::getValue(std::string &value) { value=_value; } /////////////////////////////////////////////////////////////////////////////// // Equal operator //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// TdkSelectedFeaturesProperty& TdkSelectedFeaturesProperty::operator=(const TdkSelectedFeaturesProperty &other) { this->_value=other._value; return *this; } /////////////////////////////////////////////////////////////////////////////// // Equal operator //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// TdkSelectedFeaturesProperty& TdkSelectedFeaturesProperty::operator=(const TdkAbstractProperty &other) { this->_value=((TdkSelectedFeaturesProperty&)other)._value; return *this; } /////////////////////////////////////////////////////////////////////////////// // Split the selected features to n strings in vector //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// std::vector<std::string> TdkSelectedFeaturesProperty::split(const std::string &value) { std::vector<std::string> values; std::string curValue; unsigned int i; for(i=0;i<value.size();i++) { if(value[i]==';') { values.push_back(curValue); curValue.clear(); }else curValue+=value[i]; } if(!curValue.empty()) values.push_back(curValue); return values; } /////////////////////////////////////////////////////////////////////////////// // Get splited features //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// std::vector<std::string> TdkSelectedFeaturesProperty::getFeatures() { return this->split(_value); } /////////////////////////////////////////////////////////////////////////////// // Returns if vector of features are empty //Author : Rui Mauricio Gregório //Date : 08/2009 /////////////////////////////////////////////////////////////////////////////// bool TdkSelectedFeaturesProperty::empty() { return _value.empty(); }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 126 ] ] ]
5015f5205e8389d0616fbb5b2f1c111241fed55e
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-network/src/jingxian/utilities/NTService.cpp
caa6b227731f176c514b2be88eb78ce22a526fc4
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
GB18030
C++
false
false
16,209
cpp
# include "pro_config.h" # include <windows.h> # include <winsvc.h> # include "jingxian/lastError.h" # include "jingxian/logging/logging.h" # include "jingxian/utilities/NTService.h" _jingxian_begin #define SERVICE_NAME_SIZE 1024 static logging::logger* serviceLogger; static IInstance* serviceInstance; static SERVICE_STATUS serviceStatus; static SERVICE_STATUS_HANDLE serviceHandle; static TCHAR serviceName[SERVICE_NAME_SIZE]; static SERVICE_TABLE_ENTRY serviceTable[] = { { NULL, NULL }, { NULL, NULL } }; /** * 服务控制函数 */ static DWORD WINAPI serviceCtrlHandler(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) { serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; serviceStatus.dwCurrentState = SERVICE_RUNNING; serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; serviceStatus.dwWin32ExitCode = 0; serviceStatus.dwServiceSpecificExitCode = 0; serviceStatus.dwCheckPoint = 0; serviceStatus.dwWaitHint = 0; switch (dwControl) { case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_SHUTDOWN: //LOG_CRITICAL((*serviceLogger), serviceName << _T( " 服务收到停止请求!")); serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; serviceStatus.dwWaitHint = 4000; if (!SetServiceStatus(serviceHandle, &serviceStatus)) LOG_WARN((*serviceLogger), serviceName << _T(" 服务设置 'SERVICE_STOP_PENDING' 状态失败 - ") << lastError(GetLastError())); serviceInstance->interrupt(); break; default: serviceInstance->onControl(dwEventType, lpEventData); break; } return NO_ERROR; } /** * 服务入口函数 */ static VOID WINAPI serviceEntry(DWORD argc, LPTSTR *argv) { serviceHandle = RegisterServiceCtrlHandlerEx(serviceName, serviceCtrlHandler, NULL); if (0 == serviceHandle) { LOG_FATAL((*serviceLogger), serviceName << _T(" 服务注册控制回调失败 - ") << lastError(GetLastError())); return; } /* 启动服务 */ serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; serviceStatus.dwCurrentState = SERVICE_START_PENDING; serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; serviceStatus.dwWin32ExitCode = 0; serviceStatus.dwServiceSpecificExitCode = 0; serviceStatus.dwCheckPoint = 0; serviceStatus.dwWaitHint = 2000; if (!SetServiceStatus(serviceHandle, &serviceStatus)) { LOG_WARN((*serviceLogger), serviceName << _T(" 服务设置 'SERVICE_START_PENDING' 状态失败 - ") << lastError(GetLastError())); } /* 服务启行中 */ serviceStatus.dwCurrentState = SERVICE_RUNNING; serviceStatus.dwWaitHint = 0; if (!SetServiceStatus(serviceHandle, &serviceStatus)) { LOG_WARN((*serviceLogger), serviceName << _T(" 服务设置 'SERVICE_RUNNING' 状态失败 - ") << lastError(GetLastError())); } std::vector<tstring> arguments; for (DWORD i = 0; i < argc; ++ i) { arguments.push_back(argv[i]); } //LOG_CRITICAL((*serviceLogger), serviceName << _T( " 服务启动成功,正在运行中......")); serviceInstance->onRun(arguments); //LOG_CRITICAL((*serviceLogger), serviceName << _T( " 服务退出,运行结束!")); serviceStatus.dwCurrentState = SERVICE_STOPPED; serviceStatus.dwWin32ExitCode = 0; serviceStatus.dwCheckPoint = 0; serviceStatus.dwWaitHint = 0; if (!SetServiceStatus(serviceHandle, &serviceStatus)) LOG_FATAL((*serviceLogger), serviceName << _T(" 服务设置 'SERVICE_STOPPED' 状态失败 - ") << lastError(GetLastError())); } /** * 启动服务 */ int serviceMain(IInstance* instance) { int result = -1; if (NULL == serviceLogger) serviceLogger = new logging::logger(_T("jingxian.system")); if (0 != _tcscpy_s(serviceName, SERVICE_NAME_SIZE, instance->name().c_str())) { LOG_WARN((*serviceLogger), _T("启动服务时发生错误, 服务名 '") << instance->name() << _T("' 太长。")); SetLastError(ERROR_INVALID_NAME); result = -1; goto end; } serviceTable[0].lpServiceName = serviceName; serviceTable[0].lpServiceProc = serviceEntry; serviceInstance = instance; if (StartServiceCtrlDispatcher(serviceTable)) { result = 0; goto end; } //if(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT == GetLastError()) //{ // std::vector<tstring> arguments; // for(DWORD i = 0; i< argc; ++ i) // { // arguments.push_back(argv[i]); // } // instance->onRun(arguments); // // result = 0; // goto end; //} end: if (NULL != serviceLogger) delete serviceLogger; serviceLogger = NULL; return result; } bool waitForServiceState(SC_HANDLE hService, DWORD pendingState, SERVICE_STATUS& status) { if (!QueryServiceStatus(hService, &status)) return false; // 保存起始tick计数据和初始checkpoint. DWORD startTickCount = GetTickCount(); DWORD oldCheckPoint = status.dwCheckPoint; int tries = 60; // 轮询服务状态 while (status.dwCurrentState != pendingState) { // 计算等待时间( 1秒 到 10秒) status.dwWaitHint = 1000; Sleep(1000); // 再检测服务状态 if (!QueryServiceStatus(hService, &status)) return false; if (status.dwCheckPoint > oldCheckPoint) { // 服务前进一步了 startTickCount = GetTickCount(); oldCheckPoint = status.dwCheckPoint; tries = 60; } else if (--tries < 0) { break; } } return true; } void showServiceStatus(const tstring& msg, SERVICE_STATUS& status, tostream& out) { out << _T("CRIT ") << msg << _T(",") << _T(" 当前状态: "); switch (status.dwCurrentState) { case SERVICE_STOPPED: out << _T("已停止"); break; case SERVICE_START_PENDING: out << _T("启动中"); break; case SERVICE_STOP_PENDING: out << _T("停止中"); break; case SERVICE_RUNNING: out << _T("运行中"); break; case SERVICE_CONTINUE_PENDING: out << _T("恢复中"); break; case SERVICE_PAUSE_PENDING: out << _T("暂停中"); break; case SERVICE_PAUSED: out << _T("已暂停"); break; default: out << _T("未知"); break; } out << _T(",") << _T(" 退出代码: ") << status.dwWin32ExitCode << _T(",") << _T(" 服务退出代码: ") << status.dwServiceSpecificExitCode << _T(",") << _T(" 检测点: ") << status.dwCheckPoint << _T(",") << _T(" 等待次数据: ") << status.dwWaitHint << std::endl; } int installService(const tstring& name , const tstring& display , const tstring& description , const tstring& executable , const std::vector<tstring>& args , tostream& out) { if (name.size() >= 254) { out << _T("安装服务 '") << name << _T("' 失败 - 服务名太长!") << std::endl; return -1; } tstring disp = display; if (disp.empty()) { disp = name; } tstring exec = executable; if (exec.empty()) { // 使用本执行文件 tchar buf[_MAX_PATH]; if (GetModuleFileName(NULL, buf, _MAX_PATH) == 0) { out << _T("ERROR 安装服务 '") << name << _T("' 失败 - 没有执行文件名!") << std::endl; return -1; } exec = buf; } // 如果有空格的话加上引号 tstring command; if (executable.find(_T(' ')) != tstring::npos) { command.push_back(_T('"')); command.append(exec); command.push_back(_T('"')); } else { command = exec; } // 拼上选项字符串 for (std::vector<tstring>::const_iterator p = args.begin(); p != args.end(); ++p) { command.push_back(_T(' ')); if (p->find_first_of(_T(" \t\n\r")) != tstring::npos) { command.push_back(_T('"')); command.append(*p); command.push_back(_T('"')); } else { command.append(*p); } } SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hSCM == NULL) { out << _T("ERROR 安装服务 '") << name << _T("' 失败,不能打开 SCM - ") << ::lastError(GetLastError()) << std::endl; return -1; } SC_HANDLE hService = CreateService( hSCM, name.c_str(), disp.c_str(), SC_MANAGER_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, command.c_str(), NULL, NULL, NULL, NULL, NULL); if (hService == NULL) { out << _T("ERROR 安装服务 '") << name << _T("' 失败,不能创服务实例 - ") << ::lastError(GetLastError()) << std::endl; CloseServiceHandle(hSCM); return -1; } if (!description.empty()) { SERVICE_DESCRIPTION descr; descr.lpDescription = (tchar*)description.c_str(); if (!ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr)) { out << _T("WARN 安装服务 '") << name << _T("' 时,添加描述失败 - ") << ::lastError(GetLastError()) << std::endl; } } CloseServiceHandle(hSCM); CloseServiceHandle(hService); out << _T("CRIT 安装服务 '") << name << _T("' 成功") << std::endl; return 0; } int uninstallService(const tstring& name, tostream& out) { SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hSCM == NULL) { out << _T("ERROR 卸载服务 '") << name << _T("' 失败,不能打开 SCM - ") << ::lastError(GetLastError()) << std::endl; return -1; } SC_HANDLE hService = OpenService(hSCM, name.c_str(), SC_MANAGER_ALL_ACCESS); if (hService == NULL) { out << _T("ERROR 卸载服务 '") << name << _T("' 失败,不能打开服务 - ") << ::lastError(GetLastError()) << std::endl; CloseServiceHandle(hSCM); return -1; } BOOL b = DeleteService(hService); if (!b) { out << _T("ERROR 卸载服务 '") << name << _T("' 失败,不能删除服务 - ") << ::lastError(GetLastError()) << std::endl; } else { out << _T("CRIT 卸载服务 '") << name << _T("' 成功") << std::endl; } CloseServiceHandle(hSCM); CloseServiceHandle(hService); return (b ? 0 : -1); } int startService(const tstring& name, const std::vector<tstring>& args, tostream& out) { SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hSCM == NULL) { out << _T("ERROR 启动服务 '") << name << _T("' 失败,不能打开 SCM - ") << ::lastError(GetLastError()) << std::endl; return -1; } SC_HANDLE hService = OpenService(hSCM, name.c_str(), SC_MANAGER_ALL_ACCESS); if (hService == NULL) { out << _T("ERROR 启动服务 '") << name << _T("' 失败,不能打开服务 - ") << ::lastError(GetLastError()) << std::endl; CloseServiceHandle(hSCM); return -1; } // 将字符串拼成 char* []形式 const size_t argc = args.size(); const tchar** argv = new const tchar*[argc]; size_t i = 0; for (std::vector<tstring>::const_iterator p = args.begin(); p != args.end(); ++p) { argv[i++] = string_traits<tchar>::strdup(p->c_str()); } // 启动服务 BOOL b = StartService(hService, (DWORD)argc, argv); // 释放内存 for (i = 0; i < argc; ++i) { string_traits<tchar>::free((tchar*)argv[i]); } delete[] argv; if (!b) { out << _T("ERROR 启动服务 '") << name << _T("' 失败 - ") << ::lastError(GetLastError()) << std::endl; CloseServiceHandle(hService); CloseServiceHandle(hSCM); return -1; } out << _T("TRACE 服务正在启动中,请稍等...") << std::endl; SERVICE_STATUS status; if (!waitForServiceState(hService, SERVICE_RUNNING, status)) { out << _T("ERROR 启动服务 '") << name << _T("' 失败, 检测服务状态发生错误 - ") << ::lastError(GetLastError()) << std::endl; CloseServiceHandle(hService); CloseServiceHandle(hSCM); return -1; } CloseServiceHandle(hService); CloseServiceHandle(hSCM); if (status.dwCurrentState == SERVICE_RUNNING) { out << _T("CRIT 启动服务 '") << name << _T("' 成功, 服务运行中.") << std::endl; } else { showServiceStatus(_T("服务器启动发生错误"), status, out); return -1; } return 0; } int stopService(const tstring& name, tostream& out) { SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hSCM == NULL) { out << _T("ERROR 停止服务 '") << name << _T("' 失败, 不能打开 SCM - ") << lastError(GetLastError()) << std::endl; return -1; } SC_HANDLE hService = OpenService(hSCM, name.c_str(), SC_MANAGER_ALL_ACCESS); if (hService == NULL) { out << _T("ERROR 停止服务 '") << name << _T("' 失败, 不能打开服务 - ") << lastError(GetLastError()) << std::endl; CloseServiceHandle(hSCM); return -1; } SERVICE_STATUS status; BOOL b = ControlService(hService, SERVICE_CONTROL_STOP, &status); if (!b) { out << _T("ERROR 停止服务 '") << name << _T("' 失败 - ") << lastError(GetLastError()) << std::endl; CloseServiceHandle(hSCM); CloseServiceHandle(hService); return -1; } out << _T("TRACE 服务停止中,请稍等...") << std::endl; //// //// 等待服务停止或发生一个错误 //// //if(!waitForServiceState(hService, SERVICE_STOP_PENDING, status)) //{ // LOG_ERROR(logger_, _T("停止服务 '") << name <<_T("' 失败,检测服务状态发生错误 - ") << lastError(GetLastError()) << std::endl; // CloseServiceHandle(hService); // CloseServiceHandle(hSCM); // return -1; //} if (!waitForServiceState(hService, SERVICE_STOPPED, status)) { out << _T("ERROR 停止服务 '") << name << _T("' 失败,检测服务状态发生错误 - ") << lastError(GetLastError()) << std::endl; CloseServiceHandle(hService); CloseServiceHandle(hSCM); return -1; } CloseServiceHandle(hService); CloseServiceHandle(hSCM); if (status.dwCurrentState == SERVICE_STOPPED) { out << _T("CRIT 停止服务 '") << name << _T("' 成功.") << std::endl; } else { showServiceStatus(_T("服务器停止发生错误"), status, out); return -1; } return 0; } _jingxian_end
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 521 ] ] ]
8c710477f8d07c9a49059303c3208f1605b8dfcb
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/examples/Castles/CastlesClient/src/main.cpp
ed64ecb095cd5edd7da8f1b4fb60554acbad4865
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
21,835
cpp
#include "Engine.h" #include "Graphics/Light/PointLight.h" #include "Graphics/Renderer/ForwardRenderer.h" #include "Graphics/GUI/ProgressBar.h" #include "SceneGraph/TraverseVisitor.h" #include "Database/Collada.h" #include <SDL.h> #include <SDL_main.h> #include "Network.h" // platform specified #ifdef WIN32 #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #undef CreateFont using namespace std; using namespace net; using namespace gmath; using namespace slon; using namespace graphics; using namespace gui; using boost::asio::ip::tcp; struct Player { int health; }; typedef boost::intrusive_ptr<sg::MatrixTransform> matrix_transform_ptr; // settings unsigned screenWidth; unsigned screenHeight; float fps; bool working; bool restart; bool keys[1024]; // game int ourId; Player players[2]; // scene boost::intrusive_ptr<ForwardRenderer> renderer; boost::intrusive_ptr<sg::MatrixTransform> sceneRoot; // gui sgl::ref_ptr<sgl::Font> font; boost::shared_ptr<ProgressBar> powerGauge; // states bool gameStarted; bool freeLook; int win; bool ourTurn; float chargeTime; bool fire; bool isCharging; Vector3f position; Vector3f direction; Vector3f up; sgl::ref_ptr<sgl::ClearColorState> clearColorState; sgl::ref_ptr<sgl::VertexColorState> vertexColorState; sgl::ref_ptr<sgl::ProjectionMatrixState> projectionTransform; // game data std::vector<matrix_transform_ptr> objects; int canonId; int kernelId; int playerHealth[2]; matrix_transform_ptr canonTransform; Vector3f canonDirection; // settings bool fixedPipeline; // network boost::asio::io_service ioService; tcp::socket castlesSocket(ioService); void HandleEvents(float time) { // events SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { /* SDL_QUIT event (window close) */ case SDL_QUIT: working = false; break; case SDL_KEYDOWN: keys[event.key.keysym.sym] = true; break; case SDL_KEYUP: keys[event.key.keysym.sym] = false; break; case SDL_MOUSEBUTTONDOWN: if (ourTurn) { isCharging = true; chargeTime = time; } break; case SDL_MOUSEBUTTONUP: if (isCharging) { fire = true; isCharging = false; } break; case SDL_MOUSEMOTION: { if (event.motion.x != screenWidth/2 || event.motion.y != screenHeight/2) { Vector2f rel = Vector2f( (float)-event.motion.xrel, (float)event.motion.yrel ); direction = Mat3f::rotate_y(rel.x * 0.002f) * direction; SDL_WarpMouse(screenWidth/2, screenHeight/2); float value = sqrtf(canonDirection.x * canonDirection.x + canonDirection.z * canonDirection.z); canonDirection = Vector3f(direction.x * value, canonDirection.y, direction.z * value); canonDirection = Mat3f::rotate( -rel.y * 0.002f, cross(canonDirection, Vector3f(0.0, 1.0, 0.0)) ) * canonDirection; canonDirection = clamp( canonDirection, Vector3f(-1.0f, 0.2f, -1.0f), Vector3f(1.0f, 0.7f, 1.0f) ); normalize(canonDirection); } break; } default: break; } } // fire if power is to much if (isCharging && time - chargeTime >= 5.0f) { fire = true; isCharging = false; } } void HandleInput(float time) { static float lastTime = time; float dt = time - lastTime; if ( keys[SDLK_w] ) { position += direction * 60.0f * dt; } if ( keys[SDLK_s] ) { position -= direction * 60.0f * dt; } if ( keys[SDLK_a] ) { position += cross(up, direction) * 60.0f * dt; } if ( keys[SDLK_d] ) { position -= cross(up, direction) * 60.0f * dt; } if ( keys[SDLK_r] ) { position += up * 60.0f * dt; } if ( keys[SDLK_f] ) { position -= up * 60.0f * dt; } if ( keys[SDLK_SPACE] ) { freeLook = !freeLook; keys[SDLK_SPACE] = false; } if ( keys[SDLK_1] ) { freeLook = false; keys[SDLK_1] = false; } if ( keys[SDLK_2] ) { freeLook = true; keys[SDLK_2] = false; } if ( keys[SDLK_ESCAPE] ) { working = false; keys[SDLK_ESCAPE] = false; } lastTime = time; } void RenderCommon(float time) { glDisable(GL_CULL_FACE); // font color vertexColorState->SetColor(1.0, 1.0, 0.0, 1.0); vertexColorState->Setup(); static float lastTime = time; static int frames = 0; ++frames; if ( time - lastTime > 0.5f ) { fps = 2.0f * frames / (1.0f + (time - lastTime - 0.5f) / 0.5f); frames = 0; lastTime = time; } // draw fps { ostringstream ss; ss << "FPS: " << fps << endl; font->Bind(10, 12); font->Print( screenWidth / 2.0f - 40.0f, 10.0f, ss.str() ); font->Unbind(); } vertexColorState->SetColor(1.0, 0.5, 0.0, 1.0); vertexColorState->Setup(); // draw our health { ostringstream ss; ss << "Player HP: " << playerHealth[ourId] << endl; font->Bind(15, 20); font->Print( 30.0f, 20.0f, ss.str() ); font->Unbind(); } // draw opponent health { ostringstream ss; ss << "Opponent HP: " << playerHealth[1 - ourId] << endl; font->Bind(15, 20); font->Print( screenWidth - 200.0f, 20.0f, ss.str() ); font->Unbind(); } // draw turn notice if (ourTurn) { float opacity = (sin(time * 0.2f) + 1.0f) / 2.0f; vertexColorState->SetColor(0.0, 1.0, 0.0, opacity); vertexColorState->Setup(); font->Bind(20, 30); font->Print(screenWidth / 2.0f - 50.0f, 30.0f, "Fire Now!"); font->Unbind(); if (isCharging) { powerGauge->SetValue( (time - chargeTime) / 5.0f ); } else { powerGauge->SetValue(0.0f); } powerGauge->Draw(); } if (win > 0) { vertexColorState->SetColor(0.0f, 1.0f, 0.0f, 1.0f); vertexColorState->Setup(); font->Bind(10, 12); font->Print(5.0f, 5.0f, "You are victorious!"); font->Unbind(); } else if (win < 0) { vertexColorState->SetColor(1.0f, 0.0f, 0.0f, 1.0f); vertexColorState->Setup(); font->Bind(10, 12); font->Print(5.0f, 5.0f, "You loose!"); font->Unbind(); } } void RenderScene(float time) { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT ); //renderer->renderScene(); RenderCommon(time); SDL_GL_SwapBuffers(); } void UpdateScene(float /*time*/) { if ( !freeLook ) { position = ( canonTransform->getLocalToWorldTransform() * invert( sceneRoot->getTransformMatrix() ) ).translation(); Matrix4f cameraTransform = Mat4f::look_at( position - direction * 30.0f + Vector3f(0.0, 7.0f, 0.0f), position + Vector3f(0.0f, 6.0f, 0.0f), up ); sceneRoot->setTransformMatrix(cameraTransform); position = canonTransform->getTransformMatrix().translation(); canonTransform->setTransformMatrix( Mat4f::frame(position, canonDirection, up) ); } else { Matrix4f cameraTransform = Mat4f::look_at(position, position + direction, up); sceneRoot->setTransformMatrix(cameraTransform); } } void ConnectToServer(const std::string& serverName) { // connect tcp::resolver resolver(ioService); tcp::resolver::query query(serverName, castles_service); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; // connect boost::system::error_code error = boost::asio::error::host_not_found; while (error && endpoint_iterator != end) { castlesSocket.close(); castlesSocket.connect(*endpoint_iterator++, error); } if (error) { throw boost::system::system_error(error); } // now we must get the greeting message if ( read_header(castlesSocket) == player_state_desc::header ) { player_state_desc desc; desc.read(castlesSocket); if ( desc.state != player_state_desc::CREATE ) { throw std::runtime_error("Server doesn't send the greeting message"); } // init players ourId = desc.id; players[0].health = players[1].health = 100; } else { throw std::runtime_error("Server doesn't send the greeting message"); } } bool ReadServerMessages(float /*time*/) { // get server messages if ( castlesSocket.available() > 0 ) { if ( !gameStarted ) { gameStarted = true; } // receive sync stamp read_sync_stamp(castlesSocket); bool busy = true; while (busy) { switch( read_header(castlesSocket) ) { case object_transform_desc::header: { // find object & add it to the scene object_transform_desc desc; desc.read(castlesSocket); assert( static_cast<size_t>(desc.id) < objects.size() && desc.id >= 0 ); if ( static_cast<size_t>(desc.id) >= objects.size() || desc.id < 0 ) { cerr << "invalid object transfom desc - ignored" << endl; break; } objects[desc.id]->setTransformMatrix( desc.matrix ); break; } case player_state_desc::header: { player_state_desc desc; desc.read(castlesSocket); if (desc.state == player_state_desc::TURN) { ourTurn = true; } else if (desc.state == player_state_desc::WIN) { win = 1; } else if (desc.state == player_state_desc::LOOSE) { win = -1; } else if (desc.state == player_state_desc::EXIT) { // server restart working = false; restart = true; } break; } case player_damage_desc::header: { player_damage_desc desc; desc.read(castlesSocket); playerHealth[desc.id] = desc.health; break; } case object_desc::header: { // find object & add it to the scene object_desc desc; desc.read(castlesSocket); assert( objects.size() == desc.id ); if ( objects.size() != desc.id ) { cerr << "invalid object desc - ignored" << endl; break; } sg::MatrixTransform* transform = dynamic_cast<sg::MatrixTransform*>( sg::findNamedNode(sceneRoot.get(), desc.nodeName) ); if ( desc.clone ) { sg::MatrixTransform* newTransform = new sg::MatrixTransform(); newTransform->setTransformMatrix(desc.matrix); for(size_t i = 0; i<transform->getNumChildren(); ++i) { graphics::Mesh* mesh = dynamic_cast<graphics::Mesh*>( transform->getChild(i) ); if (mesh) { graphics::Mesh* clone = new graphics::Mesh(*mesh); newTransform->addChild(clone); } } sceneRoot->addChild(newTransform); objects.push_back( matrix_transform_ptr(newTransform) ); } else { if ( desc.id != kernelId ) { transform->getParent()->removeChild(transform); sceneRoot->addChild(transform); } objects.push_back( matrix_transform_ptr(transform) ); } break; } case sync_stamp: { busy = false; break; } default: throw std::runtime_error("Unexpected server message"); } } return true; } return false; } void handle_write() { } void SynchroniseWithServer(float time) { // get server messages static float lastSync = time; if (gameStarted) { lastSync = time; std::string message = make_message(sync_stamp); object_transform_desc desc; desc.id = canonId; desc.matrix = canonTransform->getTransformMatrix(); message += desc.message(); // if fired if (fire) { fire_canon_desc desc; desc.playerId = ourId; desc.impulse = (time - chargeTime + 1.0f) * 10000.0f; message += desc.message(); ourTurn = fire = false; } message += make_message(sync_stamp); boost::asio::write(castlesSocket, boost::asio::buffer(message)); } } void CreateScene() { boost::shared_ptr<Engine> pEngine = Engine::Instance(); // create renderer renderer.reset( new graphics::ForwardRenderer() ); // create scene root sceneRoot.reset( new sg::MatrixTransform() ); sgl::Light* light = pEngine->sglDevice()->CreateLight(); light->SetAmbient( Vector4f(0.0f, 0.0f, 0.0f, 0.0f) ); light->SetDiffuse( Vector4f(1.0f, 1.0f, 1.0f, 1.0f) ); light->SetSpecular( Vector4f(1.0f, 1.0f, 1.0f, 1.0f) ); light->SetPosition( Vector4f(-1000.0f, 1000.0f, 600.0f, 1.0f) ) ; sceneRoot->addChild( new PointLight(light) ); // transform clearColorState.reset( pEngine->sglDevice()->CreateClearColorState() ); vertexColorState.reset( pEngine->sglDevice()->CreateVertexColorState() ); projectionTransform.reset( pEngine->sglDevice()->CreateProjectionMatrixState() ); projectionTransform->SetMatrix( Mat4f::perspective(0.7853982f, 1.33f, 1.0f, 2000.0f) ); projectionTransform->Setup(); position = Vector3f(0.0f, 50.0f, 0.0f); direction = canonDirection = Vector3f(0.0f, 0.0, 1.0f); up = Vector3f(0.0f, 1.0f, 0.0f); // create font font.reset( pEngine->sglDevice()->CreateFont() ); font->LoadFromFile("data/fonts/font.png"); // create gauge powerGauge.reset( new ProgressBar( pEngine->sglDevice() ) ); powerGauge->SetFont( font.get() ); powerGauge->SetText( "Fire power" ); powerGauge->SetBorderColor(1.0f, 1.0f, 0.0f, 1.0f); powerGauge->SetColor(1.0f, 0.0f, 0.0f, 1.0f); powerGauge->SetPosition(screenWidth / 4 + 40, screenHeight - 30); powerGauge->SetSize(screenWidth / 2, 15); // default health playerHealth[0] = playerHealth[1] = 100; ourTurn = false; // fill keys fill(keys, keys + 1024, false); // hide cursor SDL_ShowCursor(false); // read scene while ( castlesSocket.available() > 0 ) { switch( read_header(castlesSocket) ) { case canon_desc::header: { // find canon canon_desc desc; desc.read(castlesSocket); canonId = desc.id; break; } case player_state_desc::header: { player_state_desc desc; desc.read(castlesSocket); if (desc.state == player_state_desc::TURN) { ourTurn = true; } break; } case kernel_desc::header: { // find kernel kernel_desc desc; desc.read(castlesSocket); kernelId = desc.id; break; } case sky_box_desc::header: { // create sky box sky_box_desc desc; desc.read(castlesSocket); SkyBox* skyBox = new SkyBox(); skyBox->MakeFromSideTextures(desc.maps); sceneRoot->addChild(skyBox); break; } case mesh_desc::header: { // load mesh mesh_desc desc; desc.read(castlesSocket); db::LoadColladaScene( desc.fileName, *sceneRoot ); sg::TraverseVisitor visitor; sceneRoot->accept(visitor); break; } case object_desc::header: { // find object & add it to the scene object_desc desc; desc.read(castlesSocket); assert( objects.size() == desc.id ); sg::MatrixTransform* transform = dynamic_cast<sg::MatrixTransform*>( sg::findNamedNode(sceneRoot.get(), desc.nodeName) ); transform->setTransformMatrix(desc.matrix); if ( desc.id != kernelId ) { transform->getParent()->removeChild(transform); sceneRoot->addChild(transform); } objects.push_back( matrix_transform_ptr(transform) ); break; } default: throw std::runtime_error("Unexpected server message"); } } // find canon transform canonTransform = objects[canonId]; // we have read all write_sync_stamp(castlesSocket); // setup data Engine::Instance()->setSceneRoot( sceneRoot.get() ); cerr << "scene created" << endl; } void UpdateAll(float time) { HandleEvents(time); bool newMessages = ReadServerMessages(time); UpdateScene(time); SynchroniseWithServer(time); HandleInput(time); } void Run() { working = true; freeLook = false; gameStarted = false; restart = false; win = 0; while (working) { float time = SDL_GetTicks() / 1000.0f; UpdateAll(time); RenderScene(time); } // close connection if ( castlesSocket.is_open() ) { write_sync_stamp(castlesSocket); player_state_desc desc; desc.id = ourId; desc.state = player_state_desc::EXIT; desc.write(castlesSocket); castlesSocket.close(); } } int main(int argc, char** argv) { //freopen("err.txt", "w", stderr); cout << "Initialization started" << endl; // create engine first boost::shared_ptr<Engine> pEngine = Engine::Instance(); int multisample = 3; bool fullscreen = false; fixedPipeline = false; screenWidth = 800; screenHeight = 600; // check settings std::string serverName; for(int i = 1; i<argc; ++i) { std::string argstr = std::string(argv[i]); if ( argstr == "-nm" ) { multisample = 0; } else if ( argstr == "-f" ) { const SDL_VideoInfo* vInfo = SDL_GetVideoInfo(); screenWidth = vInfo->current_w; screenHeight = vInfo->current_h; fullscreen = true; } else if ( argstr == "-l" ) { fixedPipeline = true; } else { serverName = argstr; } } if ( serverName.empty() ) { cerr << "Usage: castles.exe <server> [-nm] [-f]" << endl; return 1; } try { ConnectToServer(serverName); cerr << "connection to server established" << endl; } catch(boost::system::system_error& err) { cerr << "Application error: " << err.what() << endl; return 1; } pEngine->setVideoMode(screenWidth, screenHeight, 32, fullscreen, false, multisample); cerr << "video mode set" << endl; try { CreateScene(); } catch(std::runtime_error& err) { cerr << "Application error: " << err.what() << endl; return 1; } /* boost::asdb::socket_base::send_buffer_size option(512); castlesSocket.set_option(option); boost::asdb::socket_base::receive_buffer_size option; castlesSocket.get_option(option); int size = option.value(); cerr << "size: " << size << endl; */ // run main loop try { restart = true; while (restart) { // run main loop Run(); if (restart) { ConnectToServer(serverName); } } } catch(std::exception& err) { cerr << "Application error: " << err.what() << ". Player " << ourId << endl; return 0; } return 0; }
[ "devnull@localhost" ]
[ [ [ 1, 790 ] ] ]
8e0e31c44b734213012dc7d41a1620090daf0a4f
181591fda703815efe00304db5f477301a97b0f1
/assign3.cpp
2605bba572c5fdfd8fbe5e2ecac89d318b0f8e1f
[]
no_license
pgiitu/Recursive-Ray-Tracer-OPen-Gl
db3c8f8e80aa8cb4bdc4aae11b6b400b68ab3cba
bad5cc3fc2bef9d6f4c8785445ff262e79c6c1f8
refs/heads/master
2016-08-04T04:28:52.282156
2011-11-11T22:04:54
2011-11-11T22:04:54
2,758,830
0
0
null
null
null
null
UTF-8
C++
false
false
26,342
cpp
/* Author: Frank Pfenning */ #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <string.h> #include <math.h> #include "pic.h" #include <iostream> #include <stdio.h> #include "ray.h" #include "vector.h" #include "intersection_point.h" using namespace std; #define MAX_TRIANGLES 10000 #define MAX_SPHERES 10000 #define MAX_LIGHTS 10000 #define no_intersection 99999999.23372637 #define sqrt3 1.732050808 #define max_intersection 99999999 char *filename=0; //different display modes #define MODE_DISPLAY 1 #define MODE_JPEG 2 int mode=MODE_DISPLAY; //you may want to make these smaller for debugging purposes #define WIDTH 640 #define HEIGHT 480 //the field of view of the camera #define fov 75.0 #define PLANE_DIST 1.0 unsigned char buffer[HEIGHT][WIDTH][3]; enum shadow { NOT_BLOCKED = 1, BLOCKED=0 }; struct Vertex { double position[3]; double color_diffuse[3]; double color_specular[3]; double normal[3]; double shininess; }; struct ray_color { vector color; ray r; }; struct plane { // for equation of a plane ax+by+cz=d double a; double b; double c; double d; }; typedef struct _Triangle { struct Vertex v[3]; // for equation of a plane ax+by+cz=d struct plane p; } Triangle; typedef struct _Sphere { double position[3]; double color_diffuse[3]; double color_specular[3]; double shininess; double radius; } Sphere; typedef struct _Light { double position[3]; double color[3]; } Light; Triangle triangles[MAX_TRIANGLES]; Sphere spheres[MAX_SPHERES]; Light lights[MAX_LIGHTS]; double ambient_light[3]; int num_triangles=0; int num_spheres=0; int num_lights=0; int Depth=1; bool flag=true; vector RT_shading(intersection_point p,ray r,int depth); vector Recursive_RT(ray r,int depth); /* * function to store the coefficients of a plane equation ax+by+cz=d for a * triangle with index i in the array of traingles */ void calculate_plane_coefficient(int i) { vector v0(triangles[i].v[0].position[0],triangles[i].v[0].position[1],triangles[i].v[0].position[2]); vector v1(triangles[i].v[1].position[0],triangles[i].v[1].position[1],triangles[i].v[1].position[2]); vector v2(triangles[i].v[2].position[0],triangles[i].v[2].position[1],triangles[i].v[2].position[2]); vector t1=v1.subtract(v0); vector t2=v2.subtract(v0); vector n=t2.cross_product(t1); n=n.normalize(); triangles[i].p.a=n.x; triangles[i].p.b=n.y; triangles[i].p.c=n.z; triangles[i].p.d=-v0.dot_product(n); } /* * Given a ray function calculates the intersection with a triangle * with index i in the array of triangles */ double intersection_with_triangle(ray r,int i) { //first we will find intersection with plane vector d=(r.end).subtract(r.start); //direction vector vector v0(triangles[i].v[0].position[0],triangles[i].v[0].position[1],triangles[i].v[0].position[2]); vector v1(triangles[i].v[1].position[0],triangles[i].v[1].position[1],triangles[i].v[1].position[2]); vector v2(triangles[i].v[2].position[0],triangles[i].v[2].position[1],triangles[i].v[2].position[2]); vector n(triangles[i].p.a,triangles[i].p.b,triangles[i].p.c); double a=n.dot_product(r.start); double b=n.dot_product(d); if(b==0.0) { return no_intersection; } //here i have missed a condition need to take care of it double t=-(triangles[i].p.d+a)/b; // t gives us the point of intersection if(t>0.0) //if t is greater than one then only we will check whether the point lies in the triangle or not { vector u=v1.subtract(v0); vector v=v2.subtract(v0); vector intersection_point(r.start.x+d.x*t,r.start.y+d.y*t,r.start.z+d.z*t); //P_I=s*u+t1*v+P0 vector diff=intersection_point.subtract(v0); //diff=s*u+t1*v /* double t1=(diff.y*u.x-diff.x)/(v.y*u.x-v.x); double s=(diff.x-t1*v.x)/u.x; */ double den=v.dot_product(v)*u.dot_product(u)-pow(v.dot_product(u),2); double s=(u.dot_product(u)*diff.dot_product(v)-u.dot_product(v)*diff.dot_product(u))/den; double t1=(v.dot_product(v)*diff.dot_product(u)-v.dot_product(u)*diff.dot_product(v))/den; if(!(s<0 || s>1.0 || t1<0 || t1>1.0 || ((s+t1)>1.0))) { //the ray intersect the triangle return t; } } return no_intersection; } /* * function to return the interpolated value of the various coefficients and normal for a triangle with index i in the array of triangles * index=1 Interpolate Normal * index=2 Interpolate diffusion constant * index=3 Interpolate Specular constant */ vector interpolate_for_triangle(int i,vector v,int index) //v is the point in the triagular plane { vector n0,n1,n2; //vector k0,k1,k2; switch(index) { case 1: { vector k0(triangles[i].v[0].normal[0],triangles[i].v[0].normal[1],triangles[i].v[0].normal[2]); vector k1(triangles[i].v[1].normal[0],triangles[i].v[1].normal[1],triangles[i].v[1].normal[2]); vector k2(triangles[i].v[2].normal[0],triangles[i].v[2].normal[1],triangles[i].v[2].normal[2]); n0=k0;n1=k1;n2=k2; break; } case 2: { vector k0(triangles[i].v[0].color_diffuse[0],triangles[i].v[0].color_diffuse[1],triangles[i].v[0].color_diffuse[2]); vector k1(triangles[i].v[1].color_diffuse[0],triangles[i].v[1].color_diffuse[1],triangles[i].v[1].color_diffuse[2]); vector k2(triangles[i].v[2].color_diffuse[0],triangles[i].v[2].color_diffuse[1],triangles[i].v[2].color_diffuse[2]); n0=k0;n1=k1;n2=k2; break; } case 3: { vector k0(triangles[i].v[0].color_specular[0],triangles[i].v[0].color_specular[1],triangles[i].v[0].color_specular[2]); vector k1(triangles[i].v[1].color_specular[0],triangles[i].v[1].color_specular[1],triangles[i].v[1].color_specular[2]); vector k2(triangles[i].v[2].color_specular[0],triangles[i].v[2].color_specular[1],triangles[i].v[2].color_specular[2]); n0=k0;n1=k1;n2=k2; break; } } vector v0(triangles[i].v[0].position[0],triangles[i].v[0].position[1],triangles[i].v[0].position[2]); vector v1(triangles[i].v[1].position[0],triangles[i].v[1].position[1],triangles[i].v[1].position[2]); vector v2(triangles[i].v[2].position[0],triangles[i].v[2].position[1],triangles[i].v[2].position[2]); ray r1(v1,v2); // r1=v1+t1*(v2-v1) ray r2(v0,v); // r2=v0+t2*(v-v0) vector d1=v2.subtract(v1); vector d2=v.subtract(v0); /* * vector in=r1.intersect * for intersection r1=r2 ie v1+t1*(v2-v1)=v0+t2*(v-v0) * v1+t1*d1=v0+t2*d2 * cross multiplying by vector d2 on both sides to get t1 * cross multiplying by vector d1 on both sides to get t2 * the value of t1 must be <1.0 * the value of t2 must be >1.0 * */ double t1=(((v0.cross_product(d2)).subtract(v1.cross_product(d2))).magnitude())/((d1.cross_product(d2)).magnitude()); double t2=(((v1.cross_product(d1)).subtract(v0.cross_product(d1))).magnitude())/((d2.cross_product(d1)).magnitude()); vector np=n2.multiply_scalar(t1).add(n1.multiply_scalar(1.0-t1)); vector n=n0.multiply_scalar((t2-1.0)/t2).add(np.multiply_scalar(1.0/t2)); return n; } /* * function to interpolate shininess for a triangle in with index i in the array of triangles */ double interpolate_shininess(int i,vector v) { vector v0(triangles[i].v[0].position[0],triangles[i].v[0].position[1],triangles[i].v[0].position[2]); vector v1(triangles[i].v[1].position[0],triangles[i].v[1].position[1],triangles[i].v[1].position[2]); vector v2(triangles[i].v[2].position[0],triangles[i].v[2].position[1],triangles[i].v[2].position[2]); double n0=triangles[i].v[0].shininess; double n1=triangles[i].v[1].shininess; double n2=triangles[i].v[2].shininess; ray r1(v1,v2); // r1=v1+t1*(v2-v1) ray r2(v0,v); // r2=v0+t2*(v-v0) vector d1=v2.subtract(v1); vector d2=v.subtract(v0); double t1=(((v0.cross_product(d2)).subtract(v1.cross_product(d2))).magnitude())/((d1.cross_product(d2)).magnitude()); double t2=(((v1.cross_product(d1)).subtract(v0.cross_product(d1))).magnitude())/((d2.cross_product(d1)).magnitude()); //cout<<"t1 is "<<t1<<" "<<"t2 is"<<t2<<endl; double np=n2*t1 + n1*(1.0-t1); double n=n0*(t2-1.0)/t2+np*(1.0/t2); return n; } /* * this function computes the intersection of a ray with a sphere with index i in the array of spheres * */ double find_intersection_with_sphere(ray r,int i) { vector d=r.end.subtract(r.start); // d=d.normalize(); double A=d.x*d.x+d.y*d.y+d.z*d.z; double B=2*(d.x*(r.start.x-spheres[i].position[0]) + d.y*(r.start.y-spheres[i].position[1]) + d.z*(r.start.z-spheres[i].position[2])); double C=(r.start.x-spheres[i].position[0])*(r.start.x-spheres[i].position[0]) + (r.start.y-spheres[i].position[1])*(r.start.y-spheres[i].position[1]) + (r.start.z-spheres[i].position[2])*(r.start.z-spheres[i].position[2])-(spheres[i].radius*spheres[i].radius); //cout<<"A is "<<A<<" B is "<<B<<" C is "<<C<<endl; double D=B*B-4*A*C; if(D<0) { return no_intersection; } else { if(D==0) { double k23=-B/(2*A); if(k23>1.0) return k23; } else { double t1=((-B-sqrt(D))/(2.0*A)); // double t2=((-B+sqrt(D))/(2.0*A)); if(t1>0.0) { return t1; } /* else if(t2>1.0) { // return t2; return 1.0; } */ } } return no_intersection ; } /* * function to find the nearest intersection point for a ray. The function iterates through all the * objects in the scene ie the array of triangles and spheres */ intersection_point find_nearest_intersection(ray r) { int i; intersection_point I_P; I_P.index=0; I_P.r=r; double min_i=max_intersection; vector v0(r.start.x,r.start.y,r.start.z); vector v1(r.end.x,r.end.y,r.end.z); vector d=v1.subtract(v0); // d=d.normalize(); double temp; for(i=0;i<num_triangles;i++) { temp=intersection_with_triangle(r,i); if(temp<min_i && temp!=no_intersection) { //cout<<"the intersection parameter is "<<temp<<"\n"; min_i=temp; vector t(v0.x+temp*d.x,v0.y+temp*d.y,v0.z+temp*d.z); I_P.v=t; I_P.object=1; I_P.index=i; //I_P.print_intersection_point(); } } for(i=0;i<num_spheres;i++) { temp=find_intersection_with_sphere(r,i); // cout<<"temp is: "<<temp<<endl; if(temp<min_i && temp!=no_intersection) { //cout<<"the intersection parameter is "<<temp<<"\n"; min_i=temp; vector t(v0.x+temp*d.x,v0.y+temp*d.y,v0.z+temp*d.z); I_P.v=t; I_P.object=2; I_P.index=i; } } return I_P; } /* * function to calculate the normal vector on a point on a sphere with index i */ vector normal_for_sphere(int i,vector v) { vector center(spheres[i].position[0],spheres[i].position[1],spheres[i].position[2]); vector n=(v.subtract(center)).multiply_scalar(1.0/spheres[i].radius); n=n.normalize(); return n; } /* * function to find distance between two points */ double find_distance(vector v1,vector v2) { vector diff=v1.subtract(v2); return v1.magnitude(); } /* * Function to calculate shadow for a intersection point * This function returns whether the ray to light intersects any object or not. * a return value of 0 represents blocked * a return value of 1 represents not blocked */ int find_intersection_light(ray r,intersection_point p) { int i; double temp; for(i=0;i<num_triangles;i++) { if(p.object==1 && p.index==i) { //not to find intersection with the same triangle } else { temp=intersection_with_triangle(r,i); if(temp!=no_intersection && temp<1.0 && temp>0.0) //checking for blocking { return 0; } } } for(i=0;i<num_spheres;i++) { temp=find_intersection_with_sphere(r,i); if(temp!=no_intersection && temp<1.0 && temp>0.0) { return 0; } } return 1; } /* * function to calculate diffuse color at an intersection point p * l:- light vector * Id= intensity of light * The function calculated on the basis of the intersection point(whether it is a part of a sphere or triangle) */ vector diffuse_color(intersection_point p,vector l,vector Id) { if(p.object==1) { vector diffuse_color; vector n=interpolate_for_triangle(p.index,p.v,1); n=n.normalize(); vector Kd=interpolate_for_triangle(p.index,p.v,2); // double dis=find_distance(l,p.v); double cos_theta=l.dot_product(n); double fac=cos_theta; if(cos_theta<0.0) cos_theta=0.0; diffuse_color.x=Id.x*Kd.x*fac; diffuse_color.y=Id.y*Kd.y*fac; diffuse_color.z=Id.z*Kd.z*fac; return diffuse_color; } else if(p.object==2) { vector n=normal_for_sphere(p.index,p.v); n=n.normalize(); //for diffusion vector diffuse_color; double cos_theta=l.dot_product(n); if(cos_theta<0.0) cos_theta=0.0; double fac=cos_theta; vector Kd(spheres[p.index].color_diffuse[0],spheres[p.index].color_diffuse[1],spheres[p.index].color_diffuse[2]); diffuse_color.x=Id.x*Kd.x*fac; diffuse_color.y=Id.y*Kd.y*fac; diffuse_color.z=Id.z*Kd.z*fac; return diffuse_color; } } /* * function to calculate specular color * l:- light vector * Id= intensity of light * The function calculated on the basis of the intersection point(whether it is a part of a sphere or triangle) */ vector specular_color(intersection_point p,vector l,vector Id,ray r) { // struct ray_color rc; if(p.object==1) { //for specular reflection vector n=interpolate_for_triangle(p.index,p.v,1); vector specular_color; vector proj=n.multiply_scalar(n.dot_product(l)); vector reflection=(proj.multiply_scalar(2.0)).subtract(l); reflection=reflection.normalize(); vector V=r.start.subtract(r.end); V=V.normalize(); vector Ks=interpolate_for_triangle(p.index,p.v,3); //double fac1=s*pow(V.dot_product(reflection),shine)/(dis*dis); double shine=interpolate_shininess(p.index,p.v); double cos_theta=V.dot_product(reflection); if(cos_theta<0.0) cos_theta=0.0; double fac1=pow(cos_theta,shine); specular_color.x=Id.x*Ks.x*fac1; specular_color.y=Id.y*Ks.y*fac1; specular_color.z=Id.z*Ks.z*fac1; return specular_color; } else if(p.object==2) { //for specular reflection vector n=normal_for_sphere(p.index,p.v); n=n.normalize(); vector specular_color; vector proj=n.multiply_scalar(n.dot_product(l)); //proj=ncos(0) vector reflection=(proj.multiply_scalar(2.0)).subtract(l); reflection=reflection.normalize(); // vector V=(r.end).subtract(p.v); vector V=r.start.subtract(r.end); V=V.normalize(); vector Ks(spheres[p.index].color_specular[0],spheres[p.index].color_specular[1],spheres[p.index].color_specular[2]); // double fac1=s*pow(V.dot_product(reflection),spheres[p.index].shininess)/(dis*dis); double cos_theta=V.dot_product(reflection); double fac1=0.0; if(cos_theta<0.0) { cos_theta=0.0; } else { fac1=pow(cos_theta,spheres[p.index].shininess); } specular_color.x=Id.x*Ks.x*fac1; specular_color.y=Id.y*Ks.y*fac1; specular_color.z=Id.z*Ks.z*fac1; return specular_color; } } /* * function to calculate the ambient color at an intersection point */ vector ambient_color(intersection_point p) { vector I_a(ambient_light[0],ambient_light[1],ambient_light[2]); if(p.object==1) //for triangle { vector K_a=interpolate_for_triangle(p.index,p.v,2); vector ambient_color(I_a.x*K_a.x,I_a.y*K_a.y,I_a.z*K_a.z); return ambient_color; } else if(p.object==2) //for sphere { //for ambient light vector K_a(spheres[p.index].color_diffuse[0],spheres[p.index].color_diffuse[1],spheres[p.index].color_diffuse[2]); vector ambient_color(I_a.x*K_a.x,I_a.y*K_a.y,I_a.z*K_a.z); return ambient_color; } } /* * function to calculate the refleted ray for an intersection point */ ray find_reflective_ray(intersection_point p) { vector l=p.r.start.subtract(p.r.end); l=l.normalize(); vector n; if(p.object==1) //for triangle { n=interpolate_for_triangle(p.index,p.v,1); n=n.normalize(); } else if(p.object==2) //for sphere { n=normal_for_sphere(p.index,p.v); n=n.normalize(); } vector proj=n.multiply_scalar(n.dot_product(l)); vector reflection=(proj.multiply_scalar(2.0)).subtract(l); ray r(p.v,p.v.add(reflection)); return r; } /* * Function to calculate shininess at a intersection point p */ double find_shininess(intersection_point p) { double shine=0.0; if(p.object==1) //for triangle { shine=interpolate_shininess(p.index,p.v); } else if(p.object==2) //for sphere { shine=spheres[p.index].shininess; } return shine; } /* * function to calculate the specular constant at an intersection point as requied for recursive ray tracing */ vector find_specular_coeffcient(intersection_point p) { if(p.object==1) //for triangle { vector ks=interpolate_for_triangle(p.index,p.v,3); return ks; } else if(p.object==2) //for sphere { vector v(spheres[p.index].color_specular[0],spheres[p.index].color_specular[1],spheres[p.index].color_specular[2]); return v; } } /* * function which return the color for a ray and the depth of the ray. this function uses all the above mentioned functions and gives * us the total color at the point of intersection */ vector Recursive_RT(ray r,int depth) { vector color; intersection_point p=find_nearest_intersection(r); if(p.object>0) { color=RT_shading(p,r,depth); } else { color.x=0.0; color.y=0.0; color.z=0.0; } return color; } /* * Function to calculate the shading at an intersection point p , for a given ray. * This function calls recursively RT_shading function */ vector RT_shading(intersection_point p,ray r,int depth) { vector color=ambient_color(p); //ray reflected_ray; for(int i=0;i<num_lights;i++) { vector l1(lights[i].position[0],lights[i].position[1],lights[i].position[2]); ray l_ray(p.v,l1); int s=find_intersection_light(l_ray,p); //for shadow vector Id(lights[i].color[0],lights[i].color[1],lights[i].color[2]); vector l=l1.subtract(p.v); l=l.normalize(); vector d_c= diffuse_color(p,l,Id); vector s_c= specular_color(p,l,Id,r); color=color.add((d_c.add(s_c)).multiply_scalar(s)); } ray reflected_ray=find_reflective_ray(p); vector ks=find_specular_coeffcient(p); //double shine=find_shininess(p); vector c(0.0,0.0,0.0); if(depth<Depth && ks.x>0.0 && ks.y>0.0 && ks.z>0.0) { c=Recursive_RT(reflected_ray,depth+1); c.x=c.x*pow(ks.x,depth); c.y=c.x*pow(ks.y,depth); c.z=c.x*pow(ks.z,depth); //color=color.add(c.multiply_scalar(shine)); color.x=color.x*(1-ks.x); color.y=color.y*(1-ks.y); color.z=color.z*(1-ks.z); } color=color.add(c); return color; } void plot_pixel_display(int x,int y,unsigned char r,unsigned char g,unsigned char b); void plot_pixel_jpeg(int x,int y,unsigned char r,unsigned char g,unsigned char b); void plot_pixel(int x,int y,unsigned char r,unsigned char g,unsigned char b); /* * function which initially calculates the dimensions of the screen given the plane distance and then generate rays * the camera/eye point and the color to be shown at that pixel(as returned by other functions) is stored in the buffer * and then lated displayed in one go. * */ void fill_buffer() { double height=PLANE_DIST*tan((fov/2)*M_PI/180); double width=PLANE_DIST*tan((fov/2)*M_PI/180); double increment_height=2*height/HEIGHT; double increment_width=2*width/WIDTH; vector V0,V1; V0.x=V0.y=V0.z=0.0; V1.z=-PLANE_DIST; unsigned int x,y; //simple output for(x=0;x < WIDTH;x++) { glBegin(GL_POINTS); V1.x = -width+x*increment_width; for(y=0;y < HEIGHT;y++) { vector color; //it denotes the total color V1.y = -height+y*increment_height; ray r(V0,V1); color=Recursive_RT(r,1); if(color.x==0.0 && color.y==0.0 && color.z==0.0) { color.x=1.0; color.y=1.0; color.z=1.0; } if(color.x>1.0) color.x=1.0; if(color.y>1.0) color.y=1.0; if(color.z>1.0) color.z=1.0; buffer[y][x][0]=color.x*255; buffer[y][x][1]=color.y*255; buffer[y][x][2]=color.z*255; plot_pixel_display(x,y,buffer[y][x][0]%256,buffer[y][x][1]%256,buffer[y][x][2]%256); } glEnd(); glFlush(); } printf("Done!\n"); // fflush(stdout); } //MODIFY THIS FUNCTION void draw_scene() { fill_buffer(); /* unsigned int x,y; //simple output for(x=0;x < WIDTH;x++) { //glPointSize(5.0); glBegin(GL_POINTS); for(y=0;y < HEIGHT;y++) { //plot_pixel(x,y,x%256,y%256,(x+y)%256); plot_pixel_display(x,y,buffer[y][x][0]%256,buffer[y][x][1]%256,buffer[y][x][2]%256); } glEnd(); glFlush(); } */ // printf("Done!\n"); // fflush(stdout); // printf("Done!\n"); } void plot_pixel_display(int x,int y,unsigned char r,unsigned char g,unsigned char b) { glPointSize(1.0); glColor3f(((double)r)/256.f,((double)g)/256.f,((double)b)/256.f); glVertex2i(x,y); } void plot_pixel_jpeg(int x,int y,unsigned char r,unsigned char g,unsigned char b) { buffer[HEIGHT-y-1][x][0]=r; buffer[HEIGHT-y-1][x][1]=g; buffer[HEIGHT-y-1][x][2]=b; } void plot_pixel(int x,int y,unsigned char r,unsigned char g, unsigned char b) {// this function computes the intersection of a ray with a triangle with index i in the array of triangles plot_pixel_display(x,y,r,g,b); if(mode == MODE_JPEG) plot_pixel_jpeg(x,y,r,g,b); } void save_jpg() { Pic *in = NULL; /* in = pic_alloc(640, 480, 3, NULL); */ printf("Saving JPEG file: %s\n", filename); memcpy(in->pix,buffer,3*WIDTH*HEIGHT); /* if (jpeg_write(filename, in)) printf("File saved Successfully\n"); else printf("Error in Saving\n"); pic_free(in); */ } void parse_check(char *expected,char *found) { if(strcasecmp(expected,found)) { char error[100]; printf("Expected '%s ' found '%s '\n",expected,found); printf("Parse error, abnormal abortion\n"); exit(0); } } void parse_doubles(FILE*file, char *check, double p[3]) { char str[100]; fscanf(file,"%s",str); parse_check(check,str); fscanf(file,"%lf %lf %lf",&p[0],&p[1],&p[2]); printf("%s %lf %lf %lf\n",check,p[0],p[1],p[2]); } void parse_rad(FILE*file,double *r) { char str[100]; fscanf(file,"%s",str); parse_check("rad:",str); fscanf(file,"%lf",r); printf("rad: %f\n",*r); } void parse_shi(FILE*file,double *shi) { char s[100]; fscanf(file,"%s",s); parse_check("shi:",s); fscanf(file,"%lf",shi); printf("shi: %f\n",*shi); } int loadScene(char *argv) { FILE *file = fopen(argv,"r"); int number_of_objects; char type[50]; int i; Triangle t; Sphere s; Light l; fscanf(file,"%i",&number_of_objects); printf("number of objects: %i\n",number_of_objects); char str[200]; parse_doubles(file,"amb:",ambient_light); for(i=0;i < number_of_objects;i++) { fscanf(file,"%s\n",type); printf("%s\n",type); if(strcasecmp(type,"triangle")==0) { printf("found triangle\n"); int j; for(j=0;j < 3;j++) { parse_doubles(file,"pos:",t.v[j].position); parse_doubles(file,"nor:",t.v[j].normal); parse_doubles(file,"dif:",t.v[j].color_diffuse); parse_doubles(file,"spe:",t.v[j].color_specular); parse_shi(file,&t.v[j].shininess); } if(num_triangles == MAX_TRIANGLES) { printf("too many triangles, you should increase MAX_TRIANGLES!\n"); exit(0); } triangles[num_triangles++] = t; calculate_plane_coefficient(num_triangles-1); } else if(strcasecmp(type,"sphere")==0) { printf("found sphere\n"); parse_doubles(file,"pos:",s.position); parse_rad(file,&s.radius); parse_doubles(file,"dif:",s.color_diffuse); parse_doubles(file,"spe:",s.color_specular); parse_shi(file,&s.shininess); if(num_spheres == MAX_SPHERES) { printf("too many spheres, you should increase MAX_SPHERES!\n"); exit(0); } spheres[num_spheres++] = s; } else if(strcasecmp(type,"light")==0) { printf("found light\n"); parse_doubles(file,"pos:",l.position); parse_doubles(file,"col:",l.color); if(num_lights == MAX_LIGHTS) { printf("too many lights, you should increase MAX_LIGHTS!\n"); exit(0); } lights[num_lights++] = l; } else { printf("unknown type in scene description:\n%s\n",type); exit(0); } } return 0; } void display() { } void init() { glMatrixMode(GL_PROJECTION); //glOrtho(-1*WIDTH,WIDTH,-HEIGHT,HEIGHT,1,-1); glOrtho(0, WIDTH, 0, HEIGHT,1,-1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); } void idle() { //hack to make it only draw once static int once=0; if(!once) { draw_scene(); // fill_buffer(); /* if(mode == MODE_JPEG) save_jpg(); */ } once=1; } int main (int argc, char ** argv) { if (argc<2 || argc > 3) { printf ("usage: %s <scenefile> <Recursive(0)/NonRecursive(1) Ray Tracing> [jpegname]\n", argv[0]); exit(0); } if(argc == 3) { mode = MODE_JPEG; if(atoi(argv[2])==0) { Depth=1; } else if(atoi(argv[2])==1) { Depth=3; } else { Depth=1; } filename = argv[3]; } else if(argc == 2) mode = MODE_DISPLAY; glutInit(&argc,argv); loadScene(argv[1]); // display(); glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE); glutInitWindowPosition(0,0); glutInitWindowSize(WIDTH,HEIGHT); int window = glutCreateWindow("Ray Tracer"); glutDisplayFunc(display); glutIdleFunc(idle); init(); glutMainLoop(); }
[ [ [ 1, 1038 ] ] ]
7801df349bdf6e6048ff3650e1de21a6a3b55471
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testharness/inc/testharness.h
6cae742f114dcc9e3187f6a7d78fa53ccff70c76
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
7,377
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "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: * */ /* * ============================================================================== * Name : testharness.h * Part of : testharness * * Description : * Version: * * Copyright (C) 2005-6 Nokia Corporation. * This material, including documentation and any related * computer programs, is protected by copyright controlled by * Nokia Corporation. All rights are reserved. Copying, * including reproducing, stor */ #ifndef __TestHarness_H__ #define __TestHarness_H__ #include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <string.h> #if 0 #define MSG(n) \ { \ if(aThreadData->iCommonData->iTestModuleBase) \ { \ aThreadData->iCommonData->iTestModuleBase->TestModuleIf().Printf( 0, _L(""), n); \ }\ } #define TRACE(n) \ { \ TBuf<255> msg; \ msg.Format(_L(n)); \ TestModuleIf().Printf( 0, _L(""),msg); \ } #else #define MSG(n) #define TRACE(n) #endif enum ThreadCommand { ELastCommand, EThreadCreate, EThreadDestroy, EVerifyResult, ESetErrno, EVerifyErrno, ECheckValue, EVerifyTimeOutOrPostSignal, EStartLog, EStopLog, ENoOp, ELoop, EWaitForSignal, EPostSignal, EWaitTillSuspended, EBusySpin, EVerifySpin, EVerifyNoSpin, EWaitTillSpin, EStopSpin, ESemClose, ESemDestroy, ESemGetValue, ESemInit, ESemOpen, ESemPost, ESemTimedWait, ESemMicroSleepWait, ESemTryWait, ESemUnlink, ESemWait, EMutexDestroy, EMutexInitNULL, EMutexInitDefault, EMutexInitErrorCheck, EMutexInitRecursive, EMutexInitStaticDefault, EMutexInitStaticErrorCheck, EMutexInitStaticRecursive, EMutexLock, EMutexTimedLock, EMutexTryLock, EMutexUnlock, EMutexAttrDestroy, EMutexAttrGetType, EMutexAttrGetPShared, EMutexAttrSetType, EMutexAttrSetPShared, EMutexAttrInit, EOnceInit, ECallOnce, EMicroSleepTime, EErrno, ECondBroadcast, ECondDestroy, ECondInit, ECondInitStatic, ECondSignal, ECondWait, ECondTimedWait, ECondAttrDestroy, ECondAttrInit, ESem274Init, ESem274Destroy, ESem282, ESem284B, ESem697B, ESem698B, ESemPostAsNeeded, ESem701A, ESem701B, EMutex330, ECond403Init, ECond403Destroy, ECond452A, ECond452B, ECond453A, ECond453B, ECond676A, ECond676B, ECond677A, ECond677B, ECond679A, ECond679B, ECond680A, ECond680B, ECond681A, ECond681B, ECond683A, ECond683B, EPrintSuspendedStatus, EFStat, EStat, EWStat, EWriteName, EWriteWName, EWriteFd, EStop, ESemPost284 }; enum HarnessThread { EThread1, EThread2, EThread3, EThread4, EThread5, EThreadMain, ENoThread, }; struct HarnessCommand { HarnessThread iThread; ThreadCommand iAction; void* iArgument; }; class CTestModuleBase; #ifdef HARNESS_LOG struct HarnessBuffer { bool before; struct HarnessCommand iCommand; struct HarnessBuffer* iNext; }; #endif struct CommonData { pthread_mutex_t* iStaticMutex; pthread_mutex_t* iErrorCheckMutex; pthread_mutex_t* iRecursiveMutex; pthread_cond_t* iStaticCondVar; pthread_once_t iOnceControl; CTestModuleBase* iTestModuleBase; #ifdef HARNESS_LOG FILE* iFile; pthread_mutex_t iFileMutex; HarnessBuffer* iHead; #endif CommonData() :iStaticMutex(NULL) ,iErrorCheckMutex(NULL) ,iRecursiveMutex(NULL) ,iStaticCondVar(NULL) ,iTestModuleBase(NULL) #ifdef HARNESS_LOG ,iHead(NULL) #endif { #ifdef HARNESS_LOG int ret; iFile = fopen("C:\\Logs\\testframework\\P_Alone.txt","w"); if(!iFile) { printf("Unable to open log file!\n"); } ret = pthread_mutex_init(&iFileMutex,NULL); if(ret != 0) { printf("Unable to init file mutex!\n"); } #endif } ~CommonData() { #ifdef HARNESS_LOG char buff[255]; HarnessBuffer* node = iHead; HarnessBuffer* temp; while(node) { sprintf(buff,"thread %d command %d\n",node->iCommand.iThread,node->iCommand.iAction); if(node->before) { if(iFile) { fprintf(iFile,"+"); } } else { if(iFile) { fprintf(iFile,"-"); } } if(iFile) { fprintf(iFile,buff); } temp = node; node = node->iNext; delete temp; } pthread_mutex_destroy(&iFileMutex); if(iFile) { fclose(iFile); } #endif } #ifdef HARNESS_LOG void BeforeRun(HarnessCommand& aCommand) { Buffer(aCommand,true); } void AfterRun(HarnessCommand& aCommand) { Buffer(aCommand,false); } void Buffer(HarnessCommand& aCommand, bool before) { HarnessBuffer* node = new HarnessBuffer; pthread_mutex_lock(&iFileMutex); node->iCommand = aCommand; node->iNext = iHead; node->before = before; iHead = node; pthread_mutex_unlock(&iFileMutex); } #endif }; struct ThreadData { sem_t* iSignalSemaphore; sem_t* iSuspendSemaphore; sem_t* iTestSemaphore; pthread_mutex_t* iTestMutex; pthread_mutexattr_t* iTestMutexAttr; pthread_cond_t* iTestCondVar; pthread_mutexattr_t* iDefaultAttr; pthread_mutexattr_t* iErrorcheckAttr; pthread_mutexattr_t* iRecursiveAttr; pthread_condattr_t* iCondAttr; //bool iSpinFlag; bool iSuspending; int iSpinCounter; HarnessCommand* iCommandArr; int iCurrentCommand; HarnessThread iSelf; int iValue; int iRetValue; int ierrno; int iExpectederrno; int iTimes; bool iStopped; CommonData* iCommonData; void* iInitTwiceData; ThreadData* iTDArr[EThreadMain]; pthread_t iIdArr[EThreadMain]; }; void* StartFn(void* arg); int NewThread(ThreadData* aThreadData, HarnessThread aThreadId); int DeleteThread(ThreadData* aThreadData, HarnessThread aThreadId); int Loop(ThreadData* aThreadData, ThreadCommand aCommand); int RunCommand(ThreadData* aThreadData, HarnessCommand aCommand); int ProcessCommands(ThreadData* aThreadData); void CopyArr(HarnessCommand* aDstArr, HarnessCommand* aSrcArr); IMPORT_C int LoadHarnessActual(HarnessCommand* aCommandArr, CTestModuleBase* aBase); #ifdef WINDOWS #define LoadHarness(x) LoadHarnessActual(x,NULL) #else #define LoadHarness(x) LoadHarnessActual(x,NULL) #endif enum TestReturn { KUnexpectedResult = 1, KPrematureError, KNoPermission, KNoArgument, KNotSupported, KIllegalCommand, KValueMismatch, KNoMemory, KSpinChanged, KSpinNotChanged, }; struct semParam_t { int pshared; int value; }; #endif // __TestHarness_H__
[ "none@none" ]
[ [ [ 1, 405 ] ] ]
733c42df702b9f4fb69e4e249f18f7247d8f0c84
282057a05d0cbf9a0fe87457229f966a2ecd3550
/EIBStdLib/src/CCemi_L_Data_Frame.cpp
5c2e08855299eee997760b66c2e3b1cb8a93e485
[]
no_license
radtek/eibsuite
0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd
4504fcf4fa8c7df529177b3460d469b5770abf7a
refs/heads/master
2021-05-29T08:34:08.764000
2011-12-06T20:42:06
2011-12-06T20:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,889
cpp
#include "CCemi_L_Data_Frame.h" #include "EibNetwork.h" using namespace EibStack; CCemi_L_Data_Frame::CCemi_L_Data_Frame(const CCemi_L_Data_Frame& rhs) : _addil_data(NULL) { _data = rhs._data; CopyAddilData(rhs._data.apci_length, rhs._addil_data); } CCemi_L_Data_Frame::CCemi_L_Data_Frame() : _addil_data(NULL) { memset(&_data,0,sizeof(_data)); } CCemi_L_Data_Frame::CCemi_L_Data_Frame(unsigned char message_control, const CEibAddress& source_addr, const CEibAddress& dst_addr, const unsigned char* data, int data_len) : _addil_data(NULL) { if(message_control != L_DATA_REQ && message_control != L_DATA_CON && message_control != L_DATA_IND){ throw CEIBException(GeneralError,"Unknown message code"); } _data.mc = message_control; _data.addil = 0; _data.ctrl1 = 0; _data.ctrl2 = 0x60; // default: routing counter = 6 SetPriority(PRIORITY_NORMAL); if (dst_addr.IsGroupAddress()){ _data.ctrl2 |= 0x0080; } else{ _data.ctrl2 &= ~0x0080; } SetFrameFormatStandard(); ASSERT_ERROR(!source_addr.IsGroupAddress(),"Source address can't be of type group address"); _data.saddr = source_addr.ToByteArray(); _data.daddr = dst_addr.ToByteArray(); ASSERT_ERROR((data_len >= 1),"Illegal cEMI data. Length should be at least 1 Byte"); _data.apci_length = (unsigned char)data_len; _data.tpci = 0; //YGYG ???? this is the type field. should be GROUP_READ / GROUP_WRITE / GROUP_RESPONSE _data.apci = data[0]; CopyAddilData(data_len, &data[1]); ASSERT_ERROR(data_len <= MAX_EIB_VALUE_LEN,"Maximum allowable TPDU length is 6 octets (including APCI) in this implementation"); } CCemi_L_Data_Frame::CCemi_L_Data_Frame(unsigned char* data) : _addil_data(NULL) { Parse(data); } bool CCemi_L_Data_Frame::IsPositiveConfirmation() const { if((_data.ctrl1 & 0x01) == 0x01){ return false; } return true; } void CCemi_L_Data_Frame::SetDestAddress(const CEibAddress& add) { _data.daddr = add.ToByteArray(); if (add.IsGroupAddress()){ _data.ctrl2 |= 0x0080; } else{ _data.ctrl2 &= ~0x0080; } } void CCemi_L_Data_Frame::Parse(unsigned char* data) { CEMI_L_DATA_MESSAGE *ptr = (CEMI_L_DATA_MESSAGE *)data; _data.mc = ptr->mc; ASSERT_ERROR(ptr->addil == 0,"Only cEMI packets with additional info length 0 are supported"); _data.addil = ptr->addil; _data.ctrl1 = ptr->ctrl1; _data.ctrl2 = ptr->ctrl2; _data.saddr = htons(ptr->saddr); _data.daddr = htons(ptr->daddr); _data.apci_length = ptr->apci_length; _data.tpci = ptr->tpci; _data.apci = ptr->apci; CopyAddilData(ptr->apci_length, &data[11]); //ASSERT_ERROR(!IsExtendedFrame(),"Only standard frames are supported"); } CCemi_L_Data_Frame::~CCemi_L_Data_Frame() { if (_addil_data != NULL){ delete _addil_data; _addil_data = NULL; } } void CCemi_L_Data_Frame::FillBuffer(unsigned char* buffer, int max_length) const { ASSERT_ERROR(max_length >= GetTotalSize(),"Buffer is too small"); CEMI_L_DATA_MESSAGE *ptr = (CEMI_L_DATA_MESSAGE *)buffer; ptr->mc = _data.mc; ptr->addil = _data.addil; ASSERT_ERROR(ptr->addil == 0,"Only cEMI packets with additional info length 0 are supported"); ptr->ctrl1 = _data.ctrl1; ptr->ctrl2 = _data.ctrl2; ptr->saddr = htons(_data.saddr); ptr->daddr = htons(_data.daddr); ptr->apci_length = _data.apci_length; ptr->tpci = _data.tpci; ptr->apci = _data.apci; memcpy(&buffer[11],_addil_data,_data.apci_length -1); } int CCemi_L_Data_Frame::GetTotalSize() const { int res = (11 + _data.apci_length -1); return res; } void CCemi_L_Data_Frame::SetFrameFormatStandard() { _data.ctrl1 |= 0x80; _data.ctrl2 &= 0xF0; } bool CCemi_L_Data_Frame::IsExtendedFrame() const { if ((_data.ctrl1 & 0x0080) == 0){ return true; } return false; } CEibAddress CCemi_L_Data_Frame::GetSourceAddress() const { return CEibAddress((unsigned int)_data.saddr,false); } void CCemi_L_Data_Frame::SetValue(unsigned char* val, unsigned char val_len) { if(val_len < 1 || val_len > MAX_EIB_VALUE_LEN){ throw CEIBException(GeneralError,"Value length must be at least 1 and maximum 6"); } /* YGYG - need to optimize this..[no need to delete anyway.] if(_data.apci_length > 1){ if(_addil_data == NULL){ throw CEIBException(GeneralError,"Current packet is corrupted"); } delete _addil_data; _addil_data = NULL; } */ _data.apci_length = val_len; _data.apci = val[0]; CopyAddilData(val_len, &val[1]); } CEibAddress CCemi_L_Data_Frame::GetDestAddress() const { return CEibAddress((unsigned int)_data.daddr,(_data.ctrl2 & 0x0080) == 0x0080); } bool CCemi_L_Data_Frame::IsRepeatedFrame() const { return ((_data.ctrl1 & 0x20) == 0); } void CCemi_L_Data_Frame::SetRepeatFlag(bool val) { if (val){ _data.ctrl1 &= ~0x20; }else{ _data.ctrl1 |= 0x20; } } CEMI_FRAME_PRIORITY CCemi_L_Data_Frame::GetPriority() const { return (CEMI_FRAME_PRIORITY)(_data.ctrl1 & 0x000C); } void CCemi_L_Data_Frame::SetPriority(CEMI_FRAME_PRIORITY priority) { _data.ctrl1 &= 0xFFF3; _data.ctrl1 |= (unsigned char)priority; } bool CCemi_L_Data_Frame::GetAcknowledgeRequested() const { if ((_data.ctrl1 & 0x02) == 0){ return false; } return true; } unsigned char CCemi_L_Data_Frame::GetHopCount() const { return (unsigned char)((_data.ctrl2 & 0x70) >> 4); } void CCemi_L_Data_Frame::SetAcknowledgeRequest(bool val) { if (val){ _data.ctrl1 |= 0x0002; }else{ _data.ctrl1 &= ~0x0002; } } CCemi_L_Data_Frame& CCemi_L_Data_Frame::operator=(const CCemi_L_Data_Frame& rhs) { _data = rhs._data; CopyAddilData(rhs._data.apci_length, rhs._addil_data); return *this; } void CCemi_L_Data_Frame::FillBufferWithFrameData(unsigned char* buffer, int max_length) { ASSERT_ERROR(max_length >= _data.apci_length, "Buffer is too small for packet data"); buffer[0] = _data.apci; if(_data.apci_length > 1){ memcpy(&buffer[1],_addil_data,_data.apci_length - 1); } } void CCemi_L_Data_Frame::CopyAddilData(byte acpi_len, const unsigned char* data) { if (acpi_len > 1) { if(_addil_data != NULL){ delete _addil_data; } _addil_data = new unsigned char[acpi_len - 1]; memcpy(_addil_data, data, acpi_len - 1); } else { _addil_data = NULL; } } void CCemi_L_Data_Frame::Dump() const { //message code switch(_data.mc) { case L_DATA_REQ: printf("Message code: L_DATA_REQ (%#x)\n",_data.mc); break; case L_DATA_CON: printf("Message code: L_DATA_CON (%#x)\n",_data.mc); break; case L_DATA_IND: printf("Message code: L_DATA_IND (%#x)\n",_data.mc); break; default: break; } if(_data.mc == L_DATA_CON){ printf("Confirmation: %s\n", IsPositiveConfirmation() ? "Positive\n" : "Negative\n"); } printf("Source: %s\n",GetSourceAddress().ToString().GetBuffer()); printf("Destination: %s\n",GetDestAddress().ToString().GetBuffer()); printf("Priority: "); switch (GetPriority()) { case PRIORITY_SYSTEM: printf("System (%#x)\n",PRIORITY_SYSTEM); break; case PRIORITY_URGENT: printf("PRIORITY_URGENT (%#x)\n",PRIORITY_URGENT); break; case PRIORITY_NORMAL: printf("PRIORITY_NORMAL (%#x)\n",PRIORITY_NORMAL); break; case PRIORITY_LOW: printf("PRIORITY_LOW (%#x)\n",PRIORITY_LOW); break; default: printf("UNKNOWN (%#x)\n",GetPriority()); break; } printf("Hop count: %d\n",GetHopCount()); printf("Is Ack requested: %s\n",GetAcknowledgeRequested() ? "true" : "false"); printf("Is Repetition: %s\n",IsRepeatedFrame() ? "true" : "false"); printf("TPDU: 0x"); for(int i=0; i<_data.apci_length; ++i){ if(i == 0) printf("%x",_data.apci); else printf("%x",_addil_data[i-1]); } printf("\n"); }
[ [ [ 1, 321 ] ] ]
00247ea19f1f953b0c5ca9e3dbb55517590c793b
6e3cc7846bdba91f1d8dde0eb0a8b7c7bd8100c8
/Projects/agent/include/_common/utils.h
30cbfb4fa0dfb5e0983658f514c0ee53f870bec0
[]
no_license
shilinxu/hcmus-it-asset-management
fd74c9fdd7667f345bd9da4c7b95ef6caae3367c
740c040a6b13463a826a98e437845b197f7b282f
refs/heads/master
2020-05-04T10:47:24.800734
2010-07-13T06:51:36
2010-07-13T06:51:36
42,918,774
0
0
null
null
null
null
UTF-8
C++
false
false
12,139
h
// Document modified at : Wednesday, March 29, 2006 4:37:33 PM , by user : Didier LIROULET , from computer : SNOOPY-XP-PRO //==================================================================================== // Open Computer and Software Inventory // Copyleft PIERRE LEMMET 2005 // Web: http://ocsinventory.sourceforge.net // This code is open source and may be copied and modified as long as the source // code is always made freely available. // Please refer to the General Public Licence http://www.gnu.org/ or Licence.txt //==================================================================================== #ifndef _UTILS_H_ #define _UTILS_H_ #include "net_utils.h" #include "../include/zlib/flate.h" #include <afxinet.h> #include <string.h> #include "../include/_common/defines.h" #include "../include/xml/markup.h" #include "sysinfo.h" #include "debuglog.h" class CDeviceProperties; class CUtils { public: /** * Returns the path to: * conf file (dir==0) * accountinfo file (otherwise) */ static CString getDir(int dir=0) { char direc[_MAX_PATH+1]; GetCurrentDirectory(_MAX_PATH,direc); CString ret; if(dir==0) { ret.Format("%s\\%s",direc,OCS_IDENTIFICATION_FILE); } else { ret.Format("%s\\%s",direc,OCS_ACCOUNTINFO_FILE); } return ret; } /** * writes in OCS_ACCOUNTINFO_FILE every accountinfo in xml */ static void parseAccountParams(CMarkup xml) { DeleteFile(getDir(1)); xml.ResetPos(); xml.FindElem("REPLY"); xml.IntoElem(); while(xml.FindElem("ACCOUNTINFO")) { xml.FindChildElem("KEYNAME"); CString name=xml.GetChildData(); xml.ResetChildPos(); xml.FindChildElem("KEYVALUE"); CString value=xml.GetChildData(); CUtils::writeParamFile(name,value,FALSE,1); AddLog("Couple ( %s <=> %s ) added in configuration file\n",name,value); } } /** * Returns TRUE if server option "option" is present in xml */ static BOOL isActivatedOption(CMarkup xml,CString option) { xml.ResetPos(); xml.FindElem("REPLY"); xml.IntoElem(); while(xml.FindElem("OPTION")) { xml.IntoElem(); xml.FindElem("NAME"); if( option.CompareNoCase(xml.GetData()) == 0 ) return TRUE; xml.OutOfElem(); } return FALSE; } static CMapStringToString* getOptionAttributes(CMarkup xml,int rang,CString option,...) { xml.ResetPos(); xml.FindElem("REPLY"); xml.IntoElem(); CMapStringToString * pMap = new CMapStringToString(); int rangAct=1; while(xml.FindElem("OPTION")) { xml.IntoElem(); xml.FindElem("NAME"); if( option.CompareNoCase(xml.GetData()) != 0 ) { xml.OutOfElem(); continue; } while(xml.FindElem("PARAM")) { if( rang > rangAct) { rangAct++; continue; } pMap->SetAt("VAL",xml.GetData()); CString i=option; va_list marker; va_start( marker,option ); /* Initialize variable arguments. */ if (i != "") do { i = va_arg( marker, LPCSTR); if( i != "" ) pMap->SetAt(i,xml.GetAttrib(i)); } while( i != "" ); va_end( marker ); return pMap; } } return pMap; } /** * Empty pM */ static void cleanCm(CMapStringToString* & pM) { if( pM != NULL) { pM->RemoveAll(); delete pM; pM = NULL; } } /** * Writes the couple name/value in the "file" file * If noEmpty==TRUE AND Value=="" the line is not written */ static BOOL writeParamFile(CString name,CString value,BOOL noEmpty=FALSE,int file=0) { if(noEmpty&&value.GetLength()==0) return TRUE; HANDLE hFile; // Create the file with system and hidden attributes if ((hFile = CreateFile( CUtils::getDir(file), GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN, NULL)) == INVALID_HANDLE_VALUE) { //AddLog( _T( "Failed in call to <CreateFile> function with error %lu !\n"), GetLastError()); } else CloseHandle( hFile); if (WritePrivateProfileString( OCS_AGENT_KEY, name, value, CUtils::getDir(file)) == 0) { AddLog( _T( "Failed in call to <WritePrivateProfileString> function with error %lu !\n"), GetLastError()); return FALSE; } return TRUE; } /** * reads the "param" parameter */ static CString readParamFile(CString param,int file=0) { CString fileToRead; BOOL specialCase = FALSE; if(param=="Agent"||param=="tagDialog") { fileToRead = param=="Agent" ? VERSION_FILE : LABEL_FILE ; specialCase = TRUE; } if(specialCase) { CFile cf; CString reto=""; if(cf.Open(fileToRead,CFile::modeRead)) { const int MAX=50; char buf[MAX]; int nb=0; do { nb= cf.Read(buf,MAX); buf[MAX]=0; if(nb<MAX) buf[nb]=0; reto+=buf; } while(nb==MAX); cf.Close(); reto.TrimLeft(_T(" \t\n\r")); reto.TrimRight(_T(" \t\n\r")); } return reto; } char ret[_MAX_PATH+1]; if (GetPrivateProfileString( OCS_AGENT_KEY, param, _T(""), ret, _MAX_PATH, CUtils::getDir(file)) == 0) { return ""; } return (CString)ret; } /** * Writes the byte array pointed by pB in a "filename" file */ static BOOL byteToFile(CByteArray* pB,CString filename) { if(pB==NULL) return FALSE; try { CFile f; if (!f.Open(filename,CFile::modeCreate|CFile::modeWrite)) { return FALSE; } f.Write(pB->GetData(),pB->GetSize()); f.Close(); } catch (CException* pEx) { AddLog("ERROR: could not write file %s\n", filename); pEx->Delete(); return FALSE; } return TRUE; } /** * Writes the byte array pointed by pB in a "filename" file */ static CByteArray* fileToByte( CString filename ) { CByteArray* res = new CByteArray(); try { BYTE lu; CFile f; if( f.Open(filename,CFile::modeRead)) { while( f.Read(&lu,1)) res->Add( lu ); f.Close(); } else { delete res; res = NULL; } } catch (CException* pEx) { AddLog("ERROR: could not read file %s\n", filename); pEx->Delete(); if (res != NULL) { delete res; res = NULL; } } return res; } /** * Returns TRUE if the option "option" was asked, FALSE otherwise */ static BOOL IsRequired( LPCTSTR lpstrCommandLine, CString csOption) { CString csCommand = lpstrCommandLine; CString csOpt; csOption.MakeLower(); csOpt.Format( _T( "/%s "),csOption); csCommand.MakeLower(); int tst = 0; int iRgOpt = csCommand.Find( _T(csOpt)); if( iRgOpt == -1 ) { if( csOption.Compare( csCommand.Right(csOption.GetLength()) ) == 0 && csCommand.GetAt( csCommand.GetLength() - csOption.GetLength() - 1 ) == '/' ) { return TRUE; } } return iRgOpt != -1; } static INTERNET_PORT getPort( LPCTSTR lpstrCommandLine) { CString csPar = getParamValue( lpstrCommandLine, "pnum"); INTERNET_PORT iPort; if ((iPort = _ttoi(csPar)) == 0) // No option port defined, used default port iPort = DEFAULT_PORT; return iPort; } /** * Returns TRUE if the option "option" was asked, FALSE otherwise */ static CString getParamValue( LPCTSTR lpstrCommandLine, CString csParam) { CString csCommand = lpstrCommandLine, csOptionName, csValue, csSeparator; int iRngOpt, iOptionNameLength, iFin; // First, find option name position in command // (convert command line to lower case for this test only) csOptionName.Format( _T( "%s:"), csParam); csSeparator = csCommand; csSeparator.MakeLower(); iRngOpt = csSeparator.Find( _T( csOptionName)); if( iRngOpt == -1 ) { // Option name not found return _T( ""); } // Next, check option separator, space or " if (csCommand.GetAt( iRngOpt + csOptionName.GetLength()) == '\"') { // Option value is between double quotes csSeparator = _T( "\""); iOptionNameLength = csOptionName.GetLength() + 1; } else { // Option value is not between ", so use space as separator csSeparator = _T( " "); iOptionNameLength = csOptionName.GetLength(); } // Find end of value name position if ((iFin = csCommand.Find( csSeparator, iRngOpt+iOptionNameLength)) == -1) // Separator not found, assume end of argument value is end on command line iFin = csCommand.GetLength(); // Extract option value from command line csValue = csCommand.Mid( iRngOpt + iOptionNameLength, iFin - iRngOpt - iOptionNameLength ); return csValue; } /** * Removes any binary data from the "pX" xml markup */ static void cleanXml( CMarkup* pX ) { CString bef = pX->GetDoc(); for(int i=0;i<bef.GetLength();i++) { UCHAR cut = (UCHAR)bef.GetAt(i); if( (cut<32) && cut!=10 && cut!=13 ) { bef.SetAt(i,'x'); } } pX->SetDoc(bef); } /** * Returns the "RESPONSE" tag value of the xmlresp markup */ static CString getResponse(CMarkup xmlResp) { if(xmlResp.GetDoc()=="") return CString(""); xmlResp.ResetPos(); xmlResp.FindElem("REPLY"); xmlResp.IntoElem(); xmlResp.FindElem("RESPONSE"); return xmlResp.GetData(); } static CString getVersion( LPCTSTR lpstrFile) { CFileVersion fileVer; CString myVer; // myVer.Format("%u%u%u%u",VER_D1, VER_D2, VER_D3, VER_D4); if (fileVer.Open( lpstrFile)) { myVer = fileVer.GetProductVersion(); myVer.Remove( ' '); myVer.Remove( ','); fileVer.Close(); } else myVer.Empty(); return myVer; } static CString getMacs(SysInfo* pSysInfo, CDeviceProperties & m_ThePC) { CNetworkAdapter cObject; POSITION pos; BOOL bContinue; CString lesMacs, tmpMac; CString TabMac[32]={ "00:53:45:00:00:00", // WAN (PPP/SLIP) Interface "44:45:53:54:42:00", // Nortel IPSECSHM Adapter "80:00:60:0F:E8:00", // Windows Mobile-based "BA:D0:BE:EF:FA:CE", // GlobeTrotter Module 3G+ Network Card "00:00:00:00:00:00"}; int i, Nb=5; pSysInfo->getNetworkAdapters( &m_ThePC.m_NetworkList ); pos = m_ThePC.m_NetworkList.GetHeadPosition(); bContinue = (pos != NULL); if (bContinue) cObject = m_ThePC.m_NetworkList.GetNext( pos); while (bContinue) { bContinue = (pos != NULL); tmpMac = cObject.GetMACAddress(); for (i=0 ; i<Nb && TabMac[i]!=tmpMac ; i++); if (i>=Nb) { // New MAC (not in BlackList nor already found) if (Nb<32) { // Always true, I hope TabMac[Nb++] = tmpMac; } lesMacs += tmpMac; } if (pos != NULL) cObject = m_ThePC.m_NetworkList.GetNext( pos); } return lesMacs; } static CString cleanVersion(CString target) { target.Replace(" ",""); target.Replace(",",""); target.Replace(".",""); return target; } static void CUtils::getMacDeviceid(CString & csDeviceID, CString & csMac,LPCTSTR lpstrCommandLine) { CFile conf; CString confValue = CUtils::getParamValue( lpstrCommandLine, "conf" ); CString fileToOpen = OCS_CHECK_FILE; if(confValue != "") { if( conf.Open(confValue, CFile::modeReadWrite|CFile::modeCreate|CFile::modeNoTruncate) != 0) { fileToOpen = confValue; conf.Close(); } else AddLog("ERROR: Using /conf option, file %s can't be used, use of %s instead\n", confValue, OCS_CHECK_FILE); } CByteArray * pCb = CUtils::fileToByte(fileToOpen); if (pCb == NULL) { return; } CString content = CNetUtils::deCompressStr( pCb ); delete pCb; csDeviceID = content.Left( content.Find('\n') ); csMac = content.Right( content.GetLength()-content.Find('\n')-1); if( content.GetLength() == 0 ) AddLog("CHECKINGS: No %s file found !\n",OCS_CHECK_FILE); else AddLog("CHECKINGS: read <%s> and <%s> in %s\n", csDeviceID, csMac, fileToOpen ); } static void CUtils::writeMacDeviceid(CString csDeviceID, CString csMac, LPCTSTR lpstrCommandLine) { CFile conf; CString confValue = CUtils::getParamValue( lpstrCommandLine, "conf" ); CString fileToOpen = OCS_CHECK_FILE; if(confValue != "") { if( conf.Open(confValue, CFile::modeReadWrite|CFile::modeCreate|CFile::modeNoTruncate) != 0) { fileToOpen = confValue; conf.Close(); } else AddLog("ERROR: Using /conf option, file %s can't be used, use of %s instead\n", confValue, OCS_CHECK_FILE); } AddLog("CHECKINGS: write <%s> and <%s> in %s\n", csDeviceID, csMac, fileToOpen); CByteArray * pCb = CNetUtils::compressStr( csDeviceID + '\n' + csMac); CUtils::byteToFile( pCb, fileToOpen ); delete pCb; } static void CUtils::trace(CString mess, LPCTSTR lpstrCommandLine) { if( !CUtils::IsRequired(lpstrCommandLine, "trace")) return; AfxMessageBox(mess); } }; #endif //_UTILS_H_
[ "nghdiep@d3aa494c-0344-11df-8b0e-05a2803efa1e" ]
[ [ [ 1, 515 ] ] ]
ee7dd9afbec01548a27303a87a985116c1e1f311
5b3221bdc6edd8123287b2ace0a971eb979d8e2d
/Fiew/ToolwCC.cpp
453b7a5d34263b390948a8cad233e4d77f566503
[]
no_license
jackiejohn/fedit-image-editor
0a4b67b46b88362d45db6a2ba7fa94045ad301e2
fd6a87ed042e8adf4bf88ddbd13f2e3b475d985a
refs/heads/master
2021-05-29T23:32:39.749370
2009-02-25T21:01:11
2009-02-25T21:01:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,439
cpp
/* ToolwCC.cpp This object represents the Tool Control Center that enables the user to choose from a variety of tools, also contains the tools that are activated through main menu items. */ #include "stdafx.h" #include "Core.h" ToolwCC::ToolwCC(Core *core, Toolws *controler) : Toolw(core,controler) { this->toolCurrent = NULL; this->toolHand = new ToolHand(); this->toolZoom = new ToolZoom(); this->toolPencil = new ToolPencil(); this->toolLine = new ToolLine(ICC_SHALIN); this->toolRect = new ToolLine(ICC_SHAREC); this->toolElli = new ToolLine(ICC_SHACIR); this->toolRRec = new ToolLine(ICC_SHARRC); this->toolMove = new ToolMove(); this->toolSelectRect = new ToolSelectRect(); this->toolSelectCirc = new ToolSelectRect(SELCIRC); this->toolSelectHor = new ToolSelectRect(SELHOR); this->toolSelectVer = new ToolSelectRect(SELVER); this->toolSelectPoly = new ToolSelectPoly(ICC_LASPOL); this->toolSelectFree = new ToolSelectPoly(ICC_LASMOS); this->toolSampleColor = new ToolSampleColor(); this->toolCrop = new ToolCrop(); this->toolSelectWand = new ToolSelectWand(); this->toolBucket = new ToolBucket(); this->toolText = new ToolText(); this->toolEraser = new ToolPencil(PENRUB); this->toolCut = new ToolCopy(COPCUT); this->toolCopy = new ToolCopy(COPCOP); this->toolCopyMerged = new ToolCopy(COPCPM); this->toolPaste = new ToolCopy(COPPAS); this->toolClear = new ToolCopy(COPCLR); this->toolFilter = new ToolFilter(); this->toolMerge = new ToolMerge(); this->toolRaster = new ToolRaster(); this->hColorFore = NULL; this->hColorBack = NULL; this->pen_light = new Pen(CLR_WHITE,1); this->pen_dark = new Pen(CLR_FRAME_DARK,1); this->brush_bkgnd = new SolidBrush(CLR_FRAME_DARK); this->brush_hilite = new SolidBrush(CLR_WHITE); this->color_fore = Color(255,255,255,255); this->color_back = Color(255,0,0,0); this->buttonPopup = NULL; this->tooltipControler = NULL; } ToolwCC::~ToolwCC() { this->destroy(); } void ToolwCC::destroy() { delete this->toolHand; delete this->toolZoom; delete this->toolPencil; delete this->toolLine; delete this->toolRect; delete this->toolElli; delete this->toolRRec; delete this->toolMove; delete this->toolSelectRect; delete this->toolSelectCirc; delete this->toolSelectHor; delete this->toolSelectVer; delete this->toolSelectPoly; delete this->toolSelectFree; delete this->toolSampleColor; delete this->toolCrop; delete this->toolSelectWand; delete this->toolBucket; delete this->toolText; delete this->toolEraser; delete this->toolCut; delete this->toolCopy; delete this->toolCopyMerged; delete this->toolPaste; delete this->toolClear; delete this->toolFilter; delete this->toolMerge; delete this->toolRaster; delete this->pen_light; delete this->pen_dark; delete this->brush_bkgnd; delete this->brush_hilite; } HWND ToolwCC::initialize() { this->buttons = new List<HWND__>(); this->buttonHover = NULL; this->buttonValidator = NULL; this->hToolw = CreateWindowEx( WS_EX_TOOLWINDOW, IDCL_TOOLW_CC,NULL, WS_POPUP | WS_CAPTION | WS_VISIBLE, 5,TWPOS_CC,56,13 * TW_CC_BUTH, this->core->getWindowHandle(), NULL,this->core->getInstance(),NULL); /* this->tooltipControler = CreateWindowEx( NULL, TOOLTIPS_CLASS, NULL, TTS_NOPREFIX | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, this->hToolw, NULL, NULL, NULL ); */ if( this->tooltipControler != NULL ){ SetWindowPos(this->tooltipControler,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); SendMessage(this->tooltipControler,TTM_ACTIVATE,TRUE,NULL); } SetProp(this->hToolw,ATOM_THIS,this); SendMessage(this->hToolw,WM_CREATE,NULL,NULL); return this->hToolw; } Color ToolwCC::getForeColor() { return this->color_fore; } Color ToolwCC::getBackColor() { return this->color_back; } void ToolwCC::setForeColor(Color color) { this->color_fore = color; this->setColor(); } void ToolwCC::setBackColor(Color color) { this->color_back = color; this->setColor(); } void ToolwCC::setColor() { this->invalidateButton(this->hColorFore); this->invalidateButton(this->hColorBack); } void ToolwCC::swapColor() { Color temp = this->color_fore; this->color_fore = this->color_back; this->color_back = temp; this->setColor(); } void ToolwCC::resetColor() { this->color_fore = CLR_WHITE; this->color_back = CLR_BLACK; this->setColor(); } Tool *ToolwCC::getTool() { return this->toolCurrent; } /* Set new Tool and inform children about it */ void ToolwCC::setTool(Tool *newTool) { Tool *oldTool = this->toolCurrent; this->toolCurrent = newTool; this->core->getChildren()->gotoHead(); while( this->core->getChildren()->getThat() != NULL ){ this->core->getChildren()->getThat()->setTool(newTool); if( this->core->getChildren()->next() == false ) break; } if( oldTool != NULL ){ this->uncheckButton(oldTool->getId()); HWND oldHwnd = GetDlgItem(this->hToolw,oldTool->getId()); if( oldHwnd != NULL ) InvalidateRect(oldHwnd,NULL,TRUE); } if( newTool != NULL ){ this->checkButton(newTool->getId()); HWND newHwnd = GetDlgItem(this->hToolw,newTool->getId()); if( newHwnd != NULL ) InvalidateRect(newHwnd,NULL,TRUE); } } /* Inform children about a double click on the Tool */ void ToolwCC::sendToolDblClk(UINT message, WPARAM wParam, LPARAM lParam, int itemId) { bool send = false; switch(itemId){ case ICC_ZOO: send = true; break; } if( send == true ){ ChildCore *child = this->core->getActiveChild(); if( child != NULL ) child->sendToolDblClk(message,wParam,lParam,itemId); } } /* Create spearator */ void ToolwCC::createSepH(HWND hWnd, int x, int y, int w) { CreateWindowEx( WS_EX_STATICEDGE, IDCL_STATIC, NULL, WS_VISIBLE | WS_CHILD | SS_ETCHEDHORZ, x,y,w,2, hWnd,NULL,this->core->getInstance(),NULL); } /* Create Control Center button */ HWND ToolwCC::createCC_Button(HWND hWnd, WCHAR *icon, int x, int y, int id) { HWND button = CreateWindowEx( NULL, IDCL_BUTTON, icon, WS_VISIBLE | WS_CHILD | BS_OWNERDRAW, x,y,TW_CC_BUTW,TW_CC_BUTH, hWnd,(HMENU)id, this->core->getInstance(),NULL); if( button != NULL ){ RECT client; GetClientRect(button,&client); TOOLINFO ti; ti.cbSize = sizeof(TOOLINFO); ti.uFlags = TTF_SUBCLASS | TTF_IDISHWND; ti.hwnd = this->hToolw; ti.hinst = this->core->getInstance(); ti.uId = id; ti.lpszText = LPSTR_TEXTCALLBACK ; SetProp(button,ATOM_TTL,this->tooltipControler); SetProp(button,ATOM_THIS,this); SendMessage(this->tooltipControler,TTM_ADDTOOL,0,(LPARAM)(LPTOOLINFO)&ti); this->buttonProc = (WNDPROC)GetWindowLong(button,GWL_WNDPROC); SetWindowLong(button,GWL_WNDPROC,(LONG)ToolwCC::processButtons); Toolw::tooltipSubclass(button,this->controler->toolIdToName(id)); this->buttons->add(button); } return button; } /* Create button for 'more tools...'-styled popup */ void ToolwCC::createCC_PopupButton(HWND hWnd, WCHAR *icon, int x, int y, int id) { HWND button = CreateWindowEx( NULL, IDCL_BUTTON, icon, WS_VISIBLE | WS_CHILD | BS_OWNERDRAW, x,y,TW_CC_BUTW,TW_CC_BUTH, hWnd,(HMENU)id, this->core->getInstance(),NULL); if( button != NULL ){ SetProp(button,ATOM_THIS,this); SetProp(button,ATOM_PARENT,hWnd); this->popupButtonProc = (WNDPROC)GetWindowLong(button,GWL_WNDPROC); SetWindowLong(button,GWL_WNDPROC,(LONG)ToolwCC::processPopupButtons); Toolw::tooltipSubclass(button,this->controler->toolIdToName(id)); } } /* Create 'more tools...'-styled popup */ HWND ToolwCC::createCC_Popup(HWND hButton, int x, int y) { RECT client; DWORD popupExStyle = NULL; DWORD popupStyle = WS_POPUP | WS_BORDER; SetRect( &client, 0,0, this->getPopupList(hButton)->getCount() * TW_CC_BUTW, TW_CC_BUTH ); AdjustWindowRectEx(&client,popupStyle,FALSE,popupExStyle); HWND popup = CreateWindowEx( popupExStyle, IDCL_TOOLW_CCP, NULL, popupStyle, x,y - 1, client.right - client.left, client.bottom - client.top, hButton, NULL, this->core->getInstance(), NULL ); if( popup != NULL ){ this->buttonPopup = popup; this->controler->getToolwset()->add(popup); SetProp(popup,ATOM_PARENT,hButton); SetProp(popup,ATOM_THIS,this); SendMessage(popup,WM_CREATE,NULL,NULL); ShowWindow(popup,SW_SHOW); } return popup; } /* Create the fore- and backcolor buttons */ int ToolwCC::createCC_Colorer(HWND hWnd, WCHAR *icon, int y) { RECT client; GetClientRect(hWnd,&client); int wh = (int)(1.5 * TW_CC_BUTH); int xf = 0; int yf = y; int xb = client.right - wh; int yb = yf + (int)(0.5 * wh); this->hColorBack = CreateWindowEx( NULL, IDCL_BUTTON, icon, WS_VISIBLE | WS_CHILD | BS_OWNERDRAW, xb,yb,wh,wh, hWnd,(HMENU)ICC_COLORBACK, this->core->getInstance(),NULL); this->hColorFore = CreateWindowEx( NULL, IDCL_BUTTON, icon, WS_VISIBLE | WS_CHILD | BS_OWNERDRAW, xf,yf,wh,wh, hWnd,(HMENU)ICC_COLORFORE, this->core->getInstance(),NULL); int smw = 14; int smh = 14; HWND button = Dialogs::ownerdrawButton(hWnd,NULL,xb + wh - smw,yf,smw,smh,ICC_COLSWA,FALSE); Toolw::tooltipSubclass(button,this->controler->toolIdToName(ICC_COLSWA)); button = Dialogs::ownerdrawButton(hWnd,NULL,xf,yb + wh - smh,smw,smh,ICC_COLRES,FALSE); Toolw::tooltipSubclass(button,this->controler->toolIdToName(ICC_COLRES)); SetProp(this->hColorBack,ATOM_THIS,this); SetProp(this->hColorFore,ATOM_THIS,this); return yb - yf + wh; } void ToolwCC::paintButton(LPDRAWITEMSTRUCT button) { if( this->buttonValidator != NULL && this->buttonValidator != button->hwndItem ) return; RECT client = button->rcItem; Bitmap *bmp = new Bitmap(client.right,client.bottom,Core::getPixelFormat()); Graphics *g = new Graphics(bmp); if( button->itemState & ODS_SELECTED ) g->Clear(CLR_WHITE); else g->Clear(CLR_FRAME_LIGHT); client.right -= 1; client.bottom -= 1; Pen *lite = this->pen_light; Pen *dark = this->pen_dark; if( button->itemState & ODS_SELECTED ){ lite = this->pen_dark; dark = this->pen_light; } if( (button->itemState & ODS_SELECTED) || this->buttonHover == button->hwndItem ){ g->DrawLine(lite,client.left,client.top,client.left,client.bottom); g->DrawLine(lite,client.left,client.top,client.right,client.top); g->DrawLine(dark,client.right,client.top,client.right,client.bottom); g->DrawLine(dark,client.right,client.bottom,client.left,client.bottom); } if( button->CtlID != NULL ){ if( button->hwndItem == this->hColorFore ){ SolidBrush *tmp = new SolidBrush(this->color_fore); g->FillRectangle(tmp,client.left,client.top,client.right,client.bottom); g->DrawRectangle( this->pen_light,client.left,client.top,client.right - 1,client.bottom - 1); delete tmp; } else if( button->hwndItem == this->hColorBack ){ SolidBrush *tmp = new SolidBrush(this->color_back); g->FillRectangle(tmp,client.left,client.top,client.right,client.bottom); g->DrawRectangle( this->pen_light,client.left,client.top,client.right - 1,client.bottom - 1); delete tmp; } else { Image *icon = Core::getImageResource(button->CtlID,RC_PNG); g->DrawImage(icon,0,0); delete icon; if( this->getPopupList(button->hwndItem) != NULL ){ int size = 4; Point arrow[3] = { Point(client.right,client.bottom - size), Point(client.right,client.bottom), Point(client.right - size,client.bottom) }; g->FillPolygon(this->brush_bkgnd,arrow,3); } } } Graphics *gdc = new Graphics(button->hDC); gdc->DrawImage(bmp,0,0); delete gdc; delete bmp; delete g; if( button->itemAction & ODA_SELECT ) InvalidateRect(button->hwndItem,NULL,TRUE); } void ToolwCC::invalidateButton(HWND hItem) { if( hItem == NULL ) return; RECT rect; GetClientRect(hItem,&rect); this->buttonValidator = hItem; InvalidateRect(hItem,&rect,TRUE); this->buttonValidator = NULL; } void ToolwCC::uncheckButtons(int exceptId) { HWND except = NULL; if( exceptId != NULL ) except = GetDlgItem(this->hToolw,exceptId); this->buttons->gotoHead(); do { if( this->buttons->getThat() != except ) SendMessage(this->buttons->getThat(),BM_SETSTATE,FALSE,NULL); } while( this->buttons->next() == true ); } void ToolwCC::uncheckButton(int id) { this->uncheckButton(GetDlgItem(this->hToolw,id)); } void ToolwCC::uncheckButton(HWND hItem) { SendMessage(hItem,BM_SETSTATE,FALSE,NULL); } void ToolwCC::checkButton(int id) { this->checkButton(GetDlgItem(this->hToolw,id)); } void ToolwCC::checkButton(HWND hItem) { SendMessage(hItem,BM_SETSTATE,TRUE,NULL); } void ToolwCC::clickButton(HWND hItem) { this->clickButton(this->hToolw,hItem); } /* Emulate button click */ void ToolwCC::clickButton(HWND hWnd, HWND hItem) { WPARAM wParam = MAKEWPARAM(GetDlgCtrlID(hItem),BN_CLICKED); LPARAM lParam = (LPARAM) hItem; SendMessage(hWnd,WM_COMMAND,wParam,lParam); } void ToolwCC::closePopup() { if( this->buttonPopup != NULL ){ DestroyWindow(this->buttonPopup); this->buttonPopup = NULL; } } /* Subscribe a list of buttons for 'more tools...'-styled popup for a specified button hButton - owner (button) of the popup list list - the list containing popup button control id and index in list, Point(id,index) */ void ToolwCC::addPopupList(HWND hButton, List<Point> *list) { SetProp(hButton,ATOM_POPLIST,list); } List<Point> *ToolwCC::getPopupList(HWND hButton) { return (List<Point> *)GetProp(hButton,ATOM_POPLIST); } /* Process normal Control Center buttons */ LRESULT CALLBACK ToolwCC::processButtons(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { ToolwCC *that = (ToolwCC *)GetProp(hDlg,ATOM_THIS); if( that == NULL ) return 0; MSG msg; RECT tmp; POINT pt; HWND hTemp; HWND hToolTip = (HWND)GetProp(hDlg,ATOM_TTL); if( hToolTip != NULL ){ switch(message){ case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_MOUSEMOVE: case WM_RBUTTONDOWN: case WM_RBUTTONUP: msg.hwnd = hDlg; msg.message = message; msg.wParam = wParam; msg.lParam = lParam; pt = Core::makePoint(lParam); // MapWindowPoints(hDlg,GetParent(hDlg),&pt,1); msg.pt = pt; msg.time = GetTickCount(); SendMessage(hToolTip,TTM_RELAYEVENT,NULL,(LPARAM)&msg); break; } } switch (message) { case WM_LBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_RBUTTONDBLCLK: that->sendToolDblClk(message,wParam,lParam,GetDlgCtrlID(hDlg)); break; case WM_RBUTTONDOWN: case WM_LBUTTONDOWN: that->uncheckButtons(); that->checkButton(hDlg); that->clickButton(hDlg); that->closePopup(); if( that->getPopupList(hDlg) != NULL ){ if( message == WM_RBUTTONDOWN ){ GetWindowRect(hDlg,&tmp); that->buttonPopup = that->createCC_Popup(hDlg,tmp.right,tmp.top); } else { SetTimer(hDlg,TIMER_TCC,TW_CC_POPTOUT,NULL); } } break; case WM_LBUTTONUP: KillTimer(hDlg,TIMER_TCC); break; // timer used when LBUTTONMOUSE hold on tool, // show 'more tools...'-styled popup list if timout was satisfied case WM_TIMER: KillTimer(hDlg,TIMER_TCC); switch(wParam){ case TIMER_TCC: if( that->buttonPopup == NULL ){ GetWindowRect(hDlg,&tmp); that->buttonPopup = that->createCC_Popup(hDlg,tmp.right,tmp.top); } break; } break; case WM_MOUSEMOVE: if( that->buttonHover != hDlg ){ hTemp = that->buttonHover; that->buttonHover = hDlg; that->invalidateButton(hTemp); that->invalidateButton(hDlg); } return CallWindowProc(that->buttonProc,hDlg,message,wParam,lParam); default: return CallWindowProc(that->buttonProc,hDlg,message,wParam,lParam); } return 0; } /* Process buttons form 'more tools...'-styled popup list */ LRESULT CALLBACK ToolwCC::processPopupButtons(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { ToolwCC *that = (ToolwCC *)GetProp(hDlg,ATOM_THIS); if( that == NULL ) return 0; HWND hTemp, hParent; switch (message) { case WM_RBUTTONDOWN: case WM_LBUTTONDOWN: that->clickButton((HWND)GetProp(hDlg,ATOM_PARENT),hDlg); break; case WM_RBUTTONUP: case WM_LBUTTONUP: hParent = (HWND)GetProp(hDlg,ATOM_PARENT); hTemp = (HWND)GetProp(hParent,ATOM_PARENT); if( hTemp != NULL ){ SetWindowLong(hTemp,GWL_ID,(LONG)GetDlgCtrlID(hDlg)); SetProp(hTemp,ATOM_TTL,(HANDLE)that->controler->toolIdToName(GetDlgCtrlID(hDlg))); that->clickButton(hTemp); DestroyWindow(hParent); } break; case WM_MOUSEMOVE: if( (wParam & MK_LBUTTON) || (wParam & MK_RBUTTON) ) that->clickButton((HWND)GetProp(hDlg,ATOM_PARENT),hDlg); if( that->buttonHover != hDlg ){ hTemp = that->buttonHover; that->buttonHover = hDlg; that->invalidateButton(hTemp); that->invalidateButton(hDlg); } break; default: return CallWindowProc(that->buttonProc,hDlg,message,wParam,lParam); } return 0; } /* Process the messages of the Tool Window Control Center itself */ LRESULT ToolwCC::processMessages(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { ToolwCC *that = (ToolwCC *)GetProp(hDlg,ATOM_THIS); if( that == NULL ) return DefWindowProc(hDlg,message,wParam,lParam); int toolId, offset; HWND hTemp, hButton; List<Point> *idList; NMTTDISPINFO *ttText; switch (message) { // create buttons that represent Tools case WM_CREATE: offset = 0; hButton = that->createCC_Button(hDlg,NULL,0,offset,ICC_SELREC); idList = new List<Point>(); idList->add( new Point(ICC_SELREC,0) ); idList->add( new Point(ICC_SELCIR,1) ); idList->add( new Point(ICC_SELHOR,2) ); idList->add( new Point(ICC_SELVER,3) ); that->addPopupList(hButton,idList); that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,ICC_MOV); offset += TW_CC_BUTH; hButton = that->createCC_Button(hDlg,NULL,0,offset,ICC_LASPOL); idList = new List<Point>(); idList->add( new Point(ICC_LASPOL,0) ); idList->add( new Point(ICC_LASMOS,1) ); that->addPopupList(hButton,idList); that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,ICC_MAG); offset += TW_CC_BUTH; that->createCC_Button(hDlg,NULL,0,offset,ICC_CRO); //that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,NULL); offset += TW_CC_BUTH; offset += TW_CC_SEP; that->createSepH(hDlg,0,offset,3 * TW_CC_BUTW); offset += 2 * TW_CC_SEP; that->createCC_Button(hDlg,NULL,0,offset,ICC_ERSNOR); that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,ICC_DRAPEN); offset += TW_CC_BUTH; that->createCC_Button(hDlg,NULL,0,offset,ICC_FILBUC); hButton = that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,ICC_SHALIN); offset += TW_CC_BUTH; idList = new List<Point>(); idList->add( new Point(ICC_SHALIN,0) ); idList->add( new Point(ICC_SHAREC,1) ); idList->add( new Point(ICC_SHACIR,2) ); //idList->add( new Point(ICC_SHARRC,3) ); that->addPopupList(hButton,idList); //that->createCC_Button(hDlg,NULL,0,offset,NULL); //that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,NULL); //offset += TW_CC_BUTH; //that->createCC_Button(hDlg,NULL,0,offset,NULL); //that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,NULL); //offset += TW_CC_BUTH; offset += TW_CC_SEP; that->createSepH(hDlg,0,offset,3 * TW_CC_BUTW); offset += 2 * TW_CC_SEP; that->createCC_Button(hDlg,NULL,0,offset,ICC_SMPCOL); //ICC_VECSEL that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,ICC_TEX); offset += TW_CC_BUTH; //that->createCC_Button(hDlg,NULL,0,offset,ICC_VECDRA); //that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,NULL); //offset += TW_CC_BUTH; offset += TW_CC_SEP; that->createSepH(hDlg,0,offset,3 * TW_CC_BUTW); offset += 2 * TW_CC_SEP; //that->createCC_Button(hDlg,NULL,0,offset,ICC_SMPCOL); //that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,ICC_ZOO); //offset += TW_CC_BUTH; that->createCC_Button(hDlg,NULL,0,offset,ICC_HAN); that->createCC_Button(hDlg,NULL,TW_CC_BUTW,offset,ICC_ZOO); offset += TW_CC_BUTH; offset += TW_CC_SEP; that->createSepH(hDlg,0,offset,3 * TW_CC_BUTW); offset += 2 * TW_CC_SEP; offset += that->createCC_Colorer(hDlg,NULL,offset); offset += TW_CC_SEP; that->createSepH(hDlg,0,offset,3 * TW_CC_BUTW); offset += 2 * TW_CC_SEP; break; case WM_DRAWITEM: that->paintButton( (LPDRAWITEMSTRUCT)lParam ); break; // process clicks on buttons case WM_COMMAND: if(HIWORD(wParam) == BN_CLICKED){ toolId = LOWORD(wParam); switch(toolId){ case ICC_SELREC: that->setTool(that->toolSelectRect); break; case ICC_SELCIR: that->setTool(that->toolSelectCirc); break; case ICC_SELHOR: that->setTool(that->toolSelectHor); break; case ICC_SELVER: that->setTool(that->toolSelectVer); break; case ICC_MOV: that->setTool(that->toolMove); break; case ICC_LASPOL: that->setTool(that->toolSelectPoly); break; case ICC_LASMOS: that->setTool(that->toolSelectFree); break; case ICC_MAG: that->setTool(that->toolSelectWand); break; case ICC_CRO: that->setTool(that->toolCrop); break; case ICC_ERSNOR: that->setTool(that->toolEraser); break; case ICC_DRAPEN: that->setTool(that->toolPencil); break; case ICC_FILBUC: that->setTool(that->toolBucket); break; case ICC_SHALIN: that->setTool(that->toolLine); break; case ICC_SHAREC: that->setTool(that->toolRect); break; case ICC_SHACIR: that->setTool(that->toolElli); break; case ICC_SHARRC: that->setTool(that->toolRRec); break; case ICC_TEX: that->setTool(that->toolText); break; case ICC_HAN: that->setTool(that->toolHand); break; case ICC_ZOO: that->setTool(that->toolZoom); break; case ICC_SMPCOL: that->setTool(that->toolSampleColor); break; case ICC_COLORFORE: if( that->core->getDialogs()->showDialog( (LPCTSTR)IDD_CLR, (DLGPROC)Dialogs::processDlg_Clr, (LPARAM)&that->color_fore) == YES ) that->setColor(); break; case ICC_COLORBACK: if( that->core->getDialogs()->showDialog( (LPCTSTR)IDD_CLR, (DLGPROC)Dialogs::processDlg_Clr, (LPARAM)&that->color_back) == YES ) that->setColor(); break; case ICC_COLRES: that->resetColor(); break; case ICC_COLSWA: that->swapColor(); break; default: break; } } break; case WM_NOTIFY: switch( ((LPNMHDR)lParam)->code ){ case TTN_SHOW: return 0; case TTN_GETDISPINFO: ttText = (NMTTDISPINFO *)lParam; ttText->hinst = NULL; switch(ttText->hdr.idFrom){ case ICC_SELREC: ttText->lpszText = that->toolSelectRect->getName()->toWCHAR(); break; case ICC_SELCIR: ttText->lpszText = that->toolSelectCirc->getName()->toWCHAR(); break; case ICC_SELHOR: ttText->lpszText = that->toolSelectHor->getName()->toWCHAR(); break; case ICC_SELVER: ttText->lpszText = that->toolSelectVer->getName()->toWCHAR(); break; case ICC_MOV: ttText->lpszText = that->toolMove->getName()->toWCHAR(); break; case ICC_LASPOL: ttText->lpszText = that->toolSelectPoly->getName()->toWCHAR(); break; case ICC_LASMOS: ttText->lpszText = that->toolSelectFree->getName()->toWCHAR(); break; case ICC_MAG: ttText->lpszText = that->toolSelectWand->getName()->toWCHAR(); break; case ICC_CRO: ttText->lpszText = that->toolCrop->getName()->toWCHAR(); break; case ICC_ERSNOR: ttText->lpszText = that->toolEraser->getName()->toWCHAR(); break; case ICC_DRAPEN: ttText->lpszText = that->toolPencil->getName()->toWCHAR(); break; case ICC_FILBUC: ttText->lpszText = that->toolBucket->getName()->toWCHAR(); break; case ICC_SHALIN: ttText->lpszText = that->toolLine->getName()->toWCHAR(); break; case ICC_SHAREC: ttText->lpszText = that->toolRect->getName()->toWCHAR(); break; case ICC_SHACIR: ttText->lpszText = that->toolElli->getName()->toWCHAR(); break; case ICC_SHARRC: ttText->lpszText = that->toolRRec->getName()->toWCHAR(); break; case ICC_TEX: ttText->lpszText = that->toolText->getName()->toWCHAR(); break; case ICC_HAN: ttText->lpszText = that->toolHand->getName()->toWCHAR(); break; case ICC_ZOO: ttText->lpszText = that->toolZoom->getName()->toWCHAR(); break; case ICC_SMPCOL: ttText->lpszText = that->toolSampleColor->getName()->toWCHAR(); break; case ICC_COLORFORE: /*if( that->core->getDialogs()->showDialog( (LPCTSTR)IDD_CLR, (DLGPROC)Dialogs::processDlg_Clr, (LPARAM)&that->color_fore) == YES ) that->setColor();*/ break; case ICC_COLORBACK: /*if( that->core->getDialogs()->showDialog( (LPCTSTR)IDD_CLR, (DLGPROC)Dialogs::processDlg_Clr, (LPARAM)&that->color_back) == YES ) that->setColor();*/ break; case ICC_COLRES: //that->resetColor(); break; case ICC_COLSWA: //that->swapColor(); break; default: break; } } break; case WM_NCMOUSEMOVE: if( that->buttonHover != NULL ){ hTemp = that->buttonHover; that->buttonHover = NULL; that->invalidateButton(hTemp); } break; case WM_MOVING: that->closePopup(); return DefWindowProc(hDlg,message,wParam,lParam); case WM_NCACTIVATE: return that->controler->overrideNCActivate(hDlg,wParam,lParam); case WM_DESTROY: that->destroy(); break; default: return DefWindowProc(hDlg,message,wParam,lParam); } return 0; } /* Process 'more tools...'-styled popup windows */ LRESULT ToolwCC::processPopups(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { ToolwCC *that = (ToolwCC *)GetProp(hDlg,ATOM_THIS); if( that == NULL ) return DefWindowProc(hDlg,message,wParam,lParam); List<Point> *buttons; static HWND hLast; HWND hTemp; switch (message) { case WM_CREATE: buttons = that->getPopupList( (HWND)GetProp(hDlg,ATOM_PARENT) ); buttons->gotoHead(); do { that->createCC_PopupButton( hDlg, NULL, buttons->getThat()->Y * TW_CC_BUTW, 0, buttons->getThat()->X ); } while( buttons->next() == true ); break; case WM_DRAWITEM: that->paintButton( (LPDRAWITEMSTRUCT)lParam ); break; case WM_COMMAND: if(HIWORD(wParam) == BN_CLICKED){ hTemp = GetDlgItem(hDlg,LOWORD(wParam)); if( hLast == hTemp ) return 0; buttons = that->getPopupList( (HWND)GetProp(hDlg,ATOM_PARENT) ); buttons->gotoHead(); do { that->uncheckButton( GetDlgItem(hDlg,buttons->getThat()->X) ); } while( buttons->next() == true ); that->checkButton(hTemp); hLast = hTemp; } break; case WM_NCACTIVATE: return that->controler->overrideNCActivate(hDlg,wParam,lParam); case WM_DESTROY: that->buttonPopup = NULL; that->controler->getToolwset()->remove(hDlg); return DefWindowProc(hDlg,message,wParam,lParam); default: return DefWindowProc(hDlg,message,wParam,lParam); } return 0; }
[ [ [ 1, 1075 ] ] ]
16c4b91f6c12375bca88a12bf1618fc4b7dcc886
3eae8bea68fd2eb7965cca5afca717b86700adb5
/Engine/Project/Core/GnMesh/Source/GStartBackgroundLayer.cpp
16ded08b28306fd294524b27a5d6302f1e7172b6
[]
no_license
mujige77/WebGame
c0a218ee7d23609076859e634e10e29c92bb595b
73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd
refs/heads/master
2021-01-01T15:51:20.045414
2011-10-03T01:02:59
2011-10-03T01:02:59
455,950
3
1
null
null
null
null
UTF-8
C++
false
false
3,782
cpp
#include "GnGamePCH.h" #include "GStartBackgroundLayer.h" GStartBackgroundLayer* GStartBackgroundLayer::CreateBackground() { GStartBackgroundLayer* background = new GStartBackgroundLayer(); if( background->InitBackground() == false || background->InitClouds() == false ) { delete background; return NULL; } return background; } bool GStartBackgroundLayer::InitBackground() { gstring fileName; GetFullPathFromWorkPath( "StartScene/0_60.png", fileName ); GnReal2DMesh* mesh = GnReal2DMesh::spriteWithFile( fileName.c_str() ); mesh->setPosition( CCPointMake( GetGameState()->GetGameWidth() / 2 , GetGameState()->GetGameHeight() / 2 ) ); addChild( mesh, 0 ); GetFullPathFromWorkPath( "StartScene/23_50.png", fileName ); mesh = GnReal2DMesh::spriteWithFile( fileName.c_str() ); CCSize size = mesh->getContentSize(); mesh->setPosition( CCPointMake( 23 + ( size.width / 2 ) , GetGameState()->GetGameHeight() - 50 - ( size.height / 2 ) ) ); addChild( mesh, 20 ); return true; } bool GStartBackgroundLayer::InitClouds() { float centerX = GetGameState()->GetGameWidth(); // for ( gtuint i = 0; i < NUM_CLOUD; i++) // { // gchar fileName[64] = { 0, }; // GnSprintf( fileName, sizeof( fileName ), "StartScene/%d.png", i + 1 ); // gstring fullPath; // GetFullPathFromWorkPath( fileName, fullPath ); // mpCloudsMeshs[i] = GnReal2DMesh::spriteWithFile( fullPath.c_str() ); // CCSize size = mpCloudsMeshs[i]->getContentSize(); // mpCloudsMeshs[i]->setPosition( CCPointMake( centerX * i, size.height * 0.5f ) ); // CCFiniteTimeAction* action = CCSequence::actions( // CCMoveBy::actionWithDuration( 10444.0f + ( 100.0f * ( NUM_CLOUD - i ) ) , CCPointMake( -GetGameState()->GetGameWidth() * i, 0 ) ), // CCCallFunc::actionWithTarget( this, callfunc_selector( GStartBackgroundLayer::CloudActionCallback ) ), // NULL ); // mpCloudsMeshs[i]->runAction( action ); // addChild( mpCloudsMeshs[i], 1 + i ); // } gstring fullPath; GetFullPathFromWorkPath( "StartScene/5.png", fullPath ); GnReal2DMesh* mesh = GnReal2DMesh::spriteWithFile( fullPath.c_str() ); CCSize size = mesh->getContentSize(); mesh->setPosition( CCPointMake( centerX, size.height * 0.5f ) ); CCFiniteTimeAction* action = CCSequence::actions( CCMoveBy::actionWithDuration( 304.0f , CCPointMake( -GetGameState()->GetGameWidth(), 0 ) ), CCCallFunc::actionWithTarget( this, callfunc_selector( GStartBackgroundLayer::CloudActionCallback ) ), NULL ); mesh->runAction( action ); addChild( mesh, 1 ); return true; } void GStartBackgroundLayer::CloudActionCallback(CCNode* pSender) { float startX = GetGameState()->GetGameWidth() + GetGameState()->GetGameWidth(); GnReal2DMesh* mesh = (GnReal2DMesh*)pSender; CCSize size = mesh->getContentSize(); mesh->setPosition( CCPointMake( startX, size.height * 0.5f ) ); CCFiniteTimeAction* action = CCSequence::actions( CCMoveBy::actionWithDuration( 304.0f , CCPointMake( -GetGameState()->GetGameWidth(), 0 ) ), CCCallFunc::actionWithTarget( this, callfunc_selector( GStartBackgroundLayer::CloudActionCallback ) ), NULL ); mesh->runAction( action ); // for ( gtuint i = 0; i < NUM_CLOUD; i++ ) // { // if( mpCloudsMeshs[i] == pSender ) // { // CCFiniteTimeAction* action = CCSequence::actions( // CCMoveBy::actionWithDuration( 10444.0f + ( 100.0f * ( NUM_CLOUD - i ) ) , CCPointMake( -startX * 1.5f, 0.0f ) ), // CCCallFunc::actionWithTarget( this, callfunc_selector( GStartBackgroundLayer::CloudActionCallback ) ), // NULL ); // CCSize size = mpCloudsMeshs[i]->getContentSize(); // mpCloudsMeshs[i]->setPosition( CCPointMake( startX, size.height * 0.5f ) ); // mpCloudsMeshs[i]->runAction( action ); // } // } }
[ [ [ 1, 91 ] ] ]
d2c40f268ceb170bbb18eeae62337cb02280e360
e9fd66e6db68ca4d1a9f14aece84a0aff99323e4
/CCB2010/RGBSAMP/RGBSAMPDlg.cpp
f1953942e7b3add600b7d401618eae5b5895b207
[]
no_license
radtek/bbmonitoring
70fd4a4c4d553503717a474da39bef67834cc675
ff77607e77616b84395e095f396df496e7f0054a
refs/heads/master
2020-09-22T07:27:15.827047
2011-01-04T05:37:46
2011-01-04T05:37:46
null
0
0
null
null
null
null
GB18030
C++
false
false
55,160
cpp
// RGBSAMPDlg.cpp : implementation file // ***************************************************************************** // RGBSAMPDlg VERSION: 1.0 DATE: 2008-10-29 // ---------------------------------------------------------------------------- // FileName: RGBSAMPDlg.cpp // Created: 2008-10-29 16:57 // Author: 孟娟 // Purpose: 采集图象,显示图像,通过修改图象参数调节显示图象质量 // Version: // 【V1.0 2008-10-29 孟娟】 // Initial // Remark: N/A // ---------------------------------------------------------------------------- // Copyright (C) 2008 // Nanjing Talent Electronics and Technology Co., LTD. // All Rights Reserved // ***************************************************************************** #include "stdafx.h" #include "RGBSAMP.h" #include "RGBSAMPDlg.h" #include "AdjParamDlg.h" #include "QualPropDlg.h" #include "ColorSpace.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ////////////////////////////////////////////////////////////////////////// // RECT client; // RECT screen; /* *声明存放错误报告消息的函数 */ char * RGBErrorToString(RGBERROR error); /* Map Pixel format to number of bytes per pixel */ static int PixelFormatToBytesPerPixel[] = { 0 /* RGBPIXELFORMAT_UNKNOWN */, 4 /* RGBPIXELFORMAT_555 */, 4 /* RGBPIXELFORMAT_565 */, 8 /* RGBPIXELFORMAT_888 */, }; // 林云修改了该数组的值,全部扩大了两倍,因为在部分机器上运行,会内存越界 //RGBCAPTUREBUFFER *pABuffer,*pPBuffer; DWORD WINAPI thread_paint(LPVOID lpParameter) { CRGBSAMPDlg *pRGBsamp = (CRGBSAMPDlg *)lpParameter; // HDC hDC; HWND hWnd; RGBCAPTUREBUFFER *pCaptureBuffer; RGBBITMAP *pRGBBitmap; bool bExitThread = false; DWORD dwWaitResult; HANDLE threadMarks[2]; threadMarks[0] = pRGBsamp->m_hPThreadEvents[1]; threadMarks[1] = pRGBsamp->m_hPThreadEvents[0]; if (NULL == pRGBsamp->m_hCloseEvent1) { return FALSE; } WaitForSingleObject(pRGBsamp->m_hCloseEvent1, INFINITE); ResetEvent(pRGBsamp->m_hCloseEvent1); while (!bExitThread) { dwWaitResult = WaitForMultipleObjects(2, threadMarks, FALSE, INFINITE); if ((WAIT_OBJECT_0) == dwWaitResult) { // End of thread signalled. bExitThread = true; continue; } // We got a WAIT_OBJECT_0, so we want another frame. ResetEvent(threadMarks[1]); ////////////////////////////////////////////////////////////////////////// /*根据当前消息的lParam参数来判断消息来自哪个采集卡的采集事件*/ hWnd = pRGBsamp->m_hWnd; //此处固定了第1个采集卡只能对应第1个窗口控件 pCaptureBuffer = pRGBsamp->pCaptureBuffer1; pRGBBitmap = &pRGBsamp->RGBBitmap1; pRGBsamp->pABuffer->bufferflags = TRUE; //pABuffer->bufferflags = TRUE; ////////////////////////////////////////////////////////////////////////// if (!pRGBsamp->PauseRunSignal1) { // hDC = ::GetDC(hWnd); pRGBsamp->PaintFrame(hWnd, 0, *(pRGBsamp->pPBuffer), pRGBBitmap); // ::ReleaseDC(hWnd, hDC); } pRGBsamp->pPBuffer->bufferflags = FALSE; SetEvent(pRGBsamp->m_hCapEvent); //pPBuffer->bufferflags = FALSE; } CloseHandle(pRGBsamp->m_hPThreadEvents[1]); pRGBsamp->m_hPThreadEvents[1] = NULL; CloseHandle(pRGBsamp->m_hPThreadEvents[0]); pRGBsamp->m_hPThreadEvents[0] = NULL; SetEvent(pRGBsamp->m_hCloseEvent1); return 1000; } ///////////////////////////////////////////////////////////////////////////// // CRGBSAMPDlg dialog CRGBSAMPDlg::CRGBSAMPDlg(CWnd* pParent /*=NULL*/) : CDialog(CRGBSAMPDlg::IDD, pParent) { //{{AFX_DATA_INIT(CRGBSAMPDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hCloseEvent1 = NULL; m_hPThreadEvents[0] = NULL; m_hPThreadEvents[1] = NULL; m_capnum = 0; m_WorkFolder="c:"; m_maxCachePicNumber=100; } void CRGBSAMPDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CRGBSAMPDlg) DDX_Control(pDX, IDC_STATIC2, m_static); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CRGBSAMPDlg, CDialog) //{{AFX_MSG_MAP(CRGBSAMPDlg) ON_WM_SYSCOMMAND() ON_WM_QUERYDRAGICON() ON_WM_CLOSE() ON_WM_DESTROY() ON_WM_SIZE() ON_WM_TIMER() ON_WM_RBUTTONUP() ON_COMMAND(ID_Run_VGA1, OnRunVGA1) ON_MESSAGE(RGBWM_FRAMECAPTURED, OnMyMessage_Sta1) ON_COMMAND(ID_Stop_VGA1, OnStopVGA1) ON_WM_CREATE() ON_WM_CTLCOLOR() ON_COMMAND(ID_ADJUST_VGA1, OnAdjustVga1) ON_MESSAGE(RGBWM_MODECHANGED, OnMyMessage_modechange) ON_COMMAND(ID_PAUSE_VGA1, OnPauseVga1) ON_COMMAND(ID_GOON_VGA1, OnGoonVga1) ON_WM_LBUTTONDBLCLK() ON_COMMAND(ID_QUALPROP_VGA1, OnQualpropVga1) ON_MESSAGE(RGBWM_NOSIGNAL, OnMyMessage_nosignal) ON_MESSAGE(RGBWM_DATAMODE, OnMyMessage_datamode) ON_MESSAGE(RGBWM_DDRERROR, OnMyMessage_ddrerror) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CRGBSAMPDlg message handlers /*****************************************************************************/ /* *创建窗口,初始化采集卡 */ int CRGBSAMPDlg::OnCreate(LPCREATESTRUCT lpCreateStruct) { // MessageBox("Create Dialog","Info",MB_ICONINFORMATION|MB_OK); if (CDialog::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here if (!InitDevice()) //初始化采集卡 { return -1; } return 0; } /*****************************************************************************/ /* *初始化设备 */ BOOL CRGBSAMPDlg::InitDevice() { unsigned long ulNumber = 0; //存放检测到的采集卡总数量 RGBERROR error; error = RGBCaptureInitialise(&ulNumber); if (RGBERROR_NO_ERROR != error) { //初始化失败,返回值仅为:RGBERROR_HARDWARE_NOT_FOUND if (RGBERROR_HARDWARE_NOT_FOUND == error) { //没有找到硬件设备,打印日志 TRACE("RGBCaptureInitialise() 初始化,没有找到硬件设备\n"); return(FALSE); } } if (0 == ulNumber) { MessageBox("没有找到硬件设备","系统提示",MB_ICONWARNING | MB_OK); return(FALSE); } return(TRUE); } /*****************************************************************************/ /* *对话框初始化,设定窗口大小,创建背景画刷 */ BOOL CRGBSAMPDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here // ModifyStyle(WS_CAPTION,0,0); //如果不想去掉标题栏,去掉该句。 // SendMessage(WM_SYSCOMMAND,SC_MAXIMIZE,0); // ShowWindow(SW_SHOWMAXIMIZED); hRGBCapture1 = 0; ////////////////////////////////////////////////////////////////////////// /*设定窗口大小*/ // RECT myRect; // this->GetClientRect(&myRect); // MoveWindow(&myRect,TRUE); //m_static1.MoveWindow(0, 0, myRect.right, myRect.bottom,TRUE); ////////////////////////////////////////////////////////////////////////// /*??????*/ // m_Brush.CreateSolidBrush(RGB(0,0,0)); // // ////////////////////////////////////////////////////////////////////////// // /*????????*/ // CFont * cFont=new CFont; // cFont->CreateFont(0,0,0,0,FW_BOLD,TRUE,FALSE,0, // ANSI_CHARSET,OUT_DEFAULT_PRECIS, // CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY, // DEFAULT_PITCH&FF_SWISS,_T("Arial")); // SetFont(cFont); // delete cFont; pData = new LPVOID[1600*1200*4]; hRGBCapture1 = 0; ActiveStatic = 0; //标志当前窗口的状态:0-没有最大化;1-最大化窗口。 PauseRunSignal1 = false; //采集事件暂停标志:true暂停,false运行 bUsingAccBuffer1=false; //标志当前缓存是否已被使用,true是;false否 bufferSize1 = 0L; //第1个采集卡对应的缓存大小 startcount1 = FALSE; g_framecount1 = 0; //存放第一个采集卡采集图象数量 signalflag = FALSE; datamode = 1; // OnRunVGA1(); // MessageBox("Init Dialog","Info",MB_ICONINFORMATION|MB_OK); return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. /*****************************************************************************/ /*****************************************************************************/ /* *窗口颜色控制 */ HBRUSH CRGBSAMPDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); // // // TODO: Change any attributes of the DC here // hbr = m_Brush; //?????? // switch(nCtlColor) // { // case CTLCOLOR_STATIC: //对所有静态文本控件的设置 // { // CFont * cFont=new CFont; // cFont->CreateFont(30,0,0,0,FW_SEMIBOLD,FALSE,FALSE,0, // ANSI_CHARSET,OUT_DEFAULT_PRECIS, // CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY, // DEFAULT_PITCH&FF_SWISS,"Arial"); // pDC->SetBkMode(TRANSPARENT); // //设置背景为透明 // pDC->SetTextColor(RGB(255,255,255)); //设置字体颜色 // pWnd->SetFont(cFont); //设置字体 // delete cFont; // } // } // TODO: Return a different brush if the default is not desired return hbr; } /*****************************************************************************/ /* *右击,弹出对话框 */ void CRGBSAMPDlg::OnRButtonUp(UINT nFlags, CPoint point) { RECT clientRect; //存放显示控件的尺寸 GetWindowRect(&clientRect); //获取第一个显示控件的尺寸 this->GetWindowRect(&clientRect); ClientToScreen(&point); if (PtInRect(&clientRect, point)) { TRACE("OnRButtonUp(),鼠标在状态控件中\n"); //鼠标在第一个状态控件中 CMenu menuPopup; if (menuPopup.CreatePopupMenu()) { //向菜单 menuPopup 中添加菜单项 menuPopup.AppendMenu(MF_STRING, ID_Run_VGA1, "开始VGA"); menuPopup.AppendMenu(MF_STRING, ID_Stop_VGA1, "停止VGA"); menuPopup.AppendMenu(MF_SEPARATOR); menuPopup.AppendMenu(MF_STRING, ID_ADJUST_VGA1, "VGA参数调节"); menuPopup.AppendMenu(MF_STRING, ID_QUALPROP_VGA1, "质量管理"); menuPopup.AppendMenu(MF_SEPARATOR); menuPopup.AppendMenu(MF_STRING, ID_PAUSE_VGA1, "暂停VGA"); menuPopup.AppendMenu(MF_STRING, ID_GOON_VGA1, "继续VGA"); menuPopup.AppendMenu(MF_SEPARATOR); //显示弹出式菜单,并对用户选择的菜单项作出反应 menuPopup.TrackPopupMenu(TPM_RIGHTBUTTON, point.x, point.y, this, 0); } } CDialog::OnRButtonUp(nFlags, point); } /*****************************************************************************/ /* *运行采集卡 */ void CRGBSAMPDlg::OnRunVGA1() { // TODO: Add your command handler code here if (0 == hRGBCapture1) { m_hPThreadEvents[0] = CreateEvent(NULL, TRUE, FALSE, NULL); m_hPThreadEvents[1] = CreateEvent(NULL, FALSE, FALSE, NULL); m_hPaintThread = CreateThread(NULL, 0, thread_paint, this, 0, &m_dwThreadID); m_hCapEvent = CreateEvent(NULL, TRUE, FALSE, NULL); SetEvent(m_hCapEvent); m_hCloseEvent1 = CreateEvent(NULL, TRUE, FALSE, NULL); SetEvent(m_hCloseEvent1); pCaptureBuffer1 = new RGBCAPTUREBUFFER[2]; RunVGA(m_hWnd, &hRGBCapture1, pCaptureBuffer1, &bufferSize1, &RGBBitmap1, m_iIndex); } else { // ::MessageBox(m_hWnd, "VGA1采集卡已运行 !","系统提示",MB_ICONWARNING | MB_OK); } } /*****************************************************************************/ /* *运行采集程序 */ void CRGBSAMPDlg::RunVGA( HWND hWnd , HRGBCAPTURE *phRGBCapture , RGBCAPTUREBUFFER *pCaptureBuffer , unsigned long *pBufferSize , RGBBITMAP *pRGBBitmap , unsigned long usDevice) { RGBCAPTUREPARMS CaptureParms; //存放当前采集卡的参数 ////////////////////////////////////////////////////////////////////////// /*设置采集卡参数*/ if (!SetVGAParameter(m_hWnd,&CaptureParms, phRGBCapture, pRGBBitmap, usDevice)) { TRACE("SetVGAParameter(),设置采集卡参数失败"); MessageBox("没有找到硬件设备","系统提示",MB_ICONWARNING | MB_OK); return; } Sleep(1); ////////////////////////////////////////////////////////////////////////// /*获取当前像素模式*/ // pixelFormat = DetectPixelFormat (hWnd,(DWORD *)&pRGBBitmap->bmiColors[0]); switch (pixelFormat) { case RGBPIXELFORMAT_555: case RGBPIXELFORMAT_565: { pRGBBitmap->bmiHeader.biBitCount = 16; break; } case RGBPIXELFORMAT_888: //当前只支持这个模式 { pRGBBitmap->bmiHeader.biBitCount = 32; break; } default: { break; } } Sleep(1); ////////////////////////////////////////////////////////////////////////// /* 确定缓存的大小值 ,分配缓存*/ *pBufferSize =1600 * 1200 * PixelFormatToBytesPerPixel[pixelFormat]; if (!AllocateBuffers(*phRGBCapture, &pCaptureBuffer[0], hWnd, *pBufferSize)) { return ; } Sleep(1); if (!AllocateBuffers(*phRGBCapture, &pCaptureBuffer[1], hWnd, *pBufferSize)) { return ; } Sleep(1); ////////////////////////////////////////////////////////////////////////// /*设置采集参数*/ if (!SetCapture(hWnd, &CaptureParms, phRGBCapture, pCaptureBuffer, pBufferSize, pRGBBitmap)) { TRACE("SetCapture(),设置采集参数失败"); return; } } /*****************************************************************************/ /* *设置采集卡参数 */ BOOL CRGBSAMPDlg::SetVGAParameter(HWND hWnd , RGBCAPTUREPARMS *pCaptureParms , HRGBCAPTURE *phRGBCapture , RGBBITMAP *pRGBBitmap , unsigned long usDevice) { RGBERROR error; //unsigned short pixelFormat; //存放当前检测到的像素模式 ////////////////////////////////////////////////////////////////////////// /* 打开采集卡*/ error = RGBCaptureOpen(usDevice,phRGBCapture); if (RGBERROR_NO_ERROR != error) //打开设备失败,返回结果如下: { switch (error) { case RGBERROR_HARDWARE_NOT_FOUND : { TRACE("RGBCaptureOpen() 打开设备,没有找到硬件设备\n");//没有找到设备 break; } case RGBERROR_INVALID_POINTER : { TRACE("RGBCaptureOpen() 打开设备,没有找到指向该硬件设备的指针\n");//没有找到设备 break; } case RGBERROR_INVALID_INDEX : { TRACE("RGBCaptureOpen() 打开设备,没有找到硬件设备的索引\n");//没有找到设备 break; } case RGBERROR_DEVICE_IN_USE : { TRACE("RGBCaptureOpen() 打开设备,硬件设备正在被使用\n");//硬件设备正在被使用 break; } case RGBERROR_UNABLE_TO_LOAD_DRIVER : { TRACE("RGBCaptureOpen() 打开设备,不能加载驱动\n");//软硬件不批配 break; } case RGBERROR_INVALID_DEVICE : { TRACE("RGBCaptureOpen() 打开设备,硬件不存在\n");//软硬件不批配 break; } default: { break; } } return FALSE; } ////////////////////////////////////////////////////////////////////////// /*设置采集参数*/ pCaptureParms->Size = sizeof (*pCaptureParms); pCaptureParms->Flags = RGBCAPTURE_PARM_PIXELFORMAT | RGBCAPTURE_PARM_HWND | RGBCAPTURE_PARM_NOTIFY_FLAGS | RGBCAPTURE_PARM_VDIF_DESCRIPTION; //设置的参数有:当前像素模式,主窗口句柄,通知消息模式 //pixelFormat = DetectPixelFormat(hWnd,(DWORD *)&pRGBBitmap->bmiColors[0]); pixelFormat = DetectPixelFormat(hWnd,(DWORD *)&pRGBBitmap->colorMark); pCaptureParms->PixelFormat = pixelFormat; pCaptureParms->HWnd = m_hWnd; pCaptureParms->NotifyFlags = RGBNOTIFY_NO_SIGNAL | RGBNOTIFY_MODE_CHANGE; sprintf(pCaptureParms->VideoTimings.Description, "titleTCAPI"); error = RGBCaptureSetParameters(*phRGBCapture, pCaptureParms, RGBCAPTURE_FLAG_CURRENT|RGBCAPTURE_FLAG_REAL_WORLD); if (RGBERROR_NO_ERROR != error) { switch (error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,没有找到硬件设备\n");//没有找到硬件设备 break; } case RGBERROR_INVALID_POINTER: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,没有找到参数指针\n");//没有找到参数指针 break; } case RGBERROR_INVALID_SIZE: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,参数指针大小错误\n");//参数指针大小错误 break; } case RGBERROR_INVALID_FLAGS: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,不支持的标志位操作\n");//不支持的标志位操作 break; } case RGBERROR_INVALID_FORMAT: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,不支持的输入信号格式\n");//不支持的输入信号格式 break; } case RGBERROR_INVALID_BLACKLEVEL: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,不支持的黑色度\n");//不支持的黑色度 break; } case RGBERROR_INVALID_PIXEL_FORMAT: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,不支持的像素模式\n");//不支持的像素模式 break; } case RGBERROR_INVALID_HWND: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,不是当前窗口句柄\n");//不是当前窗口句柄 break; } case RGBERROR_INVALID_SYNCEDGE: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,不支持的同步沿\n");//不支持的同步沿 break; } case RGBERROR_HSCALED_OUT_OF_RANGE: { TRACE("RGBCaptureSetParameters() 设置采集卡参数,不支持的缩放比例\n");//不支持的缩放比例 break; } default: { break; } } return FALSE; } ////////////////////////////////////////////////////////////////////////// /*开始采集事件*/ error = RGBCaptureEnable(*phRGBCapture, TRUE); if (RGBERROR_NO_ERROR != error) //打开设备失败,返回结果如下: { switch (error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureEnable() 启动采集卡,打开队列中没有找到该硬件设备句柄\n");//打开队列中没有找到该硬件设备句柄 break; } case RGBERROR_CAPTURE_OUTSTANDING: { TRACE("RGBCaptureEnable() 启动采集卡,硬件设备没有打开\n");//硬件设备没有打开 break; } case RGBERROR_THREAD_FAILURE: { TRACE("RGBCaptureEnable() 启动采集卡,启动线程失败\n");//启动线程失败 break; } default: { break; } } return FALSE; } //////////////////////////////////////////////////////////////////////// /*设置窗口参数*/ // { // RECT rect; // GetWindowRect(&rect); // AdjustWindowRect(&rect, GetWindowLong(m_hWnd, GWL_STYLE), NULL); // ::SetWindowPos( m_hWnd, NULL,0, 0, // rect.right - rect.left, // rect.bottom - rect.top, // SWP_NOMOVE|SWP_NOZORDER); // } return TRUE; } /*****************************************************************************/ /* *设置采集参数 */ BOOL CRGBSAMPDlg::SetCapture(HWND hWnd , RGBCAPTUREPARMS *pCaptureParms , HRGBCAPTURE *phRGBCapture , RGBCAPTUREBUFFER *pCaptureBuffer , unsigned long *pBufferSize , RGBBITMAP *pRGBBitmap) { RGBERROR error; memset(pCaptureParms, 0, sizeof (*pCaptureParms)); ////////////////////////////////////////////////////////////////////////// /*检测当前输入的VGA视频信号分辨率*/ error = RGBCaptureDetectVideoMode(*phRGBCapture, 0, 0, &pCaptureParms->VideoTimings, FALSE); if (RGBERROR_NO_ERROR != error) { switch (error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureDetectVideoMode(), 检测当前输入的VGA视频信号分辨率,检测失败(打开的设备队列中没有找到该硬件设备句柄)\n");//检测失败(打开的设备队列中没有找到该硬件设备句柄) break; } case RGBERROR_INVALID_POINTER: { TRACE("RGBCaptureDetectVideoMode(), 检测当前输入的VGA视频信号分辨率,没有找到参数指针\n");//没有找到参数指针 break; } default: { break; } } return FALSE; } ////////////////////////////////////////////////////////////////////////// /*设置窗口标题*/ char szWndTitle[120]; wsprintf(szWndTitle, "VGA采集卡: "); ::SetWindowText(::GetParent(this->m_hWnd), szWndTitle); ////////////////////////////////////////////////////////////////////////// /* 设置位图参数为输出采集数据做准备 */ pRGBBitmap->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pRGBBitmap->bmiHeader.biPlanes = 1; pRGBBitmap->bmiHeader.biCompression = BI_BITFIELDS; pRGBBitmap->bmiHeader.biSizeImage = 0; pRGBBitmap->bmiHeader.biXPelsPerMeter = 3000; pRGBBitmap->bmiHeader.biYPelsPerMeter = 3000; pRGBBitmap->bmiHeader.biClrUsed = 0; pRGBBitmap->bmiHeader.biClrImportant = 0; pRGBBitmap->bmiHeader.biWidth = pCaptureParms->VideoTimings.HorAddrTime; pRGBBitmap->bmiHeader.biHeight = - (int)pCaptureParms->VideoTimings.VerAddrTime; // if (DD_OK !=ddrawRGB.DDRelease()) // { // TRACE("CRGBSAMPDlg::SetCapture DDRelease???!!! \n"); // //return FALSE; // } // if (DD_OK !=ddrawRGB.DDInit(hWnd,pCaptureParms->VideoTimings.HorAddrTime,pCaptureParms->VideoTimings.VerAddrTime)) // { // TRACE("CRGBSAMPDlg::SetCapture DDInit????????!!! \n"); // //return FALSE; // } pCaptureBuffer[0].bufferflags = FALSE; pCaptureBuffer[1].bufferflags = FALSE; pABuffer = &pCaptureBuffer[0]; pPBuffer = &pCaptureBuffer[1]; ////////////////////////////////////////////////////////////////////////// /*此处检测缓存是否就绪,成功则继续采集事件*/ error = RGBCaptureFrameBufferReady (*phRGBCapture, pCaptureBuffer[0].Index, *pBufferSize); if (error != RGBERROR_NO_ERROR) { switch (error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,检测失败(打开的设备队列中没有找到该硬件设备句柄)\n");//检测失败(打开的设备队列中没有找到该硬件设备句柄) break; } case RGBERROR_INVALID_INDEX: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,没有找到设备索引\n");//没有找到参数指针 break; } case RGBERROR_BUFFER_TOO_SMALL: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,缓存太小\n");//没有找到参数指针 break; } default: { break; } } char text[80]; wsprintf(text, "RGBCaptureFrameBufferReady returned: %s", RGBErrorToString(error)); ::MessageBox(NULL, text, NULL, MB_OK | MB_ICONERROR); RGBCaptureClose(*phRGBCapture); *phRGBCapture = 0; if (!FreeBuffers(*phRGBCapture, hWnd, &pCaptureBuffer[0])) { TRACE("FreeBuffers(),释放缓存失败!"); return FALSE; } return FALSE; } pCaptureBuffer[0].bufferflags = TRUE; return TRUE; } /*****************************************************************************/ /* *检测当前像素模式 */ unsigned short CRGBSAMPDlg::DetectPixelFormat( HWND hWnd, DWORD *pColourMask ) /* * Summary: Detects the pixel format of the graphics card frame buffer. * * Purpose: * pColourMask points to an array of three DWORDs. Each DWORD is * loaded with a bit mask representing the bits for red, green * and blue respectively. * * Return: One of the following values: * RGBPIXELFORMAT_555, * RGBPIXELFORMAT_565, * RGBPIXELFORMAT_888, * RGBPIXELFORMAT_UNKNOWN. */ { HDC hDC, hDCCompatible; HBITMAP hBitmap, hBitmapOld; DWORD dwPixel, dwMask; int nBytes, end, red, i, green, blue; unsigned short format; hDC = ::GetDC(hWnd); hDCCompatible = CreateCompatibleDC(hDC); hBitmap = CreateCompatibleBitmap(hDC, 1, 1); hBitmapOld = (HBITMAP)SelectObject(hDCCompatible, hBitmap); SetPixel(hDCCompatible, 0, 0, RGB (255, 0, 0)); nBytes = GetBitmapBits(hBitmap, sizeof (dwPixel), &dwPixel); end = (nBytes << 3) - 1; red = CountBits(dwPixel, 0, end); dwMask = 0; for (i = 0; i < nBytes; i++) { dwMask |= (0xff << ( i << 3 )); } pColourMask[0] = dwPixel & dwMask; SetPixel(hDCCompatible, 0, 0, RGB (0, 255, 0)); GetBitmapBits(hBitmap, sizeof(dwPixel ), &dwPixel); green = CountBits(dwPixel, 0, end); pColourMask[1] = dwPixel & dwMask; SetPixel(hDCCompatible, 0, 0, RGB (0, 0, 255)); GetBitmapBits(hBitmap, sizeof (dwPixel), &dwPixel); blue = CountBits(dwPixel, 0, end); pColourMask[2] = dwPixel & dwMask; SelectObject(hDCCompatible, hBitmapOld); DeleteDC(hDCCompatible); DeleteObject(hBitmap); ::ReleaseDC(hWnd, hDC); if ((green == 5) && (red == 5) && (blue == 5)) { format = RGBPIXELFORMAT_555; } else if ((green == 6) && (red == 5) && (blue == 5)) { format = RGBPIXELFORMAT_565; } else if ((green == 8) && (red == 8) && (blue == 8)) { format = RGBPIXELFORMAT_888; } else { format = RGBPIXELFORMAT_UNKNOWN; } // char temp[128]; // sprintf(temp,"Format:%d,%u,%d",format,*pColourMask,*pColourMask); // // MessageBox(temp,"Info",MB_ICONQUESTION|MB_OK); return format; } /*****************************************************************************/ /* *数出像素位数 */ int CRGBSAMPDlg::CountBits(unsigned long ulValue, int start, int end) { int count = 0, i; unsigned long ulMask; for (i = start, ulMask = 1 << start; i <= end; i++, ulMask <<= 1) { if (ulMask & ulValue) { count++; } } return count; } /*****************************************************************************/ /* *按照指定大小分配缓存 */ BOOL CRGBSAMPDlg::AllocateBuffers(HRGBCAPTURE hRGBCapture, RGBCAPTUREBUFFER *pCaptureBuffer, HWND hWnd, UINT BufferSize) { ////////////////////////////////////////////////////////////////////////// /*分配缓存*/ pCaptureBuffer->LpVoidBuffer = GlobalAlloc(GMEM_FIXED, BufferSize); if (pCaptureBuffer->LpVoidBuffer == NULL) { return FALSE; } TRACE("%d",GlobalSize(pCaptureBuffer->LpVoidBuffer)); ////////////////////////////////////////////////////////////////////////// /*注册当前的VGA采集事件*/ RGBERROR error; error = RGBCaptureUseMemoryBuffer(hRGBCapture, pCaptureBuffer->LpVoidBuffer, BufferSize, &pCaptureBuffer->Index); if (RGBERROR_NO_ERROR != error) { switch (error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureUseMemoryBuffer(), 注册当前的VGA采集事件,注册失败(打开的设备队列中没有找到该硬件设备句柄)\n");//检测失败(打开的设备队列中没有找到该硬件设备句柄) break; } case RGBERROR_INVALID_POINTER: { TRACE("RGBCaptureUseMemoryBuffer(), 注册当前的VGA采集事件,没有找到指向当前缓存存储区的指针\n");//没有找到指向当前缓存存储区的指针 break; } case RGBERROR_INVALID_INDEX: { TRACE("RGBCaptureUseMemoryBuffer(), 注册当前的VGA采集事件,没有找到对应当前缓存存储区的索引\n");//没有找到对应当前缓存存储区的索引 break; } default: { break; } } return FALSE; } if ((bUsingAccBuffer1 == FALSE) && (hRGBCapture == hRGBCapture1)) { bUsingAccBuffer1 = true; //修改标志缓存使用的参数为TRUE } return TRUE; } /*****************************************************************************/ /* *窗口尺寸控制 */ // void CRGBSAMPDlg::OnSize(UINT nType, int cx, int cy) // { // CDialog::OnSize(nType, cx, cy); // // TODO: Add your message handler code here // // if (NULL != m_static1.m_hWnd /*|| NULL != m_static2.m_hWnd || NULL != m_static3.m_hWnd || NULL != m_static4.m_hWnd*/) // // { // // RECT wdrect; // // this->GetClientRect(&wdrect); // // m_static1.MoveWindow(&wdrect,TRUE); // // m_static1.GetWindowRect(&wdrect); // // } // } // void CRGBSAMPDlg::OnClose() // { // // TODO: Add your message handler code here and/or call default // if ( MessageBox("确定要退出系统吗 ?\t","系统提示",MB_ICONQUESTION | MB_OKCANCEL ) != IDOK ) // { // return ; // } // CDialog::OnClose(); // } void CRGBSAMPDlg::OnDestroy() { PostQuitMessage(1); CDialog::OnDestroy(); // TODO: Add your message handler code here if ((NULL != m_hPThreadEvents[0])&&(NULL != m_hPThreadEvents[1])) { SetEvent(m_hPThreadEvents[1]); } if (NULL != m_hCloseEvent1) { WaitForSingleObject(m_hCloseEvent1,INFINITE); ResetEvent(m_hCloseEvent1); CloseHandle(m_hCloseEvent1); m_hCloseEvent1 = NULL; CloseHandle(m_hPaintThread); m_hPaintThread = NULL; } if (hRGBCapture1) { PauseRunSignal1 = FALSE; // this->RedrawWindow(); stopVGA(m_hWnd, &hRGBCapture1, pCaptureBuffer1); } ddrawRGB.DDRelease(); delete pData; // DeleteObject(m_Brush); } /******************************************************************************/ /* *释放缓存区 */ BOOL CRGBSAMPDlg::FreeBuffers(HRGBCAPTURE hRGBCapture, HWND hWnd, RGBCAPTUREBUFFER *pCaptureBuffer) { RGBERROR error; HDC hDC = ::GetDC(hWnd); if (bUsingAccBuffer1 && (hRGBCapture == hRGBCapture1)) { bUsingAccBuffer1 = false; //修改标志缓存是否使用的参数为false } ::ReleaseDC(hWnd, hDC); if (pCaptureBuffer[0].LpVoidBuffer) { ////////////////////////////////////////////////////////////////////////// /*删除当前的VGA采集缓存区在使用队列中的索引*/ error = RGBCaptureReleaseBuffer(hRGBCapture, pCaptureBuffer[0].Index); if (RGBERROR_NO_ERROR != error) { switch(error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureReleaseBuffer(), 删除当前的VGA采集缓存区在使用队列中的索引,注册失败(打开的设备队列中没有找到该硬件设备句柄)\n");//检测失败(打开的设备队列中没有找到该硬件设备句柄) break; } case RGBERROR_INVALID_POINTER: { TRACE("RGBCaptureReleaseBuffer(), 删除当前的VGA采集缓存区在使用队列中的索引,没有找到指向当前缓存存储区的指针\n");//没有找到指向当前缓存存储区的指针 break; } default: { break; } } return FALSE; } ////////////////////////////////////////////////////////////////////////// /*释放缓存区*/ GlobalFree(pCaptureBuffer[0].LpVoidBuffer); pCaptureBuffer[0].LpVoidBuffer = NULL; } if (pCaptureBuffer[1].LpVoidBuffer) { ////////////////////////////////////////////////////////////////////////// /*删除当前的VGA采集缓存区在使用队列中的索引*/ error = RGBCaptureReleaseBuffer(hRGBCapture, pCaptureBuffer[1].Index); if (RGBERROR_NO_ERROR != error) { switch(error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureReleaseBuffer(), 删除当前的VGA采集缓存区在使用队列中的索引,注册失败(打开的设备队列中没有找到该硬件设备句柄)\n");//检测失败(打开的设备队列中没有找到该硬件设备句柄) break; } case RGBERROR_INVALID_POINTER: { TRACE("RGBCaptureReleaseBuffer(), 删除当前的VGA采集缓存区在使用队列中的索引,没有找到指向当前缓存存储区的指针\n");//没有找到指向当前缓存存储区的指针 break; } default: { break; } } return FALSE; } ////////////////////////////////////////////////////////////////////////// /*释放缓存区*/ GlobalFree(pCaptureBuffer[1].LpVoidBuffer); pCaptureBuffer[1].LpVoidBuffer = NULL; } delete (pCaptureBuffer); return TRUE; } /******************************************************************************/ /* *处理SDK发出的消息RGBWM_FRAMECAPTURED *消息RGBWM_FRAMECAPTURED:表明当前采集卡缓存准备就绪,其中有一帧图象数据等待被处理 */ void CRGBSAMPDlg::OnMyMessage_Sta1(WPARAM wParam, LPARAM lParam) { if ((NULL == hRGBCapture1) || (0 == hRGBCapture1)) { return; } if (NULL == m_hCapEvent) { return; } WaitForSingleObject(m_hCapEvent, INFINITE); ResetEvent(m_hCapEvent); RGBERROR error; if (!signalflag) { signalflag = TRUE; // SetWindowText(""); } pABuffer->bufferflags = TRUE; ////////////////////////////////////////////////////////////////////////// if (FALSE == pCaptureBuffer1[0].bufferflags) { pABuffer = &pCaptureBuffer1[0]; } else { pPBuffer = &pCaptureBuffer1[0]; } if (FALSE == pCaptureBuffer1[1].bufferflags) { pABuffer = &pCaptureBuffer1[1]; } else { pPBuffer = &pCaptureBuffer1[1]; } error = RGBCaptureFrameBufferReady (hRGBCapture1, pABuffer->Index, bufferSize1); if (error != RGBERROR_NO_ERROR) { switch (error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,检测失败(打开的设备队列中没有找到该硬件设备句柄)\n");//检测失败(打开的设备队列中没有找到该硬件设备句柄) break; } case RGBERROR_INVALID_INDEX: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,没有找到设备索引\n");//没有找到参数指针 break; } case RGBERROR_BUFFER_TOO_SMALL: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,缓存太小\n");//没有找到参数指针 break; } default: { break; } } // char text[80]; // wsprintf(text, "RGBCaptureFrameBufferReady returned: %s", RGBErrorToString(error)); // ::MessageBox(m_hWnd, text, NULL, MB_OK | MB_ICONERROR); } SetEvent(m_hPThreadEvents[0]); } namespace { int RGB24WriteBmp(int width, int height, unsigned char *R,unsigned char *G,unsigned char *B, int datasize,char *BmpFileName) { // fprintf(stdout, "[%.3f]:Begin BMP To:%s\n",_now,BmpFileName); int x=0; int y=0; int i=0; int j=0; FILE *fp; unsigned char *WRGB; unsigned char *WRGB_Start; int yu = width*3%4; int BytePerLine = 0; yu = yu!=0 ? 4-yu : yu; BytePerLine = width*3+yu; if((fp = fopen(BmpFileName, "wb")) == NULL) return 0; WRGB = (unsigned char*)malloc(BytePerLine*height+54); memset(WRGB, 0, BytePerLine*height+54); //BMP头 WRGB[0] = 'B'; WRGB[1] = 'M'; *((unsigned int*)(WRGB+2)) = BytePerLine*height+54; *((unsigned int*)(WRGB+10)) = 54; *((unsigned int*)(WRGB+14)) = 40; *((unsigned int*)(WRGB+18)) = width; *((unsigned int*)(WRGB+22)) = height; *((unsigned short*)(WRGB+26)) = 1; *((unsigned short*)(WRGB+28)) = 24; *((unsigned short*)(WRGB+34)) = BytePerLine*height; WRGB_Start = WRGB + 54; for(y=height-1,j=0; y >= 0; y--,j++) { for(x=0,i=0; x <width; x++) { if((j*width+x)*3<datasize) { WRGB_Start[y*BytePerLine+i++] = B[(j*width+x)*3]; WRGB_Start[y*BytePerLine+i++] = G[(j*width+x)*3]; WRGB_Start[y*BytePerLine+i++] = R[(j*width+x)*3]; } } } fwrite(WRGB, 1, BytePerLine*height+54, fp); free(WRGB); fclose(fp); // fprintf(stdout, "[%.3f]:End Save BMP To:%s\n",_now,BmpFileName); return 1; } int RGB24WriteBmp_EX(int width, int height, unsigned char *R,unsigned char *G,unsigned char *B, int datasize,char *BmpFileName) { // fprintf(stdout, "[%.3f]:Begin BMP To:%s\n",_now,BmpFileName); int x=0; int y=0; int i=0; int j=0; FILE *fp; unsigned char *WRGB; unsigned char *WRGB_Start; int yu = width*3%4; int BytePerLine = 0; yu = yu!=0 ? 4-yu : yu; BytePerLine = width*3+yu; if((fp = fopen(BmpFileName, "wb")) == NULL) return 0; WRGB = (unsigned char*)malloc(BytePerLine*height+54); memset(WRGB, 0, BytePerLine*height+54); //BMP头 WRGB[0] = 'B'; WRGB[1] = 'M'; *((unsigned int*)(WRGB+2)) = BytePerLine*height+54; *((unsigned int*)(WRGB+10)) = 54; *((unsigned int*)(WRGB+14)) = 40; *((unsigned int*)(WRGB+18)) = width; *((unsigned int*)(WRGB+22)) = height; *((unsigned short*)(WRGB+26)) = 1; *((unsigned short*)(WRGB+28)) = 24; *((unsigned short*)(WRGB+34)) = BytePerLine*height; WRGB_Start = WRGB + 54; for(y=height-1,j=0; y >= 0; y--,j++) { for(x=0,i=0; x <width; x++) { if((j*width+x)*4<datasize) { WRGB_Start[y*BytePerLine+i++] = B[(j*width+x)*4]; WRGB_Start[y*BytePerLine+i++] = G[(j*width+x)*4]; WRGB_Start[y*BytePerLine+i++] = R[(j*width+x)*4]; } } } fwrite(WRGB, 1, BytePerLine*height+54, fp); free(WRGB); fclose(fp); // fprintf(stdout, "[%.3f]:End Save BMP To:%s\n",_now,BmpFileName); return 1; } } /******************************************************************************/ /* *画出图象 */ void CRGBSAMPDlg::PaintFrame(HWND hWnd, HDC hDC, RGBCAPTUREBUFFER captureBuffer,RGBBITMAP *pRGBBitmap) /* * This function is only called in response to a WM_PAINT message, and is, * essentially, outside of the state machine. The receipt of a notification * that a frame has been captured will invalidate the client rect, causing a * paint to happen. */ { DWORD height = -pRGBBitmap->bmiHeader.biHeight; DWORD width = pRGBBitmap->bmiHeader.biWidth; memset(pData,0,1600*1200*4); TPicRegion pDest; pDest.pdata = (TARGB32*)pData; pDest.height =height; pDest.width = width; pDest.byte_width = width << 2; if (1 == datamode) { DECODE_RGB_TO_BGRA((const TUInt8 *)captureBuffer.LpVoidBuffer, pDest); } else if (0 == datamode) { DECODE_UYVY_TO_RGB32((const TUInt8 *)captureBuffer.LpVoidBuffer, pDest); } // char temp2[128]; // sprintf(temp2,"height:%d,width=%d,bwidth=%d,datamode=%d",height,width,width<<2,datamode); // MessageBox(temp2,"Info",MB_ICONINFORMATION|MB_OK); BYTE * pbuffer = (BYTE *)pData; static int intCount=0; char bmpName[128]; sprintf(bmpName,"%s\\%d_%d_%3d.bmp",m_WorkFolder.c_str(),width,height,intCount++ % m_maxCachePicNumber); RGB24WriteBmp_EX(width,height,pbuffer+2,pbuffer+1,pbuffer+0,1600*1200*4,bmpName); ////////////////////////////////////////////////////////////////////////// /*directdraw*/ // RECT derect; // ::GetWindowRect(hWnd,&derect); // if (DD_OK !=ddrawRGB.DDDraw(hWnd,pbuffer,width*height*4,derect,width,height)) // { // TRACE("CRGBSAMPDlg::PaintFrame DDRAW?????!!! %d %d %d %d\n",derect.top, derect.bottom, derect.left, derect.right); // ////////////////////////////////////////////////////////////////////////// // CRect recttmp; //?????? // ::GetClientRect(hWnd, &recttmp); //????????? // //int height = -pRGBBitmap->bmiHeader.biHeight; // int i = SetStretchBltMode(hDC,COLORONCOLOR); // if ( GDI_ERROR == StretchDIBits(hDC, // recttmp.left, recttmp.top, recttmp.Width(), recttmp.Height(), // 0, 0, pRGBBitmap->bmiHeader.biWidth, height, // pData, // (BITMAPINFO *)pRGBBitmap, // DIB_RGB_COLORS, SRCCOPY)) // { // DWORD dwErrorCode = GetLastError(); // TRACE("CRGBSAMPDlg::PaintFrame ?????!!! %d\n", dwErrorCode); // SetStretchBltMode(hDC,i); // return; // } // SetStretchBltMode(hDC,i); // ////////////////////////////////////////////////////////////////////////// // // } ////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////// // CRect recttmp; //存放窗口尺寸 // ::GetClientRect(hWnd, &recttmp); //获取当前窗口的尺寸 // //int height = -pRGBBitmap->bmiHeader.biHeight; // int i = SetStretchBltMode(hDC,COLORONCOLOR); // if ( GDI_ERROR == StretchDIBits(hDC, // recttmp.left, recttmp.top, recttmp.Width(), recttmp.Height(), // 0, 0, pRGBBitmap->bmiHeader.biWidth, height, // pData, // (BITMAPINFO *)pRGBBitmap, // DIB_RGB_COLORS, SRCCOPY)) // { // DWORD dwErrorCode = GetLastError(); // TRACE("CRGBSAMPDlg::PaintFrame 画图不成功!!! %d\n", dwErrorCode); // SetStretchBltMode(hDC,i); // return; // } // SetStretchBltMode(hDC,i); // ////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////// // SetDIBitsToDevice(hDC, // 0, 0, pRGBBitmap->bmiHeader.biWidth, // height, 0, 0, 0, height, // pData, // (BITMAPINFO *)pRGBBitmap, // DIB_RGB_COLORS); // ////////////////////////////////////////////////////////////////////////// /*标志如果为TRUE则记录画出帧数*/ if (hWnd == m_hWnd && startcount1) { g_framecount1++; //画图总数量记录 } } /*****************************************************************************/ /* *处理像素发生改变时SDK发出的消息RGBWM_MODECHANGED *重新设置采集参数 */ void CRGBSAMPDlg::OnMyMessage_modechange(WPARAM wParam, LPARAM lParam) { unsigned long *pbufferSize = 0L; RGBCAPTUREPARMS CaptureParms; if (!SetCapture(m_hWnd, &CaptureParms, &hRGBCapture1, pCaptureBuffer1, &bufferSize1, &RGBBitmap1)) //设置采集参数 { TRACE("SetCapture(),设置采集参数失败"); return; } } /*****************************************************************************/ /* *处理当SDK采集不到正确的数据时发出的消息RGBWM_NOSIGNAL */ void CRGBSAMPDlg::OnMyMessage_nosignal(WPARAM wParam, LPARAM lParam) { CString strInfo; switch(wParam) { case NOSIGNAL_NO_RESOLUTION: { strInfo = _T("无 VGA 信 号(错误的分辨率 !!!)"); break; } case NOSIGNAL_DDRCHECK_ERROR: { strInfo = _T("无 VGA 信 号(DDR 自检出错 !!!)"); break; } case NOSIGNAL_H_OVERFLOW: { strInfo = _T("无 VGA 信 号(水平偏移量溢出 !!!)"); break; } case NOSIGNAL_V_OVERFLOW: { strInfo = _T("无 VGA 信 号(垂直偏移量溢出 !!!)"); break; } default: { break; } } signalflag = FALSE; // CRect rc; // CDC *pDC; // int x; // int y; // ////////////////////////////////////////////////////////////////////////// // /*创建字体*/ // LOGFONT ft; // // ft.lfHeight = 32; // ft.lfWidth = 16; // ft.lfEscapement = 0; // ft.lfOrientation = 0; // ft.lfWeight = FW_HEAVY; // ft.lfItalic = FALSE; // ft.lfUnderline = FALSE; // ft.lfStrikeOut = FALSE; // ft.lfCharSet = ANSI_CHARSET; // ft.lfOutPrecision = OUT_DEFAULT_PRECIS; // ft.lfClipPrecision = CLIP_DEFAULT_PRECIS; // ft.lfQuality = DEFAULT_QUALITY; // ft.lfPitchAndFamily = VARIABLE_PITCH; // strcpy(ft.lfFaceName,"宋体"); // // HFONT hFont = ::CreateFontIndirect(&ft); // pDC = GetDC(); // GetClientRect(rc); // this->RedrawWindow(); // x = ( rc.Width() - strInfo.GetLength() * ft.lfWidth ) / 2; // y = ( rc.Height() - ft.lfHeight ) / 2; // pDC->SelectObject(hFont); // ////////////////////////////////////////////////////////////////////////// // /*创建画刷*/ // CBrush brush; // brush.CreateSolidBrush(RGB(0,0,0)); // /*画图*/ // pDC->SelectObject(&brush); // pDC->SetBkColor(RGB(0,0,0)); // pDC->SetTextColor(RGB(255,255,255)); // pDC->TextOut(x,y,strInfo); // // ReleaseDC(pDC); // this->RedrawWindow(); // this->m_static.ShowWindow(SW_SHOW); // this->m_static.SetWindowText(strInfo); // this->SetWindowText(strInfo); } /*****************************************************************************/ /* *停止采集图象 */ void CRGBSAMPDlg::OnStopVGA1() { // TODO: Add your command handler code here this->m_static.ShowWindow(SW_HIDE); if ((NULL != m_hPThreadEvents[0])&&(NULL != m_hPThreadEvents[1])) { SetEvent(m_hPThreadEvents[1]); } if (NULL != m_hCloseEvent1) { WaitForSingleObject(m_hCloseEvent1,INFINITE); ResetEvent(m_hCloseEvent1); CloseHandle(m_hCloseEvent1); m_hCloseEvent1 = NULL; CloseHandle(m_hPaintThread); m_hPaintThread = NULL; CloseHandle(m_hCapEvent); m_hCapEvent = NULL; } ////////////////////////////////////////////////////////////////////////// /*设置窗口标题*/ char szWndTitle[120]; wsprintf(szWndTitle, "Stop"); //::SetWindowText(::GetParent(this->m_hWnd), szWndTitle); SetWindowText(""); ////////////////////////////////////////////////////////////////////////// if (!signalflag) { signalflag = TRUE; SetWindowText(""); } if (hRGBCapture1) { PauseRunSignal1 = FALSE; // this->RedrawWindow(); stopVGA(m_hWnd, &hRGBCapture1, pCaptureBuffer1); } else { ::MessageBox(GetTopWindow()->m_hWnd, "未运行VGA1采集卡 !","系统提示",MB_ICONWARNING | MB_OK); } } void CRGBSAMPDlg::stopVGA(HWND hWnd, HRGBCAPTURE *phRGBCapture, RGBCAPTUREBUFFER *pCaptureBuffer) { // TODO: Add your command handler code here ////////////////////////////////////////////////////////////////////////// /*释放缓存*/ if (!FreeBuffers(*phRGBCapture, hWnd, pCaptureBuffer)) { TRACE("FreeBuffers(),释放缓存失败!"); return; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /*停止采集事件*/ RGBERROR error; error = RGBCaptureEnable(*phRGBCapture, FALSE); if (RGBERROR_NO_ERROR != error) //打开设备失败,返回结果如下: { switch (error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureEnable() 启动采集卡,打开队列中没有找到该硬件设备句柄\n");//打开队列中没有找到该硬件设备句柄 break; } case RGBERROR_CAPTURE_OUTSTANDING: { TRACE("RGBCaptureEnable() 启动采集卡,硬件设备没有打开\n");//硬件设备没有打开 break; } case RGBERROR_THREAD_FAILURE: { TRACE("RGBCaptureEnable() 启动采集卡,启动线程失败\n");//启动线程失败 break; } default: { break; } } return; } /*关闭采集卡*/ RGBCaptureClose(*phRGBCapture); *phRGBCapture = 0; } /*****************************************************************************/ /* *调整采集卡参数,弹出参数调整的窗口 */ void CRGBSAMPDlg::OnAdjustVga1() { // TODO: Add your command handler code here if ( 0 == hRGBCapture1) { ::MessageBox(m_hWnd, "未运行VGA采集卡 !","系统提示",MB_ICONWARNING | MB_OK); } else { SendMessageW(::GetParent(this->m_hWnd),RGBSAMPWM_QUALADJUST,0,(LPARAM)this); } } /*****************************************************************************/ /* *打开质量管理窗口 */ void CRGBSAMPDlg::OnQualpropVga1() { // TODO: Add your command handler code here if ( 0 == hRGBCapture1 ) { ::MessageBox(m_hWnd, "未运行VGA采集卡 !","系统提示",MB_ICONWARNING | MB_OK); } else { SendMessageW(::GetParent(this->m_hWnd),RGBSAMPWM_QUALPARA,0,(LPARAM)this); } } /*****************************************************************************/ /* *暂停采集 */ void CRGBSAMPDlg::OnPauseVga1() { // TODO: Add your command handler code here if (0 == hRGBCapture1) { ::MessageBox(GetTopWindow()->m_hWnd, "未运行VGA1采集卡 !","系统提示",MB_ICONWARNING | MB_OK); return; } if (PauseRunSignal1) { ::MessageBox(GetTopWindow()->m_hWnd, "已暂停VGA1采集卡 !","系统提示",MB_ICONWARNING | MB_OK); return; } PauseRunSignal1 = TRUE; } /*****************************************************************************/ /* *继续采集 */ void CRGBSAMPDlg::OnGoonVga1() { // TODO: Add your command handler code here HRGBCAPTURE hRGBCapture; hRGBCapture = hRGBCapture1; if (0 == hRGBCapture1) { ::MessageBox(GetTopWindow()->m_hWnd, "未运行VGA1采集卡 !","系统提示",MB_ICONWARNING | MB_OK); return; } if (!PauseRunSignal1) { ::MessageBox(GetTopWindow()->m_hWnd, "未暂停VGA1采集卡 !","系统提示",MB_ICONWARNING | MB_OK); return; } PauseRunSignal1 = FALSE; ////////////////////////////////////////////////////////////////////////// /*此处检测缓存是否就绪,成功则继续采集事件*/ RGBERROR error; error = RGBCaptureFrameBufferReady (hRGBCapture, pCaptureBuffer1->Index, bufferSize1); if (error != RGBERROR_NO_ERROR) { switch (error) { case RGBERROR_INVALID_HRGBCAPTURE: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,检测失败(打开的设备队列中没有找到该硬件设备句柄)\n");//检测失败(打开的设备队列中没有找到该硬件设备句柄) break; } case RGBERROR_INVALID_INDEX: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,没有找到设备索引\n");//没有找到参数指针 break; } case RGBERROR_BUFFER_TOO_SMALL: { TRACE("RGBCaptureFrameBufferReady(), 检测当前VGA采集卡缓存是否就绪,缓存太小\n");//没有找到参数指针 break; } default: { break; } } char text[80]; wsprintf(text, "RGBCaptureFrameBufferReady returned: %s", RGBErrorToString(error)); ::MessageBox(m_hWnd, text, NULL, MB_OK | MB_ICONERROR); return; } } // *************************************************************************** // *双击,控制当前采集窗口放大/缩小 void CRGBSAMPDlg::OnLButtonDblClk(UINT nFlags, CPoint point) { // SendMessageW(::GetParent(this->m_hWnd),RGBSAMPWM_MAXSIZE,0, (LPARAM)this->m_capnum); // RedrawWindow(); // // TODO: Add your message handler code here and/or call default // // RECT rect; //存放主窗口的尺寸 // // //this->RedrawWindow(); // // ////////////////////////////////////////////////////////////////////////// // 根据当前活动窗口参数采取不同的措施// this->GetClientRect(&rect); //获取主窗口的尺寸 // switch (ActiveStatic) // { // case 0://最大化窗口位置 // { // ModifyStyle(WS_CAPTION,0,0); // this->GetClientRect(&client); //保存主窗口最大化之前的尺寸 // this->GetWindowRect(&screen); // // // int nFullWidth=GetSystemMetrics(SM_CXSCREEN)+8; // int nFullHeight=GetSystemMetrics(SM_CYSCREEN)+8; // // ClientToScreen(&point); // if (PtInRect(&screen, point)) // { // TRACE("OnRButtonUp(),鼠标在窗口中"); //鼠标在第状态控件中 // // 改变窗口和显示控件的尺寸 this->MoveWindow(-4, -4, nFullWidth, nFullHeight,TRUE); // m_static1.MoveWindow(-4, -4, nFullWidth, nFullHeight,TRUE); // ActiveStatic = 1; // } // break; // } // case 1: //双击还原窗口 // { // ModifyStyle(0,WS_CAPTION,0); // this->MoveWindow(screen.left, screen.top, client.right+6, client.bottom+6, TRUE); // this->GetClientRect(&client); // m_static1.MoveWindow(0, 0, client.right, client.bottom, TRUE); // ActiveStatic = 0; // break; // } // default: // { // TRACE("【ERROR 双击事件未匹配 LINE:%d】\n", __LINE__); // break; // } // } // RedrawWindow(); CDialog::OnLButtonDblClk(nFlags, point); } LRESULT CRGBSAMPDlg::OnMyMessage_datamode(WPARAM wParam, LPARAM lParam) { // if (IDOK == ::MessageBox(m_hWnd, "请选择输入数据模式:\n 选择RGB模式请点击“确定”;\n 选择YUV模式请点击“取消”","系统提示",MB_ICONWARNING | MB_OKCANCEL)) { datamode = 1; return(1); } // else // { // datamode = 0; // return(0); // } } void CRGBSAMPDlg::OnMyMessage_ddrerror(WPARAM wParam, LPARAM lParam) { // CRect rc; // CDC *pDC; // int x; // int y; // CString strInfo = _T("DDR????!"); // ////////////////////////////////////////////////////////////////////////// // /*????*/ // LOGFONT ft; // // ft.lfHeight = 32; // ft.lfWidth = 16; // ft.lfEscapement = 0; // ft.lfOrientation = 0; // ft.lfWeight = FW_HEAVY; // ft.lfItalic = FALSE; // ft.lfUnderline = FALSE; // ft.lfStrikeOut = FALSE; // ft.lfCharSet = ANSI_CHARSET; // ft.lfOutPrecision = OUT_DEFAULT_PRECIS; // ft.lfClipPrecision = CLIP_DEFAULT_PRECIS; // ft.lfQuality = DEFAULT_QUALITY; // ft.lfPitchAndFamily = VARIABLE_PITCH; // strcpy(ft.lfFaceName,"??"); // // HFONT hFont = ::CreateFontIndirect(&ft); // pDC = GetDC(); // GetClientRect(rc); // this->RedrawWindow(); // x = ( rc.Width() - strInfo.GetLength() * ft.lfWidth ) / 2; // y = ( rc.Height() - ft.lfHeight ) / 2; // pDC->SelectObject(hFont); // ////////////////////////////////////////////////////////////////////////// // /*????*/ // CBrush brush; // brush.CreateSolidBrush(RGB(0,0,0)); // /*??*/ // pDC->SelectObject(&brush); // pDC->SetBkColor(RGB(0,0,0)); // pDC->SetTextColor(RGB(255,255,255)); // pDC->TextOut(x,y,strInfo); // // ReleaseDC(pDC); } void CRGBSAMPDlg::OnCancel() { }
[ "damoguyan8844@00acd8f4-21d3-11df-8b29-c50f69cede6d" ]
[ [ [ 1, 1816 ] ] ]
ce3b4c59f71a7889f12f4c8cf5a899eefd64a84b
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/src/Engine/Entities/StlMesh.cpp
4890f89d6f2c844ea8dd9bc1835981982e640606
[]
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
9,130
cpp
#include "precomp.h" #include "StlMesh.h" #include <Event/Event.h> #include <Event/EventValue.h> #include <Core/CoreMgr.h> #include <Core/Cam.h> #include <Resource/ResMgr.h> #include <Resource/TexResource.h> #include <iostream> #include <sstream> #include <fstream> using namespace Engine; StlMesh::StlMesh(unsigned int id, const CL_String &type, const CL_String &name, CoreMgr *coreMgr, ComponentFactory &factory) : IEntity(id, type, name, coreMgr, factory), solid(true), size(4.0f), shouldUpdate(false), loaded(false) { pos = this->AddProperty<CL_Vec3f>("Position", CL_Vec3f(0,0,0)); rot = this->AddProperty<CL_Mat3f>("RotationMatrix", CL_Mat3f::identity()); pitch = this->AddProperty<float>("Pitch", 0.0f); pitchRate = this->AddProperty<float>("PitchRate", 1.0f); yaw = this->AddProperty<float>("Yaw", 0.0f); yawRate = this->AddProperty<float>("YawRate", 1.0f); mesh = this->AddProperty<CL_String>("Mesh", CL_String()); mirror = this->AddProperty<bool>("Mirror", false); slotPitchChanged = pitch.ValueChanged().connect(this, &StlMesh::OnPitchChanged); slotYawChanged = yaw.ValueChanged().connect(this, &StlMesh::OnYawChanged); slotMeshChanged = mesh.ValueChanged().connect(this, &StlMesh::OnMeshChanged); upDirection = CL_Vec3f(0.0f, 1.0f, 0.0f); TexResource::beginTextureCube(texture); TexResource::createTextureCube( cl_format("%1Skybox/%2", coreMgr->getResMgr()->getRootPath(), "X+.tga").c_str(), GL_TEXTURE_CUBE_MAP_POSITIVE_X); TexResource::createTextureCube( cl_format("%1Skybox/%2", coreMgr->getResMgr()->getRootPath(), "X-.tga").c_str(), GL_TEXTURE_CUBE_MAP_NEGATIVE_X); TexResource::createTextureCube( cl_format("%1Skybox/%2", coreMgr->getResMgr()->getRootPath(), "Y+.tga").c_str(), GL_TEXTURE_CUBE_MAP_POSITIVE_Y); TexResource::createTextureCube( cl_format("%1Skybox/%2", coreMgr->getResMgr()->getRootPath(), "Y-.tga").c_str(), GL_TEXTURE_CUBE_MAP_NEGATIVE_Y); TexResource::createTextureCube( cl_format("%1Skybox/%2", coreMgr->getResMgr()->getRootPath(), "Z+.tga").c_str(), GL_TEXTURE_CUBE_MAP_POSITIVE_Z); TexResource::createTextureCube( cl_format("%1Skybox/%2", coreMgr->getResMgr()->getRootPath(), "Z-.tga").c_str(), GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); TexResource::endTextureCube(texture); } StlMesh::~StlMesh() { glDeleteBuffers(1, &ibo); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); } bool StlMesh::load(const CL_String &filename) { if(loaded) return false; CL_String path = cl_format("%1Mesh/%2.stl", coreMgr->getResMgr()->getRootPath(), filename); //Open file std::ifstream fin(path.c_str(), std::ios::binary); if(fin.bad()) { fin.close(); CL_Console::write_line(cl_format("Could not open stl mesh file %1", path)); return false; } //Header fin.read((char*)&stl_header.head, sizeof(unsigned char)*80); fin.read((char*)&stl_header.num_tris, sizeof(unsigned long int)); //Triangles stl_tris = new StlTri[stl_header.num_tris]; for(unsigned long int i = 0; i < stl_header.num_tris; i++) { fin.read((char*)&stl_tris[i], sizeof(float)*12+sizeof(unsigned short)); } //Close file fin.close(); calcBufferData(); delete[] stl_tris; return true; } void StlMesh::calcBufferData() { unsigned int index_count = 0; for(unsigned long int i = 0; i < stl_header.num_tris; i++) { indices.push_back(index_count++); indices.push_back(index_count++); indices.push_back(index_count++); StlTri &tri = stl_tris[i]; vertices.push_back(tri.vert1[0]*50.0f); vertices.push_back(tri.vert1[2]*50.0f); vertices.push_back(tri.vert1[1]*50.0f); vertices.push_back(tri.vert2[0]*50.0f); vertices.push_back(tri.vert2[2]*50.0f); vertices.push_back(tri.vert2[1]*50.0f); vertices.push_back(tri.vert3[0]*50.0f); vertices.push_back(tri.vert3[2]*50.0f); vertices.push_back(tri.vert3[1]*50.0f); normals.push_back(tri.norm[0]); normals.push_back(tri.norm[2]); normals.push_back(tri.norm[1]); normals.push_back(tri.norm[0]); normals.push_back(tri.norm[2]); normals.push_back(tri.norm[1]); normals.push_back(tri.norm[0]); normals.push_back(tri.norm[2]); normals.push_back(tri.norm[1]); } unsigned int vertSize = sizeof(float)*vertices.size(); unsigned int indSize = sizeof(unsigned int)*indices.size(); unsigned int normSize = sizeof(float)*normals.size(); unsigned int vertOffset = 0; unsigned int indOffset = 0; unsigned int normOffset = vertOffset + vertSize; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indSize, &indices[0], GL_STATIC_DRAW); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vertSize+normSize, NULL, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, vertOffset, vertSize, &vertices[0]); glBufferSubData(GL_ARRAY_BUFFER, normOffset, normSize, &normals[0]); shader.setShader("resources/Shaders/stl"); shader.initShader(); Engine::shaderAttrib(shader.getShaderProg(), "vVertex", 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(vertOffset)); Engine::shaderAttrib(shader.getShaderProg(), "vNormal", 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(normOffset)); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void StlMesh::Update(float dt) { if(!loaded) return; if(shouldUpdate) { updateMatrix(dt); shouldUpdate = false; } } void StlMesh::Render() { if(!loaded) return; if(alpha.Get() == 0.0f) return; if(scale.Get() == 0.0f) return; shader.enableShader(); { bindTexture(); bindUniforms(); glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glBindVertexArray(0); unbindTexture(); } shader.disableShader(); } void StlMesh::bindUniforms() { const CL_Mat4f &viewMat = coreMgr->getCam()->getViewMatrix(); const CL_Mat4f &projMat = coreMgr->getCam()->getProjectionMatrix(); CL_Mat4f translateMat = CL_Mat4f::identity(); translateMat[12] = pos.Get().x; translateMat[13] = pos.Get().y; translateMat[14] = pos.Get().z; CL_Mat4f modelMat = CL_Mat4f::identity(); modelMat = modelMat * rot.Get(); modelMat = modelMat * translateMat; CL_Mat4f mvMat = modelMat * viewMat; CL_Mat4f normMat = CL_Mat4f::identity(); normMat[0] = mvMat[0]; normMat[1] = mvMat[1]; normMat[2] = mvMat[2]; normMat[3] = 0.0f; normMat[4] = mvMat[4]; normMat[5] = mvMat[5]; normMat[6] = mvMat[6]; normMat[7] = 0.0f; normMat[8] = mvMat[8]; normMat[9] = mvMat[9]; normMat[10] = mvMat[10]; normMat[11] = 0.0f; normMat[12] = 0.0f; normMat[13] = 0.0f; normMat[14] = 0.0f; normMat[15] = 0.0f; //normMat.inverse(); normMat.transpose(); int loc = glGetUniformLocation(shader.getShaderProg(), "projMat"); if(loc < 0) throw CL_Exception("LOC was -1"); glUniformMatrix4fv(loc, 1, GL_FALSE, &projMat[0]); loc = glGetUniformLocation(shader.getShaderProg(), "mvMat"); if(loc < 0) throw CL_Exception("LOC was -1"); glUniformMatrix4fv(loc, 1, GL_FALSE, &mvMat[0]); loc = glGetUniformLocation(shader.getShaderProg(), "normMat"); if(loc < 0) throw CL_Exception("LOC was -1"); glUniformMatrix4fv(loc, 1, GL_FALSE, &normMat[0]); loc = glGetUniformLocation(shader.getShaderProg(), "fCube"); if(loc < 0) throw CL_Exception("LOC was -1"); glUniform1i(loc, 0); loc = glGetUniformLocation(shader.getShaderProg(), "fAlpha"); if(loc < 0) throw CL_Exception("LOC was -1"); glUniform1f(loc, alpha.Get()); loc = glGetUniformLocation(shader.getShaderProg(), "vMirror"); if(loc < 0) throw CL_Exception("LOC was -1"); glUniform1f(loc, mirror.Get() ? -1.0f : 1.0f); } void StlMesh::bindTexture() { glEnable(GL_TEXTURE_CUBE_MAP); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, texture); } void StlMesh::unbindTexture() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); glDisable(GL_TEXTURE_CUBE_MAP); } void StlMesh::updateMatrix(float dt) { CL_Mat4f mat; CL_Quaternionf q; qPitch = CL_Quaternionf::axis_angle(CL_Angle(pitch.Get(), cl_radians), CL_Vec3f(1.0f, 0.0f, 0.0f)); qHeading = CL_Quaternionf::axis_angle(CL_Angle(yaw.Get(), cl_radians), CL_Vec3f(0.0f, 1.0f, 0.0f)); q = qPitch * qHeading; rot = q.to_matrix(); mat = qPitch.to_matrix(); fowardDirection.y = mat[9]; q = qHeading * qPitch; mat = q.to_matrix(); fowardDirection.x = mat[8]; fowardDirection.z = mat[10]; leftDirection = CL_Vec3f::cross(fowardDirection, upDirection); } void StlMesh::OnPitchChanged(const float &oldValue, const float &newValue) { shouldUpdate = true; } void StlMesh::OnYawChanged(const float &oldValue, const float &newValue) { shouldUpdate = true; } void StlMesh::OnMeshChanged(const CL_String &oldValue, const CL_String &newValue) { if(!load(newValue)) throw CL_Exception(cl_format("Failed to load STL mesh %1", newValue)); loaded = true; }
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 297 ] ] ]
fdd5aed0f052872c072776f11f9f6ba59b174939
24bc1634133f5899f7db33e5d9692ba70940b122
/extlibs/RakNet/include/BitStream_NoTemplate.h
d7de92fc2719e45d6f63fc4f9587ef4f4f4c7c76
[]
no_license
deft-code/ammo
9a9cd9bd5fb75ac1b077ad748617613959dbb7c9
fe4139187dd1d371515a2d171996f81097652e99
refs/heads/master
2016-09-05T08:48:51.786465
2009-10-09T05:49:00
2009-10-09T05:49:00
32,252,326
0
0
null
null
null
null
UTF-8
C++
false
false
71,063
h
/// \file /// \brief This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well. /// /// This file is part of RakNet Copyright 2003 Kevin Jenkins. /// /// Usage of RakNet is subject to the appropriate license agreement. /// Creative Commons Licensees are subject to the /// license found at /// http://creativecommons.org/licenses/by-nc/2.5/ /// Single application licensees are subject to the license found at /// http://www.jenkinssoftware.com/SingleApplicationLicense.html /// Custom license users are subject to the terms therein. /// GPL license users are subject to 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. #if defined(_MSC_VER) && _MSC_VER < 1299 // VC6 doesn't support template specialization #ifndef __BITSTREAM_H #define __BITSTREAM_H #include "RakMemoryOverride.h" #include "RakNetDefines.h" #include "Export.h" #include "RakNetTypes.h" #include <assert.h> #if defined(_PS3) #include <math.h> #else #include <cmath> #endif #include <float.h> #ifdef _MSC_VER #pragma warning( push ) #endif /// Arbitrary size, just picking something likely to be larger than most packets #define BITSTREAM_STACK_ALLOCATION_SIZE 256 /// The namespace RakNet is not consistently used. It's only purpose is to avoid compiler errors for classes whose names are very common. /// For the most part I've tried to avoid this simply by using names very likely to be unique for my classes. namespace RakNet { /// This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well. /// \sa BitStreamSample.txt class RAK_DLL_EXPORT BitStream { public: /// Default Constructor BitStream(); /// Create the bitstream, with some number of bytes to immediately allocate. /// There is no benefit to calling this, unless you know exactly how many bytes you need and it is greater than BITSTREAM_STACK_ALLOCATION_SIZE. /// In that case all it does is save you one or more realloc calls. /// \param[in] initialBytesToAllocate the number of bytes to pre-allocate. BitStream( int initialBytesToAllocate ); /// Initialize the BitStream, immediately setting the data it contains to a predefined pointer. /// Set \a _copyData to true if you want to make an internal copy of the data you are passing. Set it to false to just save a pointer to the data. /// You shouldn't call Write functions with \a _copyData as false, as this will write to unallocated memory /// 99% of the time you will use this function to cast Packet::data to a bitstream for reading, in which case you should write something as follows: /// \code /// RakNet::BitStream bs(packet->data, packet->length, false); /// \endcode /// \param[in] _data An array of bytes. /// \param[in] lengthInBytes Size of the \a _data. /// \param[in] _copyData true or false to make a copy of \a _data or not. BitStream( unsigned char* _data, unsigned int lengthInBytes, bool _copyData ); /// Destructor ~BitStream(); /// Resets the bitstream for reuse. void Reset( void ); /// Bidirectional serialize/deserialize any integral type to/from a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] var The value to write /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool Serialize(bool writeToBitstream, bool &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, unsigned char &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, char &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, unsigned short &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, short &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, unsigned int &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, int &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, unsigned long &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, long &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, long long &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, unsigned long long &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, float &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, double &var){if (writeToBitstream)Write(var);else return Read(var); return true;} bool Serialize(bool writeToBitstream, long double &var){if (writeToBitstream)Write(var);else return Read(var); return true;} /// Bidirectional serialize/deserialize any integral type to/from a bitstream. If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeDelta(bool writeToBitstream, bool &currentValue, bool lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned char &currentValue, unsigned char lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, char &currentValue, char lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned short &currentValue, unsigned short lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, short &currentValue, short lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned int &currentValue, unsigned int lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, int &currentValue, int lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned long &currentValue, unsigned long lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, long long &currentValue, long long lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned long long &currentValue, unsigned long long lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, float &currentValue, float lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, double &currentValue, double lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, long double &currentValue, long double lastValue){if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue);return true;} /// Bidirectional version of SerializeDelta when you don't know what the last value is, or there is no last value. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] currentValue The current value to write /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeDelta(bool writeToBitstream, bool &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned char &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, char &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned short &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, short &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned int &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, int &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned long &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, long long &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, unsigned long long &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, float &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, double &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} bool SerializeDelta(bool writeToBitstream, long double &currentValue){if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue);return true;} /// Bidirectional serialize/deserialize any integral type to/from a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] var The value to write /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeCompressed(bool writeToBitstream, bool &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, unsigned char &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, char &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, unsigned short &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, short &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, unsigned int &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, int &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, unsigned long &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, long &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, long long &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, unsigned long long &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, float &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, double &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} bool SerializeCompressed(bool writeToBitstream, long double &var){if (writeToBitstream)WriteCompressed(var);else return ReadCompressed(var); return true;} /// Bidirectional serialize/deserialize any integral type to/from a bitstream. If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeCompressedDelta(bool writeToBitstream, bool &currentValue, bool lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned char &currentValue, unsigned char lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, char &currentValue, char lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned short &currentValue, unsigned short lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, short &currentValue, short lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned int &currentValue, unsigned int lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, int &currentValue, int lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned long &currentValue, unsigned long lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, long long &currentValue, long long lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned long long &currentValue, unsigned long long lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, float &currentValue, float lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, double &currentValue, double lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} bool SerializeCompressedDelta(bool writeToBitstream, long double &currentValue, long double lastValue){if (writeToBitstream) WriteCompressedDelta(currentValue, lastValue); else return ReadCompressedDelta(currentValue);return true;} /// Save as SerializeCompressedDelta(templateType &currentValue, templateType lastValue) when we have an unknown second parameter bool SerializeCompressedDelta(bool writeToBitstream, bool &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned char &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, char &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned short &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, short &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned int &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, int &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned long &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, long &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, long long &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, unsigned long long &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, float &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, double &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} bool SerializeCompressedDelta(bool writeToBitstream, long double &var){if (writeToBitstream)WriteCompressedDelta(var);else return ReadCompressedDelta(var); return true;} /// Bidirectional serialize/deserialize an array or casted stream or raw data. This does NOT do endian swapping. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] input a byte buffer /// \param[in] numberOfBytes the size of \a input in bytes /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool Serialize(bool writeToBitstream, char* input, const int numberOfBytes ); /// Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. Will further compress y or z axis aligned vectors. /// Accurate to 1/32767.5. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeNormVector(bool writeToBitstream, float &x, float &y, float z ){if (writeToBitstream) WriteNormVector(x,y,z); else return ReadNormVector(x,y,z); return true;} bool SerializeNormVector(bool writeToBitstream, double &x, double &y, double &z ){if (writeToBitstream) WriteNormVector(x,y,z); else return ReadNormVector(x,y,z); return true;} /// Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12. /// Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeVector(bool writeToBitstream, float &x, float &y, float &z ){if (writeToBitstream) WriteVector(x,y,z); else return ReadVector(x,y,z); return true;} bool SerializeVector(bool writeToBitstream, double &x, double &y, double &z ){if (writeToBitstream) WriteVector(x,y,z); else return ReadVector(x,y,z); return true;} /// Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] w w /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeNormQuat(bool writeToBitstream, float &w, float &x, float &y, float &z){if (writeToBitstream) WriteNormQuat(w,x,y,z); else return ReadNormQuat(w,x,y,z); return true;} bool SerializeNormQuat(bool writeToBitstream, double &w, double &x, double &y, double &z){if (writeToBitstream) WriteNormQuat(w,x,y,z); else return ReadNormQuat(w,x,y,z); return true;} /// Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each /// for 6 bytes instead of 36 /// Lossy, although the result is renormalized bool SerializeOrthMatrix( bool writeToBitstream, float &m00, float &m01, float &m02, float &m10, float &m11, float &m12, float &m20, float &m21, float &m22 ){if (writeToBitstream) WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); else return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); return true;} bool SerializeOrthMatrix( bool writeToBitstream, double &m00, double &m01, double &m02, double &m10, double &m11, double &m12, double &m20, double &m21, double &m22 ){if (writeToBitstream) WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); else return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); return true;} /// Bidirectional serialize/deserialize numberToSerialize bits to/from the input. Right aligned /// data means in the case of a partial byte, the bits are aligned /// from the right (bit 0) rather than the left (as in the normal /// internal representation) You would set this to true when /// writing user data, and false when copying bitstream data, such /// as writing one bitstream to another /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] input The data /// \param[in] numberOfBitsToSerialize The number of bits to write /// \param[in] rightAlignedBits if true data will be right aligned /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeBits(bool writeToBitstream, unsigned char* input, int numberOfBitsToSerialize, const bool rightAlignedBits = true ); /// Write any integral type to a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] var The value to write void Write(bool var){if ( var ) Write1(); else Write0();} void Write(unsigned char var){WriteBits( ( unsigned char* ) & var, sizeof( unsigned char ) * 8, true );} void Write(char var){WriteBits( ( unsigned char* ) & var, sizeof( char ) * 8, true );} void Write(unsigned short var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned short)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned short)); WriteBits( ( unsigned char* ) output, sizeof(unsigned short) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(unsigned short) * 8, true );} void Write(short var) {if (DoEndianSwap()){unsigned char output[sizeof(short)]; ReverseBytes((unsigned char*)&var, output, sizeof(short)); WriteBits( ( unsigned char* ) output, sizeof(short) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(short) * 8, true );} void Write(unsigned int var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned int)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned int)); WriteBits( ( unsigned char* ) output, sizeof(unsigned int) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(unsigned int) * 8, true );} void Write(int var) {if (DoEndianSwap()){unsigned char output[sizeof(int)]; ReverseBytes((unsigned char*)&var, output, sizeof(int)); WriteBits( ( unsigned char* ) output, sizeof(int) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(int) * 8, true );} void Write(unsigned long var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned long)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned long)); WriteBits( ( unsigned char* ) output, sizeof(unsigned long) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(unsigned long) * 8, true );} void Write(long var) {if (DoEndianSwap()){unsigned char output[sizeof(long)]; ReverseBytes((unsigned char*)&var, output, sizeof(long)); WriteBits( ( unsigned char* ) output, sizeof(long) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(long) * 8, true );} void Write(long long var) {if (DoEndianSwap()){unsigned char output[sizeof(long long)]; ReverseBytes((unsigned char*)&var, output, sizeof(long long)); WriteBits( ( unsigned char* ) output, sizeof(long long) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(long long) * 8, true );} void Write(unsigned long long var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned long long)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned long long)); WriteBits( ( unsigned char* ) output, sizeof(unsigned long long) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(unsigned long long) * 8, true );} void Write(float var) {if (DoEndianSwap()){unsigned char output[sizeof(float)]; ReverseBytes((unsigned char*)&var, output, sizeof(float)); WriteBits( ( unsigned char* ) output, sizeof(float) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(float) * 8, true );} void Write(double var) {if (DoEndianSwap()){unsigned char output[sizeof(double)]; ReverseBytes((unsigned char*)&var, output, sizeof(double)); WriteBits( ( unsigned char* ) output, sizeof(double) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(double) * 8, true );} void Write(long double var) {if (DoEndianSwap()){unsigned char output[sizeof(long double)]; ReverseBytes((unsigned char*)&var, output, sizeof(long double)); WriteBits( ( unsigned char* ) output, sizeof(long double) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(long double) * 8, true );} void Write(void* var) {if (DoEndianSwap()){unsigned char output[sizeof(void*)]; ReverseBytes((unsigned char*)&var, output, sizeof(void*)); WriteBits( ( unsigned char* ) output, sizeof(void*) * 8, true );} WriteBits( ( unsigned char* ) & var, sizeof(void*) * 8, true );} void Write(SystemAddress var){WriteBits( ( unsigned char* ) & var.binaryAddress, sizeof(var.binaryAddress) * 8, true ); Write(var.port);} void Write(NetworkID var){if (NetworkID::IsPeerToPeerMode()) Write(var.systemAddress); Write(var.localSystemAddress);} /// Write any integral type to a bitstream. If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against void WriteDelta(bool currentValue, bool lastValue){ #pragma warning(disable:4100) // warning C4100: 'peer' : unreferenced formal parameter Write(currentValue); } void WriteDelta(unsigned char currentValue, unsigned char lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(char currentValue, char lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(unsigned short currentValue, unsigned short lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(short currentValue, short lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(unsigned int currentValue, unsigned int lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(int currentValue, int lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(unsigned long currentValue, unsigned long lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(long currentValue, long lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(long long currentValue, long long lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(unsigned long long currentValue, unsigned long long lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(float currentValue, float lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(double currentValue, double lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(long double currentValue, long double lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(SystemAddress currentValue, SystemAddress lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} void WriteDelta(NetworkID currentValue, NetworkID lastValue){if (currentValue==lastValue) {Write(false);} else {Write(true); Write(currentValue);}} /// WriteDelta when you don't know what the last value is, or there is no last value. /// \param[in] currentValue The current value to write void WriteDelta(bool var){Write(var);} void WriteDelta(unsigned char var){Write(true); Write(var);} void WriteDelta(char var){Write(true); Write(var);} void WriteDelta(unsigned short var){Write(true); Write(var);} void WriteDelta(short var){Write(true); Write(var);} void WriteDelta(unsigned int var){Write(true); Write(var);} void WriteDelta(int var){Write(true); Write(var);} void WriteDelta(unsigned long var){Write(true); Write(var);} void WriteDelta(long var){Write(true); Write(var);} void WriteDelta(long long var){Write(true); Write(var);} void WriteDelta(unsigned long long var){Write(true); Write(var);} void WriteDelta(float var){Write(true); Write(var);} void WriteDelta(double var){Write(true); Write(var);} void WriteDelta(long double var){Write(true); Write(var);} void WriteDelta(SystemAddress var){Write(true); Write(var);} void WriteDelta(NetworkID var){Write(true); Write(var);} /// Write any integral type to a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// \param[in] var The value to write void WriteCompressed(bool var) {Write(var);} void WriteCompressed(unsigned char var) {WriteCompressed( ( unsigned char* ) & var, sizeof( unsigned char ) * 8, true );} void WriteCompressed(char var) {WriteCompressed( (unsigned char* ) & var, sizeof( unsigned char ) * 8, true );} void WriteCompressed(unsigned short var) {if (DoEndianSwap()) {unsigned char output[sizeof(unsigned short)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned short)); WriteCompressed( ( unsigned char* ) output, sizeof(unsigned short) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(unsigned short) * 8, true );} void WriteCompressed(short var) {if (DoEndianSwap()) {unsigned char output[sizeof(short)]; ReverseBytes((unsigned char*)&var, output, sizeof(short)); WriteCompressed( ( unsigned char* ) output, sizeof(short) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(short) * 8, true );} void WriteCompressed(unsigned int var) {if (DoEndianSwap()) {unsigned char output[sizeof(unsigned int)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned int)); WriteCompressed( ( unsigned char* ) output, sizeof(unsigned int) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(unsigned int) * 8, true );} void WriteCompressed(int var) {if (DoEndianSwap()) { unsigned char output[sizeof(int)]; ReverseBytes((unsigned char*)&var, output, sizeof(int)); WriteCompressed( ( unsigned char* ) output, sizeof(int) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(int) * 8, true );} void WriteCompressed(unsigned long var) {if (DoEndianSwap()) {unsigned char output[sizeof(unsigned long)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned long)); WriteCompressed( ( unsigned char* ) output, sizeof(unsigned long) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(unsigned long) * 8, true );} void WriteCompressed(long var) {if (DoEndianSwap()) {unsigned char output[sizeof(long)]; ReverseBytes((unsigned char*)&var, output, sizeof(long)); WriteCompressed( ( unsigned char* ) output, sizeof(long) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(long) * 8, true );} void WriteCompressed(long long var) {if (DoEndianSwap()) {unsigned char output[sizeof(long long)]; ReverseBytes((unsigned char*)&var, output, sizeof(long long)); WriteCompressed( ( unsigned char* ) output, sizeof(long long) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(long long) * 8, true );} void WriteCompressed(unsigned long long var) {if (DoEndianSwap()) { unsigned char output[sizeof(unsigned long long)]; ReverseBytes((unsigned char*)&var, output, sizeof(unsigned long long)); WriteCompressed( ( unsigned char* ) output, sizeof(unsigned long long) * 8, true );} else WriteCompressed( ( unsigned char* ) & var, sizeof(unsigned long long) * 8, true );} void WriteCompressed(float var) {assert(var > -1.01f && var < 1.01f); if (var < -1.0f) var=-1.0f; if (var > 1.0f) var=1.0f; Write((unsigned short)((var+1.0f)*32767.5f));} void WriteCompressed(double var) {assert(var > -1.01 && var < 1.01); if (var < -1.0) var=-1.0; if (var > 1.0) var=1.0; Write((unsigned long)((var+1.0)*2147483648.0));} void WriteCompressed(long double var) {assert(var > -1.01 && var < 1.01); if (var < -1.0) var=-1.0; if (var > 1.0) var=1.0; Write((unsigned long)((var+1.0)*2147483648.0));} /// Write any integral type to a bitstream. If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against void WriteCompressedDelta(bool currentValue, bool lastValue) { #pragma warning(disable:4100) // warning C4100: 'peer' : unreferenced formal parameter Write(currentValue); } void WriteCompressedDelta(unsigned char currentValue, unsigned char lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(char currentValue, char lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(unsigned short currentValue, unsigned short lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(short currentValue, short lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(unsigned int currentValue, unsigned int lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(int currentValue, int lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(unsigned long currentValue, unsigned long lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(long currentValue, long lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(long long currentValue, long long lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(unsigned long long currentValue, unsigned long long lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(float currentValue, float lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(double currentValue, double lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} void WriteCompressedDelta(long double currentValue, long double lastValue){if (currentValue==lastValue) {Write(false);} else { Write(true); WriteCompressed(currentValue);}} /// Save as WriteCompressedDelta(templateType currentValue, templateType lastValue) when we have an unknown second parameter void WriteCompressedDelta(bool var) {Write(var);} void WriteCompressedDelta(unsigned char var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(char var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(unsigned short var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(short var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(unsigned int var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(int var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(unsigned long var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(long var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(long long var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(unsigned long long var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(float var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(double var) { Write(true); WriteCompressed(var); } void WriteCompressedDelta(long double var) { Write(true); WriteCompressed(var); } /// Read any integral type from a bitstream. Define __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] var The value to read bool Read(bool &var){if ( readOffset + 1 > numberOfBitsUsed ) return false; if ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) var = true; else var = false; // Has to be on a different line for Mac readOffset++; return true; } bool Read(unsigned char &var) {return ReadBits( ( unsigned char* ) &var, sizeof(unsigned char) * 8, true );} bool Read(char &var) {return ReadBits( ( unsigned char* ) &var, sizeof(char) * 8, true );} bool Read(unsigned short &var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned short)]; if (ReadBits( ( unsigned char* ) output, sizeof(unsigned short) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned short)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(unsigned short) * 8, true );} bool Read(short &var) {if (DoEndianSwap()){unsigned char output[sizeof(short)]; if (ReadBits( ( unsigned char* ) output, sizeof(short) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(short)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(short) * 8, true );} bool Read(unsigned int &var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned int)]; if (ReadBits( ( unsigned char* ) output, sizeof(unsigned int) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned int)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(unsigned int) * 8, true );} bool Read(int &var) {if (DoEndianSwap()){unsigned char output[sizeof(int)]; if (ReadBits( ( unsigned char* ) output, sizeof(int) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(int)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(int) * 8, true );} bool Read(unsigned long &var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned long)]; if (ReadBits( ( unsigned char* ) output, sizeof(unsigned long) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned long)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(unsigned long) * 8, true );} bool Read(long &var) {if (DoEndianSwap()){unsigned char output[sizeof(long)]; if (ReadBits( ( unsigned char* ) output, sizeof(long) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(long)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(long) * 8, true );} bool Read(long long &var) {if (DoEndianSwap()){unsigned char output[sizeof(long long)]; if (ReadBits( ( unsigned char* ) output, sizeof(long long) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(long long)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(long long) * 8, true );} bool Read(unsigned long long &var) {if (DoEndianSwap()){unsigned char output[sizeof(unsigned long long)]; if (ReadBits( ( unsigned char* ) output, sizeof(unsigned long long) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned long long)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(unsigned long long) * 8, true );} bool Read(float &var) {if (DoEndianSwap()){unsigned char output[sizeof(float)]; if (ReadBits( ( unsigned char* ) output, sizeof(float) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(float)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(float) * 8, true );} bool Read(double &var) {if (DoEndianSwap()){unsigned char output[sizeof(double)]; if (ReadBits( ( unsigned char* ) output, sizeof(double) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(double)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(double) * 8, true );} bool Read(long double &var) {if (DoEndianSwap()){unsigned char output[sizeof(long double)]; if (ReadBits( ( unsigned char* ) output, sizeof(long double) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(long double)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(long double) * 8, true );} bool Read(void* &var) {if (DoEndianSwap()){unsigned char output[sizeof(void*)]; if (ReadBits( ( unsigned char* ) output, sizeof(void*) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(void*)); return true;} return false;} else return ReadBits( ( unsigned char* ) & var, sizeof(void*) * 8, true );} bool Read(SystemAddress &var){ReadBits( ( unsigned char* ) & var.binaryAddress, sizeof(var.binaryAddress) * 8, true ); return Read(var.port);} bool Read(NetworkID &var){if (NetworkID::IsPeerToPeerMode()) Read(var.systemAddress); return Read(var.localSystemAddress);} /// Read any integral type from a bitstream. If the written value differed from the value compared against in the write function, /// var will be updated. Otherwise it will retain the current value. /// ReadDelta is only valid from a previous call to WriteDelta /// \param[in] var The value to read bool ReadDelta(bool &var) {return Read(var);} bool ReadDelta(unsigned char &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(char &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(unsigned short &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(short &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(unsigned int &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(int &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(unsigned long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(long long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(unsigned long long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(float &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(double &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(long double &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(SystemAddress &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} bool ReadDelta(NetworkID &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success;} /// Read any integral type from a bitstream. Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] var The value to read bool ReadCompressed(bool &var) {return Read(var);} bool ReadCompressed(unsigned char &var) {return ReadCompressed( ( unsigned char* ) &var, sizeof(unsigned char) * 8, true );} bool ReadCompressed(char &var) {return ReadCompressed( ( unsigned char* ) &var, sizeof(unsigned char) * 8, true );} bool ReadCompressed(unsigned short &var){if (DoEndianSwap()){unsigned char output[sizeof(unsigned short)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(unsigned short) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned short)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(unsigned short) * 8, true );} bool ReadCompressed(short &var){if (DoEndianSwap()){unsigned char output[sizeof(short)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(short) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(short)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(short) * 8, true );} bool ReadCompressed(unsigned int &var){if (DoEndianSwap()){unsigned char output[sizeof(unsigned int)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(unsigned int) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned int)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(unsigned int) * 8, true );} bool ReadCompressed(int &var){if (DoEndianSwap()){unsigned char output[sizeof(int)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(int) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(int)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(int) * 8, true );} bool ReadCompressed(unsigned long &var){if (DoEndianSwap()){unsigned char output[sizeof(unsigned long)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(unsigned long) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned long)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(unsigned long) * 8, true );} bool ReadCompressed(long &var){if (DoEndianSwap()){unsigned char output[sizeof(long)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(long) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(long)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(long) * 8, true );} bool ReadCompressed(long long &var){if (DoEndianSwap()){unsigned char output[sizeof(long long)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(long long) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(long long)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(long long) * 8, true );} bool ReadCompressed(unsigned long long &var){if (DoEndianSwap()){unsigned char output[sizeof(unsigned long long)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(unsigned long long) * 8, true )){ReverseBytes(output, (unsigned char*)&var, sizeof(unsigned long long)); return true;} return false;}else return ReadCompressed( ( unsigned char* ) & var, sizeof(unsigned long long) * 8, true );} bool ReadCompressed(float &var){unsigned short compressedFloat; if (Read(compressedFloat)) { var = ((float)compressedFloat / 32767.5f - 1.0f); return true;} return false;} bool ReadCompressed(double &var) {unsigned long compressedFloat; if (Read(compressedFloat)) { var = ((double)compressedFloat / 2147483648.0 - 1.0); return true; } return false;} bool ReadCompressed(long double &var) {unsigned long compressedFloat; if (Read(compressedFloat)) { var = ((long double)compressedFloat / 2147483648.0 - 1.0); return true; } return false;} bool ReadCompressed(SystemAddress &var) {return Read(var);} bool ReadCompressed(NetworkID &var) {return Read(var);} /// Read any integral type from a bitstream. If the written value differed from the value compared against in the write function, /// var will be updated. Otherwise it will retain the current value. /// the current value will be updated. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// ReadCompressedDelta is only valid from a previous call to WriteDelta /// \param[in] var The value to read bool ReadCompressedDelta(bool &var) {return Read(var);} bool ReadCompressedDelta(unsigned char &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(char &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(unsigned short &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(short &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(unsigned int &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(int &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(unsigned long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(long long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(unsigned long long &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(float &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(double &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} bool ReadCompressedDelta(long double &var){bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success;} /// Write an array or casted stream or raw data. This does NOT do endian swapping. /// \param[in] input a byte buffer /// \param[in] numberOfBytes the size of \a input in bytes void Write( const char* input, const int numberOfBytes ); /// Write one bitstream to another /// \param[in] numberOfBits bits to write /// \param bitStream the bitstream to copy from void Write( BitStream *bitStream, int numberOfBits ); void Write( BitStream *bitStream ); /// Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. Will further compress y or z axis aligned vectors. /// Accurate to 1/32767.5. /// \param[in] x x /// \param[in] y y /// \param[in] z z void WriteNormVector( float x, float y, float z ); void WriteNormVector( double x, double y, double z ) {WriteNormVector((float)x,(float)y,(float)z);} /// Write a vector, using 10 bytes instead of 12. /// Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important. /// \param[in] x x /// \param[in] y y /// \param[in] z z void WriteVector( float x, float y, float z ); void WriteVector( double x, double y, double z ) {WriteVector((float)x, (float)y, (float)z);} /// Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. /// \param[in] w w /// \param[in] x x /// \param[in] y y /// \param[in] z z void WriteNormQuat( float w, float x, float y, float z); void WriteNormQuat( double w, double x, double y, double z) {WriteNormQuat((float)w, (float) x, (float) y, (float) z);} /// Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each /// for 6 bytes instead of 36 /// Lossy, although the result is renormalized void WriteOrthMatrix( float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22 ) { WriteOrthMatrix((double)m00,(double)m01,(double)m02, (double)m10,(double)m11,(double)m12, (double)m20,(double)m21,(double)m22); } void WriteOrthMatrix( double m00, double m01, double m02, double m10, double m11, double m12, double m20, double m21, double m22 ); /// Read an array or casted stream of byte. The array /// is raw data. There is no automatic endian conversion with this function /// \param[in] output The result byte array. It should be larger than @em numberOfBytes. /// \param[in] numberOfBytes The number of byte to read /// \return true on success false if there is some missing bytes. bool Read( char* output, const int numberOfBytes ); /// Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. Will further compress y or z axis aligned vectors. /// Accurate to 1/32767.5. /// \param[in] x x /// \param[in] y y /// \param[in] z z bool ReadNormVector( float &x, float &y, float &z ); bool ReadNormVector( double &x, double &y, double &z ) {float fx, fy, fz; bool b = ReadNormVector(fx, fy, fz); x=fx; y=fy; z=fz; return b;} /// Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector /// Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important. /// \param[in] x x /// \param[in] y y /// \param[in] z z bool ReadVector( float x, float y, float z ); bool ReadVector( double &x, double &y, double &z ) {return ReadVector((float)x, (float)y, (float)z);} /// Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. /// \param[in] w w /// \param[in] x x /// \param[in] y y /// \param[in] z z bool ReadNormQuat( float &w, float &x, float &y, float &z){double dw, dx, dy, dz; bool b=ReadNormQuat(dw, dx, dy, dz); w=(float)dw; x=(float)dx; y=(float)dy; z=(float)dz; return b;} bool ReadNormQuat( double &w, double &x, double &y, double &z); /// Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolating the 4th. /// for 6 bytes instead of 36 /// Lossy, although the result is renormalized bool ReadOrthMatrix( float &m00, float &m01, float &m02, float &m10, float &m11, float &m12, float &m20, float &m21, float &m22 ); bool ReadOrthMatrix( double &m00, double &m01, double &m02, double &m10, double &m11, double &m12, double &m20, double &m21, double &m22 ); ///Sets the read pointer back to the beginning of your data. void ResetReadPointer( void ); /// Sets the write pointer back to the beginning of your data. void ResetWritePointer( void ); ///This is good to call when you are done with the stream to make /// sure you didn't leave any data left over void void AssertStreamEmpty( void ); /// RAKNET_DEBUG_PRINTF the bits in the stream. Great for debugging. void PrintBits( void ) const; /// Ignore data we don't intend to read /// \param[in] numberOfBits The number of bits to ignore void IgnoreBits( const int numberOfBits ); /// Ignore data we don't intend to read /// \param[in] numberOfBits The number of bytes to ignore void IgnoreBytes( const int numberOfBytes ); ///Move the write pointer to a position on the array. /// \param[in] offset the offset from the start of the array. /// \attention /// Dangerous if you don't know what you are doing! /// For efficiency reasons you can only write mid-stream if your data is byte aligned. void SetWriteOffset( const int offset ); /// Returns the length in bits of the stream inline int GetNumberOfBitsUsed( void ) const {return GetWriteOffset();} inline int GetWriteOffset( void ) const {return numberOfBitsUsed;} ///Returns the length in bytes of the stream inline int GetNumberOfBytesUsed( void ) const {return BITS_TO_BYTES( numberOfBitsUsed );} ///Returns the number of bits into the stream that we have read inline int GetReadOffset( void ) const {return readOffset;} // Sets the read bit index inline void SetReadOffset( int newReadOffset ) {readOffset=newReadOffset;} ///Returns the number of bits left in the stream that haven't been read inline int GetNumberOfUnreadBits( void ) const {return numberOfBitsUsed - readOffset;} /// Makes a copy of the internal data for you \a _data will point to /// the stream. Returns the length in bits of the stream. Partial /// bytes are left aligned /// \param[out] _data The allocated copy of GetData() int CopyData( unsigned char** _data ) const; /// Set the stream to some initial data. /// \internal void SetData( unsigned char *input ); /// Gets the data that BitStream is writing to / reading from /// Partial bytes are left aligned. /// \return A pointer to the internal state inline unsigned char* GetData( void ) const {return data;} /// Write numberToWrite bits from the input source Right aligned /// data means in the case of a partial byte, the bits are aligned /// from the right (bit 0) rather than the left (as in the normal /// internal representation) You would set this to true when /// writing user data, and false when copying bitstream data, such /// as writing one bitstream to another /// \param[in] input The data /// \param[in] numberOfBitsToWrite The number of bits to write /// \param[in] rightAlignedBits if true data will be right aligned void WriteBits( const unsigned char* input, int numberOfBitsToWrite, const bool rightAlignedBits = true ); /// Align the bitstream to the byte boundary and then write the /// specified number of bits. This is faster than WriteBits but /// wastes the bits to do the alignment and requires you to call /// ReadAlignedBits at the corresponding read position. /// \param[in] input The data /// \param[in] numberOfBytesToWrite The size of input. void WriteAlignedBytes( void *input, const int numberOfBytesToWrite ); /// Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite /// \param[in] input The data /// \param[in] inputLength The size of input. /// \param[in] maxBytesToWrite Max bytes to write void WriteAlignedBytesSafe( void *input, const int inputLength, const int maxBytesToWrite ); /// Read bits, starting at the next aligned bits. Note that the /// modulus 8 starting offset of the sequence must be the same as /// was used with WriteBits. This will be a problem with packet /// coalescence unless you byte align the coalesced packets. /// \param[in] output The byte array larger than @em numberOfBytesToRead /// \param[in] numberOfBytesToRead The number of byte to read from the internal state /// \return true if there is enough byte. bool ReadAlignedBytes( void *output, const int numberOfBytesToRead ); /// Reads what was written by WriteAlignedBytesSafe /// \param[in] input The data /// \param[in] maxBytesToRead Maximum number of bytes to read bool ReadAlignedBytesSafe( void *input, int &inputLength, const int maxBytesToRead ); /// Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to /// \param[in] input input will be deleted if it is not a pointer to 0 bool ReadAlignedBytesSafeAlloc( char **input, int &inputLength, const int maxBytesToRead ); /// Align the next write and/or read to a byte boundary. This can /// be used to 'waste' bits to byte align for efficiency reasons It /// can also be used to force coalesced bitstreams to start on byte /// boundaries so so WriteAlignedBits and ReadAlignedBits both /// calculate the same offset when aligning. void AlignWriteToByteBoundary( void ); /// Align the next write and/or read to a byte boundary. This can /// be used to 'waste' bits to byte align for efficiency reasons It /// can also be used to force coalesced bitstreams to start on byte /// boundaries so so WriteAlignedBits and ReadAlignedBits both /// calculate the same offset when aligning. void AlignReadToByteBoundary( void ); /// Read \a numberOfBitsToRead bits to the output source /// alignBitsToRight should be set to true to convert internal /// bitstream data to userdata. It should be false if you used /// WriteBits with rightAlignedBits false /// \param[in] output The resulting bits array /// \param[in] numberOfBitsToRead The number of bits to read /// \param[in] alignBitsToRight if true bits will be right aligned. /// \return true if there is enough bits to read bool ReadBits( unsigned char *output, int numberOfBitsToRead, const bool alignBitsToRight = true ); /// Write a 0 void Write0( void ); /// Write a 1 void Write1( void ); /// Reads 1 bit and returns true if that bit is 1 and false if it is 0 bool ReadBit( void ); /// If we used the constructor version with copy data off, this /// *makes sure it is set to on and the data pointed to is copied. void AssertCopyData( void ); /// Use this if you pass a pointer copy to the constructor /// *(_copyData==false) and want to overallocate to prevent /// *reallocation void SetNumberOfBitsAllocated( const unsigned int lengthInBits ); /// Reallocates (if necessary) in preparation of writing numberOfBitsToWrite void AddBitsAndReallocate( const int numberOfBitsToWrite ); /// \internal /// \return How many bits have been allocated internally unsigned int GetNumberOfBitsAllocated(void) const; static bool DoEndianSwap(void); static bool IsBigEndian(void); static bool IsNetworkOrder(void); static void ReverseBytes(unsigned char *input, unsigned char *output, int length); static void ReverseBytesInPlace(unsigned char *data, int length); private: BitStream( const BitStream &invalid) { #ifdef _MSC_VER #pragma warning(disable:4100) // warning C4100: 'invalid' : unreferenced formal parameter #endif } /// Assume the input source points to a native type, compress and write it. void WriteCompressed( const unsigned char* input, const int size, const bool unsignedData ); /// Assume the input source points to a compressed native type. Decompress and read it. bool ReadCompressed( unsigned char* output, const int size, const bool unsignedData ); int numberOfBitsUsed; int numberOfBitsAllocated; int readOffset; unsigned char *data; /// true if the internal buffer is copy of the data passed to the constructor bool copyData; /// BitStreams that use less than BITSTREAM_STACK_ALLOCATION_SIZE use the stack, rather than the heap to store data. It switches over if BITSTREAM_STACK_ALLOCATION_SIZE is exceeded unsigned char stackData[BITSTREAM_STACK_ALLOCATION_SIZE]; }; inline bool BitStream::SerializeBits(bool writeToBitstream, unsigned char* input, int numberOfBitsToSerialize, const bool rightAlignedBits ) { if (writeToBitstream) WriteBits(input,numberOfBitsToSerialize,rightAlignedBits); else return ReadBits(input,numberOfBitsToSerialize,rightAlignedBits); return true; } } #ifdef _MSC_VER #pragma warning( pop ) #endif #endif // VC6 #endif
[ "PhillipSpiess@d8b90d80-bb63-11dd-bed2-db724ec49875" ]
[ [ [ 1, 784 ] ] ]
e3399e637d2cbd81ede8738fb348ec20c475bd92
06eb59d91495a2b9568d21019e4dcb61ff236b7a
/izpack-src/tags/3.11.0/src/native/ShellLink_x64/ShellLink.cpp
ee8d3628c1c9282594e1b6d89e07189a8688d679
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jponge/izpack-full-svn-history-copy
8fa773fb3f9f4004e762d29f708273533ba0ff1f
7a521ccd6ce0dd1a0664eaae12fd5bba5571d231
refs/heads/master
2016-09-01T18:24:14.656773
2010-03-01T07:38:22
2010-03-01T07:38:22
551,191
1
1
null
null
null
null
UTF-8
C++
false
false
48,599
cpp
/* * IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved. * * http://www.izforge.com/izpack/ * http://izpack.codehaus.org/ * * Copyright 2002 Elmar Grom * * 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. */ /* Defining AMD64 here because project settings do not keep the preprocessor * definition for some reason. */ #define AMD64 /* Stuff for differ between UNICODE and MBCS * May be this work only with visual studio 6.x * To switch between MBCS and UNICODE change the * precompiler defines from /D _MBCS to /D _UNICODE * ----------------- START --------------------- */ #ifdef _UNICODE #define UNICODE #define NEW_STRING(a) NewString(a, _tcslen((TCHAR*)a)) #define GET_STRING_CHARS GetStringChars #define RELEASE_STRING_CHARS ReleaseStringChars #else #define NEW_STRING(a) NewStringUTF(a) #define GET_STRING_CHARS GetStringUTFChars #define RELEASE_STRING_CHARS ReleaseStringUTFChars #endif #ifdef _WINDOWS #define WINVER 0x0400 #define _WIN32_WINNT 0x0400 #endif /* Stuff for differ between UNICODE and MBCS * May be this work only with visual studio 6.x * ----------------- END --------------------- */ #include "com_izforge_izpack_util_os_ShellLink.h" #include <winerror.h> #include <objbase.h> #include <basetyps.h> #include <shlobj.h> #include <objidl.h> #include <windows.h> #include <tchar.h> // -------------------------------------------------------------------------- // Gound rules used for the implementation of this native interface // of ShellLink: // // 1) all functions return an integer success code // 2) positive success codes report that everything went ok // 3) negative success codes report some type of problem // 4) a success code of 0 does not exist // 5) 'get' functions deposit their results in the corresponding member // variables on the Java side. // 6) "set' functions retrieve their input from the corresponding member // variables on the Java side. // 7) functions other than 'get' and 'set' recive their input -if any- in // the form of arguments. // 8) functions that are exposed on the Java side (public, protectd) // follow the Java naming conventions, in that they begin with a lower // case character. // 9) all functions that have a Java wrapper by the same name follow the // Windows naming convention, in that they start with an upper case // letter. This avoids having to invent new method names for Java and // it allows to keep a clean naming convention on the Java side. // ============================================================================ // // I M P O R T A N T ! // ------------------- // // This interface communicates with the OS via COM. In order for things to // work properly, it is necessary to observe the following pattern of // operation and to observe the order of execution (i.e. do not call // getInterface() before calling initializeCOM()). // // 1) call initializeCOM() - It's best to do this in the constructor // 2) call getInterface() - It's best to do this in the constructor as well // // 3) do your stuff (load, save, get, set ...) // // 4) call releaseInterface() before terminating the application, best done // in the finalizer // 5) call releaseCOM() before terminating the application, best done // in the finalizer. Do NOT call this if the call to initializeCOM() did // not succeed, otherwise you'll mess things up pretty badly! // ============================================================================ // Variables that must be declared on the Java side: // // private int nativeHandle; // // private String linkPath; // private String linkName; // // private String arguments; // private String description; // private String iconPath; // private String targetPath; // private String workingDirectory; // // private int hotkey; // private int iconIndex; // private int showCommand; // private int linkType; // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // Macro Definitions // -------------------------------------------------------------------------- #define ACCESS 0 // index for retrieving the registry access key #define MIN_KEY 0 // for verifying that an index received in the form of a call parameter is actually leagal #define MAX_KEY 5 // for verifying that an index received in the form of a call parameter is actually leagal // -------------------------------------------------------------------------- // Prototypes // -------------------------------------------------------------------------- // Hey C crowd, don't freak out! ShellLink.h is auto generated and I'd like // to have everything close by in this package. Besides, these are only used // in this file... // -------------------------------------------------------------------------- int getNewHandle (); void freeLinks (); // -------------------------------------------------------------------------- // Constant Definitions // -------------------------------------------------------------------------- // the registry keys to get access to the various shortcut locations for the current user const char CURRENT_USER_KEY [5][100] = { "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", // this is where the details are stored in the registry "Desktop", // this is where desktop shortcuts go "Programs", // this is where items of the progams menu go "Start Menu", // this is right in the start menu "Startup" // this is where stuff goes that should be executed on OS launch }; // the registry keys to get access to the various shortcut locations for all users const char ALL_USER_KEY [5][100] = { "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", // this is where the details are stored in the registry "Common Desktop", // this is where desktop shortcuts go "Common Programs", // this is where items of the progams menu go "Common Start Menu", // this is right in the start menu "Common Startup" // this is where stuff goes that should be executed on OS launch }; // Success Codes const jint SL_OK = 1; // returned if a call was successful const jint SL_ERROR = -1; // unspecific return if a call was not successful const jint SL_INITIALIZED = -2; // return value from initialization functions if already initialized const jint SL_NOT_INITIALIZED = -3; // return value from uninitialization functions if never initialized const jint SL_OUT_OF_HANDLES = -4; // there are no more interface handles available const jint SL_NO_IPERSIST = -5; // could not get a handle for the IPersist interface const jint SL_NO_SAVE = -6; // could not save the link const jint SL_WRONG_DATA_TYPE = -7; // an unexpected data type has been passed or received const jint SL_CAN_NOT_READ_PATH = -8; // was not able to read the link path from the Windows Registry const int MAX_TEXT_LENGTH = 1000; // buffer size for text buffers const int ALLOC_INCREMENT = 10; // allocation increment for allocation of additional storage space for link references // -------------------------------------------------------------------------- // Variable Declarations // -------------------------------------------------------------------------- int referenceCount = 0; // -------------------------------------------------------- // DLLs are not objects! // -------------------- // What this means is that if multiple references are made // to the same DLL in the same program space, no new // storage is allocated for the variables in the DLL. // For all practical purposes, variables in DLLs are equal // to static variables in classes - all instances share // the same storage space. // ======================================================== // Since this code is designed to operate in conjunction // with a Java class, there is a possibility for multiple // instances of the class to acces this code 'simultaniously'. // As a result, one instance could be modifying the link // data for another instance. To avoid this, I am // artificially creating multiple DLL 'instances' by // providing a storage array for pointers to multiple // instances of IShellLink. Each Java instance must // access its IShellLink through a handle (the array // index where its corresponding pointer is stored). // ======================================================== // For details on how this works see: // - getNewHandle() // - freeLinks() // -------------------------------------------------------- int linkCapacity = 0; // indicates the current capacity for storing pointers IShellLink** p_shellLink = NULL; // pointers to the IShellLink interface // -------------------------------------------------------------------------- // Gain COM access // // returns: SL_OK if the initialization was successfull // SL_ERROR otherwise // // I M P O R T A N T !! // -------------------- // // 1) This method must be called first! // 2) The application must call releaseCOM() just before terminating but // only if a result of SL_OK was retruned form this function! // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_initializeCOM (JNIEnv *env, jobject obj) { HRESULT hres; if (referenceCount > 0) { referenceCount++; return (SL_OK); } hres = CoInitializeEx (NULL, COINIT_APARTMENTTHREADED); if (SUCCEEDED (hres)) { referenceCount++; return (SL_OK); } return (SL_ERROR); } // -------------------------------------------------------------------------- // Releases COM and frees associated resources. This function should be // called as the very last operation before the application terminates. // Call this function only if a prior call to initializeCOM() returned SL_OK. // // returns: SL_OK under normal circumstances // SL_NOT_INITIALIZED if the reference count indicates that no // current users exist. // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_releaseCOM (JNIEnv *env, jobject obj) { referenceCount--; if (referenceCount == 0) { CoUninitialize (); // This is the end of things, so this is a good time to // free the storage for the IShellLink pointers. freeLinks (); return (SL_OK); } else if (referenceCount < 0) { referenceCount++; return (SL_NOT_INITIALIZED); } else { return (SL_OK); } } // -------------------------------------------------------------------------- // This function gains access to the ISchellLink interface. It must be // called before any other calls can be made but after initializeCOM(). // // I M P O R T A N T !! // -------------------- // // releaseInterface() must be called before terminating the application! // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_getInterface (JNIEnv *env, jobject obj) { HRESULT hres; int handle; // Get a handle handle = getNewHandle (); if (handle < 0) { return (SL_OUT_OF_HANDLES); } // Store the handle on the Java side jclass cls = (env)->GetObjectClass( obj ); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); (env)->SetIntField (obj, handleID, (jint)handle); /* * Note: CoCreateInstance() supports only the creation of a single instance. * Need to find out how to use CoGetClassObject() to create multiple instances. * It should be possible to have multiple instances available, got to make this work! */ // Get a pointer to the IShellLink interface hres = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&p_shellLink [handle]); // Do error handling if (SUCCEEDED (hres)) { return (SL_OK); } return (SL_ERROR); } // -------------------------------------------------------------------------- // This function returns a new handle to be used for the next client. If no // more handles are available -1 is returnd. // -------------------------------------------------------------------------- int getNewHandle () { IShellLink* pointer; // loop through the array to find an unoccupied location int i; for (i = 0; i < linkCapacity; i++) { pointer = p_shellLink [i]; // if an unoccupied location is found return the index if (pointer == NULL) { return (i); } } // if we get here, all locations are in use and we need to // create more storage space to satisfy the request int newSize = sizeof (IShellLink*) * (linkCapacity + ALLOC_INCREMENT); void* tempPointer = realloc ((void *)p_shellLink, newSize); if (tempPointer != NULL) { p_shellLink = (IShellLink**)tempPointer; linkCapacity = linkCapacity + ALLOC_INCREMENT; for (int k = i; k < linkCapacity; k++) { p_shellLink [k] = NULL; } return (i); } else { return (-1); } } // -------------------------------------------------------------------------- // This function frees the storage that was allocated for the storage of // pointers to IShellLink interfaces. It also cleans up any interfaces that // have not yet been reliquished (clients left a mess -> bad boy!). // -------------------------------------------------------------------------- void freeLinks () { if (p_shellLink != NULL) { // loop through the array and release any interfaces that // have not been freed yet IShellLink* pointer; for (int i = 0; i < linkCapacity; i++) { pointer = p_shellLink [i]; // if an unoccupied location is found, return the index if (pointer != NULL) { pointer->Release (); p_shellLink [i] = NULL; } } // free the pointer storage itself linkCapacity = 0; free (p_shellLink); } } // -------------------------------------------------------------------------- // This function frees this dll, allowing the operating system to remove // the code from memory and releasing the reference to the dll on disk. // After this call this dll can not be used any more. // // THIS FUNCTION DOES NOT RETURN !!! // -------------------------------------------------------------------------- JNIEXPORT void JNICALL Java_com_izforge_izpack_util_os_ShellLink_FreeLibrary (JNIEnv *env, jobject obj, jstring name) { // convert the name from Java string type const jchar *libraryName = (env)->GET_STRING_CHARS (name, 0); // get a module handle HMODULE handle = GetModuleHandle ((TCHAR*)libraryName); // release the string object (env)->RELEASE_STRING_CHARS (name, libraryName); // now we are rady to free the library FreeLibraryAndExitThread (handle, 0); } // -------------------------------------------------------------------------- // Releases the interface // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_releaseInterface (JNIEnv *env, jobject obj) { // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); if (handle < 0) { return (SL_OK); } if (p_shellLink [handle] == NULL) { return (SL_NOT_INITIALIZED); } p_shellLink [handle]->Release (); p_shellLink [handle] = NULL; (env)->SetIntField (obj, handleID, -1); return (SL_OK); } // -------------------------------------------------------------------------- // Retrieves the command-line arguments associated with a shell link object // // Result is deposited in 'arguments' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_GetArguments (JNIEnv *env, jobject obj) { TCHAR arguments [MAX_TEXT_LENGTH]; HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); hres = p_shellLink [handle]->GetArguments (arguments, MAX_TEXT_LENGTH); // ------------------------------------------------------ // set the member variables // ------------------------------------------------------ if (SUCCEEDED (hres)) { jfieldID argumentsID = (env)->GetFieldID (cls, "arguments", "Ljava/lang/String;"); jstring j_arguments = (env)->NEW_STRING ((jchar*)arguments); (env)->SetObjectField (obj, argumentsID, j_arguments); return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Retrieves the description string for a shell link object. // // Result is deposited in 'description' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_GetDescription (JNIEnv *env, jobject obj) { TCHAR description [MAX_TEXT_LENGTH]; HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); hres = p_shellLink [handle]->GetDescription (description, MAX_TEXT_LENGTH); if (SUCCEEDED (hres)) { jfieldID descriptionID = (env)->GetFieldID (cls, "description", "Ljava/lang/String;"); jstring j_description = (env)->NEW_STRING ((jchar*)description); // convert to Java String type (env)->SetObjectField (obj, descriptionID, j_description); return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Retrieves the hot key for a shell link object. // // Result is deposited in 'hotkey' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_GetHotkey (JNIEnv *env, jobject obj) { WORD hotkey; HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); hres = p_shellLink [handle]->GetHotkey (&hotkey); if (SUCCEEDED (hres)) { jfieldID hotkeyID = (env)->GetFieldID (cls, "hotkey", "I"); (env)->SetIntField (obj, hotkeyID, (jint)hotkey); return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Retrieves the location (path and index) of the icon for a shell link object. // // The path is deposited in 'iconPath' // The index is deposited in 'iconIndex' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_GetIconLocation (JNIEnv *env, jobject obj) { HRESULT hres; TCHAR iconPath [MAX_PATH]; int iconIndex; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); hres = p_shellLink [handle]->GetIconLocation (iconPath, MAX_PATH, &iconIndex); // ------------------------------------------------------ // set the member variables // ------------------------------------------------------ if (SUCCEEDED (hres)) { jfieldID pathID = (env)->GetFieldID (cls, "iconPath", "Ljava/lang/String;"); jfieldID indexID = (env)->GetFieldID (cls, "iconIndex", "I"); jstring j_iconPath = (env)->NEW_STRING ((jchar*)iconPath); (env)->SetObjectField (obj, pathID, j_iconPath); (env)->SetIntField (obj, indexID, (jint)iconIndex); return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Retrieves the path and filename of a shell link object. // // Result is deposited in 'targetPath' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_GetPath (JNIEnv *env, jobject obj) { WIN32_FIND_DATA findData; TCHAR targetPath [MAX_PATH]; HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); hres = p_shellLink [handle]->GetPath (targetPath, MAX_PATH, &findData, SLGP_UNCPRIORITY); // ------------------------------------------------------ // set the member variables // ------------------------------------------------------ if (SUCCEEDED (hres)) { jfieldID pathID = (env)->GetFieldID(cls, "targetPath", "Ljava/lang/String;"); jstring j_targetPath = (env)->NEW_STRING( (jchar*)targetPath); (env)->SetObjectField (obj, pathID, j_targetPath); return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Retrieves the show (SW_) command for a shell link object. // // Result is deposited in 'showCommand' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_GetShowCommand (JNIEnv *env, jobject obj) { HRESULT hres; int showCommand; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); hres = p_shellLink [handle]->GetShowCmd (&showCommand); // ------------------------------------------------------ // set the member variables // ------------------------------------------------------ if (SUCCEEDED (hres)) { jfieldID commandID = (env)->GetFieldID (cls, "showCommand", "I"); (env)->SetIntField (obj, commandID, (jint)showCommand); return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Retrieves the name of the working directory for a shell link object. // // Result is deposited in 'workingDirectory' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_GetWorkingDirectory (JNIEnv *env, jobject obj) { HRESULT hres; TCHAR workingDirectory [MAX_PATH]; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); hres = p_shellLink [handle]->GetWorkingDirectory (workingDirectory, MAX_PATH); // ------------------------------------------------------ // set the member variables // ------------------------------------------------------ if (SUCCEEDED (hres)) { jfieldID directoryID = (env)->GetFieldID (cls, "workingDirectory", "Ljava/lang/String;"); jstring j_workingDirectory = (env)->NEW_STRING ((jchar*)workingDirectory); (env)->SetObjectField (obj, directoryID, j_workingDirectory); return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Resolves a shell link by searching for the shell link object and // updating the shell link path and its list of identifiers (if necessary). // // I recommend to call this function before saving the shortcut. This will // ensure that the link is working and all the identifiers are updated, so // that the link will actually work when used later on. If for some reason // the link can not be resolved, at least the creating application knows // about this. // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_Resolve (JNIEnv *env, jobject obj) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); hres = p_shellLink [handle]->Resolve (NULL, SLR_NO_UI | SLR_UPDATE); if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Sets the command-line arguments associated with a shell link object. // // Input is taken from 'arguments' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_SetArguments (JNIEnv *env, jobject obj) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ------------------------------------------------------ // get the member variables // ------------------------------------------------------ jfieldID argumentsID = (env)->GetFieldID (cls, "arguments", "Ljava/lang/String;"); jstring j_arguments = (jstring)(env)->GetObjectField (obj, argumentsID); const TCHAR *arguments = (TCHAR*)(env)->GET_STRING_CHARS (j_arguments, 0); hres = p_shellLink [handle]->SetArguments (arguments); (env)->RELEASE_STRING_CHARS(j_arguments, (jchar*)arguments); if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Sets the description string for a shell link object. // // Input is taken from 'description' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_SetDescription (JNIEnv *env, jobject obj) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ------------------------------------------------------ // get the member variables // ------------------------------------------------------ jfieldID descriptionID = (env)->GetFieldID (cls, "description", "Ljava/lang/String;"); jstring j_description = (jstring)(env)->GetObjectField (obj, descriptionID); const TCHAR *description = (TCHAR*)(env)->GET_STRING_CHARS (j_description, 0); hres = p_shellLink [handle]->SetDescription( description ); (env)->RELEASE_STRING_CHARS(j_description, (jchar*)description); if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Sets the hot key for a shell link object. // // Input is taken from 'hotkey' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_SetHotkey (JNIEnv *env, jobject obj) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ------------------------------------------------------ // get the member variables // ------------------------------------------------------ jfieldID hotkeyID = (env)->GetFieldID (cls, "hotkey", "I"); jint hotkey = (env)->GetIntField (obj, hotkeyID); hres = p_shellLink [handle]->SetHotkey ((unsigned short)hotkey); if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Sets the location (path and index) of the icon for a shell link object. // // The path is taken from 'iconPath' // The index is taken from 'iconIndex' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_SetIconLocation (JNIEnv *env, jobject obj) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ------------------------------------------------------ // get the member variables // ------------------------------------------------------ jfieldID pathID = (env)->GetFieldID (cls, "iconPath", "Ljava/lang/String;"); jstring j_iconPath = (jstring)(env)->GetObjectField (obj, pathID); const TCHAR *iconPath = (TCHAR*)(env)->GET_STRING_CHARS (j_iconPath, 0); jfieldID indexID = (env)->GetFieldID (cls, "iconIndex", "I"); jint iconIndex = (env)->GetIntField (obj, indexID); hres = p_shellLink [handle]->SetIconLocation (iconPath, iconIndex); (env)->RELEASE_STRING_CHARS(j_iconPath, (jchar*)iconPath); if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Sets the path and filename of a shell link object. // // Input is taken from 'targetPath' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_SetPath (JNIEnv *env, jobject obj) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ------------------------------------------------------ // get the member variables // ------------------------------------------------------ jfieldID pathID = (env)->GetFieldID (cls, "targetPath", "Ljava/lang/String;"); jstring j_targetPath = (jstring)(env)->GetObjectField (obj, pathID); const TCHAR *targetPath = (TCHAR*)(env)->GET_STRING_CHARS (j_targetPath, 0); hres = p_shellLink [handle]->SetPath (targetPath); (env)->RELEASE_STRING_CHARS(j_targetPath, (jchar*)targetPath); if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Sets the show (SW_) command for a shell link object. // // Input is taken from 'showCommand' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_SetShowCommand (JNIEnv *env, jobject obj) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ------------------------------------------------------ // get the member variables // ------------------------------------------------------ jfieldID commandID = (env)->GetFieldID (cls, "showCommand", "I"); jint showCommand = (env)->GetIntField (obj, commandID); hres = p_shellLink [handle]->SetShowCmd (showCommand); if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // Sets the name of the working directory for a shell link object. // // Input is taken from 'workingDirectory' // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_SetWorkingDirectory (JNIEnv *env, jobject obj) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ------------------------------------------------------ // get the member variables // ------------------------------------------------------ jfieldID pathID = (env)->GetFieldID (cls, "workingDirectory", "Ljava/lang/String;"); jstring j_workingDirectory = (jstring)(env)->GetObjectField (obj, pathID); const TCHAR *workingDirectory = (TCHAR*)(env)->GET_STRING_CHARS (j_workingDirectory, 0); hres = p_shellLink [handle]->SetWorkingDirectory (workingDirectory); (env)->RELEASE_STRING_CHARS(j_workingDirectory, (jchar*)workingDirectory); if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // This function saves the shell link. // // name - the fully qualified path for saving the shortcut. // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_saveLink (JNIEnv *env, jobject obj, jstring name) { // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ---------------------------------------------------- // Query IShellLink for the IPersistFile interface for // saving the shell link in persistent storage. // ---------------------------------------------------- IPersistFile* p_persistFile; HRESULT hres = p_shellLink [handle]->QueryInterface (IID_IPersistFile, (void **)&p_persistFile); if (!SUCCEEDED (hres)) { return (SL_NO_IPERSIST); } // ---------------------------------------------------- // convert from Java string type // ---------------------------------------------------- const unsigned short *pathName = (env)->GetStringChars (name, 0); // ---------------------------------------------------- // Save the link // ---------------------------------------------------- hres = p_persistFile->Save ((wchar_t*)pathName, FALSE); p_persistFile->SaveCompleted ((wchar_t*)pathName); // ---------------------------------------------------- // Release the pointer to IPersistFile // and the string object // ---------------------------------------------------- p_persistFile->Release (); (env)->ReleaseStringChars (name, pathName); // ------------------------------------------------------ // return success code // ------------------------------------------------------ if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_NO_SAVE); } } // -------------------------------------------------------------------------- // This function loads a shell link. // // name - the fully qualified path for loading the shortcut. // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_loadLink (JNIEnv *env, jobject obj, jstring name) { HRESULT hres; // Get the handle from the Java side jclass cls = (env)->GetObjectClass (obj); jfieldID handleID = (env)->GetFieldID (cls, "nativeHandle", "I"); jint handle = (env)->GetIntField (obj, handleID); // ---------------------------------------------------- // Query IShellLink for the IPersistFile interface for // saving the shell link in persistent storage. // ---------------------------------------------------- IPersistFile* p_persistFile; hres = p_shellLink [handle]->QueryInterface (IID_IPersistFile, (void **)&p_persistFile); if (SUCCEEDED (hres)) { // convert from Java string type const unsigned short *pathName = (env)->GetStringChars (name, 0); // -------------------------------------------------- // Load the link // -------------------------------------------------- hres = p_persistFile->Load ((wchar_t *)pathName, STGM_DIRECT | STGM_READWRITE | STGM_SHARE_EXCLUSIVE); // -------------------------------------------------- // Release the pointer to IPersistFile // -------------------------------------------------- p_persistFile->Release (); (env)->ReleaseStringChars (name, pathName); } // ------------------------------------------------------ // return success code // ------------------------------------------------------ if (SUCCEEDED (hres)) { return (SL_OK); } else { return (SL_ERROR); } } // -------------------------------------------------------------------------- // resolves a Windows Standard path using SHGetPathFromIDList // inputs: // inc iCsidl - one of the CSIDL // valid CSIDL_COMMON_DESKTOPDIRECTORY // CSIDL_COMMON_STARTMENU // CSIDL_COMMON_PROGRAMS // CSIDL_COMMON_STARTUP // CSIDL_DESKTOPDIRECTORY // CSIDL_STARTMENU // CSIDL_PROGRAMS // CSIDL_STARTUP // returns: // the Windows Standard Path in szPath. // -------------------------------------------------------------------------- LONG GetLinkPath( int iCsidl, LPTSTR szPath ) { HRESULT hr; // Allocate a pointer to an Item ID list LPITEMIDLIST pidl; // Get a pointer to an item ID list that // represents the path of a special folder hr = SHGetSpecialFolderLocation(NULL, iCsidl, &pidl); if ( SUCCEEDED(hr) ) { // Convert the item ID list's binary // representation into a file system path BOOL f = SHGetPathFromIDList(pidl, szPath); // Allocate a pointer to an IMalloc interface LPMALLOC pMalloc; // Get the address of our task allocator's IMalloc interface hr = SHGetMalloc(&pMalloc); // Free the item ID list allocated by SHGetSpecialFolderLocation pMalloc->Free(pidl); // Free our task allocator pMalloc->Release(); if ( f == FALSE ) { *szPath = TCHAR('\0'); return E_FAIL; } // return the special folder's path (contained in szPath) return S_OK; } else { // null path for error return. *szPath = TCHAR('\0'); } return E_FAIL; } // -------------------------------------------------------------------------- // This function retrieves the location of the folders that hold shortcuts. // The information comes from SHGetSpecialFolderLocation, // since it's more accurate. // SHGetSpecialFolderLocation (since shell32.dll ver 4.0 - win 95, IE 3). // // target - where the path should point. The following are legal values // to use // // 1 - path for shortcuts that show on the desktop // 2 - path for shortcuts that show in the Programs menu // 3 - path for shortcuts that show in the start menu // 4 - path to the Startup group. These shortcuts are executed // at OS launch time // // Note: all other values cause an empty string to be returned // // Program groups (sub-menus) in the programs and start menus can be created // by creating a new folder at the indicated location and placing the links // in that folder. These folders can be nested to any depth with each level // creating an additional menu level. // // Results are deposited in 'currentUserLinkPath' and 'allUsersLinkPath' // respectively // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- JNIEXPORT jint JNICALL Java_com_izforge_izpack_util_os_ShellLink_GetFullLinkPath (JNIEnv *env, jobject obj, jint utype, jint ltype) { ULONG ul_size = MAX_PATH; // buffer size TCHAR szPath [MAX_PATH]; // path we are looking for int csidl; jclass cls; jfieldID pathID; jstring j_path; LONG successCode; if ((ltype > MIN_KEY) && (ltype < MAX_KEY)) { //translate request into a CSIDL, based on user-type and link-type // user type if ( utype == com_izforge_izpack_util_os_ShellLink_ALL_USERS ) { switch ( ltype ) // link type { case ( com_izforge_izpack_util_os_ShellLink_DESKTOP ) : csidl = CSIDL_COMMON_DESKTOPDIRECTORY; break; case ( com_izforge_izpack_util_os_ShellLink_START_MENU ) : csidl = CSIDL_COMMON_STARTMENU; break; case ( com_izforge_izpack_util_os_ShellLink_PROGRAM_MENU ) : csidl = CSIDL_COMMON_PROGRAMS; break; case ( com_izforge_izpack_util_os_ShellLink_STARTUP ) : csidl = CSIDL_COMMON_STARTUP; break; default : break; } successCode = GetLinkPath( csidl, szPath ); if ( SUCCEEDED(successCode) ) { // ------------------------------------------------------ // set the member variables // ------------------------------------------------------ cls = (env)->GetObjectClass (obj); pathID = (env)->GetFieldID (cls, "allUsersLinkPath", "Ljava/lang/String;"); j_path = (env)->NEW_STRING ((jchar*)szPath); (env)->SetObjectField (obj, pathID, j_path); return (SL_OK); } else { // failure code from GetLinkPath() return successCode; } } else if ( utype == com_izforge_izpack_util_os_ShellLink_CURRENT_USER ) { switch ( ltype ) // link type { case ( com_izforge_izpack_util_os_ShellLink_DESKTOP ) : csidl = CSIDL_DESKTOPDIRECTORY; break; case ( com_izforge_izpack_util_os_ShellLink_START_MENU ) : csidl = CSIDL_STARTMENU; break; case ( com_izforge_izpack_util_os_ShellLink_PROGRAM_MENU ) : csidl = CSIDL_PROGRAMS; break; case ( com_izforge_izpack_util_os_ShellLink_STARTUP ) : csidl = CSIDL_STARTUP; break; default : break; } successCode = GetLinkPath( csidl, szPath ); if ( SUCCEEDED(successCode) ) { // ------------------------------------------------------ // set the member variables // ------------------------------------------------------ cls = (env)->GetObjectClass (obj); pathID = (env)->GetFieldID (cls, "currentUserLinkPath", "Ljava/lang/String;"); j_path = (env)->NEW_STRING ((jchar*)szPath); (env)->SetObjectField (obj, pathID, j_path); return (SL_OK); } else { // failure code from GetLinkPath() return successCode; } } } return SL_CAN_NOT_READ_PATH; }
[ "jponge@7d736ef5-cfd4-0310-9c9a-b52d5c14b761" ]
[ [ [ 1, 1305 ] ] ]
2d7c1b128d936c3168fd8180164190b3b90e65ea
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Modules/include/DisplaySerial.h
563ed71233fa627ced36468f50a6311c39409bfc
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,589
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DISPLAY_SERIAL_H #define DISPLAY_SERIAL_H #include "arch.h" #include "Module.h" #include "Serial.h" #include "Buffer.h" #include "RequestList.h" #include "NavTask.h" #include "CtrlHub.h" #include "Log.h" #define I_AM_DISPLAY_SERIAL_AND_IN_DIRE_NEED_OF_OUTDATED_ENUMS #include "NavServerCom.h" #include "Matches.h" #include "PacketEnums.h" #include "Parameter.h" /** Timeout for sending data messages. in milliseconds.*/ #define DS_BUSY_TIMEOUT 1000 #define DS_IDLE_TIMEOUT 1000 #define DS_DEFAULT_TIMEOUT 1000 #define LOST_PDA_MAX_TIMEOUTS 5 #define NAV_VERSION_STRING_1 "Navigator" #define MAX_VERSION_STRING 40 /// Max size of m_pending #define MAX_PENDING 10 // Size of phonenumber, XXX: Parametermodule #define MAX_PHONE_NO_SIZE 20 using namespace isab::NavServerComEnums; namespace isab{ typedef struct packetPersistentData { Buffer *decodingBuffer; int decodingState; } packetPersistentData_t; typedef packetPersistentData_t *packetPersistentData_p; using namespace Packet_Enums; // forward declaration, not pretty but necessary. class Packet; /** * DisplaySerial is for serial communication from ... to gui (display). * */ class DisplaySerial : public Module, public SerialConsumerInterface, public NavTaskConsumerInterface, public CtrlHubAttachedInterface, public NavServerComConsumerInterface, public ParameterConsumerInterface { public: /** * Module functions */ //@{ /** * Called when shutdown starts. */ virtual void decodedShutdownNow(int16 upperTimeout); /** * Called when shutdown is complete and no further calls will * be made. */ virtual void treeIsShutdown(); /** * Called when timer has expired. * * @param timerid The id of the timer that has expired. */ virtual void decodedExpiredTimer( uint16 timerid ); /** * Called when startup is done and module is ready. */ virtual void decodedStartupComplete(); /** * Creates a new CtrlHubAttachedPublic object used to connect * this module to the CtrlHub. * * @return A new CtrlHubAttachedPublic object connected to the * queue. */ inline CtrlHubAttachedPublic* newPublicCtrlHub(); //@} /** * NavServerCom functions */ //@{ /** * Called when sync destination reply has been decoded. * XXX: Implement. */ virtual void decodedSyncDestinationsReply(std::vector<Favorite*>& favs, std::vector<uint32>& removed, uint32 src, uint32 dst); /** * Called when binary upload has been received by ... * XXX: Implement * * @param src The id of the module? * @param dst The id of the request. */ virtual void decodedBinaryUploadReply( uint32 src, uint32 dst ); /** * Called when binary download has been received by ... * XXX: Implement * * @param data The data downloaded, is valid for this method. * @param length The length of the data. * @param src The id of the module? * @param dst The id of the request. */ virtual void decodedBinaryDownload( const uint8* data, size_t length, uint32 src, uint32 dst ); /** * Called when a where an I reply has been received. * XXX: Implement * * @param country String with the name of the country where you * are. * @param municipal String with the name of the municipal where * you are. * @param city String with the name of the city where you are. * @param district String with the name of the district in the * city where you are. * @param streetname String with the name of the street where you * are. * @param lat The latitude of your current position. * @param lon The longitude of your current position. * @param src The id of the module? * @param dst The id of the request. */ virtual void decodedWhereAmIReply( const char* country, const char* municipal, const char* city, const char* district, const char* streetname, int32 lat, int32 lon, uint32 src, uint32 dst ); virtual void decodedSearchReply(unsigned nAreas, const SearchArea* const *sa, unsigned nItems, const FullSearchItem* const *fsi, uint16 begindex, uint16 total, uint32 src, uint32 dst){} /** * Called when a route reply is received. * * @param src The id of the module? * @param dst The id of the request that this is a reply for? */ virtual void decodedRouteReply( uint32 src, uint32 dst ); virtual void decodedParamSyncReply(GuiProtEnums::WayfinderType wft, uint32 src, uint32 dst) { /* this function intentionally left blank */} /** * Called when a progres message is received. * * @param status The status of the communication. * @param type The type of message that the progress is for. * @param done The number of sent bytes? * @param of The total amount of bytes? * @param src The id of the module? * @param dst The id of the request that this is progress message * for */ virtual void decodedProgressMessage( ComStatus status, GuiProtEnums::ServerActionType type, uint32 done, uint32 of, uint32 src, uint32 dst ); //@} /** * Serial Consumer functions. */ //@{ /** * Called when data is received. * * @param length The length of data. * @param data The data received. * @param src The id of the module? */ virtual void decodedReceiveData( int length, const uint8 *data, uint32 src ); //@} /** * NavTask functions. */ //@{ /** * Called when a position state has been received. * * @param p The new PositionState. * @param src The id of the module? */ virtual void decodedPositionState( const NavTaskConsumerPublic::PositionState& p, uint32 src ); virtual void setRouteCoordinate( int32 lat, int32 lon, int8 dir ); virtual void decodedInvalidateRoute(bool newRouteAvailable, int64 routeid, int32 tLat, int32 lLon, int32 bLat, int32 rLon, int32 oLat, int32 oLon, int32 dLat, int32 dLon, uint32 src); //@} /** ParameterConsumer functions. */ //@{ virtual void decodedParamNoValue(uint32 paramId, uint32 src, uint32 dst); virtual void decodedParamValue(uint32 paramId, const int32 * data, int32 numEntries, uint32 src, uint32 dst); virtual void decodedParamValue(uint32 paramId, const float * data, int32 numEntries, uint32 src, uint32 dst); virtual void decodedParamValue(uint32 paramId, const char * const * data, int32 numEntries, uint32 src, uint32 dst); virtual void decodedParamValue(uint32 paramId, const uint8* data, int size, uint32 src, uint32 dst); //@} /// The implemented nav serial protocol version. #ifndef _MSC_VER static const int protocolVersion = 8; #else enum { protocolVersion = 8 }; #endif /** * Constructor that takes an SerialProviderPublic. * * @param spp The SerialProviderPublic. */ DisplaySerial( SerialProviderPublic* spp ); virtual ~DisplaySerial(); // Macro for making a reply packet type from a request packet type #define REPLY(i) PacketType(i | 0x80) // Macro for checking if a packet type is a request. #define NAV_DISPLAY_SERIAL_IS_REQUEST(i) (!(i&0x80)) protected: /** * Called by hub when message is sent to this module? * * @param buf The request Msg? * @return MsgBuffer with the reply? */ virtual MsgBuffer* dispatch( MsgBuffer* buf ); // parameters XXX: To be moved to Parameter Module? const char* getVersionString(); uint32 getSerialNo(); const char* getSoftwareVersion(); /** * Internal functions. */ //@{ /** * Sends a simple packet to any connected NavClient. * * @param packetType A value from the enum PacketType. * @param packetID The id of the packet to ack. */ void sendAck( Packet_Enums::PacketType packetType, uint16 packetID ); /** * Sends an ExtendedError message to the NavClient. * * @param errorCode A value from the NavErrorType enum. * @param errorID The ID of the request that caused an error. * @param errorString an error message. */ void sendExtendedError( uint16 errorCode, uint16 errorID, const char* errorMessage = NULL ); /** * Sends the data stored in the m_atestNavData structure to the * NavClient. * * @param packetType A value from the PacketType enum. * @param packetID The ID of the packet to send. */ void sendLatestNavData( Packet_Enums::PacketType packetType, uint16 packetID ); //@} private: // communicate with the serial provider. SerialProviderPublic* m_provider; SerialConsumerPublic* m_consumer; // communicate with navtask NavTaskProviderPublic * m_navTaskProvider; // communicate with the parameter module. ParameterProviderPublic * m_paramProvider; // decoders. SerialConsumerDecoder m_serialDecoder; // XXX: not set! NavTaskConsumerDecoder m_navTaskDecoder; // XXX: not set NavServerComConsumerDecoder m_nscDecoder; // XXX: not set! CtrlHubAttachedDecoder m_hubDecoder; // XXX: not set! ParameterConsumerDecoder m_paramDecoder; // XXX: not set! /// The current timeout time for the timer uint16 m_timeout; /// The id of the timer uint16 m_timerId; /// If contact with display bool m_gotPda; /// If display is subscribing, to route info. bool m_subscribing; /// Counter for waiting for reply from display. uint16 m_noPda; /// Sequence id to send next to display. uint16 m_navSeqID; /// Expected id from display next. uint16 m_pdaSeqID; /// GPS position data. struct NavData{ uint8 posQuality; uint8 speedQuality; uint8 headingQuality; int32 lat, lon; int32 routelat, routelon; uint8 heading; uint8 routeheading float speed; NavData() : posQuality(0), speedQuality(0), headingQuality(0), lat(0), lon(0), routelat(0), routelon(0), heading(0), routeheading(0), speed(0) {} } m_lastNavData; /// Oustanding requests. RequestList m_pending; // Parameters cached here: char* m_dataPhoneNo; char* m_voicePhoneNo; char* m_userID; char* m_passwd; uint32 m_navID; char* m_serverHostname; void setParam(Packet* packet); void getParam(Packet* packet); void setCharValue(char*& src, const char* name); /// The whole of current route. uint8* m_FIXME_fullRoute; /// The length of current route. size_t m_FIXME_fullRouteLength; /// The interface to nav server com NavServerComProviderPublic* m_serverProvider; Buffer* m_tunnelBuffer; uint16 m_tunnelPacketNumber; /** * This function is the input handler for messages sent * by the PDA(display) side to the navigator. These are always * small messages (type and 2 x uint32 etc.) * The function handles the request and sends it to nav ctrl * if so needed. When the request is simple and it can be * handled here, an ack packet is sent directly. * For more complicated requests, the routine saves the * request id together with the id from nav_ctrl. * This can later be used to match requests to replys. * * @return The function always returns zero. */ int messageReceived( Packet* packet ); /** * Packet handling functions. For handling of packets in * messageReceived that require more than a few lines to handle. */ //@{ /** * Handles a navigator type packet. * * @param p The Packet. */ void handleNavigatorType( Packet* p ); /** Handles Navigator Parameters sent from NavCtrl. * @param packet the packet. */ void handleNavigatorParams(Packet* packet); /** * Handles a get current route packet. * * @param p The Packet. */ void handleGetCurrentRoute( Packet* p ); /** * Handles a search packet. * * @param p The Packet. */ void handleSearch( Packet* p ); /** * Handles a download route packet. * * @param p The Packet. */ void handleDownLoadRoute( Packet* p ); /** Handles subscribe and unsubscribe packages. * @param packet the Packet. */ void handleSubscribe( Packet* packet); /** * Handle a server parameters packet. * * @param p The Packet. */ void handleServerParameters( Packet* p ); /** Handles a data chunk. * @param packet the packet containing the data chunk. */ void handleDataChunk(Packet* packet); //@} /** * Checks if a request already is pending then silently discard the * packet. * If not pending then try to allocate a new RequestListItem. If * that fails send error reply. * If allocated ok then return that. * Used by messageReceived. * * @param id The id of the packet. */ RequestListItem* checkForRequestAndCreate( uint16 id ); /** * Adds an request. If ID is MAX_UINT16 then an error is sent. * Used by messageReceived. * * @param req The request to add. * @param id The id of the display request. */ void addRequest( RequestListItem* req, uint16 id ); /// If module is shuting down. bool m_shutdown; ComStatus m_previousStatus; MessageType m_previousMessage; private: packetPersistentData_t m_packetPersistentData; }; // ======================================================================== // Implementation of the inlined methods = inline const char* DisplaySerial::getVersionString() { return "Navigator"; } inline uint32 DisplaySerial::getSerialNo() { return 0xdeadbeef; } inline const char* DisplaySerial::getSoftwareVersion() { return "2.5.0"; } inline CtrlHubAttachedPublic *DisplaySerial::newPublicCtrlHub() { return new CtrlHubAttachedPublic(m_queue); } } #define ENUMNAMES #ifdef ENUMNAMES //typedef isab::Packet_Enums DS; #define PACKET_TYPE_STRING(pt) \ ((!(pt & 0x80)) ? \ ((pt == ERRORE) ? "ERRORE" : \ ((pt == TEST_DATA) ? "TEST_DATA" : \ ((pt == PDA_TYPE) ? "PDA_TYPE" : \ ((pt == NAVIGATOR_TYPE) ? "NAVIGATOR_TYPE" : \ ((pt == RESET_NAVIGATOR) ? "RESET_NAVIGATOR" : \ ((pt == GET_DATA_PHONE_NO) ? "GET_DATA_PHONE_NO" : \ ((pt == SET_DATA_PHONE_NO) ? "SET_DATA_PHONE_NO" : \ ((pt == GET_VOICE_PHONE_NO) ? "GET_VOICE_PHONE_NO" : \ ((pt == SET_VOICE_PHONE_NO) ? "SET_VOICE_PHONE_NO" : \ ((pt == GET_USER_ID) ? "GET_USER_ID" : \ ((pt == GET_PASSWORD) ? "GET_PASSWORD" : \ ((pt == SET_USER_ID) ? "SET_USER_ID" : \ ((pt == SET_PASSWORD) ? "SET_PASSWORD" : \ ((pt == EXTENDED_ERROR) ? "EXTENDED_ERROR" : \ ((pt == NAVIGATOR_PARAMETERS) ? "NAVIGATOR_PARAMETERS" : \ ((pt == SERVER_PARAMETERS) ? "SERVER_PARAMETERS" : \ ((pt == START_ROUTE) ? "START_ROUTE" : \ ((pt == STOP_ROUTE) ? "STOP_ROUTE" : \ ((pt == CONTINUE_ROUTE) ? "CONTINUE_ROUTE" : \ ((pt == GET_CURRENT_ROUTE) ? "GET_CURRENT_ROUTE" : \ ((pt == GET_DESTINATIONS) ? "GET_DESTINATIONS" : \ ((pt == WHERE_AM_I) ? "WHERE_AM_I" : \ ((pt == SYNC_DESTINATIONS) ? "SYNC_DESTINATIONS" : \ ((pt == DOWNLOAD_ROUTE) ? "DOWNLOAD_ROUTE" : \ ((pt == DELETE_DEST) ? "DELETE_DEST" : \ ((pt == ADD_DEST) ? "ADD_DEST" : \ ((pt == SEARCH) ? "SEARCH" : \ ((pt == CALL_SERVER_FOR_ROUTE) ? \ "CALL_SERVER_FOR_ROUTE" : \ ((pt == CALL_VOICE_FOR_ROUTE) ? \ "CALL_VOICE_FOR_ROUTE" : \ ((pt == NEW_ROUTE) ? "NEW_ROUTE" : \ ((pt == DOWNLOAD_DATA) ? "DOWNLOAD_DATA" : \ ((pt == START_TUNNEL) ? "START_TUNNEL" : \ ((pt == DATA_CHUNK) ? "DATA_CHUNK" : \ ((pt == SUBSCRIBE) ? "SUBSCRIBE" : \ ((pt == UNSUBSCRIBE) ? "UNSUBSCRIBE" : \ ((pt == GET_INPUT_DATA) ? \ "GET_INPUT_DATA" : \ ((pt == INPUT_DATA) ? "INPUT_DATA" : \ ((pt == ROUTE_INFO) ? "ROUTE_INFO" :\ ((pt == STATUS_PACKET) ? \ "STATUS_PACKET" : \ "UNKNOWN"))) \ )))))))))))))))))))))))))))))))))))) : \ ((pt == ERRORE_REPLY) ? "ERRORE_REPLY" : \ ((pt == TEST_DATA_REPLY) ? "TEST_DATA_REPLY" : \ ((pt == PDA_TYPE_REPLY) ? "PDA_TYPE_REPLY" : \ ((pt == NAVIGATOR_TYPE_REPLY) ? "NAVIGATOR_TYPE_REPLY" : \ ((pt == RESET_NAVIGATOR_REPLY) ? "RESET_NAVIGATOR_REPLY" : \ ((pt == GET_DATA_PHONE_NO_REPLY) ? "GET_DATA_PHONE_NO_REPLY" : \ ((pt == SET_DATA_PHONE_NO_REPLY) ? "SET_DATA_PHONE_NO_REPLY" : \ ((pt == GET_VOICE_PHONE_NO_REPLY) ? "GET_VOICE_PHONE_NO_REPLY" : \ ((pt == SET_VOICE_PHONE_NO_REPLY) ? "SET_VOICE_PHONE_NO_REPLY" : \ ((pt == GET_USER_ID_REPLY) ? "GET_USER_ID_REPLY" : \ ((pt == GET_PASSWORD_REPLY) ? "GET_PASSWORD_REPLY" : \ ((pt == SET_USER_ID_REPLY) ? "SET_USER_ID_REPLY" : \ ((pt == SET_PASSWORD_REPLY) ? "SET_PASSWORD_REPLY" : \ ((pt == EXTENDED_ERROR_REPLY) ? "EXTENDED_ERROR_REPLY" : \ ((pt == NAVIGATOR_PARAMETERS_REPLY) ? \ "NAVIGATOR_PARAMETERS_REPLY" : \ ((pt == SERVER_PARAMETERS_REPLY) ? \ "SERVER_PARAMETERS_REPLY" : \ ((pt == START_ROUTE_REPLY) ? "START_ROUTE_REPLY" : \ ((pt == STOP_ROUTE_REPLY) ? "STOP_ROUTE_REPLY" : \ ((pt == CONTINUE_ROUTE_REPLY) ? \ "CONTINUE_ROUTE_REPLY" : \ ((pt == GET_CURRENT_ROUTE_REPLY) ? \ "GET_CURRENT_ROUTE_REPLY" : \ ((pt == GET_DESTINATIONS_REPLY) ? \ "GET_DESTINATIONS_REPLY" : \ ((pt == WHERE_AM_I_REPLY) ? "WHERE_AM_I_REPLY" : \ ((pt == SYNC_DESTINATIONS_REPLY) ? \ "SYNC_DESTINATIONS_REPLY" : \ ((pt == DOWNLOAD_ROUTE_REPLY) ? \ "DOWNLOAD_ROUTE_REPLY" : \ ((pt == DELETE_DEST_REPLY) ? \ "DELETE_DEST_REPLY" : \ ((pt == ADD_DEST_REPLY) ? "ADD_DEST_REPLY" : \ ((pt == SEARCH_REPLY) ? "SEARCH_REPLY" : \ ((pt == CALL_SERVER_FOR_ROUTE_REPLY) ? \ "CALL_SERVER_FOR_ROUTE_REPLY" : \ ((pt == CALL_VOICE_FOR_ROUTE_REPLY) ? \ "CALL_VOICE_FOR_ROUTE_REPLY" : \ ((pt == NEW_ROUTE_REPLY) ? \ "NEW_ROUTE_REPLY" : \ ((pt == DOWNLOAD_DATA_REPLY) ? \ "DOWNLOAD_DATA_REPLY" : \ ((pt == START_TUNNEL_REPLY) ? \ "START_TUNNEL_REPLY" : \ ((pt == DATA_CHUNK_REPLY) ? \ "DATA_CHUNK_REPLY" : \ ((pt == SUBSCRIBE_REPLY) ? \ "SUBSCRIBE_REPLY" : \ ((pt == UNSUBSCRIBE_REPLY) ? \ "UNSUBSCRIBE_REPLY" : \ ((pt == GET_INPUT_DATA_REPLY) ? \ "GET_INPUT_DATA_REPLY" : \ ((pt == INPUT_DATA_REPLY) ? \ "INPUT_DATA_REPLY" : \ "UNKNOWN" \ )))))))))))))))))))))))))))))))))))))) #else #define PACKET_TYPE_STRING(pt) #pt #endif #endif // DISPLAY_SERIAL_H
[ [ [ 1, 658 ] ] ]
8f132ac379bd4415094b44143667e16c74cd6513
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/MonitorTerminal/scanner.cpp
6404b696354289227ae5f9bb21afd44e18f1bef9
[]
no_license
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
UHC
C++
false
false
22,896
cpp
//************************************************************* // // 정수만이 가능한 Recursive descent parser // 변수의 사용이 가능하고 함수를 호출할 수 있으며, // goto 명령 등 Little C에서 제공하지 않는 기능을 제공한다. // // by Travis nam // //************************************************************* #include "stdafx.h" #include <comdef.h> #include "vutil.h" #include "xutil.h" #define Error printf // // 토큰 스트림 // WORD g_codePage = 0; // 949 namespace THAI { enum CLASS { CTRL= 0, NON= 1, CONS= 2, LV= 3, FV1= 4, FV2= 5, FV3= 6, BV1= 7, BV2= 8, BD= 9, TONE=10, AD1=11, AD2=12, AD3=13, AV1=14, AV2=15, AV3=16, }; CLASS CLASS_TABLE[256] = { CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, NON, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, FV3, CONS, FV3, CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS, NON, FV1, AV2, FV1, FV1, AV1, AV3, AV2, AV3, BV1, BV2, BD, NON, NON, NON, NON, NON, LV, LV, LV, LV, LV, FV2, NON, AD2, TONE, TONE, TONE, TONE, AD1, AD1, AD3, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, CTRL, }; namespace INPUT { enum TYPE { A, C, S, R, X }; bool COMPOSIBLE[3][5] = { { true, true, true, true, true }, { true, true, true,false, true }, { true, true,false,false, true }, }; TYPE STATE_CHECK[17][17] = { // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 { X,A,A,A,A,A,A,R,R,R,R,R,R,R,R,R,R }, // 0 { X,A,A,A,S,S,A,R,R,R,R,R,R,R,R,R,R }, // 1 { X,A,A,A,A,S,A,C,C,C,C,C,C,C,C,C,C }, // 2 { X,S,A,S,S,S,S,R,R,R,R,R,R,R,R,R,R }, // 3 { X,S,A,S,A,S,A,R,R,R,R,R,R,R,R,R,R }, // 4 { X,A,A,A,A,S,A,R,R,R,R,R,R,R,R,R,R }, // 5 { X,A,A,A,S,A,S,R,R,R,R,R,R,R,R,R,R }, // 6 { X,A,A,A,A,S,A,R,R,R,C,C,R,R,R,R,R }, // 7 { X,A,A,A,S,S,A,R,R,R,C,R,R,R,R,R,R }, // 8 { X,A,A,A,S,S,A,R,R,R,R,R,R,R,R,R,R }, // 9 { X,A,A,A,A,A,A,R,R,R,R,R,R,R,R,R,R }, // 0 { X,A,A,A,S,S,A,R,R,R,R,R,R,R,R,R,R }, // 1 { X,A,A,A,S,S,A,R,R,R,R,R,R,R,R,R,R }, // 2 { X,A,A,A,S,S,A,R,R,R,R,R,R,R,R,R,R }, // 3 { X,A,A,A,S,S,A,R,R,R,C,C,R,R,R,R,R }, // 4 { X,A,A,A,S,S,A,R,R,R,C,R,R,R,R,R,R }, // 5 { X,A,A,A,S,S,A,R,R,R,C,R,C,R,R,R,R }, // 6 }; } namespace OUTPUT { enum TYPE { N, C, X }; // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 TYPE STATE_CHECK[17][17] = { { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 0 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 1 { X,N,N,N,N,N,N,C,C,C,C,C,C,C,C,C,C }, // 2 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 3 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 4 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 5 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 6 { X,N,N,N,N,N,N,N,N,N,C,C,N,N,N,N,N }, // 7 { X,N,N,N,N,N,N,N,N,N,C,N,N,N,N,N,N }, // 8 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 9 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 0 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 1 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 2 { X,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N }, // 3 { X,N,N,N,N,N,N,N,N,N,C,C,N,N,N,N,N }, // 4 { X,N,N,N,N,N,N,N,N,N,C,N,N,N,N,N,N }, // 5 { X,N,N,N,N,N,N,N,N,N,C,N,C,N,N,N,N }, // 6 }; } } bool IsComposibleTh(BYTE prev, BYTE curr, int mode) { using namespace THAI; using namespace INPUT; if(mode > 2) { return false; } else { return COMPOSIBLE[mode][STATE_CHECK[CLASS_TABLE[prev]][CLASS_TABLE[curr]]]; } } // Unicode of thai : 0x0E00~0x0E7F (Direct Mapping) // Thai Character -> Unicode (char+0x0E00)-0xA0 = char+0x0D60 // Unicode -> Thai Character (wchar_t-0x0E00)+0xA0 = wchar_t-0x0D60 const char* CharNextTh(const char* lpsz) { using namespace THAI; using namespace OUTPUT; const BYTE* stream = (const BYTE*)(lpsz); while(STATE_CHECK [ CLASS_TABLE [ stream[ 0 ] ] ] [ CLASS_TABLE [ stream[ 1 ] ] ] == C) ++stream; return (const char*)(stream+1); } const char* CharNextEx(const char* strText, WORD codePage) { if(codePage == 874) { return CharNextTh(strText); } else { return CharNextExA(g_codePage, strText, 0); } } CScanner::CScanner( BOOL bComma ) { m_bComma = bComma; m_pProg = m_pBuf = NULL; m_bMemFlag = 1; dwValue = 0; m_lpMark = NULL; m_dwDef = 0; token = m_mszToken; m_bWideChar = FALSE; m_bErrorCheck = TRUE; } CScanner::CScanner( LPVOID p, BOOL bComma ) { m_bComma = bComma; m_pProg = m_pBuf = (CHAR*)p; m_bMemFlag = 1; dwValue = 0; m_dwDef = 0; token = m_mszToken; m_bWideChar = FALSE; m_bErrorCheck = TRUE; } CScanner::~CScanner() { Free(); } void CScanner::Free() { if(!m_bMemFlag && m_pBuf) safe_delete( m_pBuf ); m_pProg = m_pBuf = 0; } BOOL CScanner::Read( CFileIO* pFile, BOOL bMultiByte ) { m_bMemFlag = 0; char* pProg; m_nProgSize = pFile->GetLength(); pProg = new char[ m_nProgSize + 2 ]; m_pProg = m_pBuf = pProg; if( !m_pBuf ) return 0; pFile->Read( m_pBuf,m_nProgSize ); *(pProg + m_nProgSize ) = '\0'; *(pProg + m_nProgSize + 1 ) = '\0'; // 0xfffe의 2바이트를 빼고 널(0x0000)을 2바이트를 추가해서 결국 m_nProgSize는 변화 없음. // 텍스트가 유니코드일 경우 멀티바이트로 변경 if( (BYTE)*(pProg + 0 ) == 0xff && (BYTE)*(pProg + 1 ) == 0xfe ) // is unicode ? { m_bWideChar = TRUE; if( bMultiByte ) // is unicode ? { CHAR* lpMultiByte = new CHAR[ m_nProgSize + 2 ]; int nResult = WideCharToMultiByte( g_codePage, 0, (LPCWSTR)(pProg + 2), -1, lpMultiByte, (m_nProgSize + 2) * sizeof(CHAR), NULL, NULL ); //cchWideChar lpMultiByte[ nResult ] = '\0'; memcpy( pProg, lpMultiByte, nResult ); safe_delete( lpMultiByte ); m_bWideChar = FALSE; } else { memcpy( pProg, pProg + 2, m_nProgSize ); } } return 1; } BOOL CScanner::Load( LPCTSTR lpszFileName, BOOL bMultiByte ) { CResFile file; CString fileName = lpszFileName; fileName.MakeLower(); if( !file.Open(lpszFileName, "rb" ) ) return 0; m_strFileName = lpszFileName; return Read( &file, bMultiByte ); } BOOL CScanner::Load_FileIO( LPCTSTR lpszFileName, BOOL bMultiByte ) { CFileIO file; CString fileName = lpszFileName; fileName.MakeLower(); if( !file.Open(lpszFileName, "rb" ) ) return 0; m_strFileName = lpszFileName; return Read( &file, bMultiByte ); } void CScanner::SetProg( LPVOID pProg ) { m_bMemFlag = 1; m_pProg = m_pBuf = (CHAR*)pProg; } int CScanner::GetLineNum( LPVOID lpProg ) { int nLine = 0; if( lpProg == NULL ) lpProg = m_pProg; if( m_bWideChar == FALSE ) { CHAR* pTemp = m_pBuf; int nLine = 0; while( lpProg != pTemp ) { if( *pTemp == '\r' ) nLine++; pTemp++; } return nLine; } else { wchar_t* pTemp = (wchar_t*)m_pBuf; int nLine = 0; while( lpProg != pTemp ) { if( *pTemp == '\r' ) nLine++; pTemp++; } return nLine; } return nLine; } void CScanner::GetLastFull() // 현재부터 끝까지 한번에 읽는다. { if( m_bWideChar ) { wchar_t* pProg = (wchar_t*)m_pProg; // 앞쪽 white space를 스킵 while( iswhite( *pProg ) && *pProg && *pProg != '\r' ) pProg++; wchar_t* pTemp = m_wszToken; while( *pProg && *pProg!='\r' ) { *pTemp++ = *pProg++; } // 뒤쪽 white space를 스킵 if( pTemp != m_wszToken ) { pTemp--; while( iswhite( *pTemp ) && *pTemp ) pTemp--; pTemp++; } m_pProg = (char*)pProg; *pTemp = '\0'; WideCharToMultiByte(g_codePage, 0, m_wszToken, -1, m_mszToken, sizeof(m_mszToken), NULL, NULL); Token = m_wszToken; } else { // 앞쪽 white space를 스킵 while( iswhite( *m_pProg ) && *m_pProg && *m_pProg != '\r' ) m_pProg++; char* pTemp = token; while( *m_pProg && *m_pProg!='\r' ) { int count = CopyChar( m_pProg, pTemp ); m_pProg += count; pTemp += count; } // 뒤쪽 white space를 스킵 if( pTemp != token ) { pTemp--; while( iswhite( *pTemp ) && *pTemp ) pTemp--; pTemp++; } *pTemp = '\0'; Token = token; } } int CScanner::GetToken( BOOL bComma ) { if( m_bWideChar == TRUE ) return GetToken_Wide( bComma ); char* pszTemp = m_mszToken; *pszTemp = '\0'; tokenType = TEMP; tok = NONE_; m_nDoubleOps = 0; BACK: // white space를 스킵 while( iswhite( *m_pProg ) && *m_pProg ) m_pProg++; while(*m_pProg=='/') // 주석문 처리 { m_pProg++; if(*m_pProg=='/') { m_pProg++; while(*m_pProg!='\r'&&*m_pProg!='\0') m_pProg++; if(*m_pProg=='\r') m_pProg+=2; } else if(*m_pProg=='*') { m_pProg++; do { while(*m_pProg!='*'&&*m_pProg!='\0') m_pProg++; // 파일의 끝이라면? if(*m_pProg=='\0') { tok = FINISHED; tokenType = DELIMITER; return tokenType; } m_pProg++; } while(*m_pProg!='/'); m_pProg++; while(iswhite(*m_pProg) && *m_pProg) m_pProg++; } else { m_pProg--; break; } goto BACK; } // 화일의 끝 if(*m_pProg=='\0') { tok = FINISHED; tokenType = DELIMITER; goto EXIT; } // Comma 형식의 구분자인가? if( bComma || m_bComma ) { // 콤마나 데이타의 끝, 또는 엔터 코드가 나올 때까지 읽는다. // 콤마 구분일 경우는 그것은 pszTemp와 NUMBER만을 구분한다. if(*m_pProg=='"') { m_pProg++; while(*m_pProg!='"' && *m_pProg!='\r' && *m_pProg!='\0') *pszTemp++ = *m_pProg++; m_pProg++; tokenType = STRING; } else { while(*m_pProg!=',' && *m_pProg!='\r' && *m_pProg!='\0') *pszTemp++ = *m_pProg++; } if( *m_pProg == ',' || *m_pProg == '\r') m_pProg++; // skim comma // white space를 스킵 if( pszTemp != token ) { pszTemp--; while( iswhite( *pszTemp ) && *pszTemp ) pszTemp--; pszTemp++; if( isdigit2( token[0] ) ) tokenType = NUMBER; if(token[0]=='0' && token[1]=='x') tokenType = HEX; } goto EXIT; } if(strchr("!<>=",*m_pProg)) { // is or might be a relation operator switch(*m_pProg) { case '=': if(*(m_pProg+1)=='=') { *pszTemp++ = *m_pProg++; *pszTemp++ = *m_pProg++; m_nDoubleOps = EQ; } break; case '!': if(*(m_pProg+1)=='=') { *pszTemp++ = *m_pProg++; *pszTemp++ = *m_pProg++; m_nDoubleOps = NE; } else { *pszTemp++ = *m_pProg++; m_nDoubleOps = NT; } break; case '<': if(*(m_pProg+1)=='=') { *pszTemp++ = *m_pProg++; *pszTemp++ = *m_pProg++; m_nDoubleOps = LE; } else { *pszTemp++ = *m_pProg++; m_nDoubleOps = LT; } break; case '>': if(*(m_pProg+1)=='=') { *pszTemp++ = *m_pProg++; *pszTemp++ = *m_pProg++; m_nDoubleOps = GE; } else { *pszTemp++ = *m_pProg++; m_nDoubleOps = GT; } break; } if(*token) { tokenType = DELIMITER; goto EXIT; } } // delimiter if(*m_pProg == '&' && *(m_pProg+1) == '&') { *pszTemp = *(pszTemp+1) = '&'; pszTemp+=2; m_pProg+=2; tokenType = DELIMITER; goto EXIT; } if(*m_pProg == '|' && *(m_pProg+1) == '|') { *pszTemp = *(pszTemp+1) = '|'; pszTemp+=2; m_pProg+=2; tokenType = DELIMITER; goto EXIT; } if( strchr( "+-*^/%=;(),':{}.", *m_pProg ) ) { *pszTemp = *m_pProg; m_pProg++; pszTemp++; tokenType = DELIMITER; goto EXIT; } // 스트링 if(*m_pProg=='"') { m_pProg++; while( *m_pProg!='"' && *m_pProg!='\r' && *m_pProg!='\0' && ( pszTemp - token ) < MAX_TOKENSTR ) { int count = CopyChar( m_pProg, pszTemp ); m_pProg += count; pszTemp += count; } m_pProg++; tokenType = STRING; if( *(m_pProg-1 ) != '"' ) { if( *(m_pProg-1 ) == '\0' ) m_pProg--; if( m_bErrorCheck ) { CString string; if( ( pszTemp - token ) >= MAX_TOKENSTR ) string.Format( "line(%d) 파일 %s에서 \"%s\" 스트링 길이가 %d바이트를 초과했음.", GetLineNum(), m_strFileName, token, MAX_TOKENSTR ); else string.Format( "line(%d) 파일 %s에서 \"%s\" 스트링이 따옴표로 끝나지 않음.", GetLineNum(), m_strFileName, token ); Error( string ); } } goto EXIT; } // hex if( *m_pProg=='0' && *(m_pProg + 1 )=='x' ) { m_pProg+=2; while(!isdelim(*m_pProg)) *pszTemp++ = *m_pProg++; tokenType = HEX; goto EXIT; } // 숫자 if( isdigit2( *m_pProg ) && !IsMultiByte( m_pProg ) ) //숫자 검사만으로 끝나는데 왜 한글이 아닐 경우도 체크하지? { while( !isdelim( *m_pProg ) ) *pszTemp++ = *m_pProg++; tokenType = NUMBER; goto EXIT; } // 변수와 명령 if( isalpha( *m_pProg ) || IsMultiByte( m_pProg ) || *m_pProg == '#' || *m_pProg == '_' || *m_pProg == '@' || *m_pProg=='$' || *m_pProg == '?' ) { while( !isdelim( *m_pProg ) ) { int count = CopyChar( m_pProg, pszTemp ); m_pProg += count; pszTemp += count; } } else *pszTemp++ = *m_pProg++; tokenType = TEMP; EXIT: *pszTemp = '\0'; Token = token; return tokenType; } int CScanner::GetToken_Wide( BOOL bComma ) { wchar_t* pProg = (wchar_t*)m_pProg; wchar_t* pszTemp = m_wszToken; *pszTemp = '\0'; tokenType = TEMP; tok = NONE_; m_nDoubleOps = 0; BACK: while( iswhite( *pProg ) && *pProg ) pProg++; while(*pProg=='/') // 주석문 처리 { pProg++; if(*pProg=='/') { pProg++; while(*pProg!='\r'&&*pProg!='\0') pProg++; if(*pProg=='\r') pProg+=2; } else if(*pProg=='*') { pProg++; do { while(*pProg!='*'&&*pProg!='\0') pProg++; // 파일의 끝이라면? if(*pProg=='\0') { tok = FINISHED; tokenType = DELIMITER; m_pProg = (char*)pProg; return tokenType; } pProg++; } while(*pProg!='/'); pProg++; while(iswhite(*pProg) && *pProg) pProg++; } else { pProg--; break; } goto BACK; } // 화일의 끝 if(*pProg=='\0') { tok = FINISHED; tokenType = DELIMITER; goto EXIT; } // Comma 형식의 구분자인가? if( bComma || m_bComma ) { // 콤마나 데이타의 끝, 또는 엔터 코드가 나올 때까지 읽는다. // 콤마 구분일 경우는 그것은 pszTemp와 NUMBER만을 구분한다. if(*pProg=='"') { pProg++; while(*pProg!='"' && *pProg!='\r' && *pProg!='\0') *pszTemp++ = *pProg++; pProg++; tokenType = STRING; } else { while(*pProg!=',' && *pProg!='\r' && *pProg!='\0') *pszTemp++ = *pProg++; } if( *pProg == ',' || *pProg == '\r') pProg++; // skim comma // white space를 스킵 if( pszTemp != m_wszToken ) { pszTemp--; while( iswhite( *pszTemp ) && *pszTemp ) pszTemp--; pszTemp++; if( isdigit2( (CHAR)( m_wszToken[0] ) ) ) tokenType = NUMBER; if(m_wszToken[0]=='0' && m_wszToken[1]=='x') tokenType = HEX; } goto EXIT; } if(strchr("!<>=",*pProg)) { // is or might be a relation operator switch(*pProg) { case '=': if(*(pProg+1)=='=') { *pszTemp++ = *pProg++; *pszTemp++ = *pProg++; m_nDoubleOps = EQ; } break; case '!': if(*(pProg+1)=='=') { *pszTemp++ = *pProg++; *pszTemp++ = *pProg++; m_nDoubleOps = NE; } else { *pszTemp++ = *pProg++; m_nDoubleOps = NT; } break; case '<': if(*(pProg+1)=='=') { *pszTemp++ = *pProg++; *pszTemp++ = *pProg++; m_nDoubleOps = LE; } else { *pszTemp++ = *pProg++; m_nDoubleOps = LT; } break; case '>': if(*(pProg+1)=='=') { *pszTemp++ = *pProg++; *pszTemp++ = *pProg++; m_nDoubleOps = GE; } else { *pszTemp++ = *pProg++; m_nDoubleOps = GT; } break; } if(m_wszToken[0]) { tokenType = DELIMITER; goto EXIT; } } // delimiter if(*pProg == '&' && *(pProg+1) == '&') { *pszTemp = *(pszTemp+1) = '&'; pszTemp+=2; pProg+=2; tokenType = DELIMITER; goto EXIT; } if(*pProg == '|' && *(pProg+1) == '|') { *pszTemp = *(pszTemp+1) = '|'; pszTemp+=2; pProg+=2; tokenType = DELIMITER; goto EXIT; } if( strchr( "+-*^/%=;(),':{}.", *pProg ) ) { *pszTemp = *pProg; pProg++; pszTemp++; tokenType = DELIMITER; goto EXIT; } // 스트링 if(*pProg=='"') { pProg++; while(*pProg!='"' && *pProg!='\r' && *pProg!='\0' && ( pszTemp - m_wszToken ) < MAX_TOKENSTR ) *pszTemp++ = *pProg++; pProg++; tokenType = STRING; if( *(pProg-1 ) != '"' ) { if( *(pProg-1 ) == '\0' ) pProg--; if( m_bErrorCheck ) { CString string; if( ( pszTemp - m_wszToken ) >= MAX_TOKENSTR ) string.Format( "line(%d) 파일 %s에서 \"%s\" 스트링 길이가 %d바이트를 초과했음.", GetLineNum(), m_strFileName, token, MAX_TOKENSTR ); else string.Format( "line(%d) 파일 %s에서 \"%s\" 스트링이 따옴표로 끝나지 않음.", GetLineNum(), m_strFileName, token ); Error( string ); } } goto EXIT; } // hex if( *pProg=='0' && *(pProg + 1 )=='x' ) { pProg+=2; while(!isdelim(*pProg)) *pszTemp++ = *pProg++; tokenType = HEX; goto EXIT; } // 숫자 if( isdigit2( (CHAR)( *pProg ) ) && !IsDBCSLeadByte( (CHAR)( *pProg ) ) ) //숫자 검사만으로 끝나는데 왜 한글이 아닐 경우도 체크하지? { while( !isdelim( *pProg ) ) *pszTemp++ = *pProg++; tokenType = NUMBER; goto EXIT; } // 변수와 명령 if( isalpha( *pProg ) || IsDBCSLeadByte( (CHAR)( *pProg ) ) || *pProg == '#' || *pProg == '_' || *pProg == '@' || *pProg=='$' || *pProg == '?' ) { while(!isdelim(*pProg)) *pszTemp++ = *pProg++; } else *pszTemp++ = *pProg++; tokenType = TEMP; EXIT: m_pProg = (char*)pProg; *pszTemp = '\0'; Token = m_wszToken; WideCharToMultiByte(g_codePage, 0, m_wszToken, -1, m_mszToken, sizeof(m_mszToken), NULL, NULL); return tokenType; } int CScanner::GetNumber( BOOL bComma ) { m_dwDef = 1; if( GetToken( bComma ) == HEX ) { Token.MakeLower(); DWORDLONG dwlNumber = 0; DWORD dwMulCnt = 0; CHAR cVal; for( int i = Token.GetLength() - 1; i >= 0; i--) { cVal = Token[ i ]; if( cVal >= 'a' ) cVal = ( cVal - 'a' ) + 10; else cVal -= '0'; dwlNumber |= (DWORDLONG) cVal << dwMulCnt; dwMulCnt += 4; } m_dwDef = 0; return (DWORD)dwlNumber; } else if(!Token.IsEmpty()) { switch(Token[0]) { case '=': m_dwDef = 0; return NULL_ID; case '-': if( bComma == FALSE ) { GetToken(); m_dwDef = 0; return -atoi(Token); } else { m_dwDef = 0; return atoi(Token); } case '+': if( bComma == FALSE ) GetToken(); } m_dwDef = 0; return atoi(Token); } m_dwDef = 0; return 0; } __int64 CScanner::GetInt64( BOOL bComma ) { m_dwDef = 1; if( GetToken( bComma ) == HEX ) { } else if( !Token.IsEmpty() ) { switch( Token[0] ) { case '=': m_dwDef = 0; return NULL_ID; case '-': if( bComma == FALSE ) { GetToken(); m_dwDef = 0; return -_atoi64( Token ); } else { m_dwDef = 0; return _atoi64( Token ); } case '+': if( bComma == FALSE ) GetToken(); } m_dwDef = 0; return _atoi64( Token ); } m_dwDef = 0; return (__int64)0; } FLOAT CScanner::GetFloat( BOOL bComma ) { m_dwDef = 1; GetToken( bComma ); if( !Token.IsEmpty() ) { switch( Token[0] ) { case '=': m_dwDef = 0; return -1; case '-': GetToken(bComma); m_dwDef = 0; return (FLOAT)-atof(Token); case '+': GetToken(bComma); } m_dwDef = 0; return (FLOAT)atof(Token); } m_dwDef = 0; return 0.0f; } DWORD CScanner::GetHex( BOOL bComma ) { m_dwDef = 1; if( GetToken( bComma ) == HEX ) { Token.MakeLower(); DWORDLONG dwlNumber = 0; DWORD dwMulCnt = 0; CHAR cVal; for( int i = Token.GetLength() - 1; i >= 0; i--) { cVal = Token[ i ]; if( cVal >= 'a' ) cVal = ( cVal - 'a' ) + 10; else cVal -= '0'; dwlNumber |= (DWORDLONG) cVal << dwMulCnt; dwMulCnt += 4; } m_dwDef = 0; return (DWORD)dwlNumber; } m_dwDef = 0; return 0; } void CScanner::PutBack() { if( m_bWideChar ) { for( WORD *t = m_wszToken; *t; t++ ) m_pProg-=2; if( tokenType == STRING ) // 따옴표 처리 m_pProg-=4; } else { for( CHAR *t = m_mszToken; *t; t++ ) m_pProg--; if( tokenType == STRING ) // 따옴표 처리 m_pProg-=2; } } int CScanner::isdelim( wchar_t c ) { // LeadByte면 delim가 아니므로 0 if(strchr(" !:;,+-<>'/*%^=()&|\"{}",c) || c == 9 || c == '\r' || c == 0 || c == '\n' ) return 1; return 0; } int CScanner::iswhite( wchar_t c ) { if(c > 0 && c <= 0x20) return 1; return 0; } SERIALNUMBER CScanner::GetSerialNumber( BOOL bComma ) { #ifdef __EXP_SERIAL_NUMBER0323 return GetInt64( bComma ); #else // __EXP_SERIAL_NUMBER0323 return GetNumber( bComma ); #endif // __EXP_SERIAL_NUMBER0323 }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 964 ] ] ]
50c4ac5ec365e56d0fea0facef89bf1052aa0771
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/RichEditCtrlX.cpp
db74e08f9b0268fc613a36015f4ce2387d605a3d
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
11,535
cpp
//this file is part of eMule //Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "resource.h" #include "MenuCmds.h" #include "RichEditCtrlX.h" #include "OtherFunctions.h" #include "emule.h" // XP Style Menu [Xanatos] - Stulle #include "MenuXP.h" // XP Style Menu [Xanatos] - Stulle #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CRichEditCtrlX BEGIN_MESSAGE_MAP(CRichEditCtrlX, CRichEditCtrl) ON_WM_CONTEXTMENU() ON_WM_KEYDOWN() ON_WM_GETDLGCODE() ON_NOTIFY_REFLECT_EX(EN_LINK, OnEnLink) ON_CONTROL_REFLECT(EN_CHANGE, OnEnChange) ON_WM_SETCURSOR() // ==> XP Style Menu [Xanatos] - Stulle ON_WM_MEASUREITEM() ON_WM_MENUCHAR() // <== XP Style Menu [Xanatos] - Stulle END_MESSAGE_MAP() CRichEditCtrlX::CRichEditCtrlX() { m_bDisableSelectOnFocus = true; m_bSelfUpdate = false; m_bForceArrowCursor = false; m_hArrowCursor = ::LoadCursor(NULL, IDC_ARROW); } CRichEditCtrlX::~CRichEditCtrlX() { } void CRichEditCtrlX::SetDisableSelectOnFocus(bool bDisable) { m_bDisableSelectOnFocus = bDisable; } void CRichEditCtrlX::SetSyntaxColoring(const LPCTSTR* ppszKeywords, LPCTSTR pszSeperators) { int i = 0; while (ppszKeywords[i] != NULL) m_astrKeywords.Add(ppszKeywords[i++]); m_strSeperators = pszSeperators; if (m_astrKeywords.GetCount() == 0) m_strSeperators.Empty(); else { SetEventMask(GetEventMask() | ENM_CHANGE); GetDefaultCharFormat(m_cfDef); m_cfKeyword = m_cfDef; m_cfKeyword.dwMask |= CFM_COLOR; m_cfKeyword.dwEffects &= ~CFE_AUTOCOLOR; m_cfKeyword.crTextColor = RGB(0,0,255); ASSERT( GetTextMode() & TM_MULTILEVELUNDO ); } } CRichEditCtrlX& CRichEditCtrlX::operator<<(LPCTSTR psz) { ReplaceSel(psz); return *this; } CRichEditCtrlX& CRichEditCtrlX::operator<<(char* psz) { ReplaceSel(CA2T(psz)); return *this; } CRichEditCtrlX& CRichEditCtrlX::operator<<(UINT uVal) { CString strVal; strVal.Format(_T("%u"), uVal); ReplaceSel(strVal); return *this; } CRichEditCtrlX& CRichEditCtrlX::operator<<(int iVal) { CString strVal; strVal.Format(_T("%d"), iVal); ReplaceSel(strVal); return *this; } CRichEditCtrlX& CRichEditCtrlX::operator<<(double fVal) { CString strVal; strVal.Format(_T("%.3f"), fVal); ReplaceSel(strVal); return *this; } UINT CRichEditCtrlX::OnGetDlgCode() { if (m_bDisableSelectOnFocus) { // Avoid that the edit control will select the entire contents, if the // focus is moved via tab into the edit control // // DLGC_WANTALLKEYS is needed, if the control is within a wizard property // page and the user presses the Enter key to invoke the default button of the property sheet! return CRichEditCtrl::OnGetDlgCode() & ~(DLGC_HASSETSEL | DLGC_WANTALLKEYS); } // if there is an auto complete control attached to the rich edit control, we have to explicitly disable DLGC_WANTTAB return CRichEditCtrl::OnGetDlgCode() & ~DLGC_WANTTAB; } BOOL CRichEditCtrlX::OnEnLink(NMHDR *pNMHDR, LRESULT *pResult) { BOOL bMsgHandled = FALSE; *pResult = 0; ENLINK* pEnLink = reinterpret_cast<ENLINK *>(pNMHDR); if (pEnLink && pEnLink->msg == WM_LBUTTONDOWN) { CString strUrl; GetTextRange(pEnLink->chrg.cpMin, pEnLink->chrg.cpMax, strUrl); ShellExecute(NULL, NULL, strUrl, NULL, NULL, SW_SHOWDEFAULT); *pResult = 1; bMsgHandled = TRUE; // do not route this message to any parent } return bMsgHandled; } void CRichEditCtrlX::OnContextMenu(CWnd* /*pWnd*/, CPoint point) { if (point.x != -1 || point.y != -1) { CRect rcClient; GetClientRect(&rcClient); ClientToScreen(&rcClient); if (!rcClient.PtInRect(point)) { Default(); return; } } long iSelStart, iSelEnd; GetSel(iSelStart, iSelEnd); int iTextLen = GetWindowTextLength(); // Context menu of standard edit control // // Undo // ---- // Cut // Copy // Paste // Delete // ------ // Select All bool bReadOnly = (GetStyle() & ES_READONLY)!=0; // ==> XP Style Menu [Xanatos] - Stulle /* CMenu menu; menu.CreatePopupMenu(); if (!bReadOnly){ menu.AppendMenu(MF_STRING, MP_UNDO, GetResString(IDS_UNDO)); menu.AppendMenu(MF_SEPARATOR); } if (!bReadOnly) menu.AppendMenu(MF_STRING, MP_CUT, GetResString(IDS_CUT)); menu.AppendMenu(MF_STRING, MP_COPYSELECTED, GetResString(IDS_COPY)); if (!bReadOnly){ menu.AppendMenu(MF_STRING, MP_PASTE, GetResString(IDS_PASTE)); menu.AppendMenu(MF_STRING, MP_REMOVESELECTED, GetResString(IDS_DELETESELECTED)); } menu.AppendMenu(MF_SEPARATOR); menu.AppendMenu(MF_STRING, MP_SELECTALL, GetResString(IDS_SELECTALL)); */ CTitleMenu menu; menu.CreatePopupMenu(); menu.AddMenuTitle(GetResString(IDS_LOGENTRY)); if (!bReadOnly){ menu.AppendMenu(MF_STRING, MP_UNDO, GetResString(IDS_UNDO), _T("UNDO")); menu.AppendMenu(MF_SEPARATOR); } if (!bReadOnly) menu.AppendMenu(MF_STRING, MP_CUT, GetResString(IDS_CUT), _T("CUT")); menu.AppendMenu(MF_STRING, MP_COPYSELECTED, GetResString(IDS_COPY), _T("COPY")); if (!bReadOnly){ menu.AppendMenu(MF_STRING, MP_PASTE, GetResString(IDS_PASTE), _T("PASTE")); menu.AppendMenu(MF_STRING, MP_REMOVESELECTED, GetResString(IDS_DELETESELECTED), _T("DELETE")); } menu.AppendMenu(MF_SEPARATOR); menu.AppendMenu(MF_STRING, MP_SELECTALL, GetResString(IDS_SELECTALL), _T("SEARCHFILETYPE_DOCUMENT")); // <== XP Style Menu [Xanatos] - Stulle menu.EnableMenuItem(MP_UNDO, CanUndo() ? MF_ENABLED : MF_GRAYED); menu.EnableMenuItem(MP_CUT, iSelEnd > iSelStart ? MF_ENABLED : MF_GRAYED); menu.EnableMenuItem(MP_COPYSELECTED, iSelEnd > iSelStart ? MF_ENABLED : MF_GRAYED); menu.EnableMenuItem(MP_PASTE, CanPaste() ? MF_ENABLED : MF_GRAYED); menu.EnableMenuItem(MP_REMOVESELECTED, iSelEnd > iSelStart ? MF_ENABLED : MF_GRAYED); menu.EnableMenuItem(MP_SELECTALL, iTextLen > 0 ? MF_ENABLED : MF_GRAYED); if (point.x == -1 && point.y == -1) { point.x = 16; point.y = 32; ClientToScreen(&point); } // Cheap workaround for the "Text cursor is showing while context menu is open" glitch. It could be solved properly // with the RE's COM interface, but because the according messages are not routed with a unique control ID, it's not // really useable (e.g. if there are more RE controls in one window). Would to envelope each RE window to get a unique ID.. m_bForceArrowCursor = true; menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this); m_bForceArrowCursor = false; VERIFY( menu.DestroyMenu() ); // XP Style Menu [Xanatos] - Stulle } BOOL CRichEditCtrlX::OnCommand(WPARAM wParam, LPARAM /*lParam*/) { switch (wParam) { case MP_UNDO: Undo(); break; case MP_CUT: Cut(); break; case MP_COPYSELECTED: Copy(); break; case MP_PASTE: Paste(); break; case MP_REMOVESELECTED: Clear(); break; case MP_SELECTALL: SetSel(0, -1); break; } return TRUE; } void CRichEditCtrlX::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { if (nChar == 'A' && (GetKeyState(VK_CONTROL) & 0x8000)) { ////////////////////////////////////////////////////////////////// // Ctrl+A: Select all SetSel(0, -1); } else if (nChar == 'C' && (GetKeyState(VK_CONTROL) & 0x8000)) { ////////////////////////////////////////////////////////////////// // Ctrl+C: Copy selected contents to clipboard Copy(); } CRichEditCtrl::OnKeyDown(nChar, nRepCnt, nFlags); } void CRichEditCtrlX::OnEnChange() { if (!m_bSelfUpdate && m_astrKeywords.GetCount()) UpdateSyntaxColoring(); } void CRichEditCtrlX::UpdateSyntaxColoring() { CString strText; GetWindowText(strText); if (strText.IsEmpty()) return; m_bSelfUpdate = true; long lCurSelStart, lCurSelEnd; GetSel(lCurSelStart, lCurSelEnd); SetSel(0, -1); SetSelectionCharFormat(m_cfDef); SetSel(lCurSelStart, lCurSelEnd); LPTSTR pszStart = const_cast<LPTSTR>((LPCTSTR)strText); LPCTSTR psz = pszStart; while (*psz != _T('\0')) { if (*psz == _T('\"')) { LPCTSTR pszEnd = _tcschr(psz + 1, _T('\"')); if (pszEnd) psz = pszEnd + 1; else break; } else { bool bFoundKeyword = false; for (int k = 0; k < m_astrKeywords.GetCount(); k++) { const CString& rstrKeyword = m_astrKeywords[k]; int iKwLen = rstrKeyword.GetLength(); if (_tcsncmp(psz, rstrKeyword, iKwLen)==0 && (psz[iKwLen]==_T('\0') || _tcschr(m_strSeperators, psz[iKwLen])!=NULL)) { int iStart = psz - pszStart; int iEnd = iStart + iKwLen; long lCurSelStart, lCurSelEnd; GetSel(lCurSelStart, lCurSelEnd); SetSel(iStart, iEnd); SetSelectionCharFormat(m_cfKeyword); SetSel(lCurSelStart, lCurSelEnd); psz += iKwLen; bFoundKeyword = true; break; } } if (!bFoundKeyword) psz++; } } UpdateWindow(); m_bSelfUpdate = false; } BOOL CRichEditCtrlX::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // Cheap workaround for the "Text cursor is showing while context menu is open" glitch. It could be solved properly // with the RE's COM interface, but because the according messages are not routed with a unique control ID, it's not // really useable (e.g. if there are more RE controls in one window). Would to envelope each RE window to get a unique ID.. if (m_bForceArrowCursor && m_hArrowCursor) { ::SetCursor(m_hArrowCursor); return TRUE; } return CRichEditCtrl::OnSetCursor(pWnd, nHitTest, message); } DWORD CALLBACK CRichEditCtrlX::StreamInCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb) { CFile* pFile = (CFile*)dwCookie; *pcb = pFile->Read(pbBuff, cb); return 0; } void CRichEditCtrlX::SetRTFText(const CStringA& rstrTextA) { CMemFile memFile((BYTE*)(LPCSTR)rstrTextA, rstrTextA.GetLength()); EDITSTREAM es = {0}; es.pfnCallback = StreamInCallback; es.dwCookie = (DWORD_PTR)&memFile; StreamIn(SF_RTF, es); } // ==> XP Style Menu [Xanatos] - Stulle void CRichEditCtrlX::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct) { HMENU hMenu = AfxGetThreadState()->m_hTrackingMenu; CMenu *pMenu = CMenu::FromHandle(hMenu); pMenu->MeasureItem(lpMeasureItemStruct); CWnd::OnMeasureItem(nIDCtl, lpMeasureItemStruct); } LRESULT CRichEditCtrlX::OnMenuChar(UINT nChar, UINT nFlags, CMenu* pMenu) { if (pMenu->IsKindOf(RUNTIME_CLASS(CTitleMenu)) ) return CTitleMenu::OnMenuChar(nChar, nFlags, pMenu); return CRichEditCtrl::OnMenuChar(nChar, nFlags, pMenu); } // <== XP Style Menu [Xanatos] - Stulle
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 396 ] ] ]
5e9ad7c5d8eee70f4cb599b07d6860a60c38fd9e
6e4f9952ef7a3a47330a707aa993247afde65597
/PROJECTS_ROOT/SmartWires/GUIClasses/DLG_Options.cpp
70e7ac24b55e85a35bec2a3965f18b7d1e6ca133
[]
no_license
meiercn/wiredplane-wintools
b35422570e2c4b486c3aa6e73200ea7035e9b232
134db644e4271079d631776cffcedc51b5456442
refs/heads/master
2021-01-19T07:50:42.622687
2009-07-07T03:34:11
2009-07-07T03:34:11
34,017,037
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
95,213
cpp
// DLG_Options.cpp : implementation file #include "stdafx.h" #include "DLG_Options.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define SPECINVERTCOL(X) 0xFFFFFF^(DWORD(X)+0x7B7B7B) #define YELLOWR 0xFF #define YELLOWG 0xFF #define YELLOWB 0xE0 CString sSafeChar; void CDLG_Options::InitExtraData() { hDefaultTopic=NULL; hLPaneRoot=FL_ROOT; hTopLPaneItem=NULL; hCurButtonsBarIRow=NULL; bAnyHotkeyWasChanged=0; hLastOpenedRPane=0; isDialogInProcess=0; } CString GetTooltipText(CToolTipCtrl* tl, CWnd* pWnd) { if(pWnd != NULL && ::IsWindow(pWnd->GetSafeHwnd())){ TOOLINFO ti; ti.hwnd = ::GetParent(pWnd->GetSafeHwnd()); ti.uFlags = TTF_IDISHWND; ti.uId = (UINT_PTR)(pWnd->GetSafeHwnd()); char sz[32000]={0}; ti.lpszText = sz; ::SendMessage(tl->GetSafeHwnd(), TTM_GETTEXT, 0, (LPARAM)&ti); return sz; } return ""; } ///////////////////////////////////////////////////////////////////////////// // CDLG_Options dialog HINSTANCE CheckPlugin(const char* sz, BOOL bAllowLoad=0) { HINSTANCE h=GetModuleHandle(CString(sz)+".wkp"); if(h){ return h; } CString sP=CString("WKPLUG_")+sz; sP.MakeUpper(); HWND hW=FindWindow("WK_MAIN",0); if(bAllowLoad && hW!=0){ HWND hMain=(HWND)GetProp(hW,"MAIN_WND"); if(hMain){ ::SendMessage(hMain,WM_USER+16/*LOADPLUGIN*/,(WPARAM)sz,0); HINSTANCE h=GetModuleHandle(CString(sz)+".wkp"); if(h){ return h; } } } if(hW!=0){ return (HINSTANCE)GetProp(hW,sP); } return 0; } void CDLG_Options::InitAll(CDLG_Options_Startup& pStartupInfo) { //{{AFX_DATA_INIT(CDLG_Options) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT iTab=0; bNoGridOnRPanel=0; bAutoSkipEmptyPanes=0; bHHideAddit=0; bHHideHelp=0; lSipleActionIconNum=0; m_bSelInBold=1; bManualPreventCommit=0; bBlockCancel=0; bShowFind=1; bRPaneOnly=0; InitExtraData(); //----------- MainRulePos=0; bDoNotSavePanePos=0; bShowColorForColorOptions=FALSE; m_pStartupInfo=&pStartupInfo; dwOptionCount=0; bParentOnTop=FALSE; dwFlg=0; #ifdef _WIREKEYS lSipleRemindIconNum=34;//Теперь всегда CheckPlugin("wp_schedule")?34:0; #else lSipleRemindIconNum=0; #endif } CDLG_Options::CDLG_Options(CDLG_Options_Startup& pStartupInfo, CWnd* pParent, DWORD dwIFlg) : CDialog(IDD_OPTIONS_DIALOG, pParent) { InitAll(pStartupInfo); pParentWnd=0; dwFlg=dwIFlg; } CDLG_Options::CDLG_Options(CDLG_Options_Startup& pStartupInfo, CWnd* pParent /*=NULL*/) : CDialog(IDD_OPTIONS_DIALOG, NULL)//CWnd::GetDesktopWindow()-убивает мышь на NT! { InitAll(pStartupInfo); pParentWnd=pParent; } void CDLG_Options::DestroyOptions(BOOL bTemp) { m_OptionsList.SetSelectionToZero(); m_LList.SetSelectionToZero(); m_ChangedClasses.RemoveAll(); m_LList.DeleteAllIRows(); m_OptionsList.DeleteAllIRows(); int i=0; for(i=0;i<aOptions.GetSize();i++){ COption* pOption=aOptions[i]; if(!pOption){ continue; } delete pOption; } aOptions.RemoveAll(); for(i=0;i<aMenuOptions.GetSize();i++){ COption* pOption=aMenuOptions[i]; if(!pOption){ continue; } delete pOption; } aMenuOptions.RemoveAll(); if(!bTemp && pParentWnd && IsWindow(pParentWnd->GetSafeHwnd())){ pParentWnd->EnableWindow(TRUE); pParentWnd->SetForegroundWindow(); if(bParentOnTop){ pParentWnd->SetWindowPos(&CWnd::wndTopMost,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); } } aFromRtoL.RemoveAll(); } CDLG_Options::~CDLG_Options() { DestroyOptions(0); } CString getHotKeyStr(CIHotkey oHotKey, BOOL bWithFollowers) { CString sRes=GetIHotkeyName(oHotKey,bWithFollowers); if(sRes==""){ sRes="<"; sRes+=_l("not defined"); sRes+=">"; } return sRes; } CString ConvertToLocaleDate(COleDateTime& dt) { SYSTEMTIME st; dt.GetAsSystemTime(st); char szTmp[128]={0}; GetDateFormat(LOCALE_USER_DEFAULT,DATE_SHORTDATE,&st,0,szTmp,sizeof(szTmp)); return szTmp; } CString getHotKeyStrAlt(CIHotkey oHotKey,CString sPrefix) { CString sRes=""; if(oHotKey.pNextHK){ sRes=GetIHotkeyName(*oHotKey.pNextHK,TRUE); } if(sRes!=""){ sRes=sPrefix+sRes; } return sRes; } void CDLG_Options::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDLG_Options) DDX_Control(pDX, IDC_OPTIONSLIST, m_OptionsList); DDX_Control(pDX, IDC_LPANE, m_LList); //}}AFX_DATA_MAP #ifdef OPTIONS_TOOLBAR DDX_Control(pDX, ID_TOOLBAR1, m_Toolbar1); DDX_Control(pDX, ID_TOOLBAR2, m_Toolbar2); DDX_Control(pDX, ID_TOOLBAR3, m_Toolbar3); DDX_Control(pDX, ID_TOOLBAR4, m_Toolbar4); DDX_Control(pDX, ID_TOOLBAR5, m_Toolbar5); DDX_Control(pDX, ID_TOOLBAR6, m_Toolbar6); #endif } BEGIN_MESSAGE_MAP(CDLG_Options, CDialog) //{{AFX_MSG_MAP(CDLG_Options) ON_NOTIFY(FLNM_ENDEDIT, IDC_OPTIONSLIST, OnEndEdit) ON_NOTIFY(FLNM_STARTEDIT, IDC_OPTIONSLIST, OnStartEdit) ON_NOTIFY(FLNM_END_INPLACE_COMBO, IDC_OPTIONSLIST, OnEndEdit) ON_NOTIFY(FLMN_CHECKBOX_TRIGGER, IDC_OPTIONSLIST, OnEndEdit) ON_NOTIFY(FLNM_END_INPLACE_DATE, IDC_OPTIONSLIST, OnEndEdit) ON_NOTIFY(FLNM_CUSTOMDIALOG, IDC_OPTIONSLIST, OnCustomDialog) ON_NOTIFY(FLNM_COMBOEXPAND, IDC_OPTIONSLIST, OnComboExpand) ON_BN_CLICKED(ID_FOLDERACTIONS1, OnAction1) ON_BN_CLICKED(ID_FOLDERACTIONS2, OnAction2) ON_BN_CLICKED(IDRESET, OnAdditional) ON_BN_CLICKED(IDHELP, OnHelp) ON_BN_CLICKED(IDAPPLY, OnApply) ON_BN_CLICKED(IDC_BUTTON_FIND, OnFind) ON_WM_CTLCOLOR() //}}AFX_MSG_MAP #ifdef OPTIONS_TOOLBAR ON_BN_CLICKED(ID_TOOLBAR1, OnTOOLBAR1) ON_BN_CLICKED(ID_TOOLBAR2, OnTOOLBAR2) ON_BN_CLICKED(ID_TOOLBAR3, OnTOOLBAR3) ON_BN_CLICKED(ID_TOOLBAR4, OnTOOLBAR4) ON_BN_CLICKED(ID_TOOLBAR5, OnTOOLBAR5) ON_BN_CLICKED(ID_TOOLBAR6, OnTOOLBAR6) #endif END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDLG_Options message handlers BOOL CDLG_Options::SetButtons() { static BOOL bWas=FALSE; if(bWas==FALSE){ bWas=TRUE; m_tooltip.AddTool(GetDlgItem(IDC_OPTIONSLIST), _l(OPTIONS_TP)); m_tooltip.AddTool(GetDlgItem(IDRESET), _l("Click here to popup menu with additional actions")); m_tooltip.AddTool(GetDlgItem(IDOK), _l("Apply changes and exit dialog")+" (Ctrl-Enter)"); m_tooltip.AddTool(GetDlgItem(IDCANCEL), _l("Exit dialog without saving changes")+" (Esc)"); m_tooltip.AddTool(GetDlgItem(IDHELP), _l("Show help page")); m_tooltip.AddTool(GetDlgItem(ID_FOLDERACTIONS1), _l("Context-specific action")); m_tooltip.AddTool(GetDlgItem(ID_FOLDERACTIONS2), _l("Menu with possible actions")); m_tooltip.AddTool(GetDlgItem(IDAPPLY), _l("Apply options")); m_tooltip.AddTool(GetDlgItem(IDC_EDIT_FIND), _l("Find Option")); m_tooltip.AddTool(GetDlgItem(IDC_BUTTON_FIND), _l("Find Option")); #ifdef OPTIONS_TOOLBAR m_tooltip.AddTool(GetDlgItem(ID_TOOLBAR1), ""); m_tooltip.AddTool(GetDlgItem(ID_TOOLBAR2), ""); m_tooltip.AddTool(GetDlgItem(ID_TOOLBAR3), ""); m_tooltip.AddTool(GetDlgItem(ID_TOOLBAR4), ""); m_tooltip.AddTool(GetDlgItem(ID_TOOLBAR5), ""); m_tooltip.AddTool(GetDlgItem(ID_TOOLBAR6), ""); #endif }else{ m_tooltip.UpdateTipText(_l(OPTIONS_TP),GetDlgItem(IDC_OPTIONSLIST)); m_tooltip.UpdateTipText(_l("Click here to popup menu with additional actions"),GetDlgItem(IDRESET)); m_tooltip.UpdateTipText(_l("Apply changes and exit dialog")+" (Ctrl-Enter)",GetDlgItem(IDOK)); m_tooltip.UpdateTipText(_l("Exit dialog without saving changes")+" (Esc)",GetDlgItem(IDCANCEL)); m_tooltip.UpdateTipText(_l("Show help page"),GetDlgItem(IDHELP)); m_tooltip.UpdateTipText(_l("Context-specific action"), GetDlgItem(ID_FOLDERACTIONS1)); m_tooltip.UpdateTipText(_l("Menu with possible actions"),GetDlgItem(ID_FOLDERACTIONS2)); m_tooltip.UpdateTipText(_l("Apply options"), GetDlgItem(IDAPPLY)); m_tooltip.UpdateTipText(_l("Find Option"), GetDlgItem(IDC_EDIT_FIND)); m_tooltip.UpdateTipText(_l("Find Option"), GetDlgItem(IDC_BUTTON_FIND)); } GetDlgItem(IDAPPLY)->SetWindowText(_l("Apply")); GetDlgItem(IDC_QHELP)->SetWindowText("");//_l("Description") GetDlgItem(IDOK)->SetWindowText(_l(m_pStartupInfo->szOkButtonText)); GetDlgItem(IDCANCEL)->SetWindowText(_l(m_pStartupInfo->szCancelButtonText)); GetDlgItem(IDRESET)->SetWindowText(_l(m_pStartupInfo->szByDefButtonText)+"..."); GetDlgItem(IDHELP)->SetWindowText(_l(m_pStartupInfo->szHelpButtonText)); GetDlgItem(IDC_BUTTON_FIND)->SetWindowText(_l("Find")); return TRUE; } #define OPT_VALUECOLUMN_WIDTH 0.4 #define OPT_FREEBORDER 7 #define OPT_BTBORDER 4 BOOL CDLG_Options::IniIList() { m_OptionsListImages.DeleteImageList(); m_OptionsListImages.Create(m_pStartupInfo->pImageList); m_OptionsListImages2.DeleteImageList(); m_OptionsListImages2.Create(m_pStartupInfo->pImageList); m_OptionsList.SetImageList(&m_OptionsListImages, LVSIL_SMALL); m_LList.SetImageList(&m_OptionsListImages2, LVSIL_SMALL); return TRUE; } BOOL CDLG_Options::OnInitDialog() { ShowWindow(SW_HIDE); CDialog::OnInitDialog(); m_OptionsList.SetReadOnly(FALSE); BOOL bROpts=(bNoGridOnRPanel?VIEW_NOGRD2:0); if(!m_pStartupInfo->bTreeOnRight){ bROpts=bROpts|VIEW_NOTREE; } m_OptionsList.SetViewOptions(bROpts); IniIList(); ListView_SetExtendedListViewStyleEx(m_OptionsList.m_hWnd, 0, LVS_EX_FULLROWSELECT);//LVS_EX_FLATSB m_OptionsList.InsertFColumn( 0, _l("Option"), TRUE, LVCFMT_LEFT, -1); m_OptionsList.InsertFColumn( 1, _l("Value") , FALSE, LVCFMT_LEFT, -1); m_OptionsList.SetIItemControlType(NULL, 0); m_OptionsList.SetIItemControlType(NULL, 1); strcpy(m_OptionsList.szName,"m_OptionsList"); m_OptionsList.m_crIItemText=RGB(70,70,70); m_OptionsList.m_crSelectedIItemBackground=-1;//RGB(70,100,250); m_OptionsList.m_crSelectedIRowBackground=-1; m_OptionsList.m_crSelectedIItemText=RGB(0,0,0); m_OptionsList.bIgnoreTabKey=TRUE; m_OptionsList.m_crSelectedBold=1; m_OptionsList.bShowButtonsAsLinks=TRUE; m_OptionsList.bSkipTreeLines=TRUE; // m_LList.SetReadOnly(FALSE); m_LList.SetViewOptions(VIEW_NOGRID|VIEW_TREE0);//VIEW_NOTREE SetWindowLong(m_LList,GWL_STYLE,GetWindowLong(m_LList,GWL_STYLE)|LVS_NOCOLUMNHEADER); ListView_SetExtendedListViewStyleEx(m_LList.m_hWnd, 0, LVS_EX_FULLROWSELECT);//LVS_EX_FLATSB m_LList.InsertFColumn( 0, _l("Settings"), TRUE, LVCFMT_LEFT, -1); m_LList.SetIItemControlType(NULL, 0); strcpy(m_LList.szName,"m_LList"); m_LList.m_crIItemText=RGB(70,70,70); m_LList.m_crSelectedIItemBackground=-1; m_LList.m_crSelectedIRowBackground=-1; m_LList.m_crSelectedIItemText=RGB(0,0,0); m_LList.m_crSelectedBold=m_bSelInBold?1:-1; m_LList.bIgnoreTabKey=TRUE; Sizer.InitSizer(this,m_pStartupInfo->iStickPix,HKEY_CURRENT_USER,m_pStartupInfo->szRegSaveKey); CRect minRect(0,0,400,300); Sizer.SetMinRect(minRect); Sizer.SetOptions(STICKABLE|SIZEABLE); Sizer.AddDialogElement(IDC_OPTIONSLIST,bottomResize); Sizer.AddDialogElement(IDOK,widthSize|heightSize); Sizer.AddDialogElement(IDCANCEL,widthSize|heightSize); if(bHHideHelp){ Sizer.AddDialogElement(IDHELP,widthSize|heightSize|alwaysInvisible); }else{ Sizer.AddDialogElement(IDHELP,widthSize|heightSize); } if(bHHideAddit){ GetDlgItem(IDRESET)->ShowWindow(SW_HIDE); Sizer.AddDialogElement(IDRESET,widthSize|heightSize|alwaysInvisible); }else{ Sizer.AddDialogElement(IDRESET,widthSize|heightSize|hidable); } Sizer.AddDialogElement(IDAPPLY,widthSize|heightSize);//|hidable-низя if(!bRPaneOnly){ Sizer.AddDialogElement(IDC_LPANE,rightResize); }else{ Sizer.AddDialogElement(IDC_LPANE,0); } Sizer.AddDialogElement(ID_FOLDERACTIONS1,heightSize); Sizer.AddDialogElement(ID_FOLDERACTIONS2,widthSize|heightSize); #ifdef OPTIONS_TOOLBAR Sizer.AddDialogElement(ID_TOOLBAR1,widthSize|heightSize); Sizer.AddDialogElement(ID_TOOLBAR2,widthSize|heightSize); Sizer.AddDialogElement(ID_TOOLBAR3,widthSize|heightSize); Sizer.AddDialogElement(ID_TOOLBAR4,widthSize|heightSize); Sizer.AddDialogElement(ID_TOOLBAR5,widthSize|heightSize); Sizer.AddDialogElement(ID_TOOLBAR6,widthSize|heightSize); #endif Sizer.AddDialogElement(IDC_QHELP,0);//|hidable-низя Sizer.AddDialogElement(IDC_QHELP_TXT,0);//|hidable-низя Sizer.AddDialogElement(IDC_EDIT_FIND,heightSize); Sizer.AddDialogElement(IDC_BUTTON_FIND,widthSize|heightSize); Sizer.AddDialogElement(IDC_SLIDER_HORZ,widthSize|heightSize); if(!bRPaneOnly){ Sizer.AddDialogElement(IDC_SLIDER_VERT,widthSize|heightSize); }else{ GetDlgItem(IDC_SLIDER_VERT)->ShowWindow(SW_HIDE); } // Sizer.AddLeftAlign(IDC_LPANE,0,OPT_FREEBORDER); Sizer.AddTopAlign(IDC_LPANE,0,OPT_BTBORDER); Sizer.AddRightAlign(IDC_OPTIONSLIST,0,-OPT_FREEBORDER); Sizer.AddTopAlign(IDC_OPTIONSLIST,0,OPT_BTBORDER); Sizer.AddTopAlign(ID_FOLDERACTIONS1,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); Sizer.AddTopAlign(ID_FOLDERACTIONS2,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); #ifdef OPTIONS_TOOLBAR Sizer.AddTopAlign(ID_TOOLBAR1,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); Sizer.AddTopAlign(ID_TOOLBAR2,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); Sizer.AddTopAlign(ID_TOOLBAR3,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); Sizer.AddTopAlign(ID_TOOLBAR4,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); Sizer.AddTopAlign(ID_TOOLBAR5,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); Sizer.AddTopAlign(ID_TOOLBAR6,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); Sizer.AddLeftAlign(ID_TOOLBAR1,IDC_LPANE,rightPos,OPT_BTBORDER+2); Sizer.AddLeftAlign(ID_TOOLBAR2,ID_TOOLBAR1,rightPos,OPT_BTBORDER); Sizer.AddLeftAlign(ID_TOOLBAR3,ID_TOOLBAR2,rightPos,OPT_BTBORDER); Sizer.AddLeftAlign(ID_TOOLBAR4,ID_TOOLBAR3,rightPos,OPT_BTBORDER); Sizer.AddLeftAlign(ID_TOOLBAR5,ID_TOOLBAR4,rightPos,OPT_BTBORDER); Sizer.AddLeftAlign(ID_TOOLBAR6,ID_TOOLBAR5,rightPos,OPT_BTBORDER); #endif MainRulePos=Sizer.AddGotoRule(0);// Sizer.AddGotoLabel(0); Sizer.AddTopAlign(IDC_QHELP,IDC_OPTIONSLIST,bottomPos,OPT_BTBORDER+2); Sizer.AddGotoRule(100); Sizer.AddGotoLabel(1); Sizer.AddLeftAlign(ID_FOLDERACTIONS1,IDC_LPANE,rightPos,OPT_BTBORDER+2); Sizer.AddTopAlign(IDC_QHELP,ID_FOLDERACTIONS1,bottomPos,OPT_BTBORDER); Sizer.AddGotoRule(100); #ifdef OPTIONS_TOOLBAR Sizer.AddGotoLabel(2); Sizer.AddLeftAlign(ID_FOLDERACTIONS1,ID_TOOLBAR1,rightPos,OPT_BTBORDER); Sizer.AddTopAlign(IDC_QHELP,ID_FOLDERACTIONS1,bottomPos,OPT_BTBORDER); Sizer.AddGotoRule(100); Sizer.AddGotoLabel(3); Sizer.AddLeftAlign(ID_FOLDERACTIONS1,ID_TOOLBAR2,rightPos,OPT_BTBORDER); Sizer.AddTopAlign(IDC_QHELP,ID_FOLDERACTIONS1,bottomPos,OPT_BTBORDER); Sizer.AddGotoRule(100); Sizer.AddGotoLabel(4); Sizer.AddLeftAlign(ID_FOLDERACTIONS1,ID_TOOLBAR3,rightPos,OPT_BTBORDER); Sizer.AddTopAlign(IDC_QHELP,ID_FOLDERACTIONS1,bottomPos,OPT_BTBORDER); Sizer.AddGotoRule(100); Sizer.AddGotoLabel(5); Sizer.AddLeftAlign(ID_FOLDERACTIONS1,ID_TOOLBAR4,rightPos,OPT_BTBORDER); Sizer.AddTopAlign(IDC_QHELP,ID_FOLDERACTIONS1,bottomPos,OPT_BTBORDER); Sizer.AddGotoRule(100); Sizer.AddGotoLabel(6); Sizer.AddLeftAlign(ID_FOLDERACTIONS1,ID_TOOLBAR5,rightPos,OPT_BTBORDER); Sizer.AddTopAlign(IDC_QHELP,ID_FOLDERACTIONS1,bottomPos,OPT_BTBORDER); Sizer.AddGotoRule(100); Sizer.AddGotoLabel(7); Sizer.AddLeftAlign(ID_FOLDERACTIONS1,ID_TOOLBAR6,rightPos,OPT_BTBORDER); Sizer.AddTopAlign(IDC_QHELP,ID_FOLDERACTIONS1,bottomPos,OPT_BTBORDER); Sizer.AddGotoRule(100); #endif Sizer.AddGotoLabel(100); Sizer.AddLeftAlign(IDC_OPTIONSLIST,IDC_LPANE,rightPos,OPT_BTBORDER+2); Sizer.AddRightAlign(ID_FOLDERACTIONS2,0,-OPT_FREEBORDER); Sizer.AddRightAlign(ID_FOLDERACTIONS1,ID_FOLDERACTIONS2,leftPos,-OPT_BTBORDER); Sizer.AddBottomAlign(IDOK,0,-OPT_FREEBORDER); Sizer.AddBottomAlign(IDHELP,0,-OPT_FREEBORDER); Sizer.AddBottomAlign(IDRESET,0,-OPT_FREEBORDER); Sizer.AddBottomAlign(IDCANCEL,0,-OPT_FREEBORDER); Sizer.AddBottomAlign(IDAPPLY,0,-OPT_FREEBORDER); Sizer.AddBottomAlign(IDC_LPANE,IDOK,topPos, -OPT_BTBORDER); Sizer.AddBottomAlign(IDC_QHELP,IDOK, topPos, -OPT_BTBORDER); Sizer.AddRightAlign(IDC_QHELP,0,-OPT_FREEBORDER); Sizer.AddLeftAlign(IDC_QHELP,IDC_LPANE,rightPos,OPT_BTBORDER+2); Sizer.AddTopAlign(IDC_QHELP_TXT,IDC_QHELP,topPos,OPT_BTBORDER*4); Sizer.AddLeftAlign(IDC_QHELP_TXT,IDC_QHELP,leftPos,OPT_BTBORDER*4); Sizer.AddBottomAlign(IDC_QHELP_TXT,IDC_QHELP,bottomPos,-OPT_BTBORDER*4); Sizer.AddRightAlign(IDC_QHELP_TXT,IDC_QHELP,rightPos,-OPT_BTBORDER*4); Sizer.AddLeftAlign(IDHELP,0,OPT_FREEBORDER); Sizer.AddLeftAlign(IDRESET,IDHELP,rightPos,OPT_BTBORDER); Sizer.AddRightAlign(IDAPPLY,0,-OPT_FREEBORDER); Sizer.AddRightAlign(IDCANCEL,IDAPPLY,leftPos,-OPT_BTBORDER); Sizer.AddRightAlign(IDOK,IDCANCEL,leftPos,-OPT_BTBORDER); if(!bRPaneOnly){ Sizer.AddRightAlign(IDC_LPANE,IDCANCEL,leftPos|ifBigger,0); Sizer.AddRightAlign(IDC_LPANE,IDC_LPANE,leftPos|ifLess,0); } Sizer.AddBottomAlign(IDC_OPTIONSLIST,IDC_LPANE, bottomPos|ifBigger,-50); Sizer.AddBottomAlign(IDC_OPTIONSLIST,IDC_OPTIONSLIST, topPos|ifLess,0); if(bShowFind==2 || bShowFind==0){ GetDlgItem(IDC_BUTTON_FIND)->ShowWindow(SW_HIDE); GetDlgItem(IDC_EDIT_FIND)->ShowWindow(SW_HIDE); } if(bShowFind==3){ GetDlgItem(IDC_EDIT_FIND)->ShowWindow(SW_HIDE); } Sizer.AddRightAlign(IDC_BUTTON_FIND,IDOK,leftPos,-OPT_BTBORDER); Sizer.AddRightAlign(IDC_EDIT_FIND,IDC_BUTTON_FIND,leftPos,-OPT_BTBORDER); Sizer.AddLeftAlign(IDC_EDIT_FIND,IDRESET,rightPos,OPT_BTBORDER); Sizer.AddBottomAlign(IDC_EDIT_FIND,0,-OPT_FREEBORDER); Sizer.AddBottomAlign(IDC_BUTTON_FIND,0,-OPT_FREEBORDER); if(!bRPaneOnly){ Sizer.AddRightAlign(IDC_SLIDER_VERT,IDC_LPANE,rightPos,2); Sizer.AddLeftAlign(IDC_SLIDER_VERT,IDC_LPANE,rightPos,1); Sizer.AddSideCenterAlign(IDC_SLIDER_VERT,IDC_LPANE,sideCenter,0); } Sizer.AddBottomAlign(IDC_SLIDER_HORZ,IDC_OPTIONSLIST,bottomPos,4); Sizer.AddTopAlign(IDC_SLIDER_HORZ,IDC_OPTIONSLIST,bottomPos,3); Sizer.AddTopCenterAlign(IDC_SLIDER_HORZ,IDC_OPTIONSLIST,topCenter,0); /* //GetDlgItem(IDC_BUTTON_FIND)->ShowWindow(SW_HIDE); GetDlgItem(IDC_EDIT_FIND)->ShowWindow(SW_HIDE); SetButtonSize(this,IDC_BUTTON_FIND,CSize(GetSystemMetrics(SM_CYMENU)-3,GetSystemMetrics(SM_CYMENU)-3)); SetButtonSize(this,IDC_EDIT_FIND,CSize(GetSystemMetrics(SM_CYMENU),GetSystemMetrics(SM_CYMENU)-3)); Sizer.AddTopAlign(IDC_BUTTON_FIND,0,-GetSystemMetrics(SM_CYMENU)+1); Sizer.AddTopAlign(IDC_EDIT_FIND,0,-GetSystemMetrics(SM_CYMENU)+1); Sizer.AddRightAlign(IDC_BUTTON_FIND,0,-1); Sizer.AddRightAlign(IDC_EDIT_FIND,IDC_BUTTON_FIND,leftPos,-OPT_BTBORDER); Sizer.AddLeftAlign(IDC_EDIT_FIND,IDAPPLY,leftPos,1); */ {// CG: The following block was added by the ToolTips component. // Create the ToolTip control. m_tooltip.Create(this); m_tooltip.Activate(TRUE); m_tooltip.SetMaxTipWidth(int(GetDesktopRect().Width()*0.4)); SetButtons(); } //Остальная инициализация FillOptionListWithData(); SetWindowText(m_pStartupInfo->szWindowTitle); FinishFillOptionListWithData(); if(bBlockCancel){ GetDlgItem(IDCANCEL)->EnableWindow(FALSE); } // Показываем наконец окно SetTaskbarButton(this->GetSafeHwnd()); HICON hIMain=m_pStartupInfo->hWindowIcon; if(hIMain==0){ hIMain=::AfxGetApp()->LoadIcon(m_pStartupInfo->iWindowIcon); } SetIcon(hIMain,TRUE); SetIcon(hIMain,FALSE); ShowWindow(SW_SHOW); SwitchToWindow(GetSafeHwnd(),TRUE); // При первом запуске окно может просто не показаться, поэтому свитчим приложение if(pParentWnd){ if(GetWindowLong(pParentWnd->GetSafeHwnd(),GWL_EXSTYLE)&WS_EX_TOPMOST){ bParentOnTop=TRUE; pParentWnd->SetWindowPos(this,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); } ::EnableWindow(pParentWnd->GetSafeHwnd(),FALSE); } GetDlgItem(IDAPPLY)->EnableWindow(FALSE); // Настройки выравнивания заданы, продолжаем //SetForegroundWindow(); //::SendMessage(::GetDesktopWindow(), WM_SYSCOMMAND, (WPARAM) SC_HOTKEY, (LPARAM)this->GetSafeHwnd()); return TRUE; } LRESULT CDLG_Options::SaveColumnWidths() { long lColumn1=m_OptionsList.GetColumnWidth(0); long lColumn2=m_OptionsList.GetColumnWidth(1); CRect rt1,rt2; m_LList.GetWindowRect(&rt1); m_OptionsList.GetWindowRect(&rt2); long lH1=rt2.Height(); long lW1=rt1.Width(); CString sValue=Format("col1={%i};col2={%i};w={%i};h={%i}",lColumn1,lColumn2,lW1,lH1); CString sKeyName=Sizer.m_szRegKey; int iPos=sKeyName.ReverseFind('\\'); if(iPos==-1){ return 0; } CString sValueName=sKeyName.Mid(iPos+1); sKeyName=sKeyName.Left(iPos); CRegKey key; key.Create(Sizer.m_hKeyRoot, sKeyName); sValueName+="cW"; DWORD dwType=REG_SZ,dwSize=0; if(RegSetValueEx(key.m_hKey,sValueName,0,REG_SZ,(BYTE*)(const char*)sValue,lstrlen(sValue)+1)!= ERROR_SUCCESS){ return 0; } return 1; } LRESULT CDLG_Options::LoadColumnWidths() { CString sKeyName=Sizer.m_szRegKey; int iPos=sKeyName.ReverseFind('\\'); if(iPos==-1){ return 0; } CString sValueName=sKeyName.Mid(iPos+1); sKeyName=sKeyName.Left(iPos); char szValue[256]; CRegKey key; key.Create(Sizer.m_hKeyRoot, sKeyName); DWORD dwCount=sizeof(szValue); DWORD dwType=0; sValueName+="cW"; CRect rect; long lColumn1=0,lColumn2=0; long lW1=200,lH1=270; m_OptionsList.GetWindowRect(&rect); if(RegQueryValueEx(key.m_hKey,sValueName,NULL, &dwType,(LPBYTE)szValue, &dwCount)== ERROR_SUCCESS){ lColumn1=atol(CDataXMLSaver::GetInstringPart("col1={","}",szValue)); lColumn2=atol(CDataXMLSaver::GetInstringPart("col2={","}",szValue)); lW1=atol(CDataXMLSaver::GetInstringPart("w={","}",szValue)); lH1=atol(CDataXMLSaver::GetInstringPart("h={","}",szValue)); } // Положения окон CRect rtFull; GetWindowRect(&rtFull); m_LList.GetWindowRect(&rect); if(bDoNotSavePanePos){ rect.right=rect.left+3; }else{ if(lW1>rtFull.Width()){ lW1=rtFull.Width()-200; } if(lW1<30){ lW1=30; } rect.right=rect.left+lW1; } ScreenToClient(&rect); m_LList.MoveWindow(&rect); m_OptionsList.GetWindowRect(&rect); if(lH1>rtFull.Height()){ lH1=rtFull.Height()-100; } if(lH1<30){ lH1=30; } rect.bottom=rect.top+lH1; ScreenToClient(&rect); m_OptionsList.MoveWindow(&rect); // Ширина колонок if(lColumn1==0 || lColumn2==0){ double dWndSize=rect.Width()-::GetSystemMetrics(SM_CYVSCROLL)-5; lColumn1=long(dWndSize-dWndSize*OPT_VALUECOLUMN_WIDTH); lColumn2=long(dWndSize*OPT_VALUECOLUMN_WIDTH); } if(lColumn1+lColumn2>rect.Width()){ lColumn2=rect.Width()-lColumn1-5; } m_OptionsList.SetColumnWidth(0,lColumn1); m_OptionsList.SetColumnWidth(1,lColumn2); m_LList.SetColumnWidth(0,300); Sizer.ApplyLayout(TRUE); return 1; } void CDLG_Options::AdjustRPaneW(BOOL bTwicked) { CRect rt; m_OptionsList.GetClientRect(&rt); int iCol0=m_OptionsList.GetColumnWidth(0); int iW=rt.Width(); if(iCol0>iW){ iCol0=int(double(iW)*0.7); m_OptionsList.SetColumnWidth(0,iCol0); } int iCol1=iW-iCol0-1; if(bTwicked){ m_OptionsList.SetColumnWidth(1,iCol1+2); } m_OptionsList.SetColumnWidth(1,iCol1); m_LList.GetClientRect(&rt); m_LList.SetColumnWidth(0,iW); m_OptionsList.Invalidate(); } LRESULT CDLG_Options::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { LRESULT DispatchResultFromSizer; int iSizerState1=Sizer.iInit; static BOOL bScheduleAdjust=0; static CRect rtPrev; if(bScheduleAdjust && GetKeyState(VK_LBUTTON)>=0){ bScheduleAdjust=0; AdjustRPaneW(1); DrawNC(); } if(Sizer.HandleWndMesages(message, wParam, lParam, DispatchResultFromSizer)==TRUE){ if(message==WM_SIZE || (message==WM_MOUSEMOVE && Sizer.bInResizingLock)){ // Меряем изменение bScheduleAdjust=1; CRect rtNow; m_OptionsList.GetWindowRect(rtNow); if(rtPrev.Width()<rtNow.Width() || rtPrev.Height()<rtNow.Height() || GetKeyState(VK_LBUTTON)>=0){ AdjustRPaneW(); } rtPrev.CopyRect(rtNow); } return DispatchResultFromSizer; } int iSizerState2=Sizer.iInit; if(iSizerState1==2 && iSizerState2!=2){ LoadColumnWidths(); } if(message==WM_DESTROY){ SaveColumnWidths(); } if(message==WM_HELP){ OnHelp(); return TRUE; } if(message==WM_COMMAND && wParam==IDCANCEL){ CancelThis(); return TRUE; } if(message==WM_COMMAND && wParam==REMOVE_OPTIONS){ PopSomeDataFromScreen(lParam); Invalidate(); return TRUE; } if(message==WM_COMMAND && lParam==0 && wParam>=UPMENU_ID && m_pStartupInfo->fpUpMenuAction){ (*m_pStartupInfo->fpUpMenuAction)(wParam,lParam,this); return TRUE; } LRESULT lOut=CDialog::WindowProc(message, wParam, lParam); if(message==WM_MOUSEMOVE || message==WM_ACTIVATE ||message==WM_NCACTIVATE || message==WM_MOVING || message==WM_SIZING ||message==WM_SIZE || message==WM_NCPAINT || message==WM_PAINT || message==WM_SHOWWINDOW){ DrawNC(); } return lOut; } void CDLG_Options::OnStartEdit(NMHDR * pNotifyStruct, LRESULT * result) { FLNM_ROWSTATE *pRowState=(FLNM_ROWSTATE*) pNotifyStruct; *result=0; if(pRowState==NULL){ return; } DWORD dwItemData=m_OptionsList.GetIItemData(pRowState->hIRow,pRowState->iIItem); COption* pOpt=aOptions[dwItemData]; if(!pOpt){ return; } if(pOpt && pOpt->iOptionType==OPTTYPE_HOTKEY){ *result=(DWORD)(new CIHotkey(((COptionHotKey*)pOpt)->m_Value)); } if(pRowState->dwNotifyData==IDC_INPLACE_SLIDER && pOpt && pOpt->iOptionType==OPTTYPE_NUMBER){ *result=MAKELONG(((COptionNumber*)pOpt)->m_dwMin,((COptionNumber*)pOpt)->m_dwMax); } return; } void CDLG_Options::OnEndEdit(NMHDR * pNotifyStruct, LRESULT * result) { FLNM_ROWSTATE *pRowState=(FLNM_ROWSTATE*) pNotifyStruct; if(pRowState==NULL){ *result=-1; return; } *result=0;//принять измененное значение DWORD dwItemData=m_OptionsList.GetIItemData(pRowState->hIRow,pRowState->iIItem); COption* pOpt=aOptions[dwItemData]; if(!pOpt){ *result=-1; return; } if(pOpt->iOptionType==OPTTYPE_BOOL){ ((COptionBOOL*)pOpt)->m_Value=pRowState->dwNotifyData; OnChanged(pOpt); }else if(pOpt->iOptionType==OPTTYPE_DATE){ int iY=LOWORD(pRowState->dwNotifyData); int iM=LOBYTE(HIWORD(pRowState->dwNotifyData)); int iD=HIBYTE(HIWORD(pRowState->dwNotifyData)); ((COptionDate*)pOpt)->m_Value=COleDateTime(iY,iM,iD,0,0,0); m_OptionsList.SetIItemText(pOpt->hIRow, 1, ConvertToLocaleDate(((COptionDate*)pOpt)->m_Value)); OnChanged(pOpt); }else if(pOpt->iOptionType==OPTTYPE_NUMBER){ long dwVal=atol(pRowState->strText); CString sNew=Format("%i",dwVal); if(sNew!=pRowState->strText || dwVal<((COptionNumber*)pOpt)->m_dwMin || dwVal>((COptionNumber*)pOpt)->m_dwMax){ this->MessageBox(_l("Value must be between")+" "+Format("%i",((COptionNumber*)pOpt)->m_dwMin)+" "+_l("and")+" "+Format("%i",((COptionNumber*)pOpt)->m_dwMax)); *result=-1; }else{ ((COptionNumber*)pOpt)->m_Value=dwVal; OnChanged(pOpt); } }else if(pOpt->iOptionType==OPTTYPE_STRING){ // Здесь можно не проверять на ForGroup... ((COptionString*)pOpt)->m_Value=pRowState->strText; OnChanged(pOpt); }else if(pOpt->iOptionType==OPTTYPE_COMBO){ CString sComboItemsData=((COptionCombo*)pOpt)->m_ComboData; CStringArray sItemsData; ConvertComboDataToArray(sComboItemsData,sItemsData); for(int i=0;i<sItemsData.GetSize();i++){ if(sItemsData[i]==pRowState->strText){ ((COptionCombo*)pOpt)->m_Value=i; OnChanged(pOpt); break; } } }else if(pOpt->iOptionType==OPTTYPE_HOTKEY){ CIHotkey* pHotkey=(CIHotkey*)(pRowState->dwNotifyData); if(pHotkey){ bAnyHotkeyWasChanged=1; ((COptionHotKey*)pOpt)->m_Value=*pHotkey; pRowState->strText=getHotKeyStr(((COptionHotKey*)pOpt)->m_Value,TRUE); OnChanged(pOpt); delete pHotkey; } }else{ *result=-1;//оставить прежнее значение } return; } void CDLG_Options::OnCustomDialog(NMHDR * pNotifyStruct, LRESULT * result) { FLNM_ROWSTATE *pRowState=(FLNM_ROWSTATE*) pNotifyStruct; if(pRowState==NULL || isDialogInProcess>0){ *result=-1; return; } SimpleTracker Track(isDialogInProcess); *result=0;//принять измененное значение DWORD dwItemData=m_OptionsList.GetIItemData(pRowState->hIRow,pRowState->iIItem); COption* pOpt=aOptions[dwItemData]; if(!pOpt){ *result=-1; return; } if(pOpt && pOpt->iOptionType==OPTTYPE_STRING){ // Здксь можно не проверять на ForGroup dwItemData=m_OptionsList.GetIItemData(pRowState->hIRow,0); pOpt=aOptions[dwItemData]; if(!pOpt){ *result=-1; return; } } if(pOpt && pOpt->iOptionType==OPTTYPE_ACTION){ LPVOID fpData= ((COptionAction*)pOpt)->functionParam; if(((COptionAction*)pOpt)->function){ FP_OPTIONACTION fp = ((COptionAction*)pOpt)->function; if(fp){ if((*fp)(HIROW(fpData),this)){ OnChanged(pOpt); } } }else{ FP_OPTIONACTION2 fp = ((COptionAction*)pOpt)->function2; if(fp){ if((*fp)(fpData,this)){ OnChanged(pOpt); } } } }else if(pOpt && pOpt->iOptionType==OPTTYPE_COLOR){ CColorDialog dlg(((COptionColor*)pOpt)->m_Value,0,this); if(dlg.DoModal()==IDOK){ DWORD dwColor=dlg.GetColor(); ((COptionColor*)pOpt)->m_Value=dwColor; m_OptionsList.SetIItemColors(((COptionColor*)pOpt)->hIRow,1,SPECINVERTCOL(dwColor),dwColor); m_OptionsList.SetIRowTextStyle(((COptionColor*)pOpt)->hIRow,FL_SELBORD); if(bShowColorForColorOptions){ m_OptionsList.SetIItemText(((COptionColor*)pOpt)->hIRow, 1, Format("#%02X%02X%02X",GetRValue(dwColor),GetGValue(dwColor),GetBValue(dwColor))); } OnChanged(pOpt); } }else if(pOpt && pOpt->iOptionType==OPTTYPE_FONT){ LOGFONT logfont; DWORD dwEffects=CF_EFFECTS|CF_SCREENFONTS; CFont** font=((COptionFont*)pOpt)->m_Value_Real; if(font){ (*font)->GetLogFont(&logfont); CFontDialog dlg(&logfont,dwEffects,NULL,this); dlg.m_cf.Flags|=dwEffects|CF_INITTOLOGFONTSTRUCT|CF_FORCEFONTEXIST|CF_NOVERTFONTS; dlg.m_cf.lpLogFont=&logfont; if(dlg.DoModal()==IDOK){ delete (*font); (*font)=new CFont(); (*font)->CreateFontIndirect(dlg.m_cf.lpLogFont); m_OptionsList.SetIItemText(((COptionFont*)pOpt)->hIRow,1,GetFontTextDsc((*font))); OnChanged(pOpt); } } }else if(pOpt && pOpt->iOptionType==OPTTYPE_DATE){ static long lAlreadyOpened=0; if(lAlreadyOpened==0){ SimpleTracker Track(lAlreadyOpened); CRect rect(0,0,0,0); m_OptionsList.GetItemRect(m_OptionsList.GetIRowIndex(((COptionDate*)pOpt)->hIRow), &rect, LVIR_BOUNDS); m_OptionsList.ClientToScreen(&rect); //ClientToScreen(&rect); CInPlaceDate* pEdit = new CInPlaceDate(((COptionDate*)pOpt)->hIRow, 1, ((COptionDate*)pOpt)->m_Value,&m_OptionsList); pEdit->CreateEx(0,"SysMonthCal32","",WS_POPUP|WS_BORDER, rect, &m_OptionsList, 0); //pEdit->Create(WS_CHILD|WS_BORDER, rect, &m_OptionsList, IDC_INPLACE_DATE); if(IsWindow(pEdit->GetSafeHwnd())){ CRect rtMin; pEdit->GetMinReqRect(&rtMin); rect.left=rect.right-rtMin.Width(); rect.bottom=rect.top+rtMin.Height(); pEdit->SetWindowPos(&wndTopMost,rect.left,rect.top,rect.Width(),rect.Height(),SWP_SHOWWINDOW|SWP_DRAWFRAME); pEdit->SetFocus(); } } }else{ *result=-1;//оставить прежнее значение } } void CDLG_Options::OnComboExpand(NMHDR * pNotifyStruct, LRESULT * result) { FLNM_COMBOSTATE *pRowState=(FLNM_COMBOSTATE*) pNotifyStruct; structInPlaceComboItem ci; // Вытаскиваем данные... DWORD dwItemData=m_OptionsList.GetIItemData(pRowState->hIRow,pRowState->iIItem); COption* pOpt=aOptions[dwItemData]; if(!pOpt){ *result=-1; return; } if(pOpt->iOptionType==OPTTYPE_COMBO){ CString sComboItemsData=((COptionCombo*)pOpt)->m_ComboData; CStringArray sItemsData; ConvertComboDataToArray(sComboItemsData,sItemsData); for(int i=0;i<sItemsData.GetSize();i++){ ci.dwData=i; ci.strText=sItemsData[i]; pRowState->paComboItems->Add(ci); } // выбираем элемент, который будет выделен в списке for(int j=0; j<pRowState->paComboItems->GetSize(); j++){ if(pRowState->paComboItems->GetAt(j).strText==pRowState->strText){ pRowState->iSelectedItem=j; break; } } } } CString GetOptionStrings(const char* szText,CString& sTitle,CString& sDsc) { sTitle=szText; sTitle=sTitle.SpanExcluding("\t"); if(strlen(szText)>strlen(sTitle)){ sDsc=szText+sTitle.GetLength()+1; } if(sDsc==""){ return sTitle; } return sDsc; } HIROW CDLG_Options::AddRow(HIROW fParent, const char* szText, long dwIconNum, BOOL bAtStart) { HIROW hThis=m_OptionsList.InsertIRow(fParent, bAtStart?FL_FIRST:FL_LAST, szText, dwIconNum); m_OptionsList.SetIItemControlType(hThis, 0, FLC_READONLY); m_OptionsList.SetIItemControlType(hThis, 1, FLC_READONLY); m_OptionsList.SetIItemData(hThis, 0, -1); m_OptionsList.SetIItemData(hThis, 1, -1); //m_OptionsList.SetIItemColors(hThis, 0, 0, RGB(255,255,255)); return hThis; } BOOL CDLG_Options::isOptionClassChanged(long iOptionsClass) { if(iOptionsClass==-1){ return m_ChangedClasses.GetSize()>0; } for(int i=0;i<m_ChangedClasses.GetSize();i++){ if(long(m_ChangedClasses[i])==iOptionsClass){ return TRUE; } } return FALSE; } HIROW CDLG_Options::GetAliasHIROW(HIROW hRPane) { HIROW hLeft=NULL; aFromRtoL.Lookup(hRPane,hLeft); return hLeft; } HIROW CDLG_Options::SetLAliasTarget(HIROW hLPaneFrom,HIROW hRPaneTo) { m_LList.SetIItemData(hLPaneFrom, 0, (DWORD)hRPaneTo); return hLPaneFrom; } HIROW CDLG_Options::GetOrAddAlias(HIROW hRPane, const char* szText, DWORD dwIcon, HIROW fRParent, HIROW hAfter) { HIROW hLeft=GetAliasHIROW(hRPane); if(hLeft!=NULL){ SetLAliasTarget(hLeft, hRPane); return hLeft; } HIROW hRParent=GetAliasHIROW(fRParent); if(hRParent==NULL){ hRParent=hLPaneRoot; } if(hAfter==FL_ROOT){ hAfter=hTopLPaneItem; } if(hRParent==FL_ROOT && hAfter==FL_ROOT){ hAfter=FL_LAST; } hLeft=m_LList.InsertIRow(hRParent, (hAfter)?(hAfter==HIROW(-1)?FL_FIRST:hAfter):FL_LAST, szText, dwIcon); m_LList.SetIItemControlType(hLeft, 0, FLC_READONLY); m_LList.SetIItemData(hLeft, 0, (DWORD)hRPane); if(hRPane!=NULL){ aFromRtoL.SetAt(hRPane,hLeft); } return hLeft; } BOOL CDLG_Options::CompareToDefTopic(const char* szText) { if(m_pStartupInfo->szDefaultTopicTitle && strlen(m_pStartupInfo->szDefaultTopicTitle)>0){ //&& stricmp(m_pStartupInfo->szDefaultTopicTitle,szText)==0 CString s1=m_pStartupInfo->szDefaultTopicTitle; CString s2=szText; s1=s1.SpanExcluding("[({})]"); s2=s2.SpanExcluding("[({})]"); if(s1.CompareNoCase(s2)==0){ //CString s; s.Format("Def %s vs %s",s1,s2); AfxMessageBox(s); return TRUE; } } return 0; } HIROW CDLG_Options::Option_AddAlias(HIROW hData, const char* szText, DWORD dwIcon, HIROW hParent, BOOL bToBeginning) { HIROW hLeft=GetOrAddAlias(hData, szText, dwIcon, hParent, bToBeginning?HIROW(-1):0); if(m_pStartupInfo->szDefaultTopicTitle && CompareToDefTopic(szText)){ hDefaultTopic=hData; } return hLeft; } //bWithAlias==0 - без пункта слева //bWithAlias==1 - с пунктом слева, ведущим на правую половину //bWithAlias==2 - с пунктом слева, не ведущим никуда //bWithAlias==3 - с пунктом слева, ведущим на правую половину, добавленным в начало списка HIROW CDLG_Options::Option_AddTitleEx(HIROW fParent, const char* szText, DWORD dwIcon, BOOL bWithAlias, HIROW hAfter) { CString sTitle,sDsc; GetOptionStrings(szText,sTitle,sDsc); HIROW hThisParent=fParent; if(bWithAlias){ hThisParent=FL_ROOT; } HIROW hThis=AddRow(hThisParent,sTitle,dwIcon); if(hThisParent==FL_ROOT){ m_OptionsList.SetIRowTextStyle(hThis,FL_SKIPTRI); } if(bWithAlias){ HIROW hLeft=GetOrAddAlias((bWithAlias==2)?NULL:hThis,sTitle,dwIcon,fParent,hAfter); } Option_SetRowColor(hThis,0,90); Option_SetRowColor(hThis,1,90); if(sDsc!=""){ m_OptionsList.SetIItemText(hThis, 1, sDsc); /* { DWORD crText1=0,crBg1=0; m_OptionsList.GetIItemColors(hThis,1,crText1,crBg1); DWORD crText=m_OptionsList.m_crIItemText,crBackground=m_OptionsList.m_crIRowBackground; m_OptionsList.SetIItemColors(hThis,1,RGB(GetRValue(crText)+int(GetRValue(crBackground)-GetRValue(crText))/2,GetGValue(crText)+int(GetGValue(crBackground)-GetGValue(crText))/2,GetBValue(crText)+int(GetBValue(crBackground)-GetBValue(crText))/2),crBg1); } */ }else{ m_OptionsList.SetIItemColSpan(hThis, 0, 1); } m_OptionsList.SetIItemControlType(hThis, 1, FLC_READONLY); if(!hDefaultTopic && CompareToDefTopic(sTitle)){ hDefaultTopic=hThis; } return hThis; } HIROW CDLG_Options::Option_AddHeader(HIROW fParent, const char* szText, DWORD dwIcon, BOOL bWithoutAlias, HIROW hAfter) { return Option_AddTitleEx(fParent, szText, dwIcon, bWithoutAlias?2:1, hAfter); } HIROW CDLG_Options::Option_AddTitle(HIROW fParent, const char* szText, DWORD dwIcon) { return Option_AddTitleEx(fParent, szText, dwIcon, 0); } HIROW CDLG_Options::Option_AddDate(HIROW fParent, const char* szText, COleDateTime* pDateVariable, COleDateTime dtDefValue, long dwIcon, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); long lDateIcon=80; if(dwIcon>0){ lDateIcon=dwIcon; } if(dwIcon<-1){ lDateIcon=-dwIcon; } HIROW hThis=AddRow(fParent,sTitle, lDateIcon); m_OptionsList.SetIItemControlType(hThis, 1, FLC_CUSTOMDIALOG); m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); if(pDateVariable->GetStatus()!=COleDateTime::valid){ *pDateVariable=COleDateTime::GetCurrentTime(); } CString sText=ConvertToLocaleDate(*pDateVariable); m_OptionsList.SetIItemText(hThis, 1, sText); COption* pOpt=new COptionDate(dtDefValue, pDateVariable, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; if(!hDefaultTopic && CompareToDefTopic(sTitle)){ hDefaultTopic=hThis; } return hThis; } HIROW CDLG_Options::Option_AddBOOL(HIROW fParent, const char* szText, long* pBoolVariable, long dwDefValue, long dwIcon, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); long lBoolIcon=-1; if(dwIcon>0){ lBoolIcon=dwIcon; } if(dwIcon<-1){ lBoolIcon=-dwIcon; } HIROW hThis=AddRow(fParent,sTitle, lBoolIcon); if(dwIcon>=0){ m_OptionsList.SetIItemControlType(hThis, 0, FLC_CHECKBOX); } m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); m_OptionsList.SetIItemColSpan(hThis, 0, 1); m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); m_OptionsList.SetIItemCheck(hThis,0, (*pBoolVariable)!=0,TRUE, FALSE); COption* pOpt=new COptionBOOL(dwDefValue,pBoolVariable, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; if(!hDefaultTopic && CompareToDefTopic(sTitle)){ hDefaultTopic=hThis; } return hThis; } HIROW CDLG_Options::Option_AddBOOL_Plain(HIROW fParent, const char* szText, long* pBoolVariable, long dwDefValue, long dwIcon, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); HIROW hThis=AddRow(fParent,sTitle, dwIcon? dwIcon:52); m_OptionsList.SetIItemControlType(hThis, 1, FLC_CHECKBOX); m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); m_OptionsList.SetIItemCheck(hThis,1, (*pBoolVariable)!=0,TRUE, FALSE); COption* pOpt=new COptionBOOL(dwDefValue,pBoolVariable, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; return hThis; } HIROW CDLG_Options::Option_AddNString(HIROW fParent, const char* szText, long* pNStrVariable, long dwDefValue, long dwMin, long dwMax, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); HIROW hThis=(sTitle=="")?fParent:AddRow(fParent,sTitle,57); m_OptionsList.SetIItemControlType(hThis, 1, FLC_EDIT); if(sTitle!=""){ m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); }else{ m_OptionsList.SetIItemColSpan(hThis, 0, -1); } m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); CString sText=Format("%i",*pNStrVariable); m_OptionsList.SetIItemText(hThis, 1, sText); COption* pOpt=new COptionNumber(dwDefValue,pNStrVariable, dwMin, dwMax, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; return hThis; } HIROW CDLG_Options::Option_AddNSlider(HIROW fParent, const char* szText, long* pNStrVariable, long dwDefValue, long dwMin, long dwMax, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); HIROW hThis=(sTitle=="")?fParent:AddRow(fParent,sTitle,57); m_OptionsList.SetIItemControlType(hThis, 1, FLC_SLIDER); if(sTitle!=""){ m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); }else{ m_OptionsList.SetIItemColSpan(hThis, 0, -1); } m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); CString sText=Format("%lu",*pNStrVariable); m_OptionsList.SetIItemText(hThis, 1, sText); COption* pOpt=new COptionNumber(dwDefValue,pNStrVariable, dwMin, dwMax, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; return hThis; } typedef int (WINAPI *_WKPluginShowEvent)(char szEvent[128],HWND pParent); typedef int (WINAPI *_WKPluginIsEventPresent)(char szEvent[128]); BOOL IsEventReminded(const char* szId) { HINSTANCE h=CheckPlugin("wp_schedule",1); if(h){ _WKPluginIsEventPresent fp=(_WKPluginIsEventPresent)GetProcAddress(h,"WKPluginIsEventPresent"); if(fp){ char szEvent[128]={0}; strcpy(szEvent,szId); return (*fp)(szEvent); } } return 0; } #ifdef _WIREKEYS typedef int (WINAPI *_WKIHOTKEYS_GetHotkeyDscByID)(char const* szEventID,char* szOut,int iOut); typedef int (WINAPI *_AddTypingAlias)(char const* szEventID,int iType); BOOL CALLBACK AddModifyTAlias(LPVOID pData,CDLG_Options* pDialog) { CString sId=pDialog->aCommonStrings[(int)pData]; HINSTANCE h=CheckPlugin("wp_autotext",1); if(h && sId!=""){ CString sActionTitle=_l("Start item"); HINSTANCE hLLHookInst=CheckPlugin("WP_KeyMaster"); _WKIHOTKEYS_GetHotkeyDscByID fpHk=(_WKIHOTKEYS_GetHotkeyDscByID)GetProcAddress(hLLHookInst,"WKIHOTKEYS_GetHotkeyDscByID"); if(fpHk){ char szTitle[256]={0}; (*fpHk)(sId,szTitle,sizeof(szTitle)); if(szTitle[0]!=0){ sActionTitle+=" '"; sActionTitle+=szTitle; sActionTitle+="'"; } } sActionTitle+="\r\n---\r\n"; sActionTitle+=_l("Item identifier (leave intact)"); sActionTitle+=":\r\n[ID="; sActionTitle+=sId; sActionTitle+="]"; _AddTypingAlias fpTA=(_AddTypingAlias)GetProcAddress(h,"AddTypingAlias"); if(fpTA){ (*fpTA)(sActionTitle,1); } } return 0; } BOOL CALLBACK AddModifyReminder(LPVOID pData,CDLG_Options* pDialog) { CString sId=pDialog->aCommonStrings[(int)pData]; HINSTANCE h=CheckPlugin("wp_schedule",1); if(h && sId!=""){ CString sTitle=_l("Do you want to\nschedule this action"); { HINSTANCE hLLHookInst=CheckPlugin("WP_KeyMaster"); _WKIHOTKEYS_GetHotkeyDscByID fpHk=(_WKIHOTKEYS_GetHotkeyDscByID)GetProcAddress(hLLHookInst,"WKIHOTKEYS_GetHotkeyDscByID"); if(fpHk){ char szTitle[256]={0}; (*fpHk)(sId,szTitle,sizeof(szTitle)); if(szTitle[0]!=0){ sTitle+="\r\n'"; sTitle+=szTitle; sTitle+="'"; } } } sTitle+="?"; if(!IsEventReminded(sId)){ if(MessageBox(pDialog->GetSafeHwnd(),sTitle,_l("Scheduler"),MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL)!=IDYES){ return 0; } } _WKPluginShowEvent fp=(_WKPluginShowEvent)GetProcAddress(h,"WKPluginShowEvent"); if(fp){ char szEvent[128]={0}; strcpy(szEvent,sId); (*fp)(szEvent,pDialog->GetSafeHwnd()); } } return 0; } BOOL CALLBACK AddModifyDLink(LPVOID pData,CDLG_Options* pDialog) { CString sTitle=_l("Action"); CString sId=pDialog->aCommonStrings[(int)pData]; HINSTANCE hLLHookInst=CheckPlugin("WP_KeyMaster"); _WKIHOTKEYS_GetHotkeyDscByID fpHk=(_WKIHOTKEYS_GetHotkeyDscByID)GetProcAddress(hLLHookInst,"WKIHOTKEYS_GetHotkeyDscByID"); if(fpHk){ char szTitle[256]={0}; (*fpHk)(sId,szTitle,sizeof(szTitle)); if(szTitle[0]!=0){ sTitle=szTitle; } } CString sExe=GetApplicationDir(); sExe+=GetApplicationName(); sExe+=".exe"; CString sTitleSafe=sTitle; MakeSafeFileName(sTitleSafe,sSafeChar.GetLength()?sSafeChar[0]:0); CString sTargetFolder=Format("%s\\Link to %s.lnk",getDesktopPath(),sTitleSafe); CString sParameter="-execute="; sParameter+=sId; CString sLinkDsc=Format("%s %s",_l("Shortcut to"),sTitle); BOOL bRes=(CreateLink(sExe, sTargetFolder, sLinkDsc,sParameter)==S_OK); if(bRes){ AfxMessageBox(sLinkDsc+": "+_l("created successfully")); }else{ AfxMessageBox(_l("Error: failed to create")+" "+sLinkDsc); } return TRUE; } #endif HIROW CDLG_Options::Option_AddHotKey(HIROW fParent, const char* szText, CIHotkey* pHotKeyVariable, CIHotkey dwDefValue, long iOptionsClass, int iIcon) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); HIROW hThis=AddRow(fParent,sTitle,iIcon==-1?55:iIcon); m_OptionsList.SetIItemControlType(hThis, 1, FLC_HOTKEY); m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); m_OptionsList.SetIItemText(hThis, 1, getHotKeyStr(*pHotKeyVariable,TRUE)); COption* pOpt=new COptionHotKey(dwDefValue, pHotKeyVariable, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; #ifdef _WIREKEYS if(strlen(pHotKeyVariable->GetActionId())>0){// reminder CString sHKTitle=""; HINSTANCE hLLHookInst=CheckPlugin("WP_KeyMaster"); if(hLLHookInst && pHotKeyVariable->sExcludedInApps && pHotKeyVariable->sExclusiveInApps){ Option_AddString(hThis, _l("Disable in this applications")+"\t"+_l("You can use mask with '*' char and ';' as delimiter, example: 'explorer*;*pad*'"), (pHotKeyVariable->sExcludedInApps), *(pHotKeyVariable->sExcludedInApps), iOptionsClass); Option_AddString(hThis, _l("Activate only in this applications")+"\t"+_l("You can use mask with '*' char and ';' as delimiter, example: 'explorer*;*pad*'"), (pHotKeyVariable->sExclusiveInApps), *(pHotKeyVariable->sExcludedInApps), iOptionsClass); } _WKIHOTKEYS_GetHotkeyDscByID fpHk=(_WKIHOTKEYS_GetHotkeyDscByID)GetProcAddress(hLLHookInst,"WKIHOTKEYS_GetHotkeyDscByID"); if(fpHk){ char szTitle[256]={0}; (*fpHk)(pHotKeyVariable->GetActionId(),szTitle,sizeof(szTitle)); sHKTitle=szTitle; } //HINSTANCE h=CheckPlugin("wp_schedule"); //if(h) { CString sNameA=_l("Add/Modify schedule for"); sNameA+=" '"; sNameA+=sHKTitle; sNameA+="'"; /* #ifdef _DEBUG sNameA+=" ("; sNameA+=pHotKeyVariable->GetActionId(); sNameA+=")"; #endif */ Option_AddAction2(hThis,sNameA, AddModifyReminder, (LPVOID)aCommonStrings.Add(pHotKeyVariable->GetActionId()), iOptionsClass, lSipleRemindIconNum); } //HINSTANCE h2=CheckPlugin("wp_autotext"); //if(h2) { CString sNameA=_l("Add/Modify typing alias for"); sNameA+=" '"; sNameA+=sHKTitle; sNameA+="'"; Option_AddAction2(hThis,sNameA, AddModifyTAlias, (LPVOID)aCommonStrings.Add(pHotKeyVariable->GetActionId()), iOptionsClass); } CString sNameD=_l("Add shortcut to desktop"); Option_AddAction2(hThis, sNameD, AddModifyDLink, (LPVOID)aCommonStrings.Add(pHotKeyVariable->GetActionId()), iOptionsClass); } #endif return hThis; } HIROW CDLG_Options::Option_AddString(HIROW fParent, const char* szText, CString* pStrVariable, const char* szDefValue, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); CString sDefValue=szDefValue; HIROW hThis=(sTitle=="")?fParent:AddRow(fParent,sTitle,56); m_OptionsList.SetIItemControlType(hThis, 1, FLC_EDIT); if(sTitle!=""){ m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); }else{ m_OptionsList.SetIItemColSpan(hThis, 0, -1); } m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); m_OptionsList.SetIItemText(hThis, 1, *pStrVariable); COption* pOpt=new COptionString(sDefValue,pStrVariable, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; if(!hDefaultTopic && CompareToDefTopic(sTitle)){ hDefaultTopic=hThis; } return hThis; } HIROW CDLG_Options::Option_AddPassword(HIROW fParent, const char* szText, CString* pStrVariable, const char* szDefValue, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); CString sDefValue=szDefValue; HIROW hThis=(sTitle=="")?fParent:AddRow(fParent,sTitle,56); m_OptionsList.SetIItemControlType(hThis, 1, FLC_PASSWORD); if(sTitle!=""){ m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); }else{ m_OptionsList.SetIItemColSpan(hThis, 0, -1); } m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); m_OptionsList.SetIItemText(hThis, 1, *pStrVariable); COption* pOpt=new COptionString(sDefValue,pStrVariable, iOptionsClass, TRUE); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; return hThis; } HIROW CDLG_Options::Option_AddActionToEdit(HIROW fParent, FP_OPTIONACTION fp, long iOptionsClass) { return Option_AddActionToEdit(fParent, fp, fParent, iOptionsClass); } HIROW CDLG_Options::Option_AddActionToEdit(HIROW fParent, FP_OPTIONACTION fp, HIROW hActionData, long iOptionsClass, int iNewIcon) { HIROW hThis=fParent;//AddRow(fParent,sTitle,54); m_OptionsList.SetIItemControlType(hThis, 1, FLC_EDITWITHCUSTOM); m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); if(iNewIcon!=-1){ m_OptionsList.SetIItemImage(hThis, 0, iNewIcon); } //m_OptionsList.SetIItemData(hThis, 1, dwOptionCount);// Оставляем от текстового поля //m_OptionsList.SetIItemText(hThis, 1, szButtonText); COption* pOpt=new COptionAction(fp,0,hActionData,iOptionsClass); pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; return hThis; } HIROW CDLG_Options::Option_AddAction(HIROW fParent, const char* szButtonText, FP_OPTIONACTION fp, HIROW hActionData, long iOptionsClass, int iIcon) { return Option_AddActionEx(fParent, szButtonText, fp, 0, hActionData, iIcon==-1?54:iIcon, iOptionsClass); } HIROW CDLG_Options::Option_AddAction2(HIROW fParent, const char* szButtonText, FP_OPTIONACTION2 fp, LPVOID pActionData, long iOptionsClass, int iIcon) { return Option_AddActionEx(fParent, szButtonText, 0, fp, pActionData, (iIcon==-1)?54:iIcon, iOptionsClass); } HIROW CDLG_Options::Option_AddActionEx(HIROW fParent, const char* szText, FP_OPTIONACTION fp, FP_OPTIONACTION2 fp2, LPVOID pActionData, int iIcon, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); HIROW hThis=AddRow(fParent,sTitle,iIcon); m_OptionsList.SetIItemControlType(hThis, 0, FLC_CUSTOMDIALOG2);//1 m_OptionsList.SetIItemColSpan(hThis, 0, 1); m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); m_OptionsList.SetIItemText(hThis, 0, sTitle);//1 m_OptionsList.SetIItemColors(hThis, 0, RGB(0,0,255), -1); m_OptionsList.SetIRowTextStyle(hThis, FL_UNLINE); COption* pOpt=new COptionAction(fp,fp2,pActionData,iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; if(iIcon!=lSipleActionIconNum){ if(GetAliasHIROW(fParent)==0){ fParent=m_OptionsList.GetParentIRow(fParent); } Option_AddMenuActionEx(szText, fp, fp2, pActionData,fParent,1,iIcon); } return hThis; } int CDLG_Options::Option_AddMenuActionEx(const char* szText, FP_OPTIONACTION fp, FP_OPTIONACTION2 fp2, LPVOID pActionData, HIROW hTargetItem, BOOL bPlaceAtTop, long lIcon) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); COptionAction* pOpt=new COptionAction(fp,fp2,pActionData,0); pOpt->hIRow=hTargetItem; pOpt->sDsc=sTitle; pOpt->lIcon=lIcon; if(bPlaceAtTop){ aMenuOptions.InsertAt(0,pOpt); }else{ aMenuOptions.SetAtGrow(aMenuOptions.GetSize(),pOpt); } return aMenuOptions.GetSize(); } int CDLG_Options::Option_AddMenuAction(const char* szText, FP_OPTIONACTION fp, HIROW hActionData, HIROW hTargetItem, BOOL bPlaceAtTop, long lIcon) { return Option_AddMenuActionEx(szText, fp, 0, hActionData, hTargetItem, bPlaceAtTop, lIcon); } HIROW CDLG_Options::Option_AddColor(HIROW fParent, const char* szText, long* pNStrVariable, long dwDefValue, long iOptionsClass, int iNewIcon) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); HIROW hThis=(sTitle=="")?fParent:AddRow(fParent,sTitle,(iNewIcon==-1)?54:iNewIcon); m_OptionsList.SetIItemControlType(hThis, 1, FLC_CUSTOMDIALOG); if(sTitle!=""){ m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); }else{ m_OptionsList.SetIItemColSpan(hThis, 0, -1); } m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); DWORD dwColor=*pNStrVariable; if(bShowColorForColorOptions){ m_OptionsList.SetIItemText(hThis, 1, Format("#%02X%02X%02X",GetRValue(dwColor),GetGValue(dwColor),GetBValue(dwColor))); }else{ m_OptionsList.SetIItemText(hThis, 1, ""); } m_OptionsList.SetIItemColors(hThis,1,SPECINVERTCOL(dwColor),dwColor); m_OptionsList.SetIRowTextStyle(hThis,FL_SELBORD); COption* pOpt=new COptionColor(dwDefValue,pNStrVariable, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; return hThis; } HIROW CDLG_Options::Option_AddFont(HIROW fParent, const char* szText, CFont** pFontVariable, long iOptionsClass, int iNewIcon) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); HIROW hThis=AddRow(fParent,sTitle,(iNewIcon==-1)?54:iNewIcon); m_OptionsList.SetIItemControlType(hThis, 1, FLC_CUSTOMDIALOG); m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); m_OptionsList.SetIItemText(hThis, 1, GetFontTextDsc(*pFontVariable)); COption* pOpt=new COptionFont(pFontVariable, iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; return hThis; } HIROW CDLG_Options::Option_AddCombo(HIROW fParent, const char* szText, long* pIntVariable, long iDefValue, const char* szComboItems, long iOptionsClass) { CString sTitle,sDsc; sDsc=GetOptionStrings(szText,sTitle,sDsc); HIROW hThis=(sTitle=="")?fParent:AddRow(fParent,sTitle,58); m_OptionsList.SetIItemControlType(hThis, 1, FLC_COMBOBOX); if(sTitle!=""){ m_OptionsList.SetIItemData(hThis, 0, dwOptionCount); }else{ m_OptionsList.SetIItemColSpan(hThis, 0, -1); } m_OptionsList.SetIItemData(hThis, 1, dwOptionCount); CStringArray aComboItems; ConvertComboDataToArray(szComboItems,aComboItems); long iSelected=*pIntVariable; if(iDefValue<0 || iDefValue>=aComboItems.GetSize()){ iDefValue=0; } if(iSelected<0 || iSelected>=aComboItems.GetSize()){ iSelected=iDefValue; *pIntVariable=iSelected; } m_OptionsList.SetIItemText(hThis, 1, aComboItems[iSelected]); COption* pOpt=new COptionCombo(iDefValue,pIntVariable,szComboItems,iOptionsClass); pOpt->sDsc=sDsc; pOpt->hIRow=hThis; aOptions.SetAtGrow(dwOptionCount,pOpt); dwOptionCount++; return hThis; } void CDLG_Options::Option_SetRowColor(HIROW fRow, int iItem, int iColType) { DWORD crText=m_OptionsList.m_crIItemText,crBackground=m_OptionsList.m_crIRowBackground; DWORD crRealBgColor=crBackground; double dRate=double(iColType)/100; crRealBgColor=RGB(GetRValue(crBackground)*dRate,GetGValue(crBackground)*dRate,GetBValue(crBackground)*dRate); m_OptionsList.SetIItemColors(fRow,iItem,-1,crRealBgColor); return; } void CDLG_Options::OnOK() { MyEndDialog(IDOK); } void CDLG_Options::CancelThis() { m_ChangedClasses.RemoveAll(); MyEndDialog(IDCANCEL); } void CDLG_Options::OnHelp() { ShowHelp(sHelpPage==""?"Preferences":sHelpPage); } void CDLG_Options::ResetOption(COption* pOpt) { if(!pOpt){ return; } switch(pOpt->iOptionType){ case OPTTYPE_DATE: if(((COptionDate*)pOpt)->m_Value!=((COptionDate*)pOpt)->m_Value_Def){ ((COptionDate*)pOpt)->m_Value=((COptionDate*)pOpt)->m_Value_Def; OnChanged(pOpt); m_OptionsList.SetIItemText(pOpt->hIRow, 1, ConvertToLocaleDate(((COptionDate*)pOpt)->m_Value)); } break; case OPTTYPE_BOOL: if(((COptionBOOL*)pOpt)->m_Value!=((COptionBOOL*)pOpt)->m_Value_Def){ ((COptionBOOL*)pOpt)->m_Value=((COptionBOOL*)pOpt)->m_Value_Def; OnChanged(pOpt); m_OptionsList.SetIItemCheck(pOpt->hIRow, 0, (((COptionBOOL*)pOpt)->m_Value)!=0,TRUE, FALSE); } break; case OPTTYPE_NUMBER: if(((COptionNumber*)pOpt)->m_Value!=((COptionNumber*)pOpt)->m_Value_Def){ ((COptionNumber*)pOpt)->m_Value=((COptionNumber*)pOpt)->m_Value_Def; OnChanged(pOpt); m_OptionsList.SetIItemText(pOpt->hIRow, 1, Format("%lu",((COptionNumber*)pOpt)->m_Value)); } break; case OPTTYPE_STRING: if(((COptionString*)pOpt)->m_Value!=((COptionString*)pOpt)->m_Value_Def){ ((COptionString*)pOpt)->m_Value=((COptionString*)pOpt)->m_Value_Def; OnChanged(pOpt); m_OptionsList.SetIItemText(pOpt->hIRow, 1, ((COptionString*)pOpt)->m_Value); } break; case OPTTYPE_COMBO: { if(((COptionCombo*)pOpt)->m_Value!=((COptionCombo*)pOpt)->m_Value_Def){ ((COptionCombo*)pOpt)->m_Value=((COptionCombo*)pOpt)->m_Value_Def; OnChanged(pOpt); CStringArray aComboItems; ConvertComboDataToArray(((COptionCombo*)pOpt)->m_ComboData,aComboItems); m_OptionsList.SetIItemText(pOpt->hIRow, 1, aComboItems[((COptionCombo*)pOpt)->m_Value]); } } break; case OPTTYPE_HOTKEY: if(((COptionHotKey*)pOpt)->m_Value!=((COptionHotKey*)pOpt)->m_Value_Def){ ((COptionHotKey*)pOpt)->m_Value=((COptionHotKey*)pOpt)->m_Value_Def; OnChanged(pOpt); m_OptionsList.SetIItemText(pOpt->hIRow, 1, getHotKeyStr(((COptionHotKey*)pOpt)->m_Value,TRUE)); } break; case OPTTYPE_COLOR: if(((COptionColor*)pOpt)->m_Value!=((COptionColor*)pOpt)->m_Value_Def){ ((COptionColor*)pOpt)->m_Value=((COptionColor*)pOpt)->m_Value_Def; OnChanged(pOpt); DWORD dwColor=((COptionColor*)pOpt)->m_Value; m_OptionsList.SetIItemColors(pOpt->hIRow,1,SPECINVERTCOL(dwColor),dwColor); m_OptionsList.SetIRowTextStyle(pOpt->hIRow,FL_SELBORD); if(bShowColorForColorOptions){ m_OptionsList.SetIItemText(pOpt->hIRow, 1, Format("#%02X%02X%02X",GetRValue(dwColor),GetGValue(dwColor),GetBValue(dwColor))); } } break; } m_OptionsList.UpdateIRow(pOpt->hIRow); } void CDLG_Options::OnReset() { if(AfxMessageBox(_l("Warning: *ALL* settings will be reverted to default values!\nThis operation can`t be undone. Continue")+"?",MB_YESNO|MB_ICONQUESTION)!=IDYES){ return; } int i=0; SetWindowText(m_pStartupInfo->szWindowTitle); for(i=0;i<aOptions.GetSize();i++){ COption* pOpt=aOptions[i]; ResetOption(pOpt); } return; } void CDLG_Options::CommitData(int iOptionClass) { if(bManualPreventCommit){ return; } int i=0; SetWindowText(m_pStartupInfo->szWindowTitle); for(i=0;i<aOptions.GetSize();i++){ COption* pOpt=aOptions[i]; if(!pOpt){ continue; } if(iOptionClass!=-1 && pOpt->iOptionClass!=iOptionClass){ continue; } switch(pOpt->iOptionType){ case OPTTYPE_DATE: *((COptionDate*)pOpt)->m_Value_Real=((COptionDate*)pOpt)->m_Value; break; case OPTTYPE_BOOL: *((COptionBOOL*)pOpt)->m_Value_Real=((COptionBOOL*)pOpt)->m_Value; break; case OPTTYPE_NUMBER: *((COptionNumber*)pOpt)->m_Value_Real=((COptionNumber*)pOpt)->m_Value; break; case OPTTYPE_STRING: *((COptionString*)pOpt)->m_Value_Real=((COptionString*)pOpt)->m_Value; break; case OPTTYPE_COMBO: *((COptionCombo*)pOpt)->m_Value_Real=((COptionCombo*)pOpt)->m_Value; break; case OPTTYPE_HOTKEY: *((COptionHotKey*)pOpt)->m_Value_Real=((COptionHotKey*)pOpt)->m_Value; break; case OPTTYPE_COLOR: *((COptionColor*)pOpt)->m_Value_Real=((COptionColor*)pOpt)->m_Value; break; } } return; } void CDLG_Options::PopSomeDataFromScreen(long iOptionClass) { int i=0; int iCount=aOptions.GetSize(); for(i=0;i<iCount;i++){ COption* pOpt=aOptions[i]; if(!pOpt){ continue; } if(pOpt->iOptionClass!=iOptionClass){ continue; } aOptions[i]=NULL; if(pOpt->iOptionType==OPTTYPE_HOTKEY){ bAnyHotkeyWasChanged=1; } int iListCount=m_OptionsList.GetItemCount(); HIROW hLeft=GetAliasHIROW(pOpt->hIRow); if(hLeft!=NULL){ m_LList.DeleteIRow(hLeft); aFromRtoL.RemoveKey(pOpt->hIRow); } m_OptionsList.DeleteIRow(pOpt->hIRow); pOpt->hIRow=NULL; delete pOpt; } // Чтобы небыло глюков // Иногда удаляют дефолтный топик... hDefaultTopic=0; } BOOL CDLG_Options::PushOptionOnScreen(int iOptionIndex) { COption* pOpt=aOptions[iOptionIndex]; if(!pOpt){ return FALSE; } switch(pOpt->iOptionType){ case OPTTYPE_DATE: ((COptionDate*)pOpt)->m_Value=*((COptionDate*)pOpt)->m_Value_Real; m_OptionsList.SetIItemText(pOpt->hIRow, 1, ConvertToLocaleDate(((COptionDate*)pOpt)->m_Value)); break; case OPTTYPE_BOOL: ((COptionBOOL*)pOpt)->m_Value=*((COptionBOOL*)pOpt)->m_Value_Real; m_OptionsList.SetIItemCheck(pOpt->hIRow, 0, ((COptionBOOL*)pOpt)->m_Value); break; case OPTTYPE_NUMBER: ((COptionNumber*)pOpt)->m_Value=*((COptionNumber*)pOpt)->m_Value_Real; if(((COptionNumber*)pOpt)->m_Value<((COptionNumber*)pOpt)->m_dwMin){ ((COptionNumber*)pOpt)->m_Value=((COptionNumber*)pOpt)->m_dwMin; } if(((COptionNumber*)pOpt)->m_Value>((COptionNumber*)pOpt)->m_dwMax){ ((COptionNumber*)pOpt)->m_Value=((COptionNumber*)pOpt)->m_dwMax; } m_OptionsList.SetIItemText(pOpt->hIRow,1,Format("%i",((COptionNumber*)pOpt)->m_Value)); break; case OPTTYPE_STRING: ((COptionString*)pOpt)->m_Value=*((COptionString*)pOpt)->m_Value_Real; m_OptionsList.SetIItemText(pOpt->hIRow,1,((COptionString*)pOpt)->m_Value); break; case OPTTYPE_COMBO: { CStringArray sItemsData; ((COptionCombo*)pOpt)->m_Value=*((COptionCombo*)pOpt)->m_Value_Real; ConvertComboDataToArray(((COptionCombo*)pOpt)->m_ComboData,sItemsData); m_OptionsList.SetIItemText(pOpt->hIRow,1,sItemsData[((COptionCombo*)pOpt)->m_Value]); break; } case OPTTYPE_HOTKEY: bAnyHotkeyWasChanged=1; ((COptionHotKey*)pOpt)->m_Value=*((COptionHotKey*)pOpt)->m_Value_Real; break; case OPTTYPE_COLOR: { ((COptionColor*)pOpt)->m_Value=*((COptionColor*)pOpt)->m_Value_Real; DWORD dwColor=((COptionColor*)pOpt)->m_Value; m_OptionsList.SetIItemColors(((COptionColor*)pOpt)->hIRow,1,SPECINVERTCOL(dwColor),dwColor); m_OptionsList.SetIRowTextStyle(((COptionColor*)pOpt)->hIRow,FL_SELBORD); if(bShowColorForColorOptions){ m_OptionsList.SetIItemText(((COptionColor*)pOpt)->hIRow, 1, Format("#%02X%02X%02X",GetRValue(dwColor),GetGValue(dwColor),GetBValue(dwColor))); } } break; } m_OptionsList.UpdateIRow(pOpt->hIRow); return TRUE; } void CDLG_Options::PushSomeDataOnScreen(long iOptionClass) { int i=0; for(i=0;i<aOptions.GetSize();i++){ COption* pOpt=aOptions[i]; if(pOpt){ if(iOptionClass!=-1){ if(pOpt->iOptionClass!=iOptionClass){ continue; } } if(!PushOptionOnScreen(i)){ continue; } } } } COption* CDLG_Options::GetOptionUnderCursor(int* iOptionIndex) { COption* pOpt=NULL; CPoint p; GetCursorPos(&p); m_OptionsList.ScreenToClient(&p); int iCol=-1; int iRow=m_OptionsList.HitTestEx(p, &iCol); if(iRow!=-1){ HIROW hIRow=m_OptionsList.GetIRowFromIndex(iRow); if(hIRow){ long dwItemData=m_OptionsList.GetIItemData(hIRow,1); if(dwItemData>=0 && dwItemData<aOptions.GetSize()){ pOpt=aOptions[dwItemData]; if(iOptionIndex){ *iOptionIndex=dwItemData; } } } } return pOpt; } void CDLG_Options::GetOptionDsc(HIROW hIRow, int iCol, CString& sText, CString& sPopupText) { if(hIRow){ long dwItemData=m_OptionsList.GetIItemData(hIRow,1); BOOL bSubItems=m_OptionsList.GetChildIRowCount(hIRow); COption* pOpt=NULL; BOOL bNoEditWarn=FALSE; if(dwItemData>=0 && dwItemData<aOptions.GetSize()){ pOpt=aOptions[dwItemData]; if(pOpt){ if(iCol==0){ sText=pOpt->sDsc; }else{ sText=pOpt->GetDsc(); } }else{ bNoEditWarn=TRUE; } }else{ bNoEditWarn=TRUE; } CString sItemText=""; if(iCol!=-1){ sItemText=m_OptionsList.GetIItemText(hIRow,iCol); }else{ sItemText=m_OptionsList.GetIItemText(hIRow,0); } if(sText==""){ sText=sItemText; } if(sText.Find(sItemText)==-1){ sText=sItemText+"\n"+sText; } DWORD dwType=0; sPopupText=sText; if(iCol==0){ sPopupText=sItemText; if(pOpt!=NULL){ dwType=m_OptionsList.GetIItemControlType(hIRow, 0); if(dwType==FLC_CHECKBOX){ bNoEditWarn=TRUE; sPopupText=pOpt->GetDsc(); if(sPopupText==""){ sPopupText=sItemText; } /* if(sText!=sItemText && sText!="" && sPopupText!=""){ sText=sPopupText+"; "+sText; }else{ sText=sPopupText; } */ } } } dwType=m_OptionsList.GetIItemControlType(hIRow, 1); if(dwType==FLC_READONLY || dwType==FLC_COMBOBOX){ bNoEditWarn=TRUE; } if(!bNoEditWarn){ if(dwType==FLC_HOTKEY){ sText+=" ("; sText+=_l("Hotkey"); sText+=")"; } /* if(iCol==0){ if(sText!=""){ sText+="; "; } sText+=_l("Double-click right column to edit value"); }else{ if(sText!=""){ sText+="; "; } sText+=_l("Double-click cell to edit value"); }*/ } if(bSubItems){ if(sText!=""){ sText+="; "; } sText+=_l("This item has additional options, Expand it to see them"); } } } int iLastRow=-1; int iLastCol=-1; BOOL CDLG_Options::PreTranslateMessage(MSG* pMsg) { // CG: The following block was added by the ToolTips component. if(IsWindow(m_tooltip.GetSafeHwnd())){ // Let the ToolTip process this message. m_tooltip.RelayEvent(pMsg); } UINT iCtrlID=0; if(pMsg->hwnd!=NULL){ iCtrlID=::GetDlgCtrlID(pMsg->hwnd); } if(iCtrlID==IDC_INPLACE_HOTKEY){ if(pMsg->message==WM_KEYDOWN || pMsg->message==WM_KEYUP){ return FALSE; } } if(bShowFind==2 && (pMsg->message==WM_LBUTTONDOWN || pMsg->message==WM_NCLBUTTONDOWN)){ CPoint pt; GetCursorPos(&pt); CRect rt,rtMain; GetClientRect(&rtMain); ClientToScreen(&rtMain); rt.CopyRect(rtMain); rt.left=rt.right-GetSystemMetrics(SM_CYMENU); rt.bottom=rt.top; rt.top=rt.top-GetSystemMetrics(SM_CYMENU); if(rt.PtInRect(pt)){ PostMessage(WM_COMMAND,IDC_BUTTON_FIND,0); } } if(pMsg->message==WM_KEYDOWN){ if(GetKeyState(VK_CONTROL)<0){ if(pMsg->wParam=='S'){ OnApply(); return TRUE; } if(pMsg->wParam==VK_RETURN){ OnOK(); return TRUE; } }else{ if(pMsg->wParam==VK_RETURN && iCtrlID==IDC_EDIT_FIND){ OnFind(); return TRUE; } } if(pMsg->wParam==VK_ESCAPE){ CancelThis(); return TRUE; } if(pMsg->wParam==VK_RETURN || (iCtrlID!=IDC_INPLACE_EDIT && pMsg->wParam==VK_SPACE)){ CWnd* pFocus=GetFocus(); pFocus->SendMessage(pMsg->message,pMsg->wParam,pMsg->lParam); return TRUE; } if(iCtrlID==IDC_OPTIONSLIST){ HIROW hRow=m_OptionsList.GetSelectedIRow(); int iItem=m_OptionsList.GetSelectedIItem(); if(hRow && iItem==0){ if(pMsg->wParam==VK_SPACE || pMsg->wParam==VK_LEFT || pMsg->wParam==VK_BACK){ if(m_OptionsList.IsCollapsed(hRow)){ m_OptionsList.Expand(hRow); }else{ m_OptionsList.Collapse(hRow); } return TRUE; } } /*if(pMsg->wParam==VK_TAB){ m_OptionsList.SelectIItem(hRow,1); return TRUE; }*/ } } if(pMsg->message==WM_RBUTTONUP){ if(iCtrlID==IDC_OPTIONSLIST || iCtrlID==IDC_LPANE){ CPoint p; int iCol=-1; GetCursorPos(&p); m_LList.ScreenToClient(&p); int iRow=m_LList.HitTestEx(p, &iCol); if(iRow!=-1){ HIROW hIRow=m_LList.GetIRowFromIndex(iRow); MoveGlobalFocus(hIRow,FALSE); } OnAdditionalEx(TRUE,(iCtrlID==IDC_LPANE)?1:2); return TRUE; } } if(pMsg->message==WM_MOUSEMOVE || pMsg->message==WM_LBUTTONDOWN){ CString sText; if(iCtrlID==IDC_OPTIONSLIST || iCtrlID==IDC_LPANE){ if(pMsg->message==WM_LBUTTONDOWN){ int i=0; } CPoint p; int iCol=-1; GetCursorPos(&p); m_OptionsList.ScreenToClient(&p); int iRow=m_OptionsList.HitTestEx(p, &iCol); if(iRow!=-1 && (pMsg->message==WM_LBUTTONDOWN || iLastRow!=iRow || iCol!=iLastCol)){ iLastRow=iRow; iLastCol=iCol; CString sPopupText; HIROW hIRow=m_OptionsList.GetIRowFromIndex(iRow); GetOptionDsc(hIRow, iCol, sText, sPopupText); m_tooltip.Pop(); m_tooltip.UpdateTipText((sPopupText.Find("\n")==-1)?TrimMessage(sPopupText,100):TrimMessage(sPopupText,2000),GetDlgItem(IDC_OPTIONSLIST)); }else{ GetCursorPos(&p); m_LList.ScreenToClient(&p); iRow=m_LList.HitTestEx(p, &iCol); static int iLastLRow=-1; static int iLastLCol=-1; if(iRow!=-1 && (pMsg->message==WM_LBUTTONDOWN || iLastLRow!=iRow || iLastLCol!=iCol)){ iLastLRow=iRow; iLastLCol=iCol; HIROW hIRow=m_LList.GetIRowFromIndex(iRow); sText=m_LList.GetIItemText(hIRow,iCol); } } }else{ static DWORD iLastStatId=0; if(pMsg->message==WM_LBUTTONDOWN || iLastStatId!=iCtrlID){ iLastStatId=iCtrlID; CWnd* pCtrlWnd=GetDlgItem(iCtrlID); if(pCtrlWnd){ //m_tooltip.GetText(sText,pCtrlWnd,0); sText=GetTooltipText(&m_tooltip, pCtrlWnd); } } } if(sText!="" && pMsg->message==WM_LBUTTONDOWN){ SetQHelpText(CString(" ")+sText); } } if(pMsg->message==WM_DROPFILES){ int iOptionIndex=-1; COption* pOpt=GetOptionUnderCursor(&iOptionIndex); COptionString* pOptStr=NULL; if(pOpt && pOpt->iOptionType==OPTTYPE_STRING){ pOptStr=(COptionString*)pOpt; } if(pOptStr && iOptionIndex>=0){ HDROP hDropInfo=(HDROP)pMsg->wParam; char szFilePath[256]; UINT cFiles = DragQueryFile(hDropInfo, (UINT)-1, NULL, 0); for (UINT u = 0; u < cFiles; u++){ DragQueryFile(hDropInfo, u, szFilePath, sizeof(szFilePath)); *pOptStr->m_Value_Real=szFilePath; break; } DragFinish(hDropInfo); PushOptionOnScreen(iOptionIndex); } return TRUE; } if(pMsg->message==WM_LBUTTONDBLCLK || (pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN)){ if(iCtrlID==IDC_OPTIONSLIST){ CPoint p; int iCol=-1; GetCursorPos(&p); m_OptionsList.ScreenToClient(&p); int iRow=m_OptionsList.HitTestEx(p, &iCol); if(iCol==0){ int iOptionIndex=-1; COption* pOpt=GetOptionUnderCursor(&iOptionIndex); if(pOpt && m_OptionsList.GetIItemControlType(pOpt->hIRow,1)!=FLC_READONLY && m_OptionsList.GetIItemControlType(pOpt->hIRow,0)==FLC_READONLY){ PostMessage(EDITITEM,(WPARAM)pOpt->hIRow,1); return TRUE; } } } } if(pMsg->message==EDITITEM){ m_OptionsList.SelectAndEditIItem((HIROW)pMsg->wParam,pMsg->lParam); return TRUE; } if(pMsg->message==WM_LBUTTONDOWN){ if(iCtrlID==IDC_LPANE){ BOOL bExpand=FALSE; HIROW hIRow=NULL; CPoint p; int iCol=-1; GetCursorPos(&p); m_LList.ScreenToClient(&p); int iRow=m_LList.HitTestEx(p, &iCol); if(iRow!=-1){ hIRow=m_LList.GetIRowFromIndex(iRow); if(hLastOpenedRPane!=hIRow){ hLastOpenedRPane=hIRow; bExpand=!m_LList.HitTestCollapse(hIRow,p); MoveGlobalFocus(hIRow,bExpand); } } if(bExpand){ m_LList.SelectIRow(hIRow,TRUE); return TRUE; } } } BOOL lRes=CDialog::PreTranslateMessage(pMsg); if(lRes){ if(pMsg->message==WM_KEYDOWN && (pMsg->wParam==VK_UP || pMsg->wParam==VK_DOWN)){ if(iCtrlID==IDC_LPANE){ HIROW hIRow=m_LList.GetSelectedIRow(); if(hLastOpenedRPane!=hIRow){ hLastOpenedRPane=hIRow; MoveGlobalFocus(hIRow,TRUE,TRUE); } } CString sT,sP; GetOptionDsc(m_OptionsList.GetSelectedIRow(),m_OptionsList.GetSelectedIItem(),sT,sP); if(sT=="" && sP==""){ HIROW hLeftSelected=m_LList.GetSelectedIRow(); if(hLeftSelected){ sT=m_LList.GetIItemText(hLeftSelected,0); } } SetQHelpText(CString(" ")+sT==""?sP:sT); } } UINT message=pMsg->message; if(bShowFind==2 && (message==WM_MOUSEMOVE || message==WM_ACTIVATE ||message==WM_NCACTIVATE || message==WM_MOVING || message==WM_SIZING ||message==WM_SIZE || message==WM_NCPAINT || message==WM_PAINT || message==WM_SHOWWINDOW)){ DrawNC(); } return lRes; } BOOL CDLG_Options::DrawNC() { HWND hwnd=this->GetSafeHwnd(); if(!hwnd || !IsWindow(hwnd) || bShowFind!=2){ return 0; } HDC hdc=::GetWindowDC(hwnd); CRect rt,rtMain,rtMainWnd; GetClientRect(&rtMain); GetWindowRect(&rtMainWnd); ClientToScreen(&rtMain); rt.CopyRect(rtMain); rt.left=rt.right-GetSystemMetrics(SM_CYMENU); rt.bottom=rt.top; rt.top=rt.top-GetSystemMetrics(SM_CYMENU); rt.OffsetRect(-rtMainWnd.left,-rtMainWnd.top); //DrawFrameControl(hdc,&rt,DFC_CAPTION,DFCS_CAPTIONHELP); ::SetBkMode(hdc, TRANSPARENT); ::SelectObject(hdc,HFONT(*GetFont())); ::DrawText(hdc,"[?]",3,&rt,DT_CENTER|DT_VCENTER|DT_SINGLELINE); ::ReleaseDC(hwnd, hdc); return 0; } BOOL CDLG_Options::CallApply(DWORD dwRes, BOOL bSaveAndExit) { if(m_pStartupInfo->fpApplyOptionList){ EnableWindow(FALSE); if(dwRes==IDOK){ CommitData(); } HIROW hPrevTopic=m_LList.GetSelectedIRow(); if(hPrevTopic && !bSaveAndExit){ m_pStartupInfo->szDefaultTopicTitle=m_LList.GetIItemText(hPrevTopic,0); } BOOL bRes=m_pStartupInfo->fpApplyOptionList(bSaveAndExit,dwRes,this); if(bSaveAndExit){ // Можно скрыть уже... ShowWindowAsync(GetSafeHwnd(),SW_HIDE); }else{ if(bRes){ // Перестраиваем меню! HCURSOR hCur=SetCursor(LoadCursor(NULL,MAKEINTRESOURCE(IDC_WAIT))); m_LList.m_bStopUpdateScreen++; m_OptionsList.m_bStopUpdateScreen++; DestroyOptions(1); IniIList();// Заново иницим иконки FillOptionListWithData(); m_LList.m_bStopUpdateScreen--; m_OptionsList.m_bStopUpdateScreen--; // Перерисовываем кнопки... SetButtons(); // Усе... Invalidate(); SetCursor(hCur); //pParentWnd??? } } EnableWindow(TRUE); } return TRUE; } void CDLG_Options::OnApply() { CallApply(IDOK,FALSE); GetDlgItem(IDAPPLY)->EnableWindow(FALSE); m_ChangedClasses.RemoveAll(); } BOOL CDLG_Options::MyEndDialog(DWORD dwRes) { CallApply(dwRes,TRUE); CMenu* pSysMenu=GetMenu(); if(pSysMenu){ delete pSysMenu; } EndDialog(dwRes); return TRUE; } BOOL CDLG_Options::FinishFillOptionListWithData() { Sizer.UpdateClientOffsets(); if(bRPaneOnly){ CRect rect,rect2; m_LList.GetWindowRect(&rect); ScreenToClient(&rect); m_OptionsList.GetWindowRect(&rect2); ScreenToClient(&rect2); rect2.left-=rect.Width(); rect.right=rect.left; m_LList.MoveWindow(&rect); m_LList.ShowWindow(SW_HIDE); m_OptionsList.MoveWindow(&rect2); Sizer.ApplyLayout(TRUE); } return TRUE; } BOOL CDLG_Options::FillOptionListWithData() { InitExtraData(); if(m_pStartupInfo->sz1stTopic.GetLength()){ hTopLPaneItem=m_LList.InsertIRow(FL_ROOT,FL_FIRST,m_pStartupInfo->sz1stTopic,5); m_LList.SetIRowTextStyle(hTopLPaneItem,FL_SKIPTRI); m_LList.SetIItemData(hTopLPaneItem,0,0); }else{ hTopLPaneItem=FL_ROOT; } m_OptionsList.SetSilentAddMode(TRUE); if(!(*m_pStartupInfo->fpInitOptionList)(this)){ MyEndDialog(IDCANCEL); return FALSE; } m_OptionsList.SetSilentAddMode(FALSE); if(!hDefaultTopic){ int iPos=0; HIROW h=m_LList.GetIRowFromIndex(iPos); while(m_LList.GetIItemData(h,0)==0){ h=m_LList.GetIRowFromIndex(iPos); iPos++; if(iPos>=m_LList.GetIRowCount()){ iPos--; break; } } hDefaultTopic=m_LList.GetIRowFromIndex(iPos); }else{ HIROW hRight=hDefaultTopic; hDefaultTopic=GetAliasHIROW(hDefaultTopic); while(hDefaultTopic==0 && hDefaultTopic!=FL_ROOT && hRight!=0 && hRight!=FL_ROOT){ hRight=m_OptionsList.GetParentIRow(hRight); aFromRtoL.Lookup(hRight,hDefaultTopic); } m_LList.SetIRowTextStyle(hDefaultTopic,FL_BOLD); } CArray<HIROW,HIROW> aTree; if(m_pStartupInfo->bExpandByDef){ if(m_pStartupInfo->bExpandByDef==2){ EnableWindow(FALSE); ProcessEveryFolder(FL_ROOT,FALSE,1); EnableWindow(TRUE); }else{ OnExpandAll(); } }else{ // Только дефолтный aTree.Add(hDefaultTopic); HIROW hIParent=m_LList.GetParentIRow(hDefaultTopic); while(hIParent!=FL_ROOT){ aTree.Add(hIParent); hIParent=m_LList.GetParentIRow(hIParent); } for(int i=aTree.GetSize()-1;i>=0;i--){ m_LList.Expand(aTree[i]); } } m_LList.EnsureVisible(hDefaultTopic,0,FALSE); MoveGlobalFocus(hDefaultTopic); if(m_pStartupInfo->fpPostAction){ m_pStartupInfo->fpPostAction((HIROW)m_pStartupInfo->pPostActionParam,this); } if(aFromRtoL.GetCount()<=1){ bDoNotSavePanePos=1; bRPaneOnly=1; } return TRUE; } BOOL CDLG_Options::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { FLNM_ROWSTATE *pRowState=(FLNM_ROWSTATE*) lParam; return CDialog::OnNotify(wParam, lParam, pResult); } BOOL CDLG_Options::AddChanged(int iClass) { m_ChangedClasses.Add(iClass); SetWindowText(m_pStartupInfo->szWindowTitle+" *"); GetDlgItem(IDAPPLY)->EnableWindow(TRUE); return TRUE; } BOOL CDLG_Options::OnChanged(COption* pOpt) { if(!isOptionClassChanged(pOpt->iOptionClass)){ return AddChanged(pOpt->iOptionClass); } return FALSE; } void CDLG_Options::ProcessEveryFolder(HIROW hRoot, BOOL bCollapse, BOOL bParLen) { static long lDeep=0; if(bParLen>0 && lDeep>=bParLen){ return; } int iFolders=m_LList.GetChildIRowCount(hRoot); for(int i=0;i<iFolders;i++){ HIROW hRow=m_LList.GetChildIRowAt(hRoot,i); if(hRow){ if(bCollapse){ m_LList.Collapse(hRow); }else{ m_LList.Expand(hRow); } lDeep++; ProcessEveryFolder(hRow,bCollapse,bParLen); lDeep--; } } } void CDLG_Options::OnResetCurOption() { if(m_OptionsList.GetSelectedIRow()==0){ return; } long dwItemData=m_OptionsList.GetIItemData(m_OptionsList.GetSelectedIRow(),1); COption* pOpt=NULL; if(dwItemData>=0 && dwItemData<aOptions.GetSize()){ pOpt=aOptions[dwItemData]; CString sName=m_OptionsList.GetIItemText(m_OptionsList.GetSelectedIRow(),0); if(!pOpt || AfxMessageBox(Format("%s: %s?",sName,_l("Reset to default value")),MB_YESNO|MB_ICONQUESTION)!=IDYES){ return; } ResetOption(pOpt); } } void CDLG_Options::OnCollapseAll() { HCURSOR hCur=SetCursor(AfxGetApp()->LoadCursor(IDC_WAIT)); EnableWindow(FALSE); m_LList.LockWindowUpdate(); ProcessEveryFolder(FL_ROOT,TRUE); m_LList.UnlockWindowUpdate(); EnableWindow(TRUE); SetCursor(hCur); } void CDLG_Options::OnExpandAll() { EnableWindow(FALSE); ProcessEveryFolder(FL_ROOT,FALSE); EnableWindow(TRUE); } HBRUSH CDLG_Options::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { DWORD dwID=pWnd->GetDlgCtrlID(); /*if(dwID==IDC_QHELP_TXT){ pDC->SetBkColor(GetSysColor(COLOR_INFOBK));//RGB(YELLOWR,YELLOWG,YELLOWB) pDC->SetTextColor(GetSysColor(COLOR_INFOTEXT));//RGB(0,0,0) return brYellow; }*/ return CDialog::OnCtlColor(pDC, pWnd, nCtlColor); } #define ACT_MINNUM 100 void CDLG_Options::OnAdditional() { OnAdditionalEx(FALSE,0); } void CDLG_Options::OnAdditionalEx(BOOL bAtCursor,BOOL bType) { CMenu menu; menu.CreatePopupMenu(); if(bAtCursor && hCurButtonsBarIRow){ int i=1,iPos=-1; COptionAction* act=GetMenuAction(hCurButtonsBarIRow,i,0,&iPos); if(act && iPos>=0){ do{ AddMenuString(&menu,ACT_MINNUM+iPos,act->sDsc); i++; }while((act=GetMenuAction(hCurButtonsBarIRow,i,0,&iPos))!=0); menu.AppendMenu(MF_SEPARATOR, 0, ""); } } if(bType==0 || bType==1){ AddMenuString(&menu,1,_l("Reset to defaults"));//,_bmp().Get(_IL(37))); menu.AppendMenu(MF_SEPARATOR, 0, ""); AddMenuString(&menu,2,_l("Expand all folders")); AddMenuString(&menu,3,_l("Collapse all folders")); } if(bType==0 || bType==2){ AddMenuString(&menu,4,_l("Reset current option")); } if(aMenuOptions.GetSize()>0){ BOOL bSepWas=0; for(int i=0;i<aMenuOptions.GetSize();i++){ COptionAction* act=aMenuOptions[i]; if(act->hIRow==0){ if(!bSepWas){ menu.AppendMenu(MF_SEPARATOR, 0, ""); bSepWas=1; } AddMenuString(&menu,ACT_MINNUM+i,act->sDsc); } } } // Показываем меню CPoint pt; if(bAtCursor){ GetCursorPos(&pt); }else{ CRect rt; GetDlgItem(IDRESET)->GetWindowRect(&rt); pt.x=rt.right; pt.y=rt.top; } this->PostMessage(WM_NULL,0,0); this->SetForegroundWindow(); DWORD dwRetCode=TrackPopupMenu(menu.GetSafeHmenu(), TPM_RETURNCMD|TPM_NONOTIFY|TPM_RIGHTBUTTON, pt.x, pt.y, 0, this->GetSafeHwnd(), NULL); DWORD dwError=GetLastError(); if(dwRetCode==1){ OnReset(); } if(dwRetCode==2){ OnExpandAll(); } if(dwRetCode==3){ OnCollapseAll(); } if(dwRetCode==4){ OnResetCurOption(); } if(dwRetCode>=ACT_MINNUM){ COptionAction* act=aMenuOptions[dwRetCode-ACT_MINNUM]; FP_OPTIONACTION fp = act->function; if(fp){ (*fp)((HIROW)act->functionParam,this); } } return; } BOOL CDLG_Options::MoveGlobalFocus(HIROW hLeftTopic, BOOL bExpand, BOOL bPreventFocusStealing) { HIROW hRPaneToShow=NULL; if(!m_LList.CheckIRow(hLeftTopic)){ return FALSE; } if(hLeftTopic!=NULL){ hRPaneToShow=(HIROW)m_LList.GetIItemData(hLeftTopic,0); if(hRPaneToShow==NULL){ return FALSE; } if(m_LList.GetSelectedIRow()!=hLeftTopic){ m_LList.SelectIRow(hLeftTopic,TRUE,FALSE); } } if(hRPaneToShow!=NULL){ int iRCnt = m_OptionsList.GetChildIRowCount(hRPaneToShow); if(iRCnt==0 && bAutoSkipEmptyPanes){ return MoveGlobalFocus(m_LList.GetFirstChildIRow(hLeftTopic), bExpand, bPreventFocusStealing); } if(bExpand){ m_LList.EnsureVisible(hLeftTopic,0,TRUE); m_LList.Expand(hLeftTopic); HIROW hSelIRow=m_LList.GetSelectedIRow(); m_LList.SelectIRow(hSelIRow, TRUE); } if(iRCnt==0){ return TRUE; } } //m_OptionsList.LockWindowUpdate(); m_OptionsList.ShowWindow(SW_HIDE); HIROW hRPane=NULL,hLPane=NULL; POSITION pos=NULL; //AdjustRPaneW(); {// Скрываем все pos=aFromRtoL.GetStartPosition(); while(pos){ aFromRtoL.GetNextAssoc(pos,hRPane,hLPane); m_OptionsList.SetUnCollapsible(hRPane,FALSE); m_OptionsList.Collapse(hRPane,TRUE); } m_OptionsList.RefreshIndexes(); } if(m_LList.IsValidHIRow(hDefaultTopic) && m_LList.GetIRowTextStyle(hDefaultTopic)){ m_LList.SetIRowTextStyle(hDefaultTopic,FL_NORMAL); } PushButtonsRow(hRPaneToShow); m_OptionsList.ShowWindow(SW_SHOW); //m_OptionsList.UnlockWindowUpdate(); //m_LList.Invalidate(); {// Показываем нужную CString sTitle,sTitleDsc; pos=aFromRtoL.GetStartPosition(); while(pos){ aFromRtoL.GetNextAssoc(pos,hRPane,hLPane); if(hRPane==hRPaneToShow){ m_OptionsList.SelectIRow(NULL,FALSE,FALSE); m_OptionsList.Expand(hRPane,TRUE,FALSE); m_OptionsList.SetUnCollapsible(hRPane,TRUE); sTitle=m_OptionsList.GetIItemText(hRPane,0); sTitleDsc=m_OptionsList.GetIItemText(hRPane,1); } } SetQHelpText(sTitleDsc==""?sTitle:sTitleDsc); m_OptionsList.RefreshIndexes(); } m_LList.SetFocus(); sCurrentOptionFromLPane=m_LList.GetIItemText(hLeftTopic,0); AdjustRPaneW(); return TRUE; } void CDLG_Options::SetQHelpText(CString szText) { szText.TrimLeft(); szText.TrimRight(); if(szText==""){ szText=m_pStartupInfo->szQHelpByDefault; } if(m_pStartupInfo->szTooltipPostfix!=""){ szText+=m_pStartupInfo->szTooltipPostfix; } szText.TrimLeft(); szText.TrimRight(); GetDlgItem(IDC_QHELP_TXT)->SetWindowText(szText); } COptionAction* CDLG_Options::GetMenuAction(HIROW hRightPane, int iCount, BOOL bNoIconOnly, int* iOutNumber) { if(iOutNumber){ *iOutNumber=-1; } if(hRightPane==0 || hRightPane==FL_ROOT || hRightPane==hLPaneRoot){ return 0; } HIROW hParent=NULL; if(hRightPane && hRightPane!=FL_ROOT){ HIROW hLeftTopic=GetAliasHIROW(hRightPane); /*if(bNoIconOnly==1 && hLeftTopic==0){ // Поддерживаем одиночную иерархию, так уж и быть hRightPane=m_OptionsList.GetParentIRow(hRightPane); hLeftTopic=GetAliasHIROW(hRightPane); }*/ if(hLeftTopic && hLeftTopic!=hLPaneRoot){ HIROW hLeftTopicParent=m_LList.GetParentIRow(hLeftTopic); if(hLeftTopicParent && hLeftTopicParent!=hLPaneRoot){ hParent=(HIROW)m_LList.GetIItemData(hLeftTopicParent,0); } } } if(aMenuOptions.GetSize()>0){ for(int i=0;i<aMenuOptions.GetSize();i++){ COptionAction* act=aMenuOptions[i]; if(act->hIRow==hRightPane || (bNoIconOnly==0 && hParent!=NULL && act->hIRow==hParent)){ if((bNoIconOnly==1 && act->lIcon!=0) || (bNoIconOnly==0 && act->lIcon==0)){ iCount--; if(iCount==0){ if(iOutNumber){ *iOutNumber=i; } return act; } } } } } return 0; } BOOL CDLG_Options::PushButtonsRow(HIROW hRightPane) { // Ищем... COptionAction* pAction=0; hCurButtonsBarIRow=hRightPane; BOOL bAnyButton=0; COptionAction* pAction1=GetMenuAction(hRightPane,1,0); if(pAction1){ GetDlgItem(ID_FOLDERACTIONS1)->SetWindowText(pAction1->sDsc); GetDlgItem(ID_FOLDERACTIONS1)->ShowWindow(SW_SHOW); COptionAction* pAction2=GetMenuAction(hRightPane,2,0); if(pAction2){ GetDlgItem(ID_FOLDERACTIONS2)->ShowWindow(SW_SHOW); }else{ GetDlgItem(ID_FOLDERACTIONS2)->ShowWindow(SW_HIDE); } bAnyButton++; }else{ GetDlgItem(ID_FOLDERACTIONS1)->ShowWindow(SW_HIDE); GetDlgItem(ID_FOLDERACTIONS2)->ShowWindow(SW_HIDE); } #ifdef OPTIONS_TOOLBAR CRect rtFolder; BOOL bPreventToolbar=0; GetDlgItem(ID_FOLDERACTIONS2)->GetWindowRect(&rtFolder); sSqBt=CSize(rtFolder.Width(),rtFolder.Height()); pAction=GetMenuAction(hRightPane,1,1); if(pAction && lSipleRemindIconNum && pAction->lIcon==lSipleRemindIconNum){ // Беда... одни реминдеры! // Не пойдет! bPreventToolbar=1; } if(pAction && !bPreventToolbar){ m_Toolbar1.SetStyles(CBS_NORMAL);//CBS_HIQUAL m_Toolbar1.SetBitmap(m_OptionsListImages.ExtractIcon(pAction->lIcon)); SetButtonSize(this,ID_TOOLBAR1,sSqBt); CString sDescription=TrimMessage(pAction->GetDsc(),50); m_tooltip.UpdateTipText(sDescription, GetDlgItem(ID_TOOLBAR1)); GetDlgItem(ID_TOOLBAR1)->ShowWindow(SW_SHOW); bAnyButton++; }else{ GetDlgItem(ID_TOOLBAR1)->ShowWindow(SW_HIDE); SetButtonSize(this,ID_TOOLBAR1,CSize(1,1)); } pAction=GetMenuAction(hRightPane,2,1); if(pAction && !bPreventToolbar){ m_Toolbar2.SetStyles(CBS_NORMAL);//CBS_HIQUAL m_Toolbar2.SetBitmap(m_OptionsListImages.ExtractIcon(pAction->lIcon)); SetButtonSize(this,ID_TOOLBAR2,sSqBt); CString sDescription=TrimMessage(pAction->GetDsc(),50); m_tooltip.UpdateTipText(sDescription, GetDlgItem(ID_TOOLBAR2)); GetDlgItem(ID_TOOLBAR2)->ShowWindow(SW_SHOW); bAnyButton++; }else{ GetDlgItem(ID_TOOLBAR2)->ShowWindow(SW_HIDE); SetButtonSize(this,ID_TOOLBAR2,CSize(1,1)); } pAction=GetMenuAction(hRightPane,3,1); if(pAction && !bPreventToolbar){ m_Toolbar3.SetStyles(CBS_NORMAL);//CBS_HIQUAL m_Toolbar3.SetBitmap(m_OptionsListImages.ExtractIcon(pAction->lIcon)); SetButtonSize(this,ID_TOOLBAR3,sSqBt); CString sDescription=TrimMessage(pAction->GetDsc(),50); m_tooltip.UpdateTipText(sDescription, GetDlgItem(ID_TOOLBAR3)); GetDlgItem(ID_TOOLBAR3)->ShowWindow(SW_SHOW); bAnyButton++; }else{ GetDlgItem(ID_TOOLBAR3)->ShowWindow(SW_HIDE); SetButtonSize(this,ID_TOOLBAR3,CSize(1,1)); } pAction=GetMenuAction(hRightPane,4,1); if(pAction && !bPreventToolbar){ m_Toolbar4.SetStyles(CBS_NORMAL);//CBS_HIQUAL m_Toolbar4.SetBitmap(m_OptionsListImages.ExtractIcon(pAction->lIcon)); SetButtonSize(this,ID_TOOLBAR4,sSqBt); CString sDescription=TrimMessage(pAction->GetDsc(),50); m_tooltip.UpdateTipText(sDescription, GetDlgItem(ID_TOOLBAR4)); GetDlgItem(ID_TOOLBAR4)->ShowWindow(SW_SHOW); bAnyButton++; }else{ GetDlgItem(ID_TOOLBAR4)->ShowWindow(SW_HIDE); SetButtonSize(this,ID_TOOLBAR4,CSize(1,1)); } pAction=GetMenuAction(hRightPane,5,1); if(pAction && !bPreventToolbar){ m_Toolbar5.SetStyles(CBS_NORMAL);//CBS_HIQUAL m_Toolbar5.SetBitmap(m_OptionsListImages.ExtractIcon(pAction->lIcon)); SetButtonSize(this,ID_TOOLBAR5,sSqBt); CString sDescription=TrimMessage(pAction->GetDsc(),50); m_tooltip.UpdateTipText(sDescription, GetDlgItem(ID_TOOLBAR5)); GetDlgItem(ID_TOOLBAR5)->ShowWindow(SW_SHOW); bAnyButton++; }else{ GetDlgItem(ID_TOOLBAR5)->ShowWindow(SW_HIDE); SetButtonSize(this,ID_TOOLBAR5,CSize(1,1)); } pAction=GetMenuAction(hRightPane,6,1); if(pAction && !bPreventToolbar){ m_Toolbar6.SetStyles(CBS_NORMAL);//CBS_HIQUAL m_Toolbar6.SetBitmap(m_OptionsListImages.ExtractIcon(pAction->lIcon)); SetButtonSize(this,ID_TOOLBAR6,sSqBt); CString sDescription=TrimMessage(pAction->GetDsc(),50); m_tooltip.UpdateTipText(sDescription, GetDlgItem(ID_TOOLBAR6)); GetDlgItem(ID_TOOLBAR6)->ShowWindow(SW_SHOW); bAnyButton++; }else{ GetDlgItem(ID_TOOLBAR6)->ShowWindow(SW_HIDE); SetButtonSize(this,ID_TOOLBAR6,CSize(1,1)); } #endif Sizer.SetGotoRule(MainRulePos,bAnyButton); Sizer.ApplyLayout(TRUE); return TRUE; } void CDLG_Options::ExecuteAction(COptionAction* act) { if(!hCurButtonsBarIRow || !act){ return; } FP_OPTIONACTION fp = act->function; if(fp){ (*fp)((HIROW)act->functionParam,this); }else{ FP_OPTIONACTION2 fp2 = act->function2; if(fp2){ (*fp2)(act->functionParam,this); } } } void CDLG_Options::OnAction1() { ExecuteAction(GetMenuAction(hCurButtonsBarIRow,1,0)); } void CDLG_Options::OnTOOLBAR1() { ExecuteAction(GetMenuAction(hCurButtonsBarIRow,1,1)); } void CDLG_Options::OnTOOLBAR2() { ExecuteAction(GetMenuAction(hCurButtonsBarIRow,2,1)); } void CDLG_Options::OnTOOLBAR3() { ExecuteAction(GetMenuAction(hCurButtonsBarIRow,3,1)); } void CDLG_Options::OnTOOLBAR4() { ExecuteAction(GetMenuAction(hCurButtonsBarIRow,4,1)); } void CDLG_Options::OnTOOLBAR5() { ExecuteAction(GetMenuAction(hCurButtonsBarIRow,5,1)); } void CDLG_Options::OnTOOLBAR6() { ExecuteAction(GetMenuAction(hCurButtonsBarIRow,6,1)); } void CDLG_Options::OnAction2() { if(!hCurButtonsBarIRow){ return; } CMenu menu; menu.CreatePopupMenu(); int i=1; COptionAction* act=NULL; CArray<CBitmap*,CBitmap*> bmpArr; while((act=GetMenuAction(hCurButtonsBarIRow,i,0))!=NULL){ CBitmap* bp=BitmapFromIcon(act->lIcon?m_OptionsListImages.ExtractIcon(act->lIcon):0); AddMenuString(&menu,i,act->sDsc,bp); bmpArr.Add(bp); i++; } // Показываем меню CRect rt; GetDlgItem(ID_FOLDERACTIONS2)->GetWindowRect(&rt); DWORD dwRetCode=TrackPopupMenu(menu.GetSafeHmenu(), TPM_RETURNCMD|TPM_NONOTIFY|TPM_RIGHTBUTTON, rt.right, rt.top, 0, this->GetSafeHwnd(), NULL); for(int i2=0;i2<bmpArr.GetSize();i2++){ if(bmpArr[i2]){ delete bmpArr[i2]; } } if(dwRetCode>0){ COptionAction* act=GetMenuAction(hCurButtonsBarIRow,dwRetCode,0); FP_OPTIONACTION fp = act->function; if(fp){ (*fp)((HIROW)act->functionParam,this); } } } CString& getOptionsDefaultFind() { static CString sTextOrig; return sTextOrig; } void CDLG_Options::OnFind() { CString sTextOrig=getOptionsDefaultFind(); GetDlgItem(IDC_EDIT_FIND)->GetWindowText(sTextOrig); getOptionsDefaultFind()=sTextOrig; if(bShowFind>=2){ if(fpExternalSearch){ if(!(*fpExternalSearch)(_l("Type option name to find it"),sTextOrig,this)){ return; } } } CString sText=UnifyString(sTextOrig); if(sText==""){ AfxMessageBox(_l("Type single word from option title or description first to quickly move to corresponding section")); return; } GetDlgItem(IDC_EDIT_FIND)->EnableWindow(FALSE); static CString sPrevSearch=""; static HIROW hPrevSearch1=0; if(sText!=sPrevSearch){ hPrevSearch1=0; } BOOL bCanStop=0; if(hPrevSearch1==0){ bCanStop=1; } BOOL bRes=0; sPrevSearch=sText; {// Part 1 - LPane POSITION pos=m_LList.GetStartPosition(); while(pos){ HIROW hLPane=m_LList.GetNextAssoc(pos); CString sKey=UnifyString(m_LList.GetIItemText(hLPane,0)); if(sKey.Find(sText)!=-1){ if(bCanStop){ bRes=1; hPrevSearch1=hLPane; MoveGlobalFocus(hLPane); GetDlgItem(IDC_EDIT_FIND)->EnableWindow(TRUE); return; }else if(hPrevSearch1==hLPane){ bCanStop=1; } } } } {// Part 2 - RPane POSITION pos=m_OptionsList.GetStartPosition(); while(pos){ HIROW hRPane=m_OptionsList.GetNextAssoc(pos); CString sKey=UnifyString(m_OptionsList.GetIItemText(hRPane,0)); CString sKey2=UnifyString(m_OptionsList.GetIItemText(hRPane,1)); if(sKey.Find(sText)!=-1 || sKey2.Find(sText)!=-1){ HIROW hLPane=GetAliasHIROW(hRPane); while(hLPane==0){ hRPane=m_OptionsList.GetParentIRow(hRPane); hLPane=GetAliasHIROW(hRPane); } if(hLPane!=0){ if(bCanStop){ bRes=1; hPrevSearch1=hLPane; MoveGlobalFocus(hLPane); GetDlgItem(IDC_EDIT_FIND)->EnableWindow(TRUE); return; }else if(hPrevSearch1==hLPane){ bCanStop=1; } } } } } // Ниче не нашли, бум сначала sPrevSearch=""; GetDlgItem(IDC_EDIT_FIND)->EnableWindow(TRUE); Sizer.ApplyLayout(TRUE); if(!bRes){ AfxMessageBox(_l("Sorry, nothing familiar found! Try to reformulate the query")); } return; }
[ "wplabs@3fb49600-69e0-11de-a8c1-9da277d31688" ]
[ [ [ 1, 2935 ] ] ]
d944ef2c7c176e9c8d25e635f1c236e2bf996478
b4d726a0321649f907923cc57323942a1e45915b
/CODE/GRAPHICS/GRBATCH.CPP
922867663599d0de5f335c440de3f87f2c5e382f
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
2,918
cpp
/* * Code created by Thomas Whittaker (RT) for a Freespace 2 source code project * * You may not sell or otherwise commercially exploit the source or things you * created based on the source. * */ #include "globalincs/pstypes.h" #include "graphics/grbatch.h" #include "graphics/2d.h" #include "cmdline/cmdline.h" typedef struct { int start, length; int flags; int bitmap; } BatchNode; const int BATCH_MAX_VERTEX = 500; const int BATCH_MAX = 50; vertex *Batch_vertex_array = NULL; BatchNode *Batch_array = NULL; bool Batch_in_process = false; int Batch_current = 0; int Batch_vertex_current = 0; bool batch_init() { if(!Cmdline_batch_3dunlit) return true; Batch_vertex_array = (vertex *) malloc(sizeof(vertex) * BATCH_MAX_VERTEX); Batch_array = (BatchNode *) malloc(sizeof(vertex) * BATCH_MAX); return (Batch_array != 0); } void batch_deinit() { if(!Cmdline_batch_3dunlit) return; if(Batch_array) free(Batch_array); } void batch_start() { Batch_in_process = true; Batch_current = 0; Batch_vertex_current = 0; } void batch_end() { Batch_in_process = false; } void batch_render() { if(!Cmdline_batch_3dunlit) return; if(Batch_current == 0) return; // Sort // Batch up again // Send to renderer for(int i = 0; i < Batch_current; i++) { vertex *vlist = &Batch_vertex_array[Batch_array[i].start]; gr_set_bitmap(Batch_array[i].bitmap); gr_tmapper_batch_3d_unlit(Batch_array[i].length, vlist, Batch_array[i].flags); } Batch_current = 0; Batch_vertex_current = 0; } vertex *batch_get_block(int num_verts, int flags) { if(!Cmdline_batch_3dunlit) return NULL; if(Batch_vertex_array == NULL || Batch_array == NULL) { Assert(0); return NULL; } //int vcurrent = 0; // We've run out of vertex slots! if(num_verts >= (BATCH_MAX_VERTEX - Batch_vertex_current)) { batch_render(); } // Not the first batch if(Batch_current > 0) { int last_batch = Batch_current - 1; // Can add to current batch if( Batch_array[last_batch].flags == flags && Batch_array[last_batch].bitmap == gr_screen.current_bitmap) { int pos = Batch_array[last_batch].start + Batch_array[last_batch].length; vertex *block = &Batch_vertex_array[pos]; Batch_array[last_batch].length += num_verts; Batch_vertex_current += num_verts; return block; } } // We've run out of batch slots! if(Batch_current >= BATCH_MAX) { batch_render(); } // Make a new batch Batch_array[Batch_current].flags = flags; Batch_array[Batch_current].start = Batch_vertex_current; Batch_array[Batch_current].length = num_verts; Batch_array[Batch_current].bitmap = gr_screen.current_bitmap; vertex *block = &Batch_vertex_array[Batch_array[Batch_current].start]; Batch_current++; Batch_vertex_current += num_verts; return block; }
[ [ [ 1, 130 ] ] ]
1e01053a7e9223a54f09079f78306cd1d9e23eab
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/DemoPlayer/DisplayRect.cpp
65cca6d07cfedf0da914d46d4de0de04ef2f4f9f
[]
no_license
080278/dvrmd-filter
176f4406dbb437fb5e67159b6cdce8c0f48fe0ca
b9461f3bf4a07b4c16e337e9c1d5683193498227
refs/heads/master
2016-09-10T21:14:44.669128
2011-10-17T09:18:09
2011-10-17T09:18:09
32,274,136
0
0
null
null
null
null
GB18030
C++
false
false
15,440
cpp
// DisplayRect.cpp : implementation file // #include "stdafx.h" #include "player.h" #include "PlayerDlg.h" #include "DisplayRect.h" #include <stdio.h> void RunInfo111(char *szFormat, ...) { char szInfo[512]; va_list ArgumentList; va_start(ArgumentList, szFormat); vsprintf(szInfo, szFormat, ArgumentList); va_end(ArgumentList); OutputDebugString(szInfo); } extern LONG m_lPort; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDisplayRect dialog CDisplayRect::CDisplayRect(CWnd* pParent /*=NULL*/) : CDialog(CDisplayRect::IDD, pParent) { //{{AFX_DATA_INIT(CDisplayRect) m_nZoom = 100; //}}AFX_DATA_INIT m_pParent = pParent; m_FocusRect.iZoom = 100; m_FocusRect.iClientHeight = 288; m_FocusRect.iClientWidth = 352; m_FocusRect.stCenterPoint.x = 288/2; m_FocusRect.stCenterPoint.y = 352/2; m_rcRect.left = 0; m_rcRect.bottom = 288; m_rcRect.right = 352; m_rcRect.top = 0; m_bValid = FALSE; m_state = State_Set; } void CDisplayRect::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDisplayRect) DDX_Control(pDX, IDC_SLIDER1, m_CtrlZoom); DDX_Text(pDX, IDC_EDIT_SIZE, m_nZoom); DDV_MinMaxUInt(pDX, m_nZoom, 100, 1100); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDisplayRect, CDialog) //{{AFX_MSG_MAP(CDisplayRect) ON_BN_CLICKED(IDC_DISPLAY, OnDisplay) ON_WM_MOVE() ON_WM_PAINT() ON_WM_SIZE() ON_WM_GETMINMAXINFO() ON_WM_HSCROLL() ON_WM_MOUSEMOVE() ON_WM_LBUTTONDOWN() ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDisplayRect message handlers void CDisplayRect::OnOK() { // TODO: Add extra validation here if(m_pParent) { if (m_state == State_Set) { Enable(FALSE); m_pParent->PostMessage(WM_DISPLAY_OK, 0, 0); } else { Enable(TRUE); m_pParent->PostMessage(WM_DISPLAY_OK, 1, 0); } } else { CDialog::OnOK(); } } void CDisplayRect::Enable(BOOL bEnable) { if (bEnable) { GetDlgItem(IDC_SLIDER1)->EnableWindow(TRUE); GetDlgItem(IDOK)->SetWindowText("Play"); GetDlgItem(IDC_DISPLAY)->EnableWindow(TRUE); m_state = State_Set; } else { GetDlgItem(IDC_SLIDER1)->EnableWindow(FALSE); GetDlgItem(IDOK)->SetWindowText("Set"); GetDlgItem(IDC_DISPLAY)->EnableWindow(FALSE); m_state = State_Play; } } void CDisplayRect::OnDisplay() { // TODO: Add your control notification handler code here m_FocusRect.iZoom = 100; m_nZoom = m_FocusRect.iZoom; UpdateData(FALSE); SetDisplayRegion(); m_CtrlZoom.SetPos(0); } void CDisplayRect::SortCtrls() { if( !(GetStyle() & WS_SIZEBOX) ) { return; } CRect rcClient; RECT rcControl; GetClientRect(&rcClient); int nTempWid = rcClient.Width() - 4; int nTempHei = rcClient.Height() - 85; if (nTempWid < 0 || nTempHei < 0) { return; } if (nTempWid * m_nVideoHeight > nTempHei * m_nVideoWidth) { m_FocusRect.stCenterPoint.x = m_StandardCenterPoint.x * nTempHei/m_nVideoHeight; m_FocusRect.stCenterPoint.y = m_StandardCenterPoint.y * nTempHei/m_nVideoHeight; TRACE("m_StandardPOint.y = %d", m_StandardCenterPoint.y); m_FocusRect.iClientWidth = m_nVideoWidth*nTempHei/m_nVideoHeight; m_FocusRect.iClientHeight = nTempHei; } else { m_FocusRect.stCenterPoint.x = m_StandardCenterPoint.x * nTempWid/m_nVideoWidth; m_FocusRect.stCenterPoint.y = m_StandardCenterPoint.y * nTempWid/m_nVideoWidth; m_FocusRect.iClientHeight = m_nVideoHeight * nTempWid/m_nVideoWidth; m_FocusRect.iClientWidth = nTempWid; } GetDlgItem(IDC_DISWND)->MoveWindow((rcClient.Width()-m_FocusRect.iClientWidth)/2, (rcClient.Height()-80-m_FocusRect.iClientHeight)/2, m_FocusRect.iClientWidth, m_FocusRect.iClientHeight, TRUE); DWORD x = (rcClient.Width()-m_FocusRect.iClientWidth)/2; DWORD y = rcClient.Height() - 70; GetDlgItem(IDC_STATIC_SIZE)->MoveWindow(x, y, 40, 20, TRUE); x += 40; GetDlgItem(IDC_EDIT_SIZE)->MoveWindow(x, y, 30, 15, TRUE); x += 30; GetDlgItem(IDC_STATIC_PST)->MoveWindow(x, y, 30, 20, TRUE); x += 50 + nTempWid/20; GetDlgItem(IDC_STATIC_MINUS)->MoveWindow(x, y, 16, 16, TRUE); x += 20; GetDlgItem(IDC_SLIDER1)->MoveWindow(x, y, 90, 20, TRUE ); x += 90; GetDlgItem(IDC_STATIC_PLUS)->MoveWindow(x, y, 16, 16, TRUE); x = (rcClient.Width()-m_FocusRect.iClientWidth)/2+5; y += 30; GetDlgItem(IDOK)->MoveWindow(x, y, 70, 20, TRUE); x += 125+nTempWid/20;; GetDlgItem(IDC_DISPLAY)->MoveWindow(x, y, 70, 20, TRUE); rcControl.left = (rcClient.Width()-m_FocusRect.iClientWidth)/2; rcControl.right = x +200; rcControl.top = rcClient.Height() - 70; rcControl.bottom = y + 25; InvalidateRect(&rcControl); } void CDisplayRect::DisplayRect(WPARAM /*wParam*/, LPARAM /*lParam*/) { // CRect * rcRect = (CRect*)lParam; UpdateData(FALSE); } void CDisplayRect::InitShow() { SortCtrls(); NAME(PlayM4_SetDisplayRegion)(m_lPort, 1, &m_rcRect, GetDlgItem(IDC_DISWND)->m_hWnd, TRUE); NAME(PlayM4_RefreshPlayEx)(m_lPort, 1); } BOOL CDisplayRect::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here m_dwScreenWidth = GetSystemMetrics(SM_CXSCREEN); m_dwScreenHeight = GetSystemMetrics(SM_CYSCREEN); m_dwOldDeviceNum = 0; m_CtrlZoom.SetRange(0, 1000); m_CtrlZoom.SetPos(m_FocusRect.iZoom - 100); m_bValid = TRUE; m_state = State_Set; return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } BOOL CDisplayRect::SetDevice(UINT nSeq) { BOOL bFunctionOK = FALSE; #if (WINVER > 0x0400) DWORD nVal = NAME(PlayM4_GetDDrawDeviceTotalNums)(); if(nVal >= 1) { if(NAME(PlayM4_SetDDrawDeviceEx)(m_lPort, 1, nSeq + 1)) { bFunctionOK = TRUE; } } #endif return bFunctionOK; } BOOL CDisplayRect::SetResolution(int nHei, int nWid) { //设置图像客户区默认大小 m_FocusRect.iClientWidth = 352; m_FocusRect.iClientHeight = nHei*352/nWid; m_nVideoWidth = nWid; m_nVideoHeight = nHei; m_rcRect.right = nWid; m_rcRect.bottom = nHei; m_FocusRect.stCenterPoint.x = m_FocusRect.iClientWidth/2; m_FocusRect.stCenterPoint.y = m_FocusRect.iClientHeight/2; m_StandardCenterPoint.x = m_FocusRect.stCenterPoint.x; m_StandardCenterPoint.y = m_FocusRect.stCenterPoint.y; m_FocusRect.iZoom = 100; m_nZoom = 100; return TRUE; } void CDisplayRect::OnMove(int x, int y) { CDialog::OnMove(x, y); // TODO: Add your message handler code here GetWindowRect(&m_rcWindow); DWORD dwNewDeviceNum; if(m_rcWindow.left < 0) { return; } if( (DWORD)m_rcWindow.right + (DWORD)m_rcWindow.left > 2 * m_dwScreenWidth ) { if( (DWORD)m_rcWindow.top + (DWORD)m_rcWindow.bottom > 2 * m_dwScreenHeight) { dwNewDeviceNum = 3; } else { dwNewDeviceNum = 1; } } else { if( (DWORD)m_rcWindow.top + (DWORD)m_rcWindow.bottom > 2 * m_dwScreenHeight) { dwNewDeviceNum = 2; } else { dwNewDeviceNum = 0; } } if(dwNewDeviceNum != m_dwOldDeviceNum) { if(SetDevice(dwNewDeviceNum)) { m_dwOldDeviceNum = dwNewDeviceNum; } } } void CDisplayRect::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: Add your message handler code here UpdateWindow(); NAME(PlayM4_RefreshPlayEx)(m_lPort, 1); DrawRectangle(); // Do not call CDialog::OnPaint() for painting messages } void CDisplayRect::DrawRectangle() { if (m_state == State_Play) { return; } RECT DisRect; CBrush brush2(RGB(255,0,0)); CDC* pDC = GetDlgItem(IDC_DISWND)->GetDC(); GetFocusRectangle(DisRect); pDC->FrameRect(&DisRect, &brush2); } void CDisplayRect::GetFocusRectangle(RECT& DisRect) { int iWidth, iHeight; CRect VideoRect; GetDlgItem(IDC_DISWND)->GetClientRect(VideoRect); iWidth = m_FocusRect.iClientWidth*100/m_FocusRect.iZoom; iHeight = m_FocusRect.iClientHeight*100/m_FocusRect.iZoom; DisRect.left = m_FocusRect.stCenterPoint.x + VideoRect.left - iWidth/2; DisRect.right = DisRect.left + iWidth; DisRect.top = VideoRect.top + m_FocusRect.stCenterPoint.y - iHeight/2; DisRect.bottom = DisRect.top + iHeight; if (DisRect.bottom > VideoRect.bottom) { DisRect.top -= (DisRect.bottom - VideoRect.bottom); m_FocusRect.stCenterPoint.y -= (DisRect.bottom - VideoRect.bottom); DisRect.bottom = VideoRect.bottom; } if (DisRect.right > VideoRect.right) { DisRect.left -= (DisRect.right - VideoRect.right); m_FocusRect.stCenterPoint.x -= (DisRect.right - VideoRect.right); DisRect.right = VideoRect.right; } if (DisRect.top < VideoRect.top) { DisRect.bottom = VideoRect.top + iHeight; DisRect.top = VideoRect.top; m_FocusRect.stCenterPoint.y = VideoRect.top + iHeight/2; } if (DisRect.left < VideoRect.left) { DisRect.right = VideoRect.left + iWidth; DisRect.left = VideoRect.left; m_FocusRect.stCenterPoint.x = VideoRect.left + iWidth/2; } // m_StandardCenterPoint.x = m_FocusRect.CenterPoint.x * m_nVideoWidth/VideoRect.Width(); // m_StandardCenterPoint.y = m_FocusRect.CenterPoint.y * m_nVideoHeight/VideoRect.Height(); } void CDisplayRect::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); // TODO: Add your message handler code here if (GetDlgItem(IDC_DISWND)->GetSafeHwnd()) { SortCtrls(); } } void CDisplayRect::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { // TODO: Add your message handler code here and/or call default lpMMI->ptMinTrackSize.x = 280; lpMMI->ptMinTrackSize.y = 350; // CDialog::OnGetMinMaxInfo(lpMMI); } void CDisplayRect::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // Get the current position of scroll box. int curpos = m_CtrlZoom.GetPos(); m_FocusRect.iZoom = 100 + curpos; m_nZoom = m_FocusRect.iZoom; UpdateData(FALSE); SetDisplayRegion(); CDialog::OnHScroll(nSBCode, nPos, pScrollBar); } void CDisplayRect::OnMouseMove(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if (m_state == State_Play) { return; } POINT VideoPoint; POINT Point1, Point2; CRect CRctFocus; CRect VideoRect; GetFocusRectangle(CRctFocus); VideoPoint.x = point.x; VideoPoint.y = point.y; ClientToScreen(&VideoPoint); if (MK_LBUTTON == nFlags) { if (PtInFocusRect(VideoPoint)) { VideoPoint.x -= m_FocusPoint.x; VideoPoint.y -= m_FocusPoint.y; m_FocusPoint = point; ClientToScreen(&m_FocusPoint); m_FocusRect.stCenterPoint.x += VideoPoint.x; m_FocusRect.stCenterPoint.y += VideoPoint.y; CRctFocus += VideoPoint; GetDlgItem(IDC_DISWND)->GetClientRect(VideoRect); Point1 = CRctFocus.TopLeft(); Point2 = VideoRect.TopLeft(); if (Point1.x - Point2.x < 0) { m_FocusRect.stCenterPoint.x += Point2.x - Point1.x; } if (Point1.y - Point2.y < 0) { m_FocusRect.stCenterPoint.y += Point2.y - Point1.y; } Point1 = CRctFocus.BottomRight(); Point2 = VideoRect.BottomRight(); if (Point1.x - Point2.x > 0) { m_FocusRect.stCenterPoint.x -= (Point1.x - Point2.x); } if (Point1.y - Point2.y > 0) { m_FocusRect.stCenterPoint.y -= (Point1.y - Point2.y); } m_StandardCenterPoint.x = m_FocusRect.stCenterPoint.x * m_nVideoWidth/m_FocusRect.iClientWidth; m_StandardCenterPoint.y = m_FocusRect.stCenterPoint.y * m_nVideoHeight/m_FocusRect.iClientHeight; SetDisplayRegion(); } } CDialog::OnMouseMove(nFlags, point); } BOOL CDisplayRect::PtInFocusRect(POINT Point) { RECT FocusRect; GetFocusRectangle(FocusRect); GetDlgItem(IDC_DISWND)->ClientToScreen(&FocusRect); return PtInRect(&FocusRect, Point); } BOOL CDisplayRect::PtInVideoRect(POINT Point) { RECT VideoRct; GetDlgItem(IDC_DISWND)->GetWindowRect(&VideoRct); return PtInRect(&VideoRct, Point); } void CDisplayRect::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if (m_state == State_Play) { return; } CRect FocusRect, VideoRect; POINT ClientPoint; ClientPoint.x = point.x; ClientPoint.y = point.y; ClientToScreen(&ClientPoint); if (PtInFocusRect(ClientPoint)) { m_FocusPoint = ClientPoint; } else { if (PtInVideoRect(ClientPoint)) { GetDlgItem(IDC_DISWND)->ScreenToClient(&ClientPoint); m_FocusRect.stCenterPoint.x = ClientPoint.x; m_FocusRect.stCenterPoint.y = ClientPoint.y; GetFocusRectangle(FocusRect); GetDlgItem(IDC_DISWND)->GetClientRect(VideoRect); if (ClientPoint.x + (FocusRect.Width())/2 >= VideoRect.right) { m_FocusRect.stCenterPoint.x = VideoRect.Width() - (FocusRect.Width())/2; } if (ClientPoint.y + (FocusRect.Height())/2 >= VideoRect.bottom) { m_FocusRect.stCenterPoint.y = VideoRect.Height() - (FocusRect.Height())/2; } if (ClientPoint.x < (FocusRect.Width())/2) { m_FocusRect.stCenterPoint.x = (FocusRect.Width())/2; } if (ClientPoint.y < (FocusRect.Height())/2) { m_FocusRect.stCenterPoint.y = (FocusRect.Height())/2; } m_StandardCenterPoint.x = m_FocusRect.stCenterPoint.x * m_nVideoWidth/m_FocusRect.iClientWidth; m_StandardCenterPoint.y = m_FocusRect.stCenterPoint.y * m_nVideoHeight/m_FocusRect.iClientHeight; } SetDisplayRegion(); } CDialog::OnLButtonDown(nFlags, point); } void CDisplayRect::SetDisplayRegion() { UpdateWindow(); NAME(PlayM4_RefreshPlayEx)(m_lPort, 1); DrawRectangle(); RECT RectFocus, RectDisplay; POINT stCenterPoint; GetFocusRectangle(RectFocus); stCenterPoint.x = m_FocusRect.stCenterPoint.x * m_nVideoWidth/m_FocusRect.iClientWidth; stCenterPoint.y = m_FocusRect.stCenterPoint.y * m_nVideoHeight/m_FocusRect.iClientHeight; RectDisplay.left = stCenterPoint.x - (RectFocus.right - RectFocus.left)/2 * m_nVideoWidth/m_FocusRect.iClientWidth; RectDisplay.right = RectDisplay.left + (RectFocus.right - RectFocus.left) * m_nVideoWidth/m_FocusRect.iClientWidth; RectDisplay.top = stCenterPoint.y - (RectFocus.bottom - RectFocus.top)/2 * m_nVideoHeight/m_FocusRect.iClientHeight; RectDisplay.bottom = RectDisplay.top + (RectFocus.bottom - RectFocus.top) * m_nVideoHeight/m_FocusRect.iClientHeight; ((CPlayerDlg*)m_pParent)->SetDisplayRegion(RectDisplay); // if (m_nZoom == 100) // { // RectDisplay.left = 0; // RectDisplay.right = m_nVideoWidth; // RectDisplay.top = 0; // RectDisplay.bottom = m_nVideoHeight; // // ((CPlayerDlg*)m_pParent)->SetDisplayRegion(RectDisplay); // } // else // { // ((CPlayerDlg*)m_pParent)->SetDisplayRegion(RectDisplay); // } // } void CDisplayRect::OnDestroy() { CDialog::OnDestroy(); // TODO: Add your message handler code here NAME(PlayM4_SetDisplayRegion)(m_lPort, 1, &m_rcRect, NULL, FALSE); m_bValid = FALSE; }
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 616 ] ] ]
2865aa3f999210e45ff93d9687fca348fbf19657
305d82f4e4a75f9366316ef1c1574982342cb342
/Person.cpp
217acbb61fbd4b892f12a7b4446d5cb3da278078
[]
no_license
jabbilabbi/cmpt212-spring10
a260e8eba3a8899ae47220e6e59be5e355781d30
64a7490a7602a32892f23e89f5e8ca270a83fe3b
refs/heads/master
2021-01-01T19:06:28.560193
2010-04-16T11:49:46
2010-04-16T11:49:46
32,115,006
0
0
null
null
null
null
UTF-8
C++
false
false
2,157
cpp
/* Biographical Dictionary - CMPT 212 Final Project - SFU Spring 2010 Alex Antonio [email protected] Jeff Harris [email protected] */ #include "Person.h" Person::Person(void) { } Person::~Person(void) { } void Person::setFirstName(string newName) { firstName = newName; } string Person::getFirstName() { return(firstName); } void Person::setLastName(string newName) { lastName = newName; } string Person::getLastName() { return(lastName); } void Person::setDate(int newDate) { date = newDate; } int Person::getDate() { return(date); } void Person::setNationality(string newNationality) { nationality = newNationality; } string Person::getNationality() { return(nationality); } void Person::setTitle(string newTitle) { title = newTitle; } string Person::getTitle() { return(title); } void Person::setBiography(string newBiography) { biography = newBiography; } string Person::getBiography() { return(biography); } string Person::display() { /*Returns a string formatted in a easy to read format, ie: "Winston Churchill (1874). British Prime Minister. Leader of Great Britan during....." */ char* year = new char(4*sizeof(char)); itoa(date, year, 10); //Convert the date (int type) to string. return (firstName+" "+lastName+" ("+year+"). "+nationality+" "+title+". "+biography+"."); } bool Person::operator<(const Person & a) const { if(strcmp(lastName.c_str(), a.lastName.c_str()) < 0) return true; else if(strcmp(lastName.c_str(), a.lastName.c_str()) > 0) return false; else if(strcmp(firstName.c_str(), a.firstName.c_str()) < 0) //If last names are equal, check first name return true; else return false; } bool Person::operator>(const Person & a) const { if(strcmp(lastName.c_str(), a.lastName.c_str()) > 0) return true; else if(strcmp(lastName.c_str(), a.lastName.c_str()) < 0) return false; else if(strcmp(firstName.c_str(), a.firstName.c_str()) > 0) //If last names are equal, check first name return true; else return false; } bool Person::author(){ return false; }
[ "jeffharris88@accf1826-6565-04f0-df9b-893c0ca74f04" ]
[ [ [ 1, 112 ] ] ]
e84b9b7dbad2e2d9a9a7a12740d7422805cc8c0e
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.6/cbear.berlios.de/windows/com/ulonglong.hpp
0345491b541d68f25d1dc1e5d1ee8e7217902803
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
1,479
hpp
/* The MIT License Copyright (c) 2005 C Bear (http://cbear.berlios.de) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CBEAR_BERLIOS_DE_WINDOWS_COM_ULONGLONG_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_COM_ULONGLONG_HPP_INCLUDED #include <cbear.berlios.de/windows/com/traits.hpp> namespace cbear_berlios_de { namespace windows { namespace com { CBEAR_BERLIOS_DE_WINDOWS_COM_DECLARE_DEFAULT_TRAITS(ulonglong_t, ::VT_UI8); } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 41 ] ] ]
c5566b53b060e4679fc1c5fa135d207fe282f29f
e53e3f6fac0340ae0435c8e60d15d763704ef7ec
/WDL/wingui/virtwnd-iaccessible.cpp
9bf6ac8286a64a8ee77a2d1c22bace0ba30805e2
[]
no_license
b-vesco/vfx-wdl
906a69f647938b60387d8966f232a03ce5b87e5f
ee644f752e2174be2fefe43275aec2979f0baaec
refs/heads/master
2020-05-30T21:37:06.356326
2011-01-04T08:54:45
2011-01-04T08:54:45
848,136
2
0
null
null
null
null
UTF-8
C++
false
false
21,875
cpp
#if defined(_WIN32) && !defined(WDL_DISABLE_IACCESSIBLE) #include <windows.h> #include <oleacc.h> #include <winable.h> #include "virtwnd-controls.h" #include "../wdltypes.h" static BSTR SysAllocStringUTF8(const char *str) { WCHAR tmp[1024]; int slen = strlen(str)+1; WCHAR *wstr = slen < 1000 ? tmp : (WCHAR*)malloc(2*slen+32); wstr[0]=0; int a=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,str,slen,wstr, slen<1000?1024:slen+16); if (!a) { wstr[0]=0; a=MultiByteToWideChar(CP_ACP,MB_ERR_INVALID_CHARS,str,slen,wstr,slen<1000?1024:slen+16); } BSTR ret = SysAllocString(wstr); if (wstr != tmp) free(wstr); return ret; } class CVWndAccessible; class VWndBridge : public WDL_VWnd_IAccessibleBridge { public: VWndBridge() { } ~VWndBridge() { } virtual void Release() { vwnd=0; } CVWndAccessible *par; WDL_VWnd *vwnd; }; static IAccessible *GetVWndIAccessible(WDL_VWnd *vwnd); static int g_freelist_acc_size; static CVWndAccessible *g_freelist_acc; static HRESULT (WINAPI *__CreateStdAccessibleObject)( HWND hwnd, LONG idObject, REFIID riidInterface, void **ppvObject ); static int allocated_cnt; class CVWndAccessible : public IAccessible { public: CVWndAccessible(WDL_VWnd *vwnd) { m_br.vwnd=vwnd; m_br.par = this; m_refCnt = 1; allocated_cnt++; } ~CVWndAccessible() { allocated_cnt--; //char buf[512]; //sprintf(buf,"allocated total = %d\n",allocated_cnt); // OutputDebugString(buf); } //IUnknown interface STDMETHOD_(HRESULT, QueryInterface)(REFIID riid , void **ppObj) { if (IsEqualIID(riid, IID_IUnknown)) { *ppObj = this; } else if (IsEqualIID(riid, IID_IAccessible)) { *ppObj = this; } else if (IsEqualIID(riid, IID_IDispatch)) { *ppObj = this; } else { *ppObj = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; } STDMETHOD_(ULONG, AddRef)() { return InterlockedIncrement(&m_refCnt); } STDMETHOD_(ULONG, Release)() { LONG nRefCount=0; nRefCount=InterlockedDecrement(&m_refCnt) ; if (nRefCount == 0) { if (m_br.vwnd) { m_br.vwnd->SetAccessibilityBridge(NULL); m_br.vwnd=0; } if (g_freelist_acc_size<2048) { g_freelist_acc_size++; _freelist_next = g_freelist_acc; g_freelist_acc = this; } else { delete this; } } return nRefCount; } //IDispatch STDMETHOD(GetTypeInfoCount)(unsigned int FAR* pctinfo ) { *pctinfo=0; return NOERROR; } STDMETHOD(GetTypeInfo)(unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo) { return S_OK; } STDMETHOD( GetIDsOfNames)( REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId ) { *rgDispId=0; return E_OUTOFMEMORY; } STDMETHOD(Invoke)( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr ) { return DISP_E_BADPARAMCOUNT; } // IAccessible STDMETHOD(get_accParent)(THIS_ IDispatch * FAR* ppdispParent) { WDL_VWnd *par=m_br.vwnd ? m_br.vwnd->GetParent() : NULL; if (par) { *ppdispParent = GetVWndIAccessible(par); if (*ppdispParent) return S_OK; } *ppdispParent = NULL; return S_FALSE; } #define ISVWNDLIST(x) ((x)&&!strcmp((x)->GetType(),"vwnd_listbox")) STDMETHOD(get_accChildCount)(THIS_ long FAR* pChildCount) { *pChildCount = m_br.vwnd ? m_br.vwnd->GetNumChildren() : 0; HWND realparent; if (__CreateStdAccessibleObject && m_br.vwnd && !m_br.vwnd->GetParent() && (realparent=m_br.vwnd->GetRealParent())) { HWND h=GetWindow(realparent,GW_CHILD); while (h) { (*pChildCount) += 1; h=GetWindow(h,GW_HWNDNEXT); } } if (ISVWNDLIST(m_br.vwnd)) { WDL_VirtualListBox *list=(WDL_VirtualListBox*)m_br.vwnd; int c = 0; if (list->m_GetItemInfo) c=list->m_GetItemInfo(list,-1,NULL,0,NULL,NULL); if(c<0)c=0; *pChildCount += c+2; } return S_OK; } STDMETHOD(get_accChild)(THIS_ VARIANT varChildIndex, IDispatch * FAR* ppdispChild) { *ppdispChild=0; if (!m_br.vwnd || varChildIndex.vt != VT_I4) return E_INVALIDARG; WDL_VWnd *vw = m_br.vwnd->EnumChildren(varChildIndex.lVal-1); if (vw) { *ppdispChild=GetVWndIAccessible(vw); if (*ppdispChild) return S_OK; } int index = varChildIndex.lVal-1 - m_br.vwnd->GetNumChildren(); if (ISVWNDLIST(m_br.vwnd)) { WDL_VirtualListBox *list=(WDL_VirtualListBox*)m_br.vwnd; int c = 0; if (list->m_GetItemInfo) c=list->m_GetItemInfo(list,-1,NULL,0,NULL,NULL); if(c<0)c=0; index -= c+2; } HWND realparent; if (index >= 0 && __CreateStdAccessibleObject && m_br.vwnd && !m_br.vwnd->GetParent() && (realparent=m_br.vwnd->GetRealParent())) { HWND h=GetWindow(realparent,GW_CHILD); while (h) { if (!index) break; index--; h=GetWindow(h,GW_HWNDNEXT); } if (h) { *ppdispChild=0; HRESULT res = __CreateStdAccessibleObject(h,OBJID_CLIENT,IID_IAccessible,(void**)ppdispChild); if (SUCCEEDED(res)) { return S_OK; } } } return S_FALSE; } STDMETHOD(get_accName)(THIS_ VARIANT varChild, BSTR* pszOut) { *pszOut=NULL; if (!m_br.vwnd || varChild.vt != VT_I4) { return E_INVALIDARG; } WDL_VWnd *vw = varChild.lVal == CHILDID_SELF ? m_br.vwnd : m_br.vwnd->EnumChildren(varChild.lVal-1); if (vw) { const char *txt=NULL; const char *ctltype = vw->GetType(); if (!strcmp(ctltype,"vwnd_iconbutton")) txt = ((WDL_VirtualIconButton*)vw)->GetTextLabel(); else if (!strcmp(ctltype,"vwnd_statictext")) txt = ((WDL_VirtualStaticText*)vw)->GetText(); else if (!strcmp(ctltype,"vwnd_combobox")) txt = ((WDL_VirtualComboBox*)vw)->GetItem(((WDL_VirtualComboBox*)vw)->GetCurSel()); const char *p = vw->GetAccessDesc(); if (p && *p && txt && *txt) { char buf[1024]; sprintf(buf,"%.500s %.500s",p,txt); *pszOut= SysAllocStringUTF8(buf); } else if (txt && *txt) { *pszOut= SysAllocStringUTF8(txt); } else if (p && *p) { *pszOut = SysAllocStringUTF8(p); } } else if (ISVWNDLIST(m_br.vwnd)) { WDL_VirtualListBox *list=(WDL_VirtualListBox*)m_br.vwnd; if (list->m_GetItemInfo) { int idx = varChild.lVal-1 - m_br.vwnd->GetNumChildren(); int ni = list->m_GetItemInfo(list,-1,NULL,0,NULL,NULL); char buf[2048]; buf[0]=0; if (idx>=0&&idx<ni) list->m_GetItemInfo(list,idx,buf,512,NULL,NULL); else if (idx==ni||idx==ni+1) { strcpy(buf,idx==ni?"Scroll previous" : "Scroll next"); } // we put this in the desc field instead /*const char *txt1 = list->GetAccessDesc(); if (txt1) { if (buf[0]) strcat(buf," "); lstrcpyn(buf+strlen(buf),txt1,512); }*/ // OutputDebugString(buf); if (buf[0]) *pszOut = SysAllocStringUTF8(buf); } } return S_OK; } STDMETHOD(get_accValue)(THIS_ VARIANT varChild, BSTR* pszValue) { *pszValue=NULL; if (!m_br.vwnd || varChild.vt != VT_I4) { return E_INVALIDARG; } return DISP_E_MEMBERNOTFOUND; } STDMETHOD(get_accDescription)(THIS_ VARIANT varChild, BSTR FAR* pszOut) { *pszOut=NULL; if (!m_br.vwnd || varChild.vt != VT_I4) { return E_INVALIDARG; } WDL_VWnd *vw = varChild.lVal == CHILDID_SELF ? m_br.vwnd : m_br.vwnd->EnumChildren(varChild.lVal-1); if (vw) { char buf[1024]; buf[0]=0; WDL_VWnd *p = vw->GetParent(); if (0) // disabled for now while (p && strlen(buf)<800) { const char *txt= p->GetAccessDesc(); if (txt && *txt) { if (buf[0]) strcat(buf," "); lstrcpyn(buf+strlen(buf),txt,200); } p=p->GetParent(); } if (buf[0]) { *pszOut = SysAllocStringUTF8(buf); return S_OK; } return S_FALSE; } else if (ISVWNDLIST(m_br.vwnd)) { WDL_VirtualListBox *list=(WDL_VirtualListBox*)m_br.vwnd; if (list->m_GetItemInfo) { const char *txt = list->GetAccessDesc(); if (txt) { *pszOut = SysAllocStringUTF8(txt); return S_OK; } } } return E_INVALIDARG; } STDMETHOD(get_accRole)(THIS_ VARIANT varChild, VARIANT *pvarRole) { if (!m_br.vwnd || varChild.vt != VT_I4) { pvarRole->vt = VT_EMPTY; return E_INVALIDARG; } WDL_VWnd *vw = varChild.lVal == CHILDID_SELF ? m_br.vwnd : m_br.vwnd->EnumChildren(varChild.lVal-1); if (!vw && ISVWNDLIST(m_br.vwnd)) { WDL_VirtualListBox *list=(WDL_VirtualListBox*)m_br.vwnd; if (list->m_GetItemInfo) { int idx = varChild.lVal-1 - m_br.vwnd->GetNumChildren(); int ni = list->m_GetItemInfo(list,-1,NULL,0,NULL,NULL); if (idx>=0&&idx<ni) { pvarRole->vt = VT_I4; pvarRole->lVal = ROLE_SYSTEM_LISTITEM; return S_OK; } else if (idx==ni || idx==ni+1) { pvarRole->vt = VT_I4; pvarRole->lVal = ROLE_SYSTEM_PUSHBUTTON; return S_OK; } } } if (!vw) { pvarRole->vt = VT_EMPTY; return E_INVALIDARG; } pvarRole->vt = VT_I4; if (vw->GetNumChildren()) pvarRole->lVal = ROLE_SYSTEM_GROUPING; else { const char *type = vw->GetType(); if (!strcmp(type,"vwnd_iconbutton")) { WDL_VirtualIconButton *vb = (WDL_VirtualIconButton*)vw; if (vb->GetIsButton()) { if (vb->GetCheckState()>=0) pvarRole->lVal = ROLE_SYSTEM_CHECKBUTTON; else pvarRole->lVal = ROLE_SYSTEM_PUSHBUTTON; } else pvarRole->lVal = ROLE_SYSTEM_STATICTEXT; } else if (!strcmp(type,"vwnd_statictext")) pvarRole->lVal = ROLE_SYSTEM_STATICTEXT; else if (!strcmp(type,"vwnd_combobox")) pvarRole->lVal = ROLE_SYSTEM_COMBOBOX; else if (!strcmp(type,"vwnd_slider")) pvarRole->lVal = ROLE_SYSTEM_SLIDER; else if (!strcmp(type,"vwnd_listbox")) pvarRole->lVal = ROLE_SYSTEM_LIST; else pvarRole->lVal=ROLE_SYSTEM_CLIENT; } return S_OK; } STDMETHOD(get_accState)(THIS_ VARIANT varChild, VARIANT *pvarState) { if (!m_br.vwnd || varChild.vt != VT_I4) { pvarState->vt = VT_EMPTY; return E_INVALIDARG; } WDL_VWnd *vw = varChild.lVal == CHILDID_SELF ? m_br.vwnd : m_br.vwnd->EnumChildren(varChild.lVal-1); if (!vw) { if (ISVWNDLIST(m_br.vwnd)) { WDL_VirtualListBox *list=(WDL_VirtualListBox*)m_br.vwnd; if (list->m_GetItemInfo) { int index = varChild.lVal-1 - m_br.vwnd->GetNumChildren(); int c=list->m_GetItemInfo(list,-1,NULL,0,NULL,NULL); if (index>=0&&index<c) { pvarState->vt = VT_I4; pvarState->lVal = 0; RECT r; if (list->GetItemRect(index,&r)) { } else pvarState->lVal|=STATE_SYSTEM_INVISIBLE; return S_OK; } else if (index==c||index==c+1) { pvarState->vt = VT_I4; pvarState->lVal = 0; if (!list->GetScrollButtonRect(index==c+1)) pvarState->lVal |= STATE_SYSTEM_UNAVAILABLE; return S_OK; } } } pvarState->vt = VT_EMPTY; return E_INVALIDARG; } const char *type = vw->GetType(); pvarState->vt = VT_I4; pvarState->lVal = 0; if (!vw->IsVisible()) pvarState->lVal |= STATE_SYSTEM_INVISIBLE; if (!strcmp(type,"vwnd_iconbutton")) { WDL_VirtualIconButton *vb = (WDL_VirtualIconButton*)vw; if (vb->GetIsButton()) { if (vb->GetCheckState()>0) pvarState->lVal |= STATE_SYSTEM_CHECKED; } } return S_OK; } STDMETHOD(get_accHelp)(THIS_ VARIANT varChild, BSTR* pszHelp) { *pszHelp=NULL; if (!m_br.vwnd || varChild.vt != VT_I4) { return E_INVALIDARG; } WDL_VWnd *vw = varChild.lVal == CHILDID_SELF ? m_br.vwnd : m_br.vwnd->EnumChildren(varChild.lVal-1); if (!vw) { return E_INVALIDARG; } return S_FALSE; } STDMETHOD(get_accHelpTopic)(THIS_ BSTR* pszHelpFile, VARIANT varChild, long* pidTopic) { return DISP_E_MEMBERNOTFOUND; } STDMETHOD(get_accKeyboardShortcut)(THIS_ VARIANT varChild, BSTR* pszKeyboardShortcut) { *pszKeyboardShortcut=NULL; if (!m_br.vwnd || varChild.vt != VT_I4) { return E_INVALIDARG; } WDL_VWnd *vw = varChild.lVal == CHILDID_SELF ? m_br.vwnd : m_br.vwnd->EnumChildren(varChild.lVal-1); if (!vw) { return E_INVALIDARG; } return S_FALSE; } STDMETHOD(get_accFocus)(THIS_ VARIANT FAR * pvarFocusChild) { pvarFocusChild->vt= VT_EMPTY; if (!m_br.vwnd) { return S_FALSE; } //return DISP_E_MEMBERNOTFOUND; if (!m_br.vwnd->GetParent() && m_br.vwnd->GetRealParent() && GetFocus()==m_br.vwnd->GetRealParent()) { pvarFocusChild->vt=VT_I4; pvarFocusChild->lVal = CHILDID_SELF; } return S_OK; } STDMETHOD(get_accSelection)(THIS_ VARIANT FAR * pvarSelectedChildren) { pvarSelectedChildren->vt= VT_EMPTY; if (!m_br.vwnd) { return S_FALSE; } return S_OK; } STDMETHOD(get_accDefaultAction)(THIS_ VARIANT varChild, BSTR* pszDefaultAction) { *pszDefaultAction=NULL; if (!m_br.vwnd || varChild.vt != VT_I4) { return E_INVALIDARG; } WDL_VWnd *vw = varChild.lVal == CHILDID_SELF ? m_br.vwnd : m_br.vwnd->EnumChildren(varChild.lVal-1); if (!vw) { return E_INVALIDARG; } return S_FALSE; } STDMETHOD(accSelect)(THIS_ long flagsSelect, VARIANT varChild) { return S_FALSE; } STDMETHOD(accLocation)(THIS_ long* pxLeft, long* pyTop, long* pcxWidth, long* pcyHeight, VARIANT varChild) { *pxLeft=*pyTop=*pcxWidth=*pcyHeight=0; if (!m_br.vwnd || varChild.vt != VT_I4) { return E_INVALIDARG; } WDL_VWnd *vw = varChild.lVal == CHILDID_SELF ? m_br.vwnd : m_br.vwnd->EnumChildren(varChild.lVal-1); if (!vw && ISVWNDLIST(m_br.vwnd)) { WDL_VirtualListBox *list=(WDL_VirtualListBox*)m_br.vwnd; if (list->m_GetItemInfo) { int idx = varChild.lVal-1 - m_br.vwnd->GetNumChildren(); int ni = list->m_GetItemInfo(list,-1,NULL,0,NULL,NULL); if (idx>=0&&idx<ni) { RECT r2={0,0,0,0}; if (list->GetItemRect(idx,&r2)) { HWND h = list->GetRealParent(); RECT r; list->GetPositionInTopVWnd(&r); ClientToScreen(h,(LPPOINT)&r); ClientToScreen(h,((LPPOINT)&r)+1); *pxLeft=r.left+r2.left; *pyTop=r.top+r2.top; *pcxWidth=r2.right-r2.left; *pcyHeight=r2.bottom-r2.top; } else *pxLeft=*pyTop=*pcxWidth=*pcyHeight=0; return S_OK; } else if (idx==ni||idx==ni+1) { RECT *rr = list->GetScrollButtonRect(idx==ni+1); if (rr) { HWND h = list->GetRealParent(); RECT r; list->GetPositionInTopVWnd(&r); ClientToScreen(h,(LPPOINT)&r); ClientToScreen(h,((LPPOINT)&r)+1); *pxLeft=r.left+rr->left; *pyTop=r.top+rr->top; *pcxWidth=rr->right-rr->left; *pcyHeight=rr->bottom-rr->top; } else *pxLeft=*pyTop=*pcxWidth=*pcyHeight=0; return S_OK; } } } if (!vw) return E_INVALIDARG; HWND h = vw->GetRealParent(); if (h) { RECT r; vw->GetPositionInTopVWnd(&r); ClientToScreen(h,(LPPOINT)&r); ClientToScreen(h,((LPPOINT)&r)+1); *pxLeft=r.left; *pyTop=r.top; *pcxWidth=r.right-r.left; *pcyHeight=r.bottom-r.top; } return S_OK; } STDMETHOD(accNavigate)(THIS_ long navDir, VARIANT varStart, VARIANT * pvarEndUpAt) { return DISP_E_MEMBERNOTFOUND; } STDMETHOD(accHitTest)(THIS_ long xLeft, long yTop, VARIANT * pvarChildAtPoint) { pvarChildAtPoint->vt = VT_EMPTY; if (!m_br.vwnd) { return E_INVALIDARG; } HWND h = m_br.vwnd->GetRealParent(); if (!h) return S_FALSE; POINT p={xLeft,yTop}; ScreenToClient(h,&p); if (!m_br.vwnd->GetParent() && __CreateStdAccessibleObject) { HWND hhit = ChildWindowFromPoint(h,p); if (hhit && hhit != h) { pvarChildAtPoint->pdispVal=0; HRESULT res = __CreateStdAccessibleObject(hhit,OBJID_CLIENT,IID_IAccessible,(void**)&pvarChildAtPoint->pdispVal); if (SUCCEEDED(res)) { pvarChildAtPoint->vt = VT_DISPATCH; return S_OK; } } } RECT r; m_br.vwnd->GetPositionInTopVWnd(&r); if (!PtInRect(&r,p)) return S_FALSE; WDL_VWnd *vw = m_br.vwnd->VirtWndFromPoint(p.x-r.left,p.y-r.top,0); if (vw&&vw != m_br.vwnd) { IAccessible *pac = GetVWndIAccessible(vw); if (pac) { pvarChildAtPoint->vt = VT_DISPATCH; pvarChildAtPoint->pdispVal = pac; return S_OK; } } else if (ISVWNDLIST(m_br.vwnd)) { WDL_VirtualListBox *list=(WDL_VirtualListBox*)m_br.vwnd; if (list->m_GetItemInfo) { int c = list->m_GetItemInfo(list,-1,NULL,0,NULL,NULL); if (c<0)c=0; int a= list->IndexFromPt(p.x-r.left,p.y-r.top); if (a>=0 && a<c) { pvarChildAtPoint->vt = VT_I4; pvarChildAtPoint->lVal = 1+list->GetNumChildren()+a;; return S_OK; } else { POINT pp = { p.x-r.left, p.y-r.top}; int x; for(x=0;x<2;x++) { RECT *rr = list->GetScrollButtonRect(!!x); if (rr && PtInRect(rr,pp)) { pvarChildAtPoint->vt = VT_I4; pvarChildAtPoint->lVal = 1+list->GetNumChildren()+c+x;; return S_OK; } } } } } pvarChildAtPoint->vt = VT_I4; pvarChildAtPoint->lVal = CHILDID_SELF; return S_OK; } STDMETHOD(accDoDefaultAction)(THIS_ VARIANT varChild) { return DISP_E_MEMBERNOTFOUND; } STDMETHOD(put_accName)(THIS_ VARIANT varChild, BSTR szName) { return E_NOTIMPL; } STDMETHOD(put_accValue)(THIS_ VARIANT varChild, BSTR pszValue) { return E_NOTIMPL; } VWndBridge m_br; LONG m_refCnt; CVWndAccessible *_freelist_next; }; static IAccessible *GetVWndIAccessible(WDL_VWnd *vwnd) { if (!vwnd) return 0; WDL_VWnd_IAccessibleBridge *br = vwnd->GetAccessibilityBridge(); if (!br) { CVWndAccessible *acc; if (g_freelist_acc) { g_freelist_acc_size--; acc=g_freelist_acc; g_freelist_acc=acc->_freelist_next; acc->m_br.vwnd = vwnd; acc->m_refCnt = 1; } else acc = new CVWndAccessible(vwnd); br = &acc->m_br; vwnd->SetAccessibilityBridge(br); } else ((VWndBridge*)br)->par->AddRef(); return ((VWndBridge*)br)->par; } LRESULT WDL_AccessibilityHandleForVWnd(bool isDialog, HWND hwnd, WDL_VWnd *vw, WPARAM wParam, LPARAM lParam) { if (vw) { if ((DWORD)lParam != (DWORD)OBJID_CLIENT) return 0; static LRESULT (WINAPI *__LresultFromObject)(REFIID riid, WPARAM, LPUNKNOWN); static int init; if (!init) { init=1; HINSTANCE hInst = LoadLibrary("oleacc.dll"); if (hInst) { *(void **)&__LresultFromObject = GetProcAddress(hInst,"LresultFromObject"); *(void **)&__CreateStdAccessibleObject = GetProcAddress(hInst,"CreateStdAccessibleObject"); } } if (!__LresultFromObject) return 0; IAccessible *ac = GetVWndIAccessible(vw); if (!ac) return 0; LRESULT res = __LresultFromObject(IID_IAccessible,wParam,ac); // lresultfromobject retains? ac->Release(); if (isDialog) { SetWindowLongPtr(hwnd,DWLP_MSGRESULT,res); return 1; } return res; } return 0; } #else #ifdef _WIN32 #include <windows.h> #else #include "../swell/swell.h" #endif class WDL_VWnd; LRESULT WDL_AccessibilityHandleForVWnd(bool isDialog, HWND hwnd, WDL_VWnd *vw, WPARAM wParam, LPARAM lParam) { return 0; } #endif
[ [ [ 1, 850 ] ] ]
7528486c78c2e7fc05296714adb17c30e4a3f120
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Scene Estimator 2/ArbiterMessage.h
b417a0239d0f3af330ca753abfb3ddbf581e6dff
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,109
h
#pragma once #include <string> //this file provides the methods that will go from the unmanaged C++ code of the scene estimator to the managed publisher //specifically for the Arbiter communication #ifdef __cplusplus_cli #pragma managed(push,off) #endif #define ARBITER_MAX_PARTITIONS 20 using namespace std; enum PartitionType { PARTITIONTYPE_INVALID = -1, PARTITIONTYPE_LANE = 0, PARTITIONTYPE_INTERCONNECT = 1, PARTITIONTYPE_ZONE = 2 }; struct UnmanagedArbiterPartition { string id; PartitionType partitionType; double confidence; UnmanagedArbiterPartition () {id = "NOID"; partitionType = PARTITIONTYPE_INVALID; confidence = 0;} UnmanagedArbiterPartition(char* id, PartitionType partitionType, double confidence) {this->id = string(id),this->partitionType = partitionType; this->confidence = confidence;} }; struct UnmanagedArbiterPositionMessage { UnmanagedArbiterPositionMessage() { eastMMSE = 0; northMMSE = 0; headingMMSE = 0; isSparseWaypoints = 0; timestamp = -1; numberPartitions = 0; } UnmanagedArbiterPositionMessage(double e, double n, double h, double* ENCovariance, UnmanagedArbiterPartition* partitions, int numberPartitions, double isSparseWaypoints, double timestamp) { eastMMSE = e; northMMSE = n; headingMMSE = h; for (int i=0; i<4; i++) this->ENCovariance[i] = ENCovariance[i]; if (numberPartitions > ARBITER_MAX_PARTITIONS) numberPartitions = ARBITER_MAX_PARTITIONS; for (int i=0; i< numberPartitions; i++) { this->partitions[i] = partitions[i]; } for (int i=numberPartitions; i<ARBITER_MAX_PARTITIONS; i++) { this->partitions[i] = UnmanagedArbiterPartition(); } this->isSparseWaypoints = isSparseWaypoints; this->timestamp = timestamp; this->numberPartitions = numberPartitions; } double timestamp; int numberPartitions; double isSparseWaypoints; double eastMMSE; double northMMSE; double headingMMSE; double ENCovariance[4]; UnmanagedArbiterPartition partitions[ARBITER_MAX_PARTITIONS]; }; #ifdef __cplusplus_cli #pragma managed(pop) #endif
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 71 ] ] ]
5e21b750ad77df2149ba56260ebb7e459f944f17
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvimage/openexr/src/IlmImf/ImfHeader.cpp
0782f6a0c24a99acc8a7810187bfd98a66da65e9
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
24,477
cpp
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic 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. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class Header // //----------------------------------------------------------------------------- #include <ImfHeader.h> #include <ImfStdIO.h> #include <ImfVersion.h> #include <ImfCompressor.h> #include <ImfMisc.h> #include <ImfBoxAttribute.h> #include <ImfChannelListAttribute.h> #include <ImfChromaticitiesAttribute.h> #include <ImfCompressionAttribute.h> #include <ImfDoubleAttribute.h> #include <ImfEnvmapAttribute.h> #include <ImfFloatAttribute.h> #include <ImfIntAttribute.h> #include <ImfKeyCodeAttribute.h> #include <ImfLineOrderAttribute.h> #include <ImfMatrixAttribute.h> #include <ImfOpaqueAttribute.h> #include <ImfPreviewImageAttribute.h> #include <ImfRationalAttribute.h> #include <ImfStringAttribute.h> #include <ImfTileDescriptionAttribute.h> #include <ImfTimeCodeAttribute.h> #include <ImfVecAttribute.h> #include "IlmThreadMutex.h" #include "Iex.h" #include <sstream> #include <stdlib.h> #include <time.h> namespace Imf { using Imath::Box2i; using Imath::V2i; using Imath::V2f; using IlmThread::Mutex; using IlmThread::Lock; namespace { int maxImageWidth = 0; int maxImageHeight = 0; int maxTileWidth = 0; int maxTileHeight = 0; void initialize (Header &header, const Box2i &displayWindow, const Box2i &dataWindow, float pixelAspectRatio, const V2f &screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression) { header.insert ("displayWindow", Box2iAttribute (displayWindow)); header.insert ("dataWindow", Box2iAttribute (dataWindow)); header.insert ("pixelAspectRatio", FloatAttribute (pixelAspectRatio)); header.insert ("screenWindowCenter", V2fAttribute (screenWindowCenter)); header.insert ("screenWindowWidth", FloatAttribute (screenWindowWidth)); header.insert ("lineOrder", LineOrderAttribute (lineOrder)); header.insert ("compression", CompressionAttribute (compression)); header.insert ("channels", ChannelListAttribute ()); } } // namespace Header::Header (int width, int height, float pixelAspectRatio, const V2f &screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression) : _map() { staticInitialize(); Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); initialize (*this, displayWindow, displayWindow, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); } Header::Header (int width, int height, const Box2i &dataWindow, float pixelAspectRatio, const V2f &screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression) : _map() { staticInitialize(); Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); initialize (*this, displayWindow, dataWindow, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); } Header::Header (const Box2i &displayWindow, const Box2i &dataWindow, float pixelAspectRatio, const V2f &screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression) : _map() { staticInitialize(); initialize (*this, displayWindow, dataWindow, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); } Header::Header (const Header &other): _map() { for (AttributeMap::const_iterator i = other._map.begin(); i != other._map.end(); ++i) { insert (*i->first, *i->second); } } Header::~Header () { for (AttributeMap::iterator i = _map.begin(); i != _map.end(); ++i) { delete i->second; } } Header & Header::operator = (const Header &other) { if (this != &other) { for (AttributeMap::iterator i = _map.begin(); i != _map.end(); ++i) { delete i->second; } _map.erase (_map.begin(), _map.end()); for (AttributeMap::const_iterator i = other._map.begin(); i != other._map.end(); ++i) { insert (*i->first, *i->second); } } return *this; } void Header::insert (const char name[], const Attribute &attribute) { if (name[0] == 0) THROW (Iex::ArgExc, "Image attribute name cannot be an empty string."); AttributeMap::iterator i = _map.find (name); if (i == _map.end()) { Attribute *tmp = attribute.copy(); try { _map[name] = tmp; } catch (...) { delete tmp; throw; } } else { if (strcmp (i->second->typeName(), attribute.typeName())) THROW (Iex::TypeExc, "Cannot assign a value of " "type \"" << attribute.typeName() << "\" " "to image attribute \"" << name << "\" of " "type \"" << i->second->typeName() << "\"."); Attribute *tmp = attribute.copy(); delete i->second; i->second = tmp; } } Attribute & Header::operator [] (const char name[]) { AttributeMap::iterator i = _map.find (name); if (i == _map.end()) THROW (Iex::ArgExc, "Cannot find image attribute \"" << name << "\"."); return *i->second; } const Attribute & Header::operator [] (const char name[]) const { AttributeMap::const_iterator i = _map.find (name); if (i == _map.end()) THROW (Iex::ArgExc, "Cannot find image attribute \"" << name << "\"."); return *i->second; } Header::Iterator Header::begin () { return _map.begin(); } Header::ConstIterator Header::begin () const { return _map.begin(); } Header::Iterator Header::end () { return _map.end(); } Header::ConstIterator Header::end () const { return _map.end(); } Header::Iterator Header::find (const char name[]) { return _map.find (name); } Header::ConstIterator Header::find (const char name[]) const { return _map.find (name); } Imath::Box2i & Header::displayWindow () { return static_cast <Box2iAttribute &> ((*this)["displayWindow"]).value(); } const Imath::Box2i & Header::displayWindow () const { return static_cast <const Box2iAttribute &> ((*this)["displayWindow"]).value(); } Imath::Box2i & Header::dataWindow () { return static_cast <Box2iAttribute &> ((*this)["dataWindow"]).value(); } const Imath::Box2i & Header::dataWindow () const { return static_cast <const Box2iAttribute &> ((*this)["dataWindow"]).value(); } float & Header::pixelAspectRatio () { return static_cast <FloatAttribute &> ((*this)["pixelAspectRatio"]).value(); } const float & Header::pixelAspectRatio () const { return static_cast <const FloatAttribute &> ((*this)["pixelAspectRatio"]).value(); } Imath::V2f & Header::screenWindowCenter () { return static_cast <V2fAttribute &> ((*this)["screenWindowCenter"]).value(); } const Imath::V2f & Header::screenWindowCenter () const { return static_cast <const V2fAttribute &> ((*this)["screenWindowCenter"]).value(); } float & Header::screenWindowWidth () { return static_cast <FloatAttribute &> ((*this)["screenWindowWidth"]).value(); } const float & Header::screenWindowWidth () const { return static_cast <const FloatAttribute &> ((*this)["screenWindowWidth"]).value(); } ChannelList & Header::channels () { return static_cast <ChannelListAttribute &> ((*this)["channels"]).value(); } const ChannelList & Header::channels () const { return static_cast <const ChannelListAttribute &> ((*this)["channels"]).value(); } LineOrder & Header::lineOrder () { return static_cast <LineOrderAttribute &> ((*this)["lineOrder"]).value(); } const LineOrder & Header::lineOrder () const { return static_cast <const LineOrderAttribute &> ((*this)["lineOrder"]).value(); } Compression & Header::compression () { return static_cast <CompressionAttribute &> ((*this)["compression"]).value(); } const Compression & Header::compression () const { return static_cast <const CompressionAttribute &> ((*this)["compression"]).value(); } void Header::setTileDescription(const TileDescription& td) { insert ("tiles", TileDescriptionAttribute (td)); } bool Header::hasTileDescription() const { return findTypedAttribute <TileDescriptionAttribute> ("tiles") != 0; } TileDescription & Header::tileDescription () { return typedAttribute <TileDescriptionAttribute> ("tiles").value(); } const TileDescription & Header::tileDescription () const { return typedAttribute <TileDescriptionAttribute> ("tiles").value(); } void Header::setPreviewImage (const PreviewImage &pi) { insert ("preview", PreviewImageAttribute (pi)); } PreviewImage & Header::previewImage () { return typedAttribute <PreviewImageAttribute> ("preview").value(); } const PreviewImage & Header::previewImage () const { return typedAttribute <PreviewImageAttribute> ("preview").value(); } bool Header::hasPreviewImage () const { return findTypedAttribute <PreviewImageAttribute> ("preview") != 0; } void Header::sanityCheck (bool isTiled) const { // // The display window and the data window must each // contain at least one pixel. In addition, the // coordinates of the window corners must be small // enough to keep expressions like max-min+1 or // max+min from overflowing. // const Box2i &displayWindow = this->displayWindow(); if (displayWindow.min.x > displayWindow.max.x || displayWindow.min.y > displayWindow.max.y || displayWindow.min.x <= -(INT_MAX / 2) || displayWindow.min.y <= -(INT_MAX / 2) || displayWindow.max.x >= (INT_MAX / 2) || displayWindow.max.y >= (INT_MAX / 2)) { throw Iex::ArgExc ("Invalid display window in image header."); } const Box2i &dataWindow = this->dataWindow(); if (dataWindow.min.x > dataWindow.max.x || dataWindow.min.y > dataWindow.max.y || dataWindow.min.x <= -(INT_MAX / 2) || dataWindow.min.y <= -(INT_MAX / 2) || dataWindow.max.x >= (INT_MAX / 2) || dataWindow.max.y >= (INT_MAX / 2)) { throw Iex::ArgExc ("Invalid data window in image header."); } if (maxImageWidth > 0 && maxImageWidth < dataWindow.max.x - dataWindow.min.x + 1) { THROW (Iex::ArgExc, "The width of the data window exceeds the " "maximum width of " << maxImageWidth << "pixels."); } if (maxImageHeight > 0 && maxImageHeight < dataWindow.max.y - dataWindow.min.y + 1) { THROW (Iex::ArgExc, "The width of the data window exceeds the " "maximum width of " << maxImageHeight << "pixels."); } // // The pixel aspect ratio must be greater than 0. // In applications, numbers like the the display or // data window dimensions are likely to be multiplied // or divided by the pixel aspect ratio; to avoid // arithmetic exceptions, we limit the pixel aspect // ratio to a range that is smaller than theoretically // possible (real aspect ratios are likely to be close // to 1.0 anyway). // float pixelAspectRatio = this->pixelAspectRatio(); const float MIN_PIXEL_ASPECT_RATIO = 1e-6f; const float MAX_PIXEL_ASPECT_RATIO = 1e+6f; if (pixelAspectRatio < MIN_PIXEL_ASPECT_RATIO || pixelAspectRatio > MAX_PIXEL_ASPECT_RATIO) { throw Iex::ArgExc ("Invalid pixel aspect ratio in image header."); } // // The screen window width must not be less than 0. // The size of the screen window can vary over a wide // range (fish-eye lens to astronomical telescope), // so we can't limit the screen window width to a // small range. // float screenWindowWidth = this->screenWindowWidth(); if (screenWindowWidth < 0) throw Iex::ArgExc ("Invalid screen window width in image header."); // // If the file is tiled, verify that the tile description has resonable // values and check to see if the lineOrder is one of the predefined 3. // If the file is not tiled, then the lineOrder can only be INCREASING_Y // or DECREASING_Y. // LineOrder lineOrder = this->lineOrder(); if (isTiled) { if (!hasTileDescription()) { throw Iex::ArgExc ("Tiled image has no tile " "description attribute."); } const TileDescription &tileDesc = tileDescription(); if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0) throw Iex::ArgExc ("Invalid tile size in image header."); if (maxTileWidth > 0 && (unsigned int)maxTileWidth < tileDesc.xSize) { THROW (Iex::ArgExc, "The width of the tiles exceeds the maximum " "width of " << maxTileWidth << "pixels."); } if (maxTileHeight > 0 && (unsigned int)maxTileHeight < tileDesc.ySize) { THROW (Iex::ArgExc, "The width of the tiles exceeds the maximum " "width of " << maxTileHeight << "pixels."); } if (tileDesc.mode != ONE_LEVEL && tileDesc.mode != MIPMAP_LEVELS && tileDesc.mode != RIPMAP_LEVELS) throw Iex::ArgExc ("Invalid level mode in image header."); if (tileDesc.roundingMode != ROUND_UP && tileDesc.roundingMode != ROUND_DOWN) throw Iex::ArgExc ("Invalid level rounding mode in image header."); if (lineOrder != INCREASING_Y && lineOrder != DECREASING_Y && lineOrder != RANDOM_Y) throw Iex::ArgExc ("Invalid line order in image header."); } else { if (lineOrder != INCREASING_Y && lineOrder != DECREASING_Y) throw Iex::ArgExc ("Invalid line order in image header."); } // // The compression method must be one of the predefined values. // if (!isValidCompression (this->compression())) throw Iex::ArgExc ("Unknown compression type in image header."); // // Check the channel list: // // If the file is tiled then for each channel, the type must be one of the // predefined values, and the x and y sampling must both be 1. // // If the file is not tiled then for each channel, the type must be one // of the predefined values, the x and y coordinates of the data window's // upper left corner must be divisible by the x and y subsampling factors, // and the width and height of the data window must be divisible by the // x and y subsampling factors. // const ChannelList &channels = this->channels(); if (isTiled) { for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i) { if (i.channel().type != UINT && i.channel().type != HALF && i.channel().type != FLOAT) { THROW (Iex::ArgExc, "Pixel type of \"" << i.name() << "\" " "image channel is invalid."); } if (i.channel().xSampling != 1) { THROW (Iex::ArgExc, "The x subsampling factor for the " "\"" << i.name() << "\" channel " "is not 1."); } if (i.channel().ySampling != 1) { THROW (Iex::ArgExc, "The y subsampling factor for the " "\"" << i.name() << "\" channel " "is not 1."); } } } else { for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i) { if (i.channel().type != UINT && i.channel().type != HALF && i.channel().type != FLOAT) { THROW (Iex::ArgExc, "Pixel type of \"" << i.name() << "\" " "image channel is invalid."); } if (i.channel().xSampling < 1) { THROW (Iex::ArgExc, "The x subsampling factor for the " "\"" << i.name() << "\" channel " "is invalid."); } if (i.channel().ySampling < 1) { THROW (Iex::ArgExc, "The y subsampling factor for the " "\"" << i.name() << "\" channel " "is invalid."); } if (dataWindow.min.x % i.channel().xSampling) { THROW (Iex::ArgExc, "The minimum x coordinate of the " "image's data window is not a multiple " "of the x subsampling factor of " "the \"" << i.name() << "\" channel."); } if (dataWindow.min.y % i.channel().ySampling) { THROW (Iex::ArgExc, "The minimum y coordinate of the " "image's data window is not a multiple " "of the y subsampling factor of " "the \"" << i.name() << "\" channel."); } if ((dataWindow.max.x - dataWindow.min.x + 1) % i.channel().xSampling) { THROW (Iex::ArgExc, "Number of pixels per row in the " "image's data window is not a multiple " "of the x subsampling factor of " "the \"" << i.name() << "\" channel."); } if ((dataWindow.max.y - dataWindow.min.y + 1) % i.channel().ySampling) { THROW (Iex::ArgExc, "Number of pixels per column in the " "image's data window is not a multiple " "of the y subsampling factor of " "the \"" << i.name() << "\" channel."); } } } } void Header::setMaxImageSize (int maxWidth, int maxHeight) { maxImageWidth = maxWidth; maxImageHeight = maxHeight; } void Header::setMaxTileSize (int maxWidth, int maxHeight) { maxTileWidth = maxWidth; maxTileHeight = maxHeight; } Int64 Header::writeTo (OStream &os, bool isTiled) const { // // Write a "magic number" to identify the file as an image file. // Write the current file format version number. // Xdr::write <StreamIO> (os, MAGIC); int version = isTiled ? makeTiled (EXR_VERSION) : EXR_VERSION; Xdr::write <StreamIO> (os, version); // // Write all attributes. If we have a preview image attribute, // keep track of its position in the file. // Int64 previewPosition = 0; const Attribute *preview = findTypedAttribute <PreviewImageAttribute> ("preview"); for (ConstIterator i = begin(); i != end(); ++i) { // // Write the attribute's name and type. // Xdr::write <StreamIO> (os, i.name()); Xdr::write <StreamIO> (os, i.attribute().typeName()); // // Write the size of the attribute value, // and the value itself. // StdOSStream oss; i.attribute().writeValueTo (oss, version); std::string s = oss.str(); Xdr::write <StreamIO> (os, (int) s.length()); if (&i.attribute() == preview) previewPosition = os.tellp(); os.write (s.data(), s.length()); } // // Write zero-length attribute name to mark the end of the header. // Xdr::write <StreamIO> (os, ""); return previewPosition; } void Header::readFrom (IStream &is, int &version) { // // Read the magic number and the file format version number. // Then check if we can read the rest of this file. // int magic; Xdr::read <StreamIO> (is, magic); Xdr::read <StreamIO> (is, version); if (magic != MAGIC) { throw Iex::InputExc ("File is not an image file."); } if (getVersion (version) != EXR_VERSION) { THROW (Iex::InputExc, "Cannot read " "version " << getVersion (version) << " " "image files. Current file format version " "is " << EXR_VERSION << "."); } if (!supportsFlags (getFlags (version))) { THROW (Iex::InputExc, "The file format version number's flag field " "contains unrecognized flags."); } // // Read all attributes. // while (true) { // // Read the name of the attribute. // A zero-length attribute name indicates the end of the header. // char name[100]; Xdr::read <StreamIO> (is, sizeof (name), name); if (name[0] == 0) break; // // Read the attribute type and the size of the attribute value. // char typeName[100]; int size; Xdr::read <StreamIO> (is, sizeof (typeName), typeName); Xdr::read <StreamIO> (is, size); AttributeMap::iterator i = _map.find (name); if (i != _map.end()) { // // The attribute already exists (for example, // because it is a predefined attribute). // Read the attribute's new value from the file. // if (strncmp (i->second->typeName(), typeName, sizeof (typeName))) THROW (Iex::InputExc, "Unexpected type for image attribute " "\"" << name << "\"."); i->second->readValueFrom (is, size, version); } else { // // The new attribute does not exist yet. // If the attribute type is of a known type, // read the attribute value. If the attribute // is of an unknown type, read its value and // store it as an OpaqueAttribute. // Attribute *attr; if (Attribute::knownType (typeName)) attr = Attribute::newAttribute (typeName); else attr = new OpaqueAttribute (typeName); try { attr->readValueFrom (is, size, version); _map[name] = attr; } catch (...) { delete attr; throw; } } } } void staticInitialize () { static Mutex criticalSection; Lock lock (criticalSection); static bool initialized = false; if (!initialized) { // // One-time initialization -- register // some predefined attribute types. // Box2fAttribute::registerAttributeType(); Box2iAttribute::registerAttributeType(); ChannelListAttribute::registerAttributeType(); CompressionAttribute::registerAttributeType(); ChromaticitiesAttribute::registerAttributeType(); DoubleAttribute::registerAttributeType(); EnvmapAttribute::registerAttributeType(); FloatAttribute::registerAttributeType(); IntAttribute::registerAttributeType(); KeyCodeAttribute::registerAttributeType(); LineOrderAttribute::registerAttributeType(); M33fAttribute::registerAttributeType(); M44fAttribute::registerAttributeType(); PreviewImageAttribute::registerAttributeType(); RationalAttribute::registerAttributeType(); StringAttribute::registerAttributeType(); TileDescriptionAttribute::registerAttributeType(); TimeCodeAttribute::registerAttributeType(); V2fAttribute::registerAttributeType(); V2iAttribute::registerAttributeType(); V3fAttribute::registerAttributeType(); V3iAttribute::registerAttributeType(); initialized = true; } } } // namespace Imf
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 1003 ] ] ]
4cee05c541689c4599515cf9d4a35f7b883cd981
7d6597b8619a63f65b8a6cfcae721da7592b92aa
/spiral-core/include/spiral/internet/base/BaseConnector.h
befaef2e50c44cc10cb0dd6e7be9adf163a08b5d
[ "MIT" ]
permissive
RangelReale/spiral-io
51eb976a1def7959d364a57921cab527d30ea428
cf8dbdfcfbef5dc8092fd7ea0ce8d052edf2f35d
refs/heads/master
2023-07-06T22:39:19.708949
2009-12-10T21:00:22
2009-12-10T21:00:22
37,156,634
0
0
null
null
null
null
UTF-8
C++
false
false
1,391
h
#ifndef _SPIRAL_INTERNET_BASE_BASECONNECTOR_H__ #define _SPIRAL_INTERNET_BASE_BASECONNECTOR_H__ #include "spiral/Exception.h" #include "spiral/internet/interfaces/IConnector.h" #include "spiral/internet/protocol/ClientFactory.h" #include "spiral/internet/interfaces/IReactorCore.h" #include "spiral/sys/IntegerTypes.h" #include <boost/shared_ptr.hpp> namespace spiral { namespace internet { namespace base { using namespace interfaces; class BaseConnector : public IConnector { public: enum state_t { CONNECTING, CONNECTED, DISCONNECTED }; BaseConnector(protocol::ClientFactory *factory, int32_t timeout, IReactorCore *reactor); virtual IProtocol *buildProtocol(IAddress addr); virtual void connectionFailed(const Exception &reason); virtual void connectionLost(const Exception &reason); // IConnector virtual void stopConnecting(); virtual void disconnect(); virtual void connect(); virtual ITransport &getTransport() { return *transport_; } virtual IReactorCore &reactor() { return *reactor_; } protected: virtual ITransport *makeTransport() = 0; private: state_t state_; protocol::ClientFactory *factory_; int32_t timeout_; IReactorCore *reactor_; bool factorystarted_; std::auto_ptr<ITransport> transport_; }; }}} // spiral::internet::base #endif // _SPIRAL_INTERNET_BASE_BASECONNECTOR_H__
[ "hitnrun@6cb40615-3296-4dc8-bcc4-269c24c2e8c1" ]
[ [ [ 1, 55 ] ] ]
0b6152f9cd8db2281fc3a2cec1d5b882e355dd61
4061b5e48204bf0ee878440a602d84c1d6623396
/boilerplates/header.hpp
fe1feacf18cf5f27a41582002171bb5795a55b6e
[]
no_license
m0tive/boil
9863dabf39eedf34e932dea2f5c502da2c32cc6c
115bb5cb15fed9805be56b3b395e25136ad52fc5
refs/heads/master
2020-04-05T09:19:57.514860
2010-12-01T22:50:11
2010-12-01T22:50:11
1,130,227
0
0
null
null
null
null
UTF-8
C++
false
false
506
hpp
// File Info {{{ //------------------------------------------------------------------------------ /// \file @[email protected] /// \date @DATE@ /// \author @AUTHOR@ /// \brief /// \note Copyright (C) @YEAR@ - All Rights Reserved //}}}--------------------------------------------------------------------------- // Include catch {{{ #ifdef _MSC_VER #pragma once #endif #ifndef _@NAMESPACE@_@FILENAME@_hpp_ #define _@NAMESPACE@_@FILENAME@_hpp_ // }}} namespace @NAMESPACE@ { } #endif
[ [ [ 1, 24 ] ] ]
52fb9ea1de6b508107bb9058624f50c0f15b6689
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Include/Direct3D9Plugin/Video/Direct3D9VideoDevice.h
04ae6d300ff45ba7025378a8624374775349b560
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
17,301
h
//  // // # # ### # # -= Nuclex Project =-  // // ## # # # ## ## Direct3D9VideoDevice.h - Direct3D9 renderer  // // ### # # ###  // // # ### # ### Nuclex Direct3D9 renderer  // // # ## # # ## ##  // // # # ### # # R4 (C)2003 Markus Ewald -> License.txt  // //  // #ifndef NUCLEX_VIDEO_DIRECT3D9VIDEODEVICE_H #define NUCLEX_VIDEO_DIRECT3D9VIDEODEVICE_H #include "Direct3D9Plugin/Direct3D9Plugin.h" #include "Direct3D9Plugin/Video/Direct3D9VideoDriver.h" #include "Direct3D9Plugin/Video/Direct3D9RenderingContext.h" #include "Direct3D9Plugin/Video/Direct3D9RenderStates.h" #include "Nuclex/Video/VideoDevice.h" #include "Nuclex/Video/Surface.h" #include <deque> namespace Nuclex { class Kernel; } namespace Nuclex { namespace Video { //  // //  Nuclex::Video::Direct3D9VideoDevice  // //  // /// Direct3D9 video device /** Implementation of a video device for win32 platforms using the microsoft direct3d9 interfaces */ class Direct3D9VideoDevice : public VideoDevice { friend Direct3D9RenderingContext; public: typedef SigC::Signal0<void> RestoreSignal; typedef SigC::Signal1<void, bool> ShutdownSignal; /// Constructor NUCLEXDIRECT3D9_API Direct3D9VideoDevice( Kernel *pKernel, unsigned long nAdapter, const VideoDriver::DisplayMode &Mode ); /// Destructor NUCLEXDIRECT3D9_API ~Direct3D9VideoDevice(); // // Direct3D9VideoDevice implementation // public: /// Get output window handle NUCLEXDIRECT3D9_API HWND getWindow() const; /// Set output window handle NUCLEXDIRECT3D9_API void setWindow(HWND hWnd); NUCLEXDIRECT3D9_API const IDirect3DDevice9Ptr &getDirect3DDevice() const { return m_spDirect3DDevice; } NUCLEXDIRECT3D9_API const D3DCAPS9 &getDeviceCaps() const { return m_DeviceCaps; } /// On device shutdown ShutdownSignal OnDeviceShutdown; /// On device reset RestoreSignal OnDeviceRestore; // // VideoDevice implementation // public: /// Retrieve the currently set display mode NUCLEXDIRECT3D9_API const VideoDriver::DisplayMode &getDisplayMode() { return m_DisplayMode; } /// Select a display mode to use NUCLEXDIRECT3D9_API void setDisplayMode(const VideoDriver::DisplayMode &DisplayMode); /// Get video context NUCLEXDIRECT3D9_API shared_ptr<RenderingContext> renderFrame( const shared_ptr<RenderTarget> &spDestination = shared_ptr<RenderTarget>() ); /// Create a new texture NUCLEXDIRECT3D9_API shared_ptr<Texture> createTexture( const Point2<size_t> &Size, Surface::PixelFormat eFormat, ResourceClass eResourceClass = RC_DYNAMIC ); /// Create a new texture NUCLEXDIRECT3D9_API shared_ptr<Texture> createTexture( const Point2<size_t> &Size, AlphaChannel eAlphaChannel, ResourceClass eResourceClass = RC_DYNAMIC ); /// Create a new vertex buffer NUCLEXDIRECT3D9_API shared_ptr<VertexBuffer> createVertexBuffer( const VertexDeclaration &Declaration, size_t nSize, ResourceClass eResourceClass = RC_DYNAMIC ); /// Create a new index buffer NUCLEXDIRECT3D9_API shared_ptr<IndexBuffer> createIndexBuffer( size_t nSize, ResourceClass eResourceClass = RC_DYNAMIC ); /// Create a new render state set NUCLEXDIRECT3D9_API shared_ptr<RenderStates> createRenderStates(); /// Create a new vertex shader NUCLEXDIRECT3D9_API shared_ptr<VertexShader> createVertexShader( const string &sShader ); /// Create a new pixel shader NUCLEXDIRECT3D9_API shared_ptr<PixelShader> createPixelShader( const string &sShader ); /// Retrieve the maximum texture size supported NUCLEXDIRECT3D9_API const Point2<size_t> &getMaxTextureSize() const { return m_MaxTextureSize; } NUCLEXDIRECT3D9_API size_t getVideoMemorySize() const { return m_VideoMemorySize; } NUCLEXDIRECT3D9_API void setCursor(const shared_ptr<Image> &spCursor); protected: /// Create Direct3D device void createDevice(); /// Destroy Direct3D device void destroyDevice(); /// Reset Direct3D device void resetDevice(); protected: class ActiveRenderStates; std::auto_ptr<ActiveRenderStates> m_spActiveRenderStates; ///< Currently set render states unsigned long m_nAdapter; ///< Owner bool m_bUse16BitTextures; ///< Whether to use 16 bit textures weak_ptr<RenderingContext> m_wpRenderingContext; ///< Current rendering context VideoDriver::DisplayMode m_DisplayMode; ///< Current display mode D3DPRESENT_PARAMETERS m_PresentParameters; ///< Associated present parameters IDirect3DDevice9Ptr m_spDirect3DDevice; ///< The Direct3D device D3DCAPS9 m_DeviceCaps; ///< Rendering device caps Point2<size_t> m_MaxTextureSize; ///< Max texture size supported size_t m_VideoMemorySize; ///< Total amount of video memory available Kernel *m_pKernel; ///< Kernel instance IDirect3DSurface9Ptr m_spCursor; ///< Current cursor }; //  // //  Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates  // //  // /// Currently active render states /** Stores the current settings of all render states in the device. This is an internal class used to facilitate setting of RenderStates through state blocks or by direct modification. */ class Direct3D9VideoDevice::ActiveRenderStates : public RenderStates { public: ActiveRenderStates &operator +=(const Direct3D9RenderStates &Other) { Other.activateStateBlock(m_spDirect3DDevice); RenderStates::operator =(Other); // Change all S_SET to S_ACTIVE, because activated through state block return *this; } /// Assign another state set RenderStates &operator +=(const RenderStates &Other) { const Direct3D9RenderStates *pD3D9RS = dynamic_cast<const Direct3D9RenderStates *>(&Other); if(pD3D9RS) return operator +=(*pD3D9RS); else return RenderStates::operator +=(Other); } // // ActiveRenderStateSet implementation // public: /// Select the Direct3D device to be used void setDevice(const IDirect3DDevice9Ptr &spDevice) { m_spDirect3DDevice = spDevice; } // // RenderStateSet implementation // public: /// Enable or disable alpha blending void enableAlphaBlend(bool bEnable) { if((m_bLightingEnabled.getStatus() != RenderState<bool>::S_ACTIVE) || (static_cast<bool>(m_bAlphaBlendEnabled) != bEnable)) { m_bAlphaBlendEnabled = bEnable; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setAlphaBlendEnable()", "IDirect3DDevice9::SetRenderState()", m_spDirect3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, bEnable)); m_bAlphaBlendEnabled.setStatus(RenderState<bool>::S_ACTIVE); } } /// Enable or disable lighting void enableLighting(bool bEnable) { if((m_bLightingEnabled.getStatus() != RenderState<bool>::S_ACTIVE) || (static_cast<bool>(m_bLightingEnabled) != bEnable)) { m_bLightingEnabled = bEnable; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setLightingEnable()", "IDirect3DDevice9::SetRenderState()", m_spDirect3DDevice->SetRenderState(D3DRS_LIGHTING, bEnable)); m_bLightingEnabled.setStatus(RenderState<bool>::S_ACTIVE); } } /// Enable z buffering or depth sorting void enableDepthBuffer(bool bEnable) { if((m_bDepthBufferEnabled.getStatus() != RenderState<bool>::S_ACTIVE) || (static_cast<bool>(m_bDepthBufferEnabled) != bEnable)) { m_bDepthBufferEnabled = bEnable; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setZEnableEnable()", "IDirect3DDevice9::SetRenderState()", m_spDirect3DDevice->SetRenderState(D3DRS_ZENABLE, bEnable)); m_bDepthBufferEnabled.setStatus(RenderState<bool>::S_ACTIVE); } } /// Set blend mode to use for the source surface (eg. a texture to be rendered) void setSourceBlendMode(BlendMode eMode) { if((m_eSourceBlendMode.getStatus() != RenderState<BlendMode>::S_ACTIVE) || (static_cast<BlendMode>(m_eSourceBlendMode) != eMode)) { m_eSourceBlendMode = eMode; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setSourceBlendMode()", "IDirect3DDevice9::SetRenderState()", m_spDirect3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLENDFromBlendMode(eMode))); m_eSourceBlendMode.setStatus(RenderState<BlendMode>::S_ACTIVE); } } /// Set blend mode to use for the destination surface (eg. a texture to be rendered) void setDestinationBlendMode(BlendMode eMode) { if((m_eDestinationBlendMode.getStatus() != RenderState<BlendMode>::S_ACTIVE) || (static_cast<BlendMode>(m_eDestinationBlendMode) != eMode)) { m_eDestinationBlendMode = eMode; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setDestinationBlendMode()", "IDirect3DDevice9::SetRenderState()", m_spDirect3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLENDFromBlendMode(eMode))); m_eDestinationBlendMode.setStatus(RenderState<BlendMode>::S_ACTIVE); } } /// Set blend mode to use for the destination surface (eg. a texture to be rendered) void setCullMode(CullMode eMode) { if((m_eCullMode.getStatus() != RenderState<CullMode>::S_ACTIVE) || (static_cast<CullMode>(m_eCullMode) != eMode)) { m_eCullMode = eMode; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setCullMode()", "IDirect3DDevice9::SetRenderState()", m_spDirect3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULLFromCullMode(eMode))); m_eCullMode.setStatus(RenderState<CullMode>::S_ACTIVE); } } /// Set polygon fill mode void setFillMode(FillMode eMode) { if((m_eFillMode.getStatus() != RenderState<FillMode>::S_ACTIVE) || (static_cast<FillMode>(m_eFillMode) != eMode)) { m_eFillMode = eMode; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setFillMode()", "IDirect3DDevice9::SetRenderState()", m_spDirect3DDevice->SetRenderState(D3DRS_FILLMODE, D3DFILLMODEFromFillMode(eMode))); m_eFillMode.setStatus(RenderState<FillMode>::S_ACTIVE); } } /// Set color blend operation void setColorOperation(size_t Stage, BlendOperation eOperation) { if((m_peColorOperation[Stage].getStatus() != RenderState<BlendOperation>::S_ACTIVE) || (static_cast<BlendOperation>(m_peColorOperation[Stage]) != eOperation)) { m_peColorOperation[Stage] = eOperation; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setColorOperation()", "IDirect3DDevice9::SetTextureStageState()", m_spDirect3DDevice->SetTextureStageState(Stage, D3DTSS_COLOROP, D3DTEXTUREOPFromBlendOperation(eOperation))); m_peColorOperation[Stage].setStatus(RenderState<BlendOperation>::S_ACTIVE); } } /// Set color blend operation void setColorArgument(size_t Stage, size_t Argument, BlendArgument eArgument) { if((m_ppeColorArgument[Stage][Argument].getStatus() != RenderState<BlendArgument>::S_ACTIVE) || (static_cast<BlendArgument>(m_ppeColorArgument[Stage][Argument]) != eArgument)) { m_ppeColorArgument[Stage][Argument] = eArgument; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setColorArgument()", "IDirect3DDevice9::SetTextureStageState()", m_spDirect3DDevice->SetTextureStageState(Stage, D3DTSS_COLORARG1, D3DTEXTURESTAGESTATETYPEFromBlendArgument(eArgument))); m_ppeColorArgument[Stage][Argument].setStatus(RenderState<BlendArgument>::S_ACTIVE); } } /// Set alpha blend operation void setAlphaOperation(size_t Stage, BlendOperation eOperation) { if((m_peAlphaOperation[Stage].getStatus() != RenderState<BlendOperation>::S_ACTIVE) || (static_cast<BlendOperation>(m_peAlphaOperation[Stage]) != eOperation)) { m_peAlphaOperation[Stage] = eOperation; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setAlphaOperation()", "IDirect3DDevice9::SetTextureStageState()", m_spDirect3DDevice->SetTextureStageState(Stage, D3DTSS_ALPHAOP, D3DTEXTUREOPFromBlendOperation(eOperation))); m_peAlphaOperation[Stage].setStatus(RenderState<BlendOperation>::S_ACTIVE); } } /// Set alpha blend operation void setAlphaArgument(size_t Stage, size_t Argument, BlendArgument eArgument) { if((m_ppeAlphaArgument[Stage][Argument].getStatus() != RenderState<BlendArgument>::S_ACTIVE) || (static_cast<BlendArgument>(m_ppeAlphaArgument[Stage][Argument]) != eArgument)) { m_ppeAlphaArgument[Stage][Argument] = eArgument; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setAlphaArgument()", "IDirect3DDevice9::SetTextureStageState()", m_spDirect3DDevice->SetTextureStageState(Stage, D3DTSS_ALPHAARG1, D3DTEXTURESTAGESTATETYPEFromBlendArgument(eArgument))); m_ppeAlphaArgument[Stage][Argument].setStatus(RenderState<BlendArgument>::S_ACTIVE); } } /// Set minification filter type void setMinificationFilter(size_t Stage, TextureFilter eFilter) { if((m_peMinificationFilter[Stage].getStatus() != RenderState<TextureFilter>::S_ACTIVE) || (static_cast<TextureFilter>(m_peMinificationFilter[Stage]) != eFilter)) { m_peMinificationFilter[Stage] = eFilter; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setMinificationFilter()", "IDirect3DDevice9::SetTextureStageState()", m_spDirect3DDevice->SetSamplerState(Stage, D3DSAMP_MINFILTER, D3DTEXTUREFILTERTYPEFromTextureFilter(eFilter))); m_peMinificationFilter[Stage].setStatus(RenderState<TextureFilter>::S_ACTIVE); } } /// Set magnification filter type void setMagnificationFilter(size_t Stage, TextureFilter eFilter) { if((m_peMagnificationFilter[Stage].getStatus() != RenderState<TextureFilter>::S_ACTIVE) || (static_cast<TextureFilter>(m_peMagnificationFilter[Stage]) != eFilter)) { m_peMagnificationFilter[Stage] = eFilter; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setMagnificationFilter()", "IDirect3DDevice9::SetTextureStageState()", m_spDirect3DDevice->SetSamplerState(Stage, D3DSAMP_MAGFILTER, D3DTEXTUREFILTERTYPEFromTextureFilter(eFilter))); m_peMagnificationFilter[Stage].setStatus(RenderState<TextureFilter>::S_ACTIVE); } } /// Set texture addressing mode void setTextureAddressMode(size_t Stage, Dimension eDimension, TextureAddressMode eMode) { if((m_ppeTextureAddressMode[Stage][eDimension].getStatus() != RenderState<TextureFilter>::S_ACTIVE) || (static_cast<TextureAddressMode>(m_ppeTextureAddressMode[Stage][eDimension]) != eMode)) { m_ppeTextureAddressMode[Stage][eDimension] = eMode; D3DCheck("Nuclex::Video::Direct3D9VideoDevice::ActiveRenderStates::setMagnificationFilter()", "IDirect3DDevice9::SetTextureStageState()", m_spDirect3DDevice->SetSamplerState(Stage, D3DSAMPLERSTATETYPEFromDimension(eDimension), D3DTEXTUREADDRESSFromTextureAddressMode(eMode))); m_ppeTextureAddressMode[Stage][eDimension].setStatus(RenderState<TextureAddressMode>::S_ACTIVE); } } private: IDirect3DDevice9Ptr m_spDirect3DDevice; ///< The direct3d device to use }; }} // namespace Nuclex::Video #endif // NUCLEX_VIDEO_DIRECT3D9VIDEODEVICE_H
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 373 ] ] ]
6d04a51a7c9f9b5060795665856fc4e58a49079c
2fdbf2ba994ba3ed64f0e2dc75cd2dfce4936583
/spectre/qtableviewex.h
10df695a1ea3d4d6be23a65bb1d2e83ba1acfa49
[]
no_license
TERRANZ/terragraph
36219a4e512e15a925769512a6b60637d39830bf
ea8c36070f532ad0a4af08e46b19f4ee1b85f279
refs/heads/master
2020-05-25T10:31:26.994233
2011-01-29T21:23:04
2011-01-29T21:23:04
1,047,237
0
0
null
null
null
null
UTF-8
C++
false
false
419
h
#ifndef QTABLEVIEWEX_H #define QTABLEVIEWEX_H #include <QTableView> class QTableViewEx : public QTableView { Q_OBJECT public: explicit QTableViewEx(QWidget *parent = 0); protected: virtual void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); signals: void changeCells(QModelIndexList indexList); public slots: }; #endif // QTABLEVIEWEX_H
[ [ [ 1, 22 ] ] ]
110404b241f02ab6be2192ef8479fba8b4f4d10d
067ff5708784b1fd2595957de78518e87073ccb4
/Image Viewer/Viewer Application/MouseGesture.cpp
cd0eeb3676ee2ba43eff3be060ce8a2041f4cef0
[]
no_license
wolfmanu/opencvthesis
637a6a6ead5c839e731faca19ae0dd3e59e33cd3
c4e806d6369b4ed80ebadce1684e32f147eafce4
refs/heads/master
2016-09-05T22:38:07.528951
2010-09-10T12:01:49
2010-09-10T12:01:49
32,142,213
0
0
null
null
null
null
UTF-8
C++
false
false
23,681
cpp
/**************************************************************************** MouseGesture.cpp: implementation of the CMouseGesture class. written by PJ Arends [email protected] Copyright (c) 2005 ----------------------------------------------------------------------------- This code is provided as is, with no warranty as to it's suitability or usefulness in any application in which it may be used. This code may be used in any way you desire. This file may be redistributed by any means as long as it is not sold for profit, and providing that this notice and the author's name are included. Any modifications not made by the original author should be clearly marked as such to remove any confusion between the original version and any other versions. If any bugs are found and fixed, a note to the author explaining the problem and fix would be nice. ----------------------------------------------------------------------------- Revision History: June 2005 - initial release on The CodeProject - http://www.codeproject.com ****************************************************************************/ #include "stdafx.h" #include "MouseGesture.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // DEBUG only stuff ////////////////////////////////////////////////////////////////////// #ifdef _DEBUG ////////////////////////////////////////////////////////////////////// // Uncomment the #define _SHOW_GESTURE line to draw mouse points and // bounding squares on screen when the gesture is being made. ////////////////////////////////////////////////////////////////////// //# define _SHOW_GESTURE // this line controls visual feedback # ifdef _SHOW_GESTURE void SHOW_BOUNDING_SQUARE (MOUSEHOOKSTRUCT *pMHS, RECT rc) { HWND hWnd = WindowFromPoint(pMHS->pt); MapWindowPoints(NULL, hWnd, (POINT *)&rc, 2); HDC hdc = GetDC(hWnd); DrawFocusRect(hdc, &rc); ReleaseDC(hWnd, hdc); } # else // _SHOW_GESTURE # define SHOW_BOUNDING_SQUARE(pMHS, rc) # endif // _SHOW_GESTURE #else // _DEBUG # define SHOW_BOUNDING_SQUARE(pMHS, rc) #endif // _DEBUG ////////////////////////////////////////////////////////////////////// // handy functions borrowed from Chris Maunder's CGridCtrl class ////////////////////////////////////////////////////////////////////// #define IsSHIFTpressed() ( (GetKeyState(VK_SHIFT) & (1 << (sizeof(SHORT)*8-1))) != 0 ) #define IsCTRLpressed() ( (GetKeyState(VK_CONTROL) & (1 << (sizeof(SHORT)*8-1))) != 0 ) ////////////////////////////////////////////////////////////////////// // Static private member variables ////////////////////////////////////////////////////////////////////// CMouseGesture::_WndMap CMouseGesture::WindowMap; CMouseGesture* CMouseGesture::Current = NULL; HHOOK CMouseGesture::MainHook = NULL; ////////////////////////////////////////////////////////////////////// // Static functions ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // GetGesturePointer // static private member function // // Gets a pointer to the CMouseGesture object that will handle mouse // gestures for the given window. ////////////////////////////////////////////////////////////////////// CMouseGesture* CMouseGesture::GetGesturePointer(HWND hWnd, POINT pt) { if (!IsWindow(hWnd)) { return NULL; } _WndMap::iterator it = WindowMap.find(hWnd); if (it == WindowMap.end()) { // hWnd not found, move up the parent chain return GetGesturePointer(GetParent(hWnd), pt); } // ensure given point is in the client area of the window RECT rc; GetClientRect(hWnd, &rc); MapWindowPoints(hWnd, NULL, (POINT *)&rc, 2); if (!PtInRect(&rc, pt)) { return NULL; } // ensure the CMouseGesture object has gestures to recognize CMouseGesture *pGestures = (CMouseGesture *)((*it).second); if (pGestures->m_GestureMap.empty()) { return NULL; } return pGestures; } ////////////////////////////////////////////////////////////////////// // MouseHookProc // static private member function ////////////////////////////////////////////////////////////////////// LRESULT CMouseGesture::MouseHookProc(int nCode, WPARAM wp, LPARAM lp) { MOUSEHOOKSTRUCT *pMHS = (MOUSEHOOKSTRUCT *)lp; if (wp == WM_LBUTTONDOWN || wp == WM_MBUTTONDOWN || wp == WM_RBUTTONDOWN) { if (Current != NULL) { Current->KillGesture(); } Current = GetGesturePointer(pMHS->hwnd, pMHS->pt); } // mouse wheel messages are ignored if (wp != WM_MOUSEWHEEL && Current != NULL) { Current = Current->MouseMessage(wp, lp); } return CallNextHookEx(MainHook, nCode, wp, lp); } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CMouseGesture::CMouseGesture() : m_hWnd(NULL), m_bCaptured(false), m_bShift(false), m_bControl(false), m_ButtonFlag(0), m_ButtonDown(None), m_CurrentGesture(NULL), m_nDistance(0), m_LastDirection(None) { } CMouseGesture::~CMouseGesture() { Detach(); } ////////////////////////////////////////////////////////////////////// // Initialization functions ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Attach // public member function // // Sets up the CMouseGesture object for use // // Parameters: // hWnd - The window that uses the gestures // Distance - The minimum distance, in pixels, that the mouse must // travel in order for a motion to be recognized // // Returns: // true if successful // false if not successful ////////////////////////////////////////////////////////////////////// bool CMouseGesture::Attach(HWND hWnd, UINT Distance /* = 25 */) { _ASSERT (Distance > 9); _ASSERT (::IsWindow(hWnd)); if (Distance < 10 || !IsWindow(hWnd)) { return false; } if (m_hWnd != NULL) { // This CMouseGesture is already attached to a window // call Detach() before calling Attach() _ASSERT (false); return false; } _WndMap::iterator it = WindowMap.find(hWnd); if (it != WindowMap.end()) { // This window already has a CMouseGesture object associated with it _ASSERT (false); return false; } if (WindowMap.insert(std::make_pair(hWnd, this)).second != true) { // failed to add this window to the WindowMap _ASSERT (false); return false; } if (MainHook == NULL) { DWORD ThreadID = GetWindowThreadProcessId(hWnd, NULL); MainHook = SetWindowsHookEx(WH_MOUSE, MouseHookProc, NULL, ThreadID); if (MainHook == NULL) { // failed to create the hook WindowMap.erase(hWnd); _ASSERT (false); return false; } } m_hWnd = hWnd; m_nDistance = Distance; return true; } ////////////////////////////////////////////////////////////////////// // AddGesture // public member functions // // Adds mouse movement patterns for the CMouseGesture object to recognize // // Parameters: // ID - An identifier number for the pattern // Motions - A pointer to an array of Motions // count - The number of Motions in the array // rGesture - A Gesture vector containing the Motions // // Returns: // -2 : gesture already present // -1 : a gesture with given ID already present // 0 : error in the supplied gesture or invalid ID // >0 : number of gestures ////////////////////////////////////////////////////////////////////// int CMouseGesture::AddGesture(UINT ID, const Motion *Motions, size_t count) { _ASSERT (Motions != NULL); _ASSERT (count > 1); if (Motions == NULL || count < 2) { return 0; } Gesture gesture; for (size_t i = 0; i < count; ++i) { gesture.push_back(Motions[i]); } return AddGesture(ID, gesture); } int CMouseGesture::AddGesture(UINT ID, const Gesture &rGesture) { _ASSERT (ID > 0); _ASSERT (rGesture.size() > 1); if (rGesture.size() < 2 || ID < 1) { return 0; } // Make sure the supplied gesture is valid if (rGesture[0] != LeftButton && rGesture[0] != MiddleButton && rGesture[0] != RightButton) { // The first element must be the mouse button _ASSERT (false); return 0; } Motion last = None; for (Gesture::const_iterator it = rGesture.begin(); it != rGesture.end(); ++it) { if (*it == LeftButton || *it == MiddleButton || *it == RightButton) { if (it != rGesture.begin()) { // mouse button can only be first _ASSERT(false); return 0; } continue; } if (*it == Shift) { if (rGesture.size() < 3) { // Gesture must be more than just Shift _ASSERT (false); return 0; } if (it != rGesture.begin() + 1) { // Shift must be in second spot _ASSERT (false); return 0; } continue; } if (*it == Control) { if (rGesture.size() < 3) { // Gesture must be more than just Control _ASSERT (false); return 0; } if (it != rGesture.begin() + 1 && it != rGesture.begin() + 2) { // Control must be either second or third _ASSERT (false); return 0; } if (it == rGesture.begin() + 2 && (rGesture[1] != Shift || rGesture.size() < 4)) { // if control is third, shift must be second, and there must be more motions _ASSERT (false); return 0; } continue; } if (*it == last || *it < Up || *it > Right) { // The motion has to be Up, Down, Left, or Right // The same motion can not immediately repeat _ASSERT (false); return 0; } last = *it; } // make sure the supplied ID is unique if (m_GestureMap.find(ID) != m_GestureMap.end()) { _ASSERT(false); return -1; } // make sure the supplied gesture is unique if (GetGestureIdFromMap(rGesture) != 0) { _ASSERT(false); return -2; } m_ButtonFlag |= rGesture[0]; m_GestureMap.insert(std::make_pair(ID, rGesture)); return m_GestureMap.size(); } ////////////////////////////////////////////////////////////////////// // Deinitialize functions ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // RemoveGesture // public member function // // Removes the gesture pattern // // Parameters: // nID - The ID of the pattern to remove // // Returns // true : the pattern was found and removed // false : the pattern was not found ////////////////////////////////////////////////////////////////////// bool CMouseGesture::RemoveGesture(UINT nID) { bool ret = m_GestureMap.erase(nID) == 1; if (ret) { // reset the m_ButtonFlag in case a mouse button is eliminated m_ButtonFlag = 0; for (GestureMap::const_iterator it = m_GestureMap.begin(); it != m_GestureMap.end(); ++it) { m_ButtonFlag |= (*it).second[0]; } } return ret; } ////////////////////////////////////////////////////////////////////// // Detach // public member function // // Detaches this CMouseGesture object from the window ////////////////////////////////////////////////////////////////////// #pragma warning(push) #pragma warning(disable: 4189) // 'erased' : local variable is initialized but not referenced void CMouseGesture::Detach() { if (m_hWnd != NULL) { int erased = WindowMap.erase(m_hWnd); _ASSERT (erased == 1); m_hWnd = NULL; } if (WindowMap.size() == 0 && MainHook != NULL) { UnhookWindowsHookEx(MainHook); MainHook = NULL; } } #pragma warning(pop) ////////////////////////////////////////////////////////////////////// // Mouse message handler functions ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // MouseMessage // private member function // // Called by the MouseHookProc to handle the mouse messages // // Returns: // the this pointer if handling a gesture // NULL if not ////////////////////////////////////////////////////////////////////// CMouseGesture* CMouseGesture::MouseMessage(WPARAM wp, LPARAM lp) { CMouseGesture *ret = NULL; DWORD Message = (DWORD)wp; MOUSEHOOKSTRUCT *pMHS = (MOUSEHOOKSTRUCT *)lp; switch (Message) { case WM_LBUTTONDOWN: if (m_ButtonFlag & LeftButton) { m_CurrentGesture.clear(); m_CurrentGesture.push_back(LeftButton); m_ButtonDown = LeftButton; ret = OnButtonDown(pMHS); } break; case WM_MBUTTONDOWN: if (m_ButtonFlag & MiddleButton) { m_CurrentGesture.clear(); m_CurrentGesture.push_back(MiddleButton); m_ButtonDown = MiddleButton; ret = OnButtonDown(pMHS); } break; case WM_RBUTTONDOWN: if (m_ButtonFlag & RightButton) { m_CurrentGesture.clear(); m_CurrentGesture.push_back(RightButton); m_ButtonDown = RightButton; ret = OnButtonDown(pMHS); } break; case WM_LBUTTONUP: if (m_ButtonDown == LeftButton) { ret = OnButtonUp(pMHS); } break; case WM_MBUTTONUP: if (m_ButtonDown == MiddleButton) { ret = OnButtonUp(pMHS); } break; case WM_RBUTTONUP: if (m_ButtonDown == RightButton) { ret = OnButtonUp(pMHS); } break; case WM_MOUSEMOVE: case WM_NCMOUSEMOVE: if (m_ButtonDown != None) { ret = OnMouseMove(pMHS); } } if (ret == NULL) { KillGesture(); } return ret; } ////////////////////////////////////////////////////////////////////// // OnButtonDown // protected virtual member function // // Handles the start of a gesture ////////////////////////////////////////////////////////////////////// CMouseGesture* CMouseGesture::OnButtonDown(MOUSEHOOKSTRUCT *pMHS) { m_BoundingSquare.left = pMHS->pt.x - m_nDistance; m_BoundingSquare.top = pMHS->pt.y - m_nDistance; m_BoundingSquare.right = pMHS->pt.x + m_nDistance; m_BoundingSquare.bottom = pMHS->pt.y + m_nDistance; SHOW_BOUNDING_SQUARE (pMHS, m_BoundingSquare); m_LastDirection = None; if (IsSHIFTpressed()) { m_bShift = true; m_CurrentGesture.push_back(Shift); } if (IsCTRLpressed()) { m_bControl = true; m_CurrentGesture.push_back(Control); } return this; } ////////////////////////////////////////////////////////////////////// // OnMouseMove // protected virtual member function // // Handles the building of the gesture ////////////////////////////////////////////////////////////////////// CMouseGesture* CMouseGesture::OnMouseMove(MOUSEHOOKSTRUCT *pMHS) { #ifdef _SHOW_GESTURE { POINT pt; pt.x = pMHS->pt.x; pt.y = pMHS->pt.y; HWND hWnd = WindowFromPoint(pt); ScreenToClient(hWnd, &pt); HDC hdc = GetDC(hWnd); SetPixel(hdc, pt.x, pt.y, RGB(255, 0, 0)); ReleaseDC(hWnd, hdc); } #endif // make sure the SHIFT and CTRL keys are in // the same state as when the gesture started if (m_bShift != IsSHIFTpressed() || m_bControl != IsCTRLpressed()) { return NULL; } // looking for next direction mouse is taking if (PtInRect(&m_BoundingSquare, pMHS->pt)) { // not yet able to determine return this; } Motion Direction = None; if ((pMHS->pt.x >= m_BoundingSquare.right) && (pMHS->pt.y >= m_BoundingSquare.top) && (pMHS->pt.y <= m_BoundingSquare.bottom)) { Direction = Right; } else if ((pMHS->pt.x <= m_BoundingSquare.left) && (pMHS->pt.y >= m_BoundingSquare.top) && (pMHS->pt.y <= m_BoundingSquare.bottom)) { Direction = Left; } else if ((pMHS->pt.y >= m_BoundingSquare.bottom) && (pMHS->pt.x >= m_BoundingSquare.left) && (pMHS->pt.x <= m_BoundingSquare.right)) { Direction = Down; } else if ((pMHS->pt.y <= m_BoundingSquare.top) && (pMHS->pt.x >= m_BoundingSquare.left) && (pMHS->pt.x <= m_BoundingSquare.right)) { Direction = Up; } if (Direction == None) { // Unable to calculate the direction, probably went // diagonally off a corner of the bounding square return NULL; } SHOW_BOUNDING_SQUARE (pMHS, m_BoundingSquare); // move the bounding square to follow the mouse if (m_LastDirection == Direction) { switch (Direction) { case Left: case Right: m_BoundingSquare.left = pMHS->pt.x - m_nDistance; m_BoundingSquare.right = pMHS->pt.x + m_nDistance; break; case Up: case Down: m_BoundingSquare.top = pMHS->pt.y - m_nDistance; m_BoundingSquare.bottom = pMHS->pt.y + m_nDistance; } } else // m_LastDirection != Direction { m_BoundingSquare.left = pMHS->pt.x - m_nDistance; m_BoundingSquare.right = pMHS->pt.x + m_nDistance; m_BoundingSquare.top = pMHS->pt.y - m_nDistance; m_BoundingSquare.bottom = pMHS->pt.y + m_nDistance; // direction changed, save the new direction m_CurrentGesture.push_back(Direction); m_LastDirection = Direction; } SHOW_BOUNDING_SQUARE (pMHS, m_BoundingSquare); if (GetCapture() == NULL) { // capture the mouse so we can continue recieving messages // if the mouse leaves the window SetCapture(m_hWnd); m_bCaptured = true; } return this; } ////////////////////////////////////////////////////////////////////// // OnButtonUp // protected virtual member function // // Handles the end of the mouse gesture ////////////////////////////////////////////////////////////////////// CMouseGesture* CMouseGesture::OnButtonUp(MOUSEHOOKSTRUCT *pMHS) { UNREFERENCED_PARAMETER(pMHS); // make sure the SHIFT and CTRL keys are in // the same state as when the gesture started if (m_bShift != IsSHIFTpressed() || m_bControl != IsCTRLpressed()) { return NULL; } #ifdef _DEBUG OutputDebugString (_T("\nDumping gesture:\n")); for (Gesture::iterator it = m_CurrentGesture.begin(); it != m_CurrentGesture.end(); ++it) { switch (*it) { case Up: OutputDebugString (_T("Up, ")); break; case Down: OutputDebugString (_T("Down, ")); break; case Left: OutputDebugString (_T("Left, ")); break; case Right: OutputDebugString (_T("Right, ")); break; case LeftButton: OutputDebugString (_T("Left Button, ")); break; case MiddleButton: OutputDebugString (_T("Middle Button, ")); break; case RightButton: OutputDebugString (_T("Right Button, ")); break; case Shift: OutputDebugString (_T("Shift, ")); break; case Control: OutputDebugString (_T("Control, ")); break; default: OutputDebugString (_T("Invalid Gesture")); } } OutputDebugString (_T("\n\n")); #endif UINT GestureID = GetGestureIdFromMap(m_CurrentGesture); if (GestureID > 0 && IsWindow(m_hWnd)) { PostMessage(m_hWnd, WMU_MOUSEGESTURE, (WPARAM)GestureID, (LPARAM)this); } return NULL; } ////////////////////////////////////////////////////////////////////// // Helper functions ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // GetGestureIdFromMap // private member function // // Finds the gesture in the map of recognized patterns // // Returns: // The ID of the pattern found // 0 if not found ////////////////////////////////////////////////////////////////////// UINT CMouseGesture::GetGestureIdFromMap(const Gesture &gesture) { UINT ret = 0; for (GestureMap::const_iterator it = m_GestureMap.begin(); it != m_GestureMap.end(); ++it) { if ((*it).second == gesture) { ret = (*it).first; break; } } return ret; } ////////////////////////////////////////////////////////////////////// // KillGesture // private member function // // Cleans up when a gesture ends or is abandoned ////////////////////////////////////////////////////////////////////// void CMouseGesture::KillGesture() { #ifdef _SHOW_GESTURE // remove any drawing done RedrawWindow(m_hWnd, NULL, NULL, RDW_INVALIDATE | RDW_ERASE); #endif OutputDebugString (_T("Gesture Ended\n")); if (m_bCaptured && GetCapture() == m_hWnd) { ReleaseCapture(); } m_ButtonDown = None; m_bShift = false; m_bControl = false; m_CurrentGesture.clear(); m_bCaptured = false; } ////////////////////////////////////////////////////////////////////// // End //////////////////////////////////////////////////////////////////////
[ "thewolfmanu@8d742ff4-5afa-cc76-88a1-f39302f5df42" ]
[ [ [ 1, 838 ] ] ]
5faa5f32ed99d62b2b3b5464bb2e9ac2b559f9d8
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/Release/Client/stubs/corlib_native_System_Array.h
83c7861b617285d264702da7cf277b2e42da175f
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,702
h
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #ifndef _CORLIB_NATIVE_SYSTEM_ARRAY_H_ #define _CORLIB_NATIVE_SYSTEM_ARRAY_H_ namespace System { struct Array { // Helper Functions to access fields of managed object // Declaration of stubs. These functions are implemented by Interop code developers static UNSUPPORTED_TYPE System_Collections_IList_get_Item( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ); static void System_Collections_IList_set_Item( CLR_RT_HeapBlock* pMngObj, INT32 param0, UNSUPPORTED_TYPE param1, HRESULT &hr ); static INT32 get_Length( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ); static UNSUPPORTED_TYPE CreateInstance( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr ); static void Copy( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, INT32 param2, UNSUPPORTED_TYPE param3, UNSUPPORTED_TYPE param4, HRESULT &hr ); static void Clear( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, INT32 param2, HRESULT &hr ); static INT8 TrySZIndexOf( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, INT32 param2, INT32 param3, UNSUPPORTED_TYPE param4, HRESULT &hr ); }; } #endif //_CORLIB_NATIVE_SYSTEM_ARRAY_H_
[ [ [ 1, 32 ] ] ]
a515577adf455e2f402fc6814e08e0f2f57ca67b
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/mm/mmf/T_MdaAudioToneUtility/inc/T_MdaAudioToneUtilityServer.h
bf61943a7fc7221c49b75ceecb52937ed049c808
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,301
h
/* * Copyright (c) 2005-2008 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "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: * */ #if (!defined __T_MDA_AUDIO_TONE_UTILITY_SERVER_H__) #define __T_MDA_AUDIO_TONE_UTILITY_SERVER_H__ // EPOC Includes #include <testblockcontroller.h> #include <testserver2.h> class CT_MdaAudioToneUtilityServer : public CTestServer2 { private: class CT_MdaAudioToneUtilityBlock : public CTestBlockController { public: inline CT_MdaAudioToneUtilityBlock(); inline ~CT_MdaAudioToneUtilityBlock(); inline CDataWrapper* CreateDataL(const TDesC& aData); }; public: inline ~CT_MdaAudioToneUtilityServer(); inline void DeleteActiveSchedulerL(); static CT_MdaAudioToneUtilityServer* NewL(); inline CTestBlockController* CreateTestBlock(); protected: inline CT_MdaAudioToneUtilityServer(); }; #include "T_MdaAudioToneUtilityServer.inl" #endif /* __T_MDA_AUDIO_TONE_UTILITY_SERVER_H__ */
[ "none@none" ]
[ [ [ 1, 53 ] ] ]
f9a7410018e61c422bacacdb117a468b3cb2e117
45229380094a0c2b603616e7505cbdc4d89dfaee
/wavelets/haar_src/src/ai/HaarFeatures.h
8ce65f37dccb4237aa52ac9c079bf2833dd89787
[]
no_license
xcud/msrds
a71000cc096723272e5ada7229426dee5100406c
04764859c88f5c36a757dbffc105309a27cd9c4d
refs/heads/master
2021-01-10T01:19:35.834296
2011-11-04T09:26:01
2011-11-04T09:26:01
45,697,313
1
2
null
null
null
null
UTF-8
C++
false
false
2,338
h
#ifndef HaarFeatures_h #define HaarFeatures_h #include "common.h" #include "vec2D.h" #include "vec2Di.h" class HaarFeatures { public: HaarFeatures(); //HaarFeatures(const HaarFeatures& hf); ~HaarFeatures(); // Operators //const HaarFeatures& operator=(const HaarFeatures& hf); // Operations int load(const wchar_t* file, unsigned int object_width, unsigned int object_height); void unload(); int estimate(const vec2Di& integral_image, //-1 ERR not initialized yet unsigned int dx, unsigned int dy, //positive - size of feature vector const HaarFeatures* pprev = 0); // Access inline unsigned int get_object_width() const; inline unsigned int get_object_height() const; inline const std::vector<Feature>& get_features() const; inline const vec2D& get_feature_vector() const; // Inquiry protected: private: HaarFeatures(const HaarFeatures& hf); const HaarFeatures& operator=(const HaarFeatures& hf); unsigned int m_object_width; unsigned int m_object_height; unsigned int m_object_size; std::vector<Feature> m_features; vec2D* m_feature_vector; }; // Inlines inline unsigned int HaarFeatures::get_object_width() const { return m_object_width; } inline unsigned int HaarFeatures::get_object_height() const { return m_object_height; } inline const std::vector<Feature>& HaarFeatures::get_features() const { return m_features; } inline const vec2D& HaarFeatures::get_feature_vector() const { return *m_feature_vector; } #endif HaarFeatures_h /* Features File: Total Features Number FeatureN Number_of_rects Left Top Right Bottom (in 1.0 unit lengths) Rect_sign 3 feature1 2 0.00 0.00 0.50 1.00 1 0.50 0.00 1.00 1.00 -1 feature2 2 0.00 0.00 1.00 0.50 1 0.00 0.50 1.00 1.00 -1 feature3 4 0.00 0.00 0.50 0.50 1 0.50 0.00 1.00 0.50 -1 0.00 0.50 0.50 1.00 1 0.50 0.50 1.00 1.00 -1 */
[ "perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671" ]
[ [ [ 1, 103 ] ] ]
d0f90f46af63450373c6b1aabb978fa13f422a68
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/BinaryIncrementation.cpp
e602f549f2c88bb45c401a77b07743201fe84224
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
5,393
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "BinaryIncrementation.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define debug(p) cout << #p << "=" << p << endl; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() #define pb push_back class BinaryIncrementation { public: string plusOne(string x) { string ret; int n=(int)x.size(); if(x[n-1]=='0') return x.substr(0,n-1)+'1'; unsigned long ul=0; unsigned long bit=0x00000001; for(int i=n-1;i>-1;i--){ if(x[i]=='1'){ ul += bit; } bit = bit << 1; } ul++; for(unsigned long i=ul;i!=0;i = i>>1){ if(i & 0x00000001){ ret = '1'+ret; }else{ ret = '0'+ret; } } return ret; } }; // BEGIN CUT HERE namespace moj_harness { int run_test_case(int); void run_test(int casenum = -1, bool quiet = false) { if (casenum != -1) { if (run_test_case(casenum) == -1 && !quiet) { cerr << "Illegal input! Test case " << casenum << " does not exist." << endl; } return; } int correct = 0, total = 0; for (int i=0;; ++i) { int x = run_test_case(i); if (x == -1) { if (i >= 100) break; continue; } correct += x; ++total; } if (total == 0) { cerr << "No test cases run." << endl; } else if (correct < total) { cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl; } else { cerr << "All " << total << " tests passed!" << endl; } } int verify_case(int casenum, const string &expected, const string &received, clock_t elapsed) { cerr << "Example " << casenum << "... "; string verdict; vector<string> info; char buf[100]; if (elapsed > CLOCKS_PER_SEC / 200) { sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC)); info.push_back(buf); } if (expected == received) { verdict = "PASSED"; } else { verdict = "FAILED"; } cerr << verdict; if (!info.empty()) { cerr << " ("; for (int i=0; i<(int)info.size(); ++i) { if (i > 0) cerr << ", "; cerr << info[i]; } cerr << ")"; } cerr << endl; if (verdict == "FAILED") { cerr << " Expected: \"" << expected << "\"" << endl; cerr << " Received: \"" << received << "\"" << endl; } return verdict == "PASSED"; } int run_test_case(int casenum) { switch (casenum) { case 0: { string x = "10011"; string expected__ = "10100"; clock_t start__ = clock(); string received__ = BinaryIncrementation().plusOne(x); return verify_case(casenum, expected__, received__, clock()-start__); } case 1: { string x = "10000"; string expected__ = "10001"; clock_t start__ = clock(); string received__ = BinaryIncrementation().plusOne(x); return verify_case(casenum, expected__, received__, clock()-start__); } case 2: { string x = "1111"; string expected__ = "10000"; clock_t start__ = clock(); string received__ = BinaryIncrementation().plusOne(x); return verify_case(casenum, expected__, received__, clock()-start__); } case 3: { string x = "1"; string expected__ = "10"; clock_t start__ = clock(); string received__ = BinaryIncrementation().plusOne(x); return verify_case(casenum, expected__, received__, clock()-start__); } case 4: { string x = "101010101010101010101010101010"; string expected__ = "101010101010101010101010101011"; clock_t start__ = clock(); string received__ = BinaryIncrementation().plusOne(x); return verify_case(casenum, expected__, received__, clock()-start__); } // custom cases /* case 5: { string x = ; string expected__ = ; clock_t start__ = clock(); string received__ = BinaryIncrementation().plusOne(x); return verify_case(casenum, expected__, received__, clock()-start__); }*/ /* case 6: { string x = ; string expected__ = ; clock_t start__ = clock(); string received__ = BinaryIncrementation().plusOne(x); return verify_case(casenum, expected__, received__, clock()-start__); }*/ /* case 7: { string x = ; string expected__ = ; clock_t start__ = clock(); string received__ = BinaryIncrementation().plusOne(x); return verify_case(casenum, expected__, received__, clock()-start__); }*/ default: return -1; } } } int main(int argc, char *argv[]) { if (argc == 1) { moj_harness::run_test(); } else { for (int i=1; i<argc; ++i) moj_harness::run_test(atoi(argv[i])); } } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 215 ] ] ]
4dfd9a82bf18065f235461ec593600e7941baee8
37f1b00f0aba269599453952c0394b105b797744
/classes/ugrad/csci1120/lab1/lab1.cc
6535264667752973d84df297785d1898483c9179
[]
no_license
palmerc/lab
58e95801619a4d9c00a8e1caae8d872952d455b0
d9c36b84dac060ce8c74251f6c42b121653dd837
refs/heads/master
2016-09-06T09:43:12.532000
2010-09-10T14:23:58
2010-09-10T14:23:58
16,708,989
3
1
null
null
null
null
UTF-8
C++
false
false
614
cc
//lab1.cc, a driver for list.cc //CSCI 1120 //Will Briggs #include <iostream.h> #include "list.h" main () { Item Letters [MAX_ITEMS]; int num_letters = 0; insert (Letters, num_letters, 'A'); insert (Letters, num_letters, 'D'); insert (Letters, num_letters, 'R'); insert (Letters, num_letters, 'E'); insert (Letters, num_letters, 'T'); insert (Letters, num_letters, 'M'); insert (Letters, num_letters, 'V'); insert (Letters, num_letters, 'P'); insert (Letters, num_letters, 'Q'); insert (Letters, num_letters, 'X'); print (Letters, num_letters); }
[ "palmerc@9c8e43f7-b2fe-0310-8927-e999a62a3b53" ]
[ [ [ 1, 26 ] ] ]
f189f1b6de3008bc940825f3a46fc45b2803bebf
8c54d89af1800c4c06959a3b7b62d04f883a11c0
/Sphere.hh
2ac3f3ac0896eb820b1eefefb3355c63765207c6
[]
no_license
dknutsen/dokray
567c79e7a69c80a97cd73bead151a12ad2d34f23
92acd2967542865963462aaf2299ab2427b89f31
refs/heads/master
2020-12-24T13:29:01.740250
2011-10-23T23:09:49
2011-10-23T23:09:49
2,639,353
0
0
null
null
null
null
UTF-8
C++
false
false
810
hh
/* Author: Daniel Knutsen Course: Comp 361, Computer Graphics Date: 5/3/09 Desc: This is the header file for the Sphere class */ #ifndef Sphere_hh #define Sphere_hh #include "Primitive.hh" #include "Vector.hh" #include "Point.hh" #include "Ray.hh" #include "HitRecord.hh" #include "RenderContext.hh" class Sphere : public Primitive { private: Point center; float radius; public: Sphere(); Sphere(Material* material, const Point& center, float radius); Point GetCenter()const; float GetRadius()const; Point& GetCenter(); float& GetRadius(); float GetRadiusSquared()const; void Preprocess(); Vector Normal(const Point& point)const; void Intersect(HitRecord& hit, const RenderContext& rc, const Ray& ray)const; }; #endif
[ [ [ 1, 41 ] ] ]
9980bebe161806e38a290ba4776a7152be083966
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/sun/src/QuestScripts/Undercity.cpp
207527be048856d98e31f2ed9c345fe02562bf74
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
1,525
cpp
#include "StdAfx.h" #include "Setup.h" #include "EAS/EasyFunctions.h" class Quest_JourneytoUndercity : public QuestScript { public: void CanSelect(Creature *creat) { creat->SetUInt32Value(UNIT_NPC_FLAGS, 2); } void OnQuestComplete(Player* mTarget, QuestLogEntry *qLogEntry) { Creature *creat = mTarget->GetMapMgr()->GetSqlIdCreature(19175); //Lady Sylvanas Windrunner - NCDB guid if(creat == NULL) return; sEAS.SpawnCreatureExtended(mTarget, 21628, 1295.222656, 314.253998, -57.320854, 2.365611, 35, 180000, true, true, true); sEAS.SpawnCreatureExtended(mTarget, 21628, 1293.403931, 311.264465, -57.320854, 1.939140, 35, 180000, true, true, true); sEAS.SpawnCreatureExtended(mTarget, 21628, 1286.532104, 311.452423, -57.320854, 0.592182, 35, 180000, true, true, true); sEAS.SpawnCreatureExtended(mTarget, 21628, 1284.536011, 314.496338, -57.320845, 0.580401, 35, 180000, true, true, true); creat->PlaySoundToSet(10896); creat->CastSpell(creat->GetGUID(), dbcSpell.LookupEntry(36568), false); creat->SetUInt32Value(UNIT_NPC_FLAGS, 0); // Players can't interact with Sylvanas for 180000 ms. TimedEvent *te = TimedEvent::Allocate(this, new CallbackP1<Quest_JourneytoUndercity, Creature*>(this, &Quest_JourneytoUndercity::CanSelect, creat), 0, 180000, 1); creat->event_AddEvent(te); } }; void SetupUndercity(ScriptMgr *mgr) { mgr->register_quest_script(9180, CREATE_QUESTSCRIPT(Quest_JourneytoUndercity)); }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 38 ] ] ]