blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
16
author_lines
sequencelengths
1
16
7c9cde8114d6e45f891b86fb51dc0244be1165f9
e8db4eeab529af596d2761e20583ebf0603bb6e9
/Charack/height.cpp
b0a9d1a2d12fc0b1bcb8c7feaacbc4a456b1df1c
[]
no_license
gamedevforks/charack
099c83fe64c076c126b1ea9212327cd3bd05b42c
c5153d3107cb2a64983d52ee37c015bcd7e93426
refs/heads/master
2020-04-11T04:18:57.615099
2008-10-29T13:26:33
2008-10-29T13:26:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
#include "height.h" Perlin gPerlinNoise(16, 6, 1, 94); Perlin gMediumPerlinNoise(16, 8, 1, 94); float fx1(float a) { return gMediumPerlinNoise.Get(a/(CK_MAX_WIDTH/50), 0.22) * 800; // return gPerlinNoise.Get(a/(CK_MAX_WIDTH/5), 0.22) * 800 + gMediumPerlinNoise.Get(a/(CK_MAX_WIDTH/50), 0.22) * 800; } float fz1(float a) { return gMediumPerlinNoise.Get(a/(CK_MAX_WIDTH/20), 0.22) * 800; }
[ [ [ 1, 13 ] ] ]
6d6cc3351ea815a8ff6c698f217fae261e275898
13ab3c3dbedde1ef5374dde02d7162bbfd728f44
/glib/md5.h
ec507961dd7b5adbce5cad6ec8eecdec519c872e
[]
no_license
pikma/Snap
f4dbb4f99a4ca7a98243c9d10bdb5e0b94ef574e
911f40a2eb0ef5330ecde983137557526955e28a
refs/heads/master
2020-05-20T04:41:03.292112
2011-12-11T22:44:18
2011-12-11T22:44:18
2,729,964
0
0
null
null
null
null
UTF-8
C++
false
false
4,203
h
#ifndef GLIB_MD5_H #define GLIB_MD5_H #include "bits.h" ///////////////////////////////////////////////// // MD5 ClassTP(TMd5, PMd5)//{ private: // first, some types: typedef TB4Def::TB4 uint4; // assumes 4 byte long typedef TB2Def::TB2 uint2; // assumes 2 byte long typedef TB1Def::TB1 uint1; // assumes 1 byte long // next, the private data: uint4 state[4]; uint4 count[2]; // number of *bits*, mod 2^64 uint1 buffer[64]; // input buffer uint1 Sig[16]; bool DefP; // last, the private methods, mostly static: void Init(); // called by all constructors void Transform(uint1* buffer); // does the real update work. static void Encode(uint1* Dst, uint4* Src, uint4 Len); static void Decode(uint4* Dst, uint1* Src, uint4 Len); static void MemCpy(uint1* Dst, uint1* Src, uint4 Len){ for (uint4 ChN=0; ChN<Len; ChN++){Dst[ChN]=Src[ChN];}} static void MemSet(uint1* Start, uint1 Val, uint4 Len){ for (uint4 ChN=0; ChN<Len; ChN++){Start[ChN]=Val;}} // RotateLeft rotates x left n bits. static uint4 RotateLeft(uint4 x, uint4 n){return (x<<n)|(x>>(32-n));} // F, G, H and I are basic MD5 functions. static uint4 F(uint4 x, uint4 y, uint4 z){return (x&y)|(~x&z);} static uint4 G(uint4 x, uint4 y, uint4 z){return (x&z)|(y&~z);} static uint4 H(uint4 x, uint4 y, uint4 z){return x^y^z;} static uint4 I(uint4 x, uint4 y, uint4 z){return y^(x|~z);} // FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. // Rotation is separate from addition to prevent recomputation. static void FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac){ a+=F(b, c, d)+x+ac; a=RotateLeft(a, s)+b;} static void GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac){ a+=G(b, c, d)+x+ac; a=RotateLeft(a, s)+b;} static void HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac){ a+=H(b, c, d)+x+ac; a=RotateLeft(a, s)+b;} static void II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac){ a+=I(b, c, d)+x+ac; a=RotateLeft(a, s)+b;} UndefCopyAssign(TMd5); public: TMd5(){Init();} static PMd5 New(){return PMd5(new TMd5());} TMd5(const PSIn& SIn){Init(); Add(SIn); Def();} static PMd5 New(const PSIn& SIn){return PMd5(new TMd5(SIn));} TMd5(TSIn&){Fail;} static PMd5 Load(TSIn& SIn){return new TMd5(SIn);} void Save(TSOut&){Fail;} // adding data & defining digest void Add(uchar* InBf, const int& InBfL); void Add(const PSIn& SIn); void Def(); // digest data retrieval void GetSigMem(TMem& Mem) const; TStr GetSigStr() const; // data package digest calculation static TStr GetMd5SigStr(const PSIn& SIn){ PMd5 Md5=TMd5::New(SIn); return Md5->GetSigStr();} static TStr GetMd5SigStr(const TStr& Str){ return GetMd5SigStr(TStrIn::New(Str));} static TStr GetMd5SigStr(const TMem& Mem){ return GetMd5SigStr(TMemIn::New(Mem));} // testing correctnes static bool Check(); friend class TMd5Sig; }; ///////////////////////////////////////////////// // MD5-Signature class TMd5Sig{ private: typedef TB1Def::TB1 uint1; // assumes 1 byte long uint1 CdT[16]; public: TMd5Sig(){memset(CdT, 0, 16);} TMd5Sig(const TMd5Sig& Md5Sig){memcpy(CdT, Md5Sig.CdT, 16);} TMd5Sig(const PSIn& SIn); TMd5Sig(const TStr& Str); TMd5Sig(const TChA& ChA); TMd5Sig(const char* CStr); TMd5Sig(const TMem& Mem); TMd5Sig(const TMd5& Md5){memcpy(CdT, Md5.Sig, 16);} TMd5Sig(TSIn& SIn){SIn.LoadBf(CdT, 16);} void Save(TSOut& SOut) const {SOut.SaveBf(CdT, 16);} TMd5Sig& operator=(const TMd5Sig& Md5Sig){ if (this!=&Md5Sig){memcpy(CdT, Md5Sig.CdT, 16);} return *this;} bool operator==(const TMd5Sig& Md5Sig) const { return memcmp(CdT, Md5Sig.CdT, 16)==0;} bool operator<(const TMd5Sig& Md5Sig) const { return memcmp(CdT, Md5Sig.CdT, 16)==-1;} int operator[](const int& CdN) const { Assert((0<=CdN)&&(CdN<16)); return CdT[CdN];} // hash codes int GetPrimHashCd() const; int GetSecHashCd() const; // string representation TStr GetStr() const; }; typedef TVec<TMd5Sig> TMd5SigV; #endif
[ [ [ 1, 119 ] ] ]
14f57de5d60823d404b4d1f37201ae61beda2acc
c2abb873c8b352d0ec47757031e4a18b9190556e
/src/MyGUIEngine/src/MyGUI_MenuBarFactory.cpp
b39a9e256fd76bfe976d431e1fd9d81d0a8625b2
[]
no_license
twktheainur/vortex-ee
70b89ec097cd1c74cde2b75f556448965d0d345d
8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6
refs/heads/master
2021-01-10T02:26:21.913972
2009-01-30T12:53:21
2009-01-30T12:53:21
44,046,528
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,581
cpp
/*! @file @author Albert Semenov @date 05/2008 @module */ #include "MyGUI_MenuBarFactory.h" #include "MyGUI_MenuBar.h" #include "MyGUI_SkinManager.h" #include "MyGUI_WidgetManager.h" namespace MyGUI { namespace factory { MenuBarFactory::MenuBarFactory() { // регестрируем себя MyGUI::WidgetManager & manager = MyGUI::WidgetManager::getInstance(); manager.registerFactory(this); // регестрируем все парсеры manager.registerDelegate("MenuBar_AddItem") = newDelegate(this, &MenuBarFactory::MenuBar_AddItem); } MenuBarFactory::~MenuBarFactory() { // удаляем себя MyGUI::WidgetManager & manager = MyGUI::WidgetManager::getInstance(); manager.unregisterFactory(this); // удаляем все парсеры manager.unregisterDelegate("MenuBar_AddItem"); } const Ogre::String& MenuBarFactory::getType() { return MenuBar::_getType(); } WidgetPtr MenuBarFactory::createWidget(const Ogre::String& _skin, const IntCoord& _coord, Align _align, CroppedRectanglePtr _parent, WidgetCreator * _creator, const Ogre::String& _name) { return new MenuBar(_coord, _align, SkinManager::getInstance().getSkin(_skin), _parent, _creator, _name); } void MenuBarFactory::MenuBar_AddItem(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value) { MYGUI_RETURN_IS_FALSE_TYPE(MenuBarPtr, _widget, _key); static_cast<MenuBarPtr>(_widget)->addItem(_value); } } // namespace factory } // namespace MyGUI
[ "twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83" ]
[ [ [ 1, 54 ] ] ]
a47cd651ec658c332ac35ff35291ac201941014d
27bde5e083cf5a32f75de64421ba541b3a23dd29
/external/GameX/source/gamex-defines.hpp
6d4a6e531d4d22377f2c87361678f0d510602ab8
[]
no_license
jbsheblak/fatal-inflation
229fc6111039aff4fd00bb1609964cf37e4303af
5d6c0a99e8c4791336cf529ed8ce63911a297a23
refs/heads/master
2021-03-12T19:22:31.878561
2006-10-20T21:48:17
2006-10-20T21:48:17
32,184,096
0
0
null
null
null
null
UTF-8
C++
false
false
24,882
hpp
// // GameX - Definition Header - Constants used by GameX // // This software is released under the GameX GNU GPL // Open Source License. See the GameX documentation included // with this source code for terms of modification, // distribution and re-release. // #ifndef GAMEX_DEFINES_INCLUDED #define GAMEX_DEFINES_INCLUDED #define DEGtoRAD (3.1415926538f/180.0f) // *** Constants for initializing GameX: // these are combinable flags to be used with GameX.Initialize() enum _GAMEX_INIT_FLAGS { // video flags: VIDEO_16BIT = 0x00002000l, // run game in 16 bit color mode -- supported, currently fastest and most common mode VIDEO_FULLSCREEN = 0x00000001l, // run in fullscreen mode (at a resolution that best fits the requested viewport size) VIDEO_WINDOWED = 0x00000002l, // run in windowed mode -- if neither VIDEO_FULLSCREEN nor VIDEO_WINDOWED is specified, the user will be prompted as to whether to run in fullscreen mode when the game starts // other flags: RUN_USEESCAPEKEY = 0x01000000l, // allow the game to detect the escape key instead of escape automatically quitting RUN_AUTOSHOWINFO = 0x02000000l, // display debugging information (such as frame rate) in the title bar RUN_ALWAYSKEEPCURSOR = 0x04000000l, // prevent GameX from hiding the cursor in fullscreen mode -- note that a visible cursor over the game window can reduce the game's framerate considerably, it's better to draw your own cursor in the game if you need it RUN_ALWAYSHIDECURSOR = 0x08000000l, // allow GameX to always hide the cursor when it is over the game RUN_NOCONFIRMQUIT = 0x10000000l, // disallow GameX from asking whether the user is sure about quitting // video flags for advanced users: VIDEO_LOWRES = 0x00000004l, // Tells GameX to use low-resolution images to save memory/speed VIDEO_NORESIZE = 0x00000008l, // GameX automatically handles window resizing and maximizing if this flag is not specified. VIDEO_ALLOWREFRESHSYNC = 0x00000010l, // sync screen updates to monitor refresh rate -- attempts to prevent visual tearing artifacts at minimal cost of CPU time -- note that this limits the framerate to the current monitor's refresh rate (which is generally a good thing) VIDEO_SLOWDEBUGDRAWING = 0x00000100l, // use this to cause GameX to draw things REALLY slowly so you can see what's happening inside individual frames VIDEO_SOFTWAREONLY = 0x00000200l, // use this to force all D3D operations to use software instead of any available hardware -- usually a bad idea, unless using an outdated video card which doesn't fully support Direct3D VIDEO_24BIT = 0x00004000l, // (NOT YET TESTED) run game in 24 bit color mode -- externally it's the same thing as 32 bit color mode -- untested for now VIDEO_32BIT = 0x00008000l, // (MOSTLY IMPLEMENTED) run game in 32 bit color mode -- supported but may be slow depending on video card // audio flags for advanced users: AUDIO_DISABLE = 0x00010000l, // disable all audio support, so sounds and music will not play -- only possible use is to mute a game when debugging to make debugging easier or something // other flags for advanced users: RUN_NOMOUSEINPUT = 0x20000000l, // prevent GameX from keeping track of mouse movement and clicks RUN_BACKGROUND = 0x40000000l, // allow game to keep running even in the background by preventing GameX from automatically pausing the game -- possible uses are for networked games or cheat prevention, maybe RUN_NOALTENTERTOGGLE = 0x80000000l, // allow the player to hit alt-enter without toggling between fullscreen/windowed mode }; typedef long GameXInitFlags; // *** Constants for drawing with GameX: // constants to be used alone or combined with | and used as flags whenever drawing images // for example, you can combine the DRAW_PLAIN and DRAWOP_CENTERED draw flags // like so: GameX.DrawImage(DRAW_PLAIN | DRAWOP_CENTERED, &ship_img, x,y); enum _DRAW_FLAGS { // Draw Mode flags: (not to be combined with each other) // These determine the main way of drawing the image (copy the image directly, or add it onto the destination for a glow effect, etc.) // Exactly one Draw Mode flag must be specified whenever drawing an image. DRAW_PLAIN = 0x001l, // DEST = SOURCE -- draw image normally -- can still be combined with options and color/alpha blending (makes use of alpha layer if image has one) DRAW_NORMAL = DRAW_PLAIN, // backward compatibility DRAW_ADD = 0x002l, // DEST = DEST + SOURCE -- draw additively using r,g,b intensity if given (multiplies by alpha layer if image has one, although alpha layer is NOT necessary for ADDED images and may slow things down) (alpha arg < 255 scales down intensity) DRAW_ADDED = DRAW_ADD, // backward compatibility DRAW_SUBTRACT = 0x004l, // DEST = DEST - SOURCE -- draw subtractively using r,g,b intensity if given (alpha arg < 255 scales down intensity) -- not supported on older video cards DRAW_GHOST = 0x008l, // DEST = DEST*(1-SOURCE) + SOURCE*SOURCE -- draw blended using color-valued alpha and r,g,b values if given (a < 255 scales down intensity/opacity) i.e. a sort of auto-alpha effect DRAW_INVERT = 0x010l, // DEST = DEST + SOURCE - 2*SOURCE*DEST -- draw by inverting destination proportionally to source colors (alpha < 255 scales down intensity) -- if instead of doing this you just want to invert the source image when drawing, that's what DRAWOP_INVERTED is for DRAW_BURN = 0x020l, // DEST = SOURCE - SOURCE*SOURCE - DEST*SOURCE -- draw by inverting destination proportionally to greyness of source colors -- may not be supported on older video cards DRAW_INTENSIFY = 0x040l, // DEST = DEST + 2*SOURCE*DEST -- draw additively, but add less as the destination becomes darker -- not supported on older video cards DRAW_ADDSOFT = 0x080l, // DEST = DEST + SOURCE - SOURCE*DEST -- similar to DRAW_ADD, but adds less to brighter areas (prevents overexposure) DRAW_ADDSHARP = 0x100l, // DEST = DEST + 4*SOURCE*SOURCE -- similar to DRAW_ADD, but colors show more sharply (increases contrast) DRAW_MULTIPLY = 0x200l, // DEST = DEST * SOURCE -- multiply destination by source -- probably not useful in most situations -- not supported on older video cards DRAWMODESMASK = 0x3FFl, // DO NOT SPECIFY THIS FLAG! -- this is a mask for all of the draw modes and is only to be used internally // (Looking for DRAW_ALPHA or DRAW_MASKED? They no longer exist. Instead, load the image with LOAD_ALPHA or LOAD_MASKED and draw with DRAW_PLAIN to achieve these effects.) // Draw Option flags: (to be combined with a Draw Mode flag or also with each other) // These let you specify extra effects that can be combined with each other which can complement any drawing mode above. // Zero or more of these flags are allowed whenever drawing images/boxes/backgrounds DRAWOP_BRIGHT = 0x1000l, // draw image with 2X brightness, so r,g,b of 128 act like 255, and r,g,b of 255 act like 510 (which is normally out of range) -- try combining with various draw modes for interesting effects DRAWOP_INVERTED = 0x2000l, // temporarily invert the image before drawing it -- try combining with various draw modes for interesting effects -- do not confuse this flag with the very different DRAW_INVERT flag DRAWOP_NOFILTER = 0x4000l, // render the image without doing bilinear filtering, i.e. turns off automatic image smoothing // note that this does NOT increase drawing speed, but sometimes images look cleaner when not smoothed. DRAWOP_NODITHER = 0x8000l, // dithering give the impression that there are more colors than really available (usually with diffusion-type pixel dithering), // i.e. this flag turns off automatic color smoothing DRAWOP_CENTERED = 0x10000l, // makes point coordinates specify center instead of top-left // useful for many objects whose positions are defined in relation to their center DRAWOP_HMIRROR = 0x20000l, // horizontally flip the image when drawing -- the flip happens before any scaling/rotation/vertex blending DRAWOP_VMIRROR = 0x40000l, // vertically flip the image when drawing -- the flip happens before any scaling/rotation/vertex blending DRAWOP_NOCULL = 0x80000l, // don't skip drawing even if the scale is negative or it's facing the wrong way DRAWOP_NOBLENDALPHA = 0x100000l, // treats alpha layer like a normal color layer to be transferred instead of using it to blend colors DRAWOP_ALPHAINTERSECT = 0x200000l, // if drawing an alpha image or texture in 3D, tells GameX to draw part of it twice to allow for 3D intersection with other 3D polygons (for advanced users) DRAWOP_KEEPSTATES = 0x400000l, // tells GameX to NOT reset draw states after calling the function this flag is given to. DRAWOP_DITHER = 0x0l, // dithering is the default now -- this does nothing and is only here for backwards compatibility DRAWOPTIONSMASK = 0x7FF000l // DO NOT SPECIFY THIS FLAG! -- to be used internally }; typedef long DrawFlags; #define VIEWPORT (ImageX *)1 // dummy image that's really the viewport // to copy from the viewport, use this constant as the source image // defaults used internally: #define DEFAULT -99999 // reserved value that signifies either a default color or image rectangle full expansion (or rarely, non-scaled centered changed to DEFAULT2) #define DEFAULT2 -99998.0f // reserved value that signifies image rectangle non-scaled expansion #define FULLRECT (*((RECT *)0)) // dummy value to mean a rectangle that fills up the entire available space (0,0,DEFAULT,DEFAULT) // different modes of 3D auto-sorting for use in Begin3DScene: enum _SCENE_SORT_MODE { SCENESORTZ = 0x1, // z-buffer byte SCENESORTD = 0x2, // depth-sort byte SCENESORTS = 0x4, // signed z byte SCENESORT2 = 0x8 // dual pass byte }; typedef long SceneSortMode; // *** Constants for image usage (for advanced and internal use only): enum _IMAGE_USAGE_FLAGS { // (combinable) // These are no longer needed whenever loading or creating images, except internally by GameX. // The only way to use these flags externally now is with ImageX::ConvertUsageTo() // (their names remain unchanged to allow some backwards compatibility, compile errors->warnings instead) LOAD_ALPHA = 0x02, // uses a transparency layer that's part of the image -- currently only affects DRAW_PLAIN and DRAW_ADD drawing of this image LOAD_MASKED = 0x04, // uses a mask to exclude 0-value pixels, or converts alpha layer to mask if LOAD_ALPHA is specified too LOAD_TARGETABLE = 0x08, // is capable of being drawn into -- automatically enabled as needed so not really necessary LOAD_NON3D = 0x10, // tells GameX to load this image without support for 3D-accelerated drawing (from) // (this flag may not be fully supported and is for advanced users and testing only) LOAD_SCREENTARGET = (LOAD_TARGETABLE|LOAD_NON3D), // if copying from the screen, can copy into an image set with this for a speed boost LOADMODESMASK = 0x1E, // DO NOT SPECIFY THIS FLAG -- this is a mask for all of the load modes and is only to be used internally }; typedef unsigned int ImageUsage; // *** Constants for playing sound with GameX: // combinable (but usually stand-alone) constants, only used for GameX.PlaySound() in the "how" parameter enum _SOUND_PLAY_MODE { PLAY_CONTINUE = 0x00, // continue playing sound if it's already playing (default) PLAY_REWIND = 0x01, // start the sound over if it's already playing (otherwise the sound continues playing) PLAY_LOOP = 0x02, // set the sound to automatically rewind and play again each time it finishes PLAY_NOTIFLESSVOL = 0x04 // if the sound is currently playing, don't play now unless it's as loud or louder now }; typedef int SoundPlayMode; // type definitions used internally for music #define MUSIC_TYPE_NONE -1 #define MUSIC_TYPE_MIDI 0 #define MUSIC_TYPE_MP3 1 #define WM_DIRECTSHOW_EVENT (WM_APP+1) // custom WindowFunc callback function for music events // *** Constants for getting input with GameX: // mouse button constants for GetMousePress() // note to self: these values must match the fields of di_mousestate.rgbButtons[] enum _MOUSE_BUTTON_ID { MOUSE_LEFT = (int)0, // left click MOUSE_RIGHT = 1, // right click MOUSE_MIDDLE = 2, // middle click (clicking on the scroll wheel, which not all mice have) MOUSE_MID = MOUSE_MIDDLE, // abbreviation MOUSE_EXTRA = 3 // no idea what the fourth button on a mouse is, but might as well support it, if/when it exists }; typedef int MouseButtonID; // prevent possible compiler complaining if the main GameX header wasn't included: #ifndef DIRECTINPUT_VERSION #pragma comment(lib,"dinput.lib") #define DIRECTINPUT_VERSION 0x0700 #include "dinput.h" #endif enum _BUFFERED_KEY_ID { // things returned by GetBufferedKeyPress, besides regular characters: BUFFERED_KEY_NOTHING = 0, BUFFERED_KEY_BACK = VK_BACK, BUFFERED_KEY_BACKSPACE = VK_BACK, BUFFERED_KEY_DELETE = VK_BACK, BUFFERED_KEY_RETURN = VK_RETURN, BUFFERED_KEY_ENTER = VK_RETURN, BUFFERED_KEY_TAB = VK_TAB, BUFFERED_KEY_ESCAPE = VK_ESCAPE, BUFFERED_KEY_ESC = VK_ESCAPE }; // Key constants for all keyboard input functions (except GetKey/GetBufferedKeyPress which doesn't take or return a key id) // These correspond to physical keys on the keyboard that a game might want to respond to: // (many keys have multiple names, for instance KEY_RETURN and KEY_ENTER are exactly the same) enum _KEY_ID { // The four arrow keys: KEY_LEFT = DIK_LEFT, // <- KEY_LEFTARROW = DIK_LEFT, KEY_RIGHT = DIK_RIGHT, // -> KEY_RIGHTARROW = DIK_RIGHT, KEY_UP = DIK_UP, // ^ KEY_UPARROW = DIK_UP, KEY_DOWN = DIK_DOWN, // v KEY_DOWNARROW = DIK_DOWN, // Major keys around the main keyboard: KEY_ESCAPE = DIK_ESCAPE, // you must Initialize GameX with RUN_USEESCAPEKEY in order to use KEY_ESCAPE KEY_ESC = DIK_ESCAPE, KEY_RETURN = DIK_RETURN, // the enter key KEY_ENTER = DIK_RETURN, KEY_SPACE = DIK_SPACE, // the space bar KEY_SPACEBAR = DIK_SPACE, KEY_BACKSPACE = DIK_BACK, KEY_BACK = DIK_BACK, // the backspace key KEY_TAB = DIK_TAB, // the tab key KEY_SLASH = DIK_SLASH, // \| KEY_BAR = DIK_SLASH, KEY_FORWARDSLASH = DIK_SLASH, // Central keyboard keys: KEY_TILDE = DIK_GRAVE, // `~ KEY_GRAVE = DIK_GRAVE, KEY_1 = DIK_1, // 1! (the key ID of 1 on the main keyboard, NOT on the number pad) KEY_2 = DIK_2, // 2@ KEY_3 = DIK_3, // 3# KEY_4 = DIK_4, // 4$ KEY_5 = DIK_5, // 5% KEY_6 = DIK_6, // 6^ KEY_7 = DIK_7, // 7& KEY_8 = DIK_8, // 8* KEY_9 = DIK_9, // 9( KEY_0 = DIK_0, // 0) KEY_MINUS = DIK_MINUS, // the -_ key on the main keyboard KEY_DASH = DIK_MINUS, KEY_EQUALS = DIK_EQUALS, // the =+ key on the main keyboard KEY_PLUS = DIK_EQUALS, KEY_Q = DIK_Q, // the letter keys KEY_W = DIK_W, KEY_E = DIK_E, KEY_R = DIK_R, KEY_T = DIK_T, KEY_Y = DIK_Y, KEY_U = DIK_U, KEY_I = DIK_I, KEY_O = DIK_O, KEY_P = DIK_P, KEY_LBRACKET = DIK_LBRACKET, // [{ KEY_LEFTBRACKET = DIK_LBRACKET, KEY_LBRACE = DIK_LBRACKET, KEY_LEFTBRACE = DIK_LBRACKET, KEY_RBRACKET = DIK_RBRACKET, // ]} KEY_RIGHTBRACKET = DIK_RBRACKET, KEY_RBRACE = DIK_RBRACKET, KEY_RIGHTBRACE = DIK_RBRACKET, KEY_A = DIK_A, KEY_S = DIK_S, KEY_D = DIK_D, KEY_F = DIK_F, KEY_G = DIK_G, KEY_H = DIK_H, KEY_J = DIK_J, KEY_K = DIK_K, KEY_L = DIK_L, KEY_SEMICOLON = DIK_SEMICOLON, // ;: KEY_COLON = DIK_SEMICOLON, KEY_APOSTROPHE = DIK_APOSTROPHE, // '" KEY_QUOTE = DIK_APOSTROPHE, KEY_Z = DIK_Z, KEY_X = DIK_X, KEY_C = DIK_C, KEY_V = DIK_V, KEY_B = DIK_B, KEY_N = DIK_N, KEY_M = DIK_M, KEY_COMMA = DIK_COMMA, // ,< KEY_LESS = DIK_COMMA, KEY_PERIOD = DIK_PERIOD, // .> KEY_GREATER = DIK_PERIOD, KEY_DOT = DIK_PERIOD, KEY_BACKSLASH = DIK_BACKSLASH, // /? KEY_QUESTION = DIK_BACKSLASH, KEY_DIVIDE = DIK_BACKSLASH, // NOT on the numeric keypad, that's KEY_NUMDIVIDE // Keys on the number pad: // (note that not all keyboards have a number pad) KEY_NUM7 = DIK_NUMPAD7, // the key ID of 7 on the numeric keypad, NOT on the main keyboard KEY_NUM8 = DIK_NUMPAD8, KEY_NUM9 = DIK_NUMPAD9, KEY_NUM4 = DIK_NUMPAD4, KEY_NUM5 = DIK_NUMPAD5, KEY_NUM6 = DIK_NUMPAD6, KEY_NUM1 = DIK_NUMPAD1, KEY_NUM2 = DIK_NUMPAD2, KEY_NUM3 = DIK_NUMPAD3, KEY_NUM0 = DIK_NUMPAD0, KEY_NUMSTAR = DIK_NUMPADSTAR, KEY_NUMTIMES = DIK_NUMPADSTAR, KEY_NUMMULTIPLY = DIK_NUMPADSTAR, KEY_NUMMINUS = DIK_SUBTRACT, KEY_NUMSUBTRACT = DIK_SUBTRACT, KEY_NUMPLUS = DIK_ADD, KEY_NUMADD = DIK_ADD, KEY_NUMDIVIDE = DIK_DIVIDE, KEY_NUMSLASH = DIK_DIVIDE, KEY_NUMDECIMAL = DIK_DECIMAL, KEY_NUMPERIOD = DIK_DECIMAL, KEY_NUMDOT = DIK_DECIMAL, // Function keys (most keyboards have F1 through F12 at the top) and keys nearby KEY_F1 = DIK_F1, KEY_F2 = DIK_F2, KEY_F3 = DIK_F3, KEY_F4 = DIK_F4, KEY_F5 = DIK_F5, KEY_F6 = DIK_F6, KEY_F7 = DIK_F7, KEY_F8 = DIK_F8, KEY_F9 = DIK_F9, KEY_F10 = DIK_F10, KEY_F11 = DIK_F11, KEY_F12 = DIK_F12, KEY_PRINT = DIK_SYSRQ, KEY_SYSRQ = DIK_SYSRQ, KEY_NUMLOCK = DIK_NUMLOCK, // NOTE: Use GameX.IsNumLockOn() instead to check whether num lock is on KEY_SCROLLOCK = DIK_SCROLL, // NOTE: Use GameX.IsScrollLockOn() instead to check whether scroll lock is on KEY_PAUSE = DIK_PAUSE, KEY_BREAK = DIK_PAUSE, KEY_INSERT = DIK_INSERT, KEY_HOME = DIK_HOME, KEY_PAGEUP = DIK_PRIOR, KEY_PGUP = DIK_PRIOR, KEY_DELETE = DIK_DELETE, KEY_END = DIK_END, KEY_PAGEDOWN = DIK_NEXT, KEY_PAGEDN = DIK_NEXT, KEY_PGDN = DIK_NEXT, // Modifier keys: // Note: use IsAltDown(), IsShiftDown(), IsCtrlDown(), and IsWinDown() instead of these when possible KEY_LALT = DIK_LMENU, KEY_LMENU = DIK_LMENU, KEY_LEFTALT = DIK_LMENU, KEY_RALT = DIK_RMENU, KEY_RMENU = DIK_RMENU, KEY_RIGHTALT = DIK_RMENU, KEY_LSHIFT = DIK_LSHIFT, KEY_LEFTSHIFT = DIK_LSHIFT, KEY_RSHIFT = DIK_RSHIFT, KEY_RIGHTSHIFT = DIK_RSHIFT, KEY_LCTRL = DIK_LCONTROL, KEY_LEFTCTRL = DIK_LCONTROL, KEY_LCONTROL = DIK_LCONTROL, KEY_LEFTCONTROL = DIK_LCONTROL, KEY_RCTRL = DIK_RCONTROL, KEY_RIGHTCTRL = DIK_RCONTROL, KEY_RCONTROL = DIK_RCONTROL, KEY_RIGHTCONTROL = DIK_RCONTROL, KEY_CAPS = DIK_CAPITAL, // Caps lock -- NOTE: Use GameX.IsCapsLockOn() instead to check whether caps lock is on. KEY_CAPSLOCK = DIK_CAPITAL, // These constants are for treating caps lock like a normal key, which it isn't. KEY_CAPITAL = DIK_CAPITAL, KEY_LWIN = DIK_LWIN, // Left Windows key KEY_RWIN = DIK_RWIN, // Right Windows key (not all keyboards have it) }; typedef int KeyID; // input byte codes used internally by GameX #define INPUT_DOUBLE 0x01 // custom bit code for double-pressed (for mouse double-click recognition) #define INPUT_HELD 0x20 // custom bit code for pressed and held, if turned on, should also turn off INPUT_PRESSED #define INPUT_PRESSED 0x80 // (must be 0x80 = 128, it's part of DirectInput functions for pressed states) #define WINDX_BUFSIZE 1024 // Keyboard Buffer Size, newest data is lost if buffer overflows enum _COLOR_SET_COND { COLOR_COND_NEGATIVE, // < 0 COLOR_COND_POSITIVE, // > 0 COLOR_COND_NEUTRAL, // -50 to 50 COLOR_COND_ANYTHING, // anything COLOR_COND_GREATER, // > other COLOR_COND_LESS, // < other COLOR_COND_NEAR // other-50 to other+50 }; typedef int ColorSetCondition; enum _COLOR_SET_TYPE { COLOR_SET_CONSTANT, // 50 COLOR_SET_A, // A COLOR_SET_B, // B COLOR_SET_ABS_A, // abs(A) COLOR_SET_ABS_B, // abs(B) COLOR_SET_MAX, // max(A,B) COLOR_SET_MIN, // min(A,B) COLOR_SET_A_PLUS_B, // A+B COLOR_SET_A_MINUS_B, // A-B COLOR_SET_ABS_A_PLUS_ABS_B, // abs(A)+abs(B) COLOR_SET_ABS_A_MINUS_ABS_B, // abs(A)-abs(B) COLOR_SET_L, // (float)(L*L*L)/(100.0f*100.0f) COLOR_SET_L_SMOOTH, // ((float)(L*L*L)/(100.0f*100.0f)-50)*2 COLOR_SET_SIN_A, // sinf((float)A*((360.0f/100.0f)*DEGtoRAD))*100.0f COLOR_SET_SIN_B, // sinf((float)B*((360.0f/100.0f)*DEGtoRAD))*100.0f COLOR_SET_COS_A, // cosf((float)A*((360.0f/100.0f)*DEGtoRAD))*100.0f COLOR_SET_COS_B, // cosf((float)B*((360.0f/100.0f)*DEGtoRAD))*100.0f COLOR_SET_SIN_L, // sinf((float)(L*L*L)/(100.0f*100.0f)*((360.0f/100.0f)*DEGtoRAD))*100.0f COLOR_SET_COS_L // cosf((float)(L*L*L)/(100.0f*100.0f)*((360.0f/100.0f)*DEGtoRAD))*100.0f }; typedef int ColorSetType; enum _COLOR_SWAP_TYPE { COLOR_SWAP_SAME=-1, // Reds->Reds, Greens->Greens, Blues->Blues COLOR_SWAP_ROTATE120=0, // Reds->Greens, Greens->Blues, Blues->Reds COLOR_SWAP_ROTATE240, // Reds->Blues, Greens->Reds, Blues->Greens COLOR_SWAP_REDGREEN, // Reds <-> Greens COLOR_SWAP_REDBLUE, // Blues <-> Reds COLOR_SWAP_GREENBLUE, // Greens <-> Blues COLOR_SWAP_BA, // ROYGBIV -> RVIBGYO COLOR_SWAP_NBA, // ROYGBIV -> GBIVROY COLOR_SWAP_BNA, // ROYGBIV -> VROYGBI COLOR_SWAP_NBNA, // ROYGBIV -> BGYORVI COLOR_SWAP_ANB, // ROYGBIV -> VIBGYOR COLOR_SWAP_NAB, // ROYGBIV -> GYORVIB COLOR_SWAP_NANB, // ROYGBIV -> BIVROYG COLOR_SWAP_BB, // ROYGBIV -> RRRRVIB COLOR_SWAP_NBB, // ROYGBIV -> GGGGYIV COLOR_SWAP_BNB, // ROYGBIV -> VVVVIYG COLOR_SWAP_NBNB, // ROYGBIV -> BBBBVIR COLOR_SWAP_AA, // ROYGBIV -> RVIBIVR COLOR_SWAP_NAA, // ROYGBIV -> GYIVIYG COLOR_SWAP_ANA, // ROYGBIV -> VIYGYIV COLOR_SWAP_NANA // ROYGBIV -> BIVRVIB }; typedef int ColorSwapType; // *** Internal Image-Handling Definitions: #define DRAW_UNDEF 0x0000 // can't be drawn or operated on #define IMG_OK 42 // chose 42 to make accidental setting to OK status more unlikely #define IMG_NOTREADY 1 #define IMG_IGNORE 2 // **** Image Pixel Channels enum _IMAGE_CHANNEL { CHAN_INDEXED=0, CHAN_RED=1, CHAN_GREEN=2, CHAN_BLUE=3, CHAN_ALPHA=4, CHAN_GRAY=5 }; // **** Image Pixel-Format Information enum _IMAGE_PIX_INFO { IMG_UNDEF = 0x00, // Image information is undefined. IMG_ALPHA = 0x01, // Image has an alpha channel (follows color data) IMG_MERGEALPHA = 0x02, // Alpha channel is merged with data at pixel level (RGBA) IMG_INDEXED = 0x04, // Image is indexed IMG_LOWCOLOR = 0x08, // Image is low color. (BPP=4+4+4+[A]) IMG_HIGHCOLOR = 0x10, // Image is high color. (BPP=5+6+5+[A]) IMG_TRUECOLOR = 0x20, // Image is true color. (BPP=8+8+8+[A]) IMG_TRUECOLORX = 0x40, // Image is true color. (BPP=8+8+8+8) IMG_MASKED = 0x80, // Image uses a 0-mask (instead of alpha) }; #define RED_LUMINANCE 0.3086f // standard empirical luminance values of the primary colors, #define GREEN_LUMINANCE 0.6094f // used to convert color to grayscale while preserving #define BLUE_LUMINANCE 0.0820f // the brightness the human eye perceives // *** Constants for initializing GameX: // current status of Gamex, // mostly used internally by GameX to signal errors enum _GAMEX_STATUS { GAMEX_NO_INIT = (int)0, GAMEX_INITCLASS_FAILED, GAMEX_INITCLASS_OK, GAMEX_INITWINTEMP_FAILED, GAMEX_INITWINTEMP_OK, GAMEX_INITWINREAL_FAILED, GAMEX_INITWINREAL_OK, GAMEX_SHOWWIN_FAILED, GAMEX_SHOWWIN_OK, GAMEX_DDSTART_FAILED, GAMEX_DDSTART_OK, GAMEX_DDSETLEVEL_FAILED, GAMEX_DDSETLEVEL_OK, GAMEX_SETMODE_FAILED, GAMEX_SETMODE_OK, GAMEX_FRONTSURFACE_FAILED, GAMEX_FRONTSURFACE_OK, GAMEX_BACKSURFACE_FAILED, GAMEX_BACKSURFACE_OK, GAMEX_READY, // important, status should be this during game GAMEX_REQSIZE_FAILED, GAMEX_BPP_FAILED, GAMEX_SOUNDINIT_FAILED, GAMEX_SOUNDCOOP_FAILED, GAMEX_SOUNDCREATE_FAILED, GAMEX_SOUNDMATCH_FAILED, GAMEX_SOUNDCAPS_FAILED, GAMEX_SOUNDBUFLEN_FAILED, GAMEX_SOUNDLOST_FAIL, GAMEX_SOUNDINVALID_FAIL, GAMEX_SOUNDPARAM_FAIL, GAMEX_SOUNDPRIOLEVEL_FAIL, GAMEX_IMAGEUSE_FAILED, GAMEX_CLIPPER_FAILED, GAMEX_SHUTTINGDOWN, GAMEX_D3DSTART_FAILED, GAMEX_UNINIT_IMG_DRAW_FAIL, GAMEX_INVALID_DRAW_TIME_FAIL, GAMEX_PIXEL_ACCESS_FAILURE, GAMEX_CREATING_TEST_SURFACE, GAMEX_TOTAL_STATUS_NUMBER }; typedef int GameXStatus; #ifdef _DEBUG #define WINDX_DEBUG // Enable WindowsDX output to debugging file if in Debug build #endif #endif
[ "jbsheblak@5660b91f-811d-0410-8070-91869aa11e15" ]
[ [ [ 1, 512 ] ] ]
c6aed6e73600112b2eb155268db1b759f2625de0
cd61c8405fae2fa91760ef796a5f7963fa7dbd37
/Sauron/Navigation/AStar.h
cba0cf7e3e5296a3262200156641fde789cbc6aa
[]
no_license
rafaelhdr/tccsauron
b61ec89bc9266601140114a37d024376a0366d38
027ecc2ab3579db1214d8a404d7d5fa6b1a64439
refs/heads/master
2016-09-05T23:05:57.117805
2009-12-14T09:41:58
2009-12-14T09:41:58
32,693,544
0
0
null
null
null
null
UTF-8
C++
false
false
474
h
#ifndef __NAVIGATION_ASTAR_H__ #define __NAVIGATION_ASTAR_H__ #include <map> #include "Node.h" namespace sauron { class AStar { public: static Path searchPath( const Node &initial, const Node &final ); private: static pose_t estimateHeuristic( const Node &current, const Node &final ); static Path buildPath( const Node &final, std::map<Node, Node> &cameFrom ); }; } // namespace sauron #endif //__NAVIGATION_ASTAR_H__
[ "fggodoy@8373e73c-ebb0-11dd-9ba5-89a75009fd5d", "budsbd@8373e73c-ebb0-11dd-9ba5-89a75009fd5d" ]
[ [ [ 1, 16 ], [ 18, 22 ] ], [ [ 17, 17 ] ] ]
b8285a2b0f1a131b7fb02afe6b63d8a57f42c453
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/knet/udp/impl/UdpConnection.cpp
908f7bbee1728fbc6424f22be8586323376f1531
[]
no_license
lvtx/gamekernel
c80cdb4655f6d4930a7d035a5448b469ac9ae924
a84d9c268590a294a298a4c825d2dfe35e6eca21
refs/heads/master
2016-09-06T18:11:42.702216
2011-09-27T07:22:08
2011-09-27T07:22:08
38,255,025
3
1
null
null
null
null
UTF-8
C++
false
false
14,818
cpp
#include "stdafx.h" #include <kcore/corebase.h> #include <knet/udp/impl/UdpConnection.h> #include <knet/message/net/NetStateMessage.h> #include <knet/udp/UdpCommunicator.h> #include <knet/udp/impl/Reliable.h> #include <knet/tcp/impl/TcpConnection.h> #include <kcore/sys/ScopedLock.h> #include <kcore/sys/Logger.h> #include <kcore/util/Random.h> namespace gk { UdpConnection::UdpConnection() : m_state( INITIAL ) , m_error( ERROR_NONE ) , m_selfTag( 0 ) , m_remoteTag( 0 ) , m_peer() , m_in() , m_ex() , m_settled( false ) , m_recvBlock1( 2048 ) , m_recvBlock2( 2048 ) , m_readBlock( 0 ) , m_accBlock( 0 ) , m_recvLock() , m_blockCount( 0 ) , m_lossRate( 0 ) , m_communicator( 0 ) , m_reliable( 0 ) { } UdpConnection::~UdpConnection() { K_ASSERT( m_reliable == 0 ); } bool UdpConnection::Init( UdpCommunicator* communicator, uint selfTag, uint remoteTag, const IpAddress& in, const IpAddress& ex ) { K_ASSERT( m_state == INITIAL ); K_ASSERT( communicator != 0 ); K_ASSERT( selfTag > 0 ); K_ASSERT( remoteTag > 0 ); K_ASSERT( selfTag != remoteTag ); m_state = INITIAL; m_communicator = communicator; m_blockCount = 0; m_lossRate = 0; m_recvBlock1.Reset(); m_recvBlock2.Reset(); m_readBlock = &m_recvBlock1; m_accBlock = &m_recvBlock2; m_settled = false; m_reliable = new Reliable; (void)m_reliable->Init( communicator, this ); m_selfTag = selfTag; m_remoteTag = remoteTag; m_in = in; m_ex = ex; sendSyn(); m_state = SYN_SENT; m_tickHpnResend.Reset(); m_tickSynResend.Reset(); m_tickOpenTimeout.Reset(); m_settled = false; LOG( FT_DEBUG, _T("UdpConnection::Connect> self[%d] remote[%d] in[%s] ex[%s]"), m_selfTag, m_remoteTag, in.ToString().c_str(), ex.ToString().c_str() ); return true; } void UdpConnection::Settle( const IpAddress& addr ) { if ( m_settled ) { K_ASSERT( addr == m_peer ); return; } m_peer = addr; m_settled = true; LOG( FT_DEBUG, _T("UdpConnection::Settle> remote[%d] self[%d] IP %s"), m_remoteTag, m_selfTag, m_peer.ToString().c_str() ); } void UdpConnection::OnRecv( void* data, uint len ) { // NOTE: data is owned by Communicator K_ASSERT( data != 0 ); K_ASSERT( len >= sizeof( UdpHeader ) ); K_ASSERT( len <= MAX_SEGMENT_SIZE ); // lock required for buffer ScopedLock sl( m_recvLock ); // this only lock for UDP m_accBlock->WriteInt( len, 16 ); // must be byte aligned m_accBlock->Write( len, data ); ++m_blockCount; // Udp cannot process messages here // since lock propagation is very deep // down to Reliable and UdpCommunicator LOG( FT_DEBUG_FLOW, _T("UdpConnection::OnRecv> remote[%d] self[%d] %d bytes"), m_remoteTag, m_selfTag, len ); } bool UdpConnection::SendReliable( void* data, uint len ) { // NOTE: data is owned by Communicator K_ASSERT( m_state == OPEN ); if ( m_state != OPEN ) { return false; } K_ASSERT( data != 0 ); K_ASSERT( len > 0 ); K_ASSERT( len < MAX_SEGMENT_SIZE ); return m_reliable->Send( data, len, false ); } bool UdpConnection::SendOrdered( void* data, uint len ) { // NOTE: data is owned by Communicator K_ASSERT( m_state == OPEN ); if ( m_state != OPEN ) { return false; } K_ASSERT( data != 0 ); K_ASSERT( len > 0 ); K_ASSERT( len < MAX_SEGMENT_SIZE ); return m_reliable->Send( data, len, true ); } bool UdpConnection::SendLossy( void* data, uint len ) { // NOTE: data is owned by Communicator K_ASSERT( m_state == OPEN ); if ( m_state != OPEN ) { return false; } K_ASSERT( data != 0 ); K_ASSERT( len > 0 ); K_ASSERT( len <= MAX_SEGMENT_SIZE ); UdpHeader header; header.Set( UdpHeader::ACK ); header.seq = 0; header.ack = m_reliable->GetSendCumAck(); header.length = sizeof( UdpHeader ); header.bodyLen = len; byte* sdata = (byte*)g_allocator.Alloc( sizeof( UdpHeader ) + len ); uint slen = sizeof( UdpHeader ) + len; ::memcpy( sdata, (void*)&header, sizeof( UdpHeader ) ); ::memcpy( (void*)(sdata + header.length), data, len ); return SendRaw( sdata, slen ); } bool UdpConnection::SendRaw( void* data, uint len ) { K_ASSERT( data != 0 ); K_ASSERT( len > 0 ); K_ASSERT( len <= MAX_SEGMENT_SIZE ); if ( m_lossRate > 0 ) { uint rand = (uint)(Random::Rand() % 100); if ( rand <= m_lossRate ) { LOG( FT_DEBUG_FLOW, _T("UdpConnection::SendRaw> remote[%d] self[%d] lost by rate %d"), m_remoteTag, m_selfTag, m_lossRate ); return true; } } int slen = 0; if ( m_settled ) { m_communicator->SendTo( (byte*)data, len, m_peer ); } else { m_communicator->SendTo( (byte*)data, len, m_in ); if ( m_in != m_ex ) { m_communicator->SendTo( (byte*)data, len, m_ex ); } } return slen > 0; } void UdpConnection::Run() { processRecvBlocks(); switch ( m_state ) { case CLOSED: // nothing to do break; case SYN_SENT: { processHpn(); processSyn(); processTimeout(); } break; case SYN_RCVD: { processHpn(); processSyn(); processAck(); processTimeout(); } break; case OPEN: { processReliable(); processKeepAlive(); } break; case CLOSE_WAIT: { processKeepAlive(); } break; } } void UdpConnection::Close() { sendRst(); m_state = CLOSE_WAIT; } void UdpConnection::Fini() { Close(); if ( m_reliable != 0 ) { m_reliable->Fini(); delete m_reliable; m_reliable = 0; } } void UdpConnection::onSynRcvd() { // UdpConnection: send SYN in SYN_SENT, SYN_RCVD // if ACK recieved, then UdpConnection is open LOG( FT_DEBUG_FLOW, _T("UdpConnection::onSynRcvd> self[%d] -> remote[%d] State %d syn"), m_selfTag, m_remoteTag, m_state ); switch ( m_state ) { case CLOSED: { m_state = SYN_RCVD; sendSyn(); } break; case SYN_SENT: { m_state = SYN_RCVD; } break; case SYN_RCVD: { sendSyn(); sendAck(); } break; case OPEN: case CLOSE_WAIT: break; } } void UdpConnection::onReset() { if ( m_state != CLOSE_WAIT ) { m_state = CLOSE_WAIT; m_tickCloseWait.Reset(); LOG( FT_DEBUG_FLOW, _T("UdpConnection::onReset> self[%d] -> remote[%d] syn"), m_selfTag, m_remoteTag ); } } void UdpConnection::onNulRcvd() { LOG( FT_DEBUG_FLOW, _T("UdpConnection::onNulRecvd> self[%d] <- remote[%d]"), m_selfTag, m_remoteTag ); sendAck(); // Needs to send something } void UdpConnection::onAckRcvd() { // UdpConnection: send SYN in SYN_SENT, SYN_RCVD // if ACK recieved, then UdpConnection is open // LOG( FT_DEBUG_FLOW, _T("UdpConnection::onAckRecvd> State %d self[%d] <- remote[%d]"), m_state, m_selfTag, m_remoteTag ); switch ( m_state ) { case INITIAL: case SYN_SENT: { sendAck(); m_state = OPEN; LOG( FT_INFO, _T("UdpConnection::onAckRcvd> self[%d] remote[%d] open from SYN_SENT"), m_selfTag, m_remoteTag ); m_tickKeepAlive.Reset(); m_tickInactive.Reset(); notifyOpen(); } break; case SYN_RCVD: { sendAck(); m_state = OPEN; LOG( FT_INFO, _T("UdpConnection::onAckRcvd> self[%d] remote[%d] open from SYN_RCVD"), m_selfTag, m_remoteTag ); m_tickKeepAlive.Reset(); m_tickInactive.Reset(); notifyOpen(); } break; case OPEN: case CLOSED: case CLOSE_WAIT: break; } } void UdpConnection::onUnreliableRecv( const UdpHeader& header, void* data, uint len ) { byte* p = (byte*)data; p = (byte*)( p + header.length ); len = len - header.length; m_communicator->OnRecv( m_remoteTag, (void*)p, len ); // pass the received data } void UdpConnection::processRecvBlocks() { uint len = 0; Buffer buf( MAX_SEGMENT_SIZE ); int blockCount = 0; { ScopedLock sl( m_recvLock ); if ( m_blockCount == 0 ) { return; } blockCount = m_blockCount; m_blockCount = 0; // buffer switch BitStream* p = m_readBlock; m_readBlock = m_accBlock; m_accBlock = p; m_readBlock->Reset(); // read from beginning } while ( blockCount > 0 ) { buf.Clear(); m_readBlock->ReadInt( len, 16 ); K_ASSERT( len > 0 ); K_ASSERT( len <= MAX_SEGMENT_SIZE ); m_readBlock->Read( len, (void*)buf.GetBuffer() ); processBlock( buf.GetBuffer(), len ); --blockCount; } K_ASSERT( blockCount == 0 ); m_readBlock->Reset(); m_readBlock->Clear(); // clear content and error } void UdpConnection::processBlock( void* data, uint len ) { K_ASSERT( data != 0 ); K_ASSERT( len >= sizeof( UdpHeader ) ); m_tickKeepAlive.Reset(); m_tickInactive.Reset(); UdpHeader header; ::memcpy( (void*)&header, data, sizeof( UdpHeader ) ); LOG( FT_DEBUG_FLOW, _T("UdpConnection::processBlock> self[%d] remote[%d] len %d body %d"), m_selfTag, m_remoteTag, len, header.bodyLen ); if ( header.IsSet( UdpHeader::SYN ) ) { K_ASSERT( header.srcId > 0 ); m_selfTag = header.dstId; onSynRcvd(); return; } if ( header.IsSet( UdpHeader::RST ) ) { onReset(); return; } if ( header.IsSet( UdpHeader::NUL ) ) { onNulRcvd(); } if ( header.IsSet( UdpHeader::ACK ) ) { if ( m_state == OPEN && header.ack > 0 ) { m_reliable->OnAck( header ); } else { onAckRcvd(); } } if ( m_state != OPEN ) { return; } // only continue when connected if ( header.IsSet( UdpHeader::EAK ) ) { m_reliable->OnEak( header, data, len ); // EAK is processed only for EAK return; } if ( header.bodyLen == 0 ) { return; } if ( header.IsSet( UdpHeader::RLE ) ) { m_reliable->OnRecv( header, data, len ); } else { onUnreliableRecv( header, data, len ); } } void UdpConnection::processHpn() { if ( m_state == SYN_SENT || m_state == SYN_RCVD ) { if ( m_tickHpnResend.Elapsed() > HPN_RESEND_INTERVAL ) { sendHpn(); LOG( FT_DEBUG_FLOW, _T("UdpConnection::processHpn> self[%d] -> remote[%d] hpn sent"), m_selfTag, m_remoteTag ); m_tickHpnResend.Reset(); } } } void UdpConnection::processSyn() { if ( m_state == SYN_SENT || m_state == SYN_RCVD ) { if ( m_tickSynResend.Elapsed() > SYN_RESEND_INTERVAL ) { sendSyn(); LOG( FT_DEBUG_FLOW, _T("UdpConnection::processSyn> self[%d] -> remote[%d] syn sent"), m_selfTag, m_remoteTag ); m_tickSynResend.Reset(); } } } void UdpConnection::processAck() { if ( m_state == SYN_RCVD ) { if ( m_tickAckResend.Elapsed() > ACK_RESEND_INTERVAL ) { sendAck(); m_tickAckResend.Reset(); } } } void UdpConnection::processTimeout() { if ( m_state == SYN_SENT || m_state == SYN_RCVD ) { if ( m_tickOpenTimeout.Elapsed() > OPEN_TIMEOUT ) { m_error = ERROR_UDP_OPEN_TIMEOUT; LOG( FT_DEBUG_FLOW, _T("UdpConnection::processTimeout> self[%d] remote[%d] timed out"), m_selfTag, m_remoteTag ); notifyOpenTimeout(); m_tickOpenTimeout.Reset(); } } } void UdpConnection::processReliable() { m_reliable->Run(); } void UdpConnection::processKeepAlive() { if ( m_state == OPEN ) { if ( m_tickKeepAlive.Elapsed() > KEEP_ALIVE_TIMEOUT ) { sendNul(); m_tickKeepAlive.Reset(); LOG( FT_DEBUG_FLOW, _T("UdpConnection::processKeepAlive> self[%d] remote[%d] Nul"), m_selfTag, m_remoteTag ); } if ( m_tickInactive.Elapsed() > CONNECTION_TIMEOUT ) { sendRst(); m_state = CLOSE_WAIT; m_tickCloseWait.Reset(); LOG( FT_DEBUG_FLOW, _T("UdpConnection::processKeepAlive> self[%d] remote[%d] Rst"), m_selfTag, m_remoteTag ); } } if ( m_state == CLOSE_WAIT ) { if ( m_tickCloseWait.Elapsed() > CLOSE_WAIT_TIMEOUT ) { m_error = ERROR_UDP_CLOSED; m_tickCloseWait.Reset(); // m_state = CLOSED; notifyClosed(); LOG( FT_INFO, _T("UdpConnection::processKeepAlive> self[%d] remote[%d] Closed"), m_selfTag, m_remoteTag ); } } } void UdpConnection::sendHpn() { UdpHeader header; header.control = 0; header.length = sizeof( UdpHeader ); header.srcId = GetSelfTag(); header.dstId = GetRemoteTag(); header.seq = m_selfTag; header.ack = 0; header.Set( UdpHeader::HPN ); SendRaw( (void*)&header, sizeof( UdpHeader ) ); } void UdpConnection::sendSyn() { UdpHeader header; header.control = 0; header.length = sizeof( UdpHeader ); header.srcId = GetSelfTag(); header.dstId = GetRemoteTag(); header.seq = m_selfTag; header.ack = 0; header.Set( UdpHeader::SYN ); SendRaw( (void*)&header, sizeof( UdpHeader ) ); } void UdpConnection::sendAck() { UdpHeader header; header.control = 0; header.length = sizeof( header ); header.srcId = GetSelfTag(); header.dstId = GetRemoteTag(); header.seq = 0; header.ack = m_reliable->GetSendCumAck(); header.Set( UdpHeader::ACK ); SendRaw( (void*)&header, sizeof( header ) ); } void UdpConnection::sendNul() { UdpHeader header; header.control = 0; header.length = sizeof( header ); header.srcId = GetSelfTag(); header.dstId = GetRemoteTag(); header.seq = 0; header.ack = m_reliable->GetSendCumAck(); header.Set( UdpHeader::NUL ); SendRaw( (void*)&header, sizeof( header ) ); } void UdpConnection::sendRst() { UdpHeader header; header.control = 0; header.length = sizeof( header ); header.srcId = GetSelfTag(); header.dstId = GetRemoteTag(); header.seq = 0; header.ack = 0; header.Set( UdpHeader::RST ); SendRaw( (void*)&header, sizeof( header ) ); } void UdpConnection::notifyOpen() { NetStateMessage* m = new NetStateMessage; m->state = NetStateMessage::UDP_OPENED; m->connectionId = m_remoteTag; m->addr = m_peer; m_communicator->Notify( MessagePtr( m ) ); } void UdpConnection::notifyOpenTimeout() { NetStateMessage* m = new NetStateMessage; m->state = NetStateMessage::UDP_OPEN_TIMEOUT; m->connectionId = m_remoteTag; m->addr = m_peer; m_communicator->Notify( MessagePtr( m ) ); } void UdpConnection::notifyClosed() { NetStateMessage* m = new NetStateMessage; m->state = NetStateMessage::UDP_CLOSED; m->connectionId = m_remoteTag; m->addr = m_peer; m_communicator->Notify( MessagePtr( m ) ); } } // gk
[ "darkface@localhost" ]
[ [ [ 1, 820 ] ] ]
38e2dfc125eec450e4671a4867f04f1d40141162
ea6b169a24f3584978f159ec7f44184f9e84ead8
/include/reflect_js/JavaScript.h
b6fd2eb7e3ac2c16f704a35902d30d9629a0d212
[]
no_license
sparecycles/reflect
e2051e5f91a7d72375dd7bfa2635cf1d285d8ef7
bec1b6e6521080ad4d932ee940073d054c8bf57f
refs/heads/master
2020-06-05T08:34:52.453196
2011-08-18T16:33:47
2011-08-18T16:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,370
h
// File: JavaScript.h // // Bindings for reflect to // Mozilla's Spidermonkey (v1.7.0). // // This provides a basic ECMA script runtime with // the following runtime support // // print() - A basic print method. // GC() - Run the garbage collector. // Console() - Runs a very basic Javascript console. // Native - An object which provides access to the reflected types by namespace. // #ifndef REFLECT_JS_JAVASCRIPT_H_ #define REFLECT_JS_JAVASCRIPT_H_ #include <reflect_js/config/config.h> #include <reflect/Reflection.h> #include <reflect/Dynamic.h> #include <reflect/Variant.h> #include <reflect/string/Fragment.h> #include <reflect/string/ConstString.h> #include <reflect/utility/Shared.hpp> #include <vector> extern "C" { struct JSRuntime; struct JSContext; struct JSObject; } namespace reflect { namespace function { class Function; template<typename FunctionType> const Function *CreateFunction(const char *, FunctionType); } } namespace reflect { namespace js { // Class: JavaScriptRuntime // Wraps a JSRuntime, a JSRuntime object represents // a single JavaScript object space which can hold // multiple contexts. JavaScript objects in different // <JavaScriptContexts> but within the same runtime // may be shared. // // A <SharedRuntime> is automatically used by default, // client code only needs to instantate a runtime object // if they want to have completely seperate runtimes. class ReflectExport(reflect_js) JavaScriptRuntime : public utility::Shared<JavaScriptRuntime> { public: JavaScriptRuntime(); JavaScriptRuntime(const JavaScriptRuntime &); ~JavaScriptRuntime(); // Function: SharedRuntime static JavaScriptRuntime SharedRuntime(); // Function: GetRuntime JSRuntime *GetRuntime() const { return mRuntime; } private: JavaScriptRuntime(JSRuntime *); static JavaScriptRuntime sSharedRuntime; JSRuntime *mRuntime; }; // Class: JavaScriptContext // // Represents a javascript context class ReflectExport(reflect_js) JavaScriptContext { public: // Constructor: JavaScriptContext JavaScriptContext(const JavaScriptRuntime & = JavaScriptRuntime::SharedRuntime()); ~JavaScriptContext(); // Function: GC // Runs the garbage collector. void GC() const; // Function: RegisterFunction // Registers a function in this context. // // Parameters: // name - the javascript name of this function // function - the function to use // take_ownership - if true, delete the *function* when destructing this context. // // See Also: // - <RegisterFunction (template)> preferred way of the registering functions. bool RegisterFunction(string::ConstString name, const function::Function *function, bool take_ownership = false); // Function: RegisterFunction (template) // // Like <RegisterFunction>, but takes a regular C function pointer, // creates the function::Function object wrapper and marks it for deletion. template<typename FunctionType> bool RegisterFunction(string::ConstString name, FunctionType function) { return RegisterFunction(name, function::CreateFunction<FunctionType>(name.c_str(), function), true); } // Function: Eval (toss result) bool Eval(string::Fragment script) const; // Function: Eval (typed result) template<typename T> bool Eval(string::Fragment script, T &result) const { Variant var_result = Variant::FromRef(result); return Eval(script, var_result); } // Function: Eval // Assigns the result of Eval into the variant *result*. // // Returns: // true - if the evaluation and assignment executed successfully // false - if the evaluation threw an exception or assignment failed. bool Eval(string::Fragment script, Variant &result) const; // Function: IncRef // Increments the reference count on a pointer that the java runtime knows about. // When java finalizes the assoicated object, the pointer will not be deleted // if it has a positive reference count. The default reference count on an object // is one, functions that allocate new objects for javascript should <DecRef> // the reference count. Note that an <IncRef>-ed object will never be deleted by // the object system if it never makes it to the java runtime. template<typename T> void IncRef(T *object) const { IncOpaqueRef(opaque_cast(object)); } // Function: DecRef template<typename T> void DecRef(T *object) const { DecOpaqueRef(opaque_cast(object)); } void IncOpaqueRef(void *opaque) const; void DecOpaqueRef(void *opaque) const; // Function: ThrowError // Throws an error from a function // to the JavaScript runtime. void ThrowError(const char *format, ...) const; // Function: GetJSContext // Returns the native context pointer. JSContext *GetJSContext() const; // for operating from within C++ methods invoked from javascript // Function: CallContext // Retrieves the current context from within a javascript call. static const JavaScriptContext *CallContext(); // Function: CallArgumentCount // Retrieves the number of arguments actually passed to the native function. static int CallArgumentCount(); // Function: CallArgument // Retrieves the argument *index* passed to the native function // through a <Variant>. static bool CallArgument(int index, Variant &variant); // Function: CallArgumentText // Retrieves the argument *index* as text (converted by javascript). // Should be the same as Eval("String(arguments[index])") static const char *CallArgumentText(int index); // Function: CallArgumentValue // Retrieves the argument *index* as whatever (converted by <Variant>). template<typename T> static bool CallArgumentValue(int index, T &value) { return CallArgument(index, Variant::Ref(value)); } // Function: CallReturn // Sets the return value of a void native function by variant. static bool CallReturn(Variant &value); // Function: CallReturnValue // Sets the return value of a void native function by value. template<typename T> static bool CallReturnValue(const T &value) { return CallReturn(Variant::ConstRef(value)); } private: JavaScriptRuntime mRuntime; JSContext *mContext; std::vector<const function::Function *> mRegisteredFunctions; }; } } #endif
[ [ [ 1, 202 ] ] ]
cfe29f972f226d1e61ba58d893e9c68332115b6d
c3a1c34a26351e2accff58a68a8a60127d9c1a8f
/src/ui/mainwindow.h
4f5e0cb7a529bcb24b6197276ec142d527dfa1d3
[]
no_license
remerico/schnote
f10c128f86860d6876e826dc5da44ce478f6373f
15b4dc54ed03105914919968344cf0b5778a4a2d
refs/heads/master
2020-04-22T08:46:07.238781
2010-11-02T03:00:15
2010-11-02T03:00:15
32,114,453
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGui> #include "../data/notelistmodel.h" #include "widgets/noteitemdelegate.h" #include "../simplenote/api.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); inline NoteListModel* getNoteModel() { return noteModel; } private: Ui::MainWindow* ui; NoteListModel* noteModel; QDialogButtonBox* buttonBox; SimpleNote::Api api; void setupUiExtra(); void showSearch(bool display); void keyPressEvent(QKeyEvent *); void keyReleaseEvent(QKeyEvent *); void resizeEvent(QResizeEvent *); public slots: void doubleClicked(const QModelIndex & index); void createButtonBox(Qt::Orientation orientation); void createNewNote(); void deleteNote(); void clearSearch(); void syncNotes(); void showSettings(); void search(const QString &search); private slots: void on_listView_pressed(QModelIndex index); }; #endif // MAINWINDOW_H
[ "remerico@1bb478cd-69f2-1541-6d56-611775ec9bb1" ]
[ [ [ 1, 57 ] ] ]
ef050d2bf67be128ea23a33b7cd7f87f54f8a93a
3ec3b97044e4e6a87125470cfa7eef535f26e376
/darkbits-secret_of_fantasy_2/src/ActionTriggerLibrary.hpp
86677e5e663a7dd7a7f10a93bbd090aed7ce1202
[]
no_license
strategist922/TINS-Is-not-speedhack-2010
6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af
718b9d037606f0dbd9eb6c0b0e021eeb38c011f9
refs/heads/master
2021-01-18T14:14:38.724957
2010-10-17T14:04:40
2010-10-17T14:04:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
314
hpp
#pragma once class ActionTrigger; class ActionTriggerLibrary { public: static void init(); static const ActionTrigger &find(const std::string &name); private: ActionTriggerLibrary() {}; static void add(ActionTrigger &trigger); static std::map<std::string, ActionTrigger> myTriggers; };
[ [ [ 1, 18 ] ] ]
3de37761900115c61751310015617c7c625d7a00
c3efe4021165e718d23ce0f853808e10c7114216
/LuaEdit/frmNewProject.h
c0c3041987e91aa5dd7e13bb67ddbbba4c375d76
[]
no_license
lkdd/modstudio2
254b47ebd28a51a7d8c8682a86c576dafcc971bf
287b4782580e37c8ac621046100dc550abd05b1d
refs/heads/master
2021-01-10T08:14:56.230097
2009-03-08T19:14:16
2009-03-08T19:14:16
52,721,924
0
0
null
null
null
null
UTF-8
C++
false
false
2,414
h
/* Copyright (c) 2008 Peter "Corsix" Cawley 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. */ #pragma once // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif // ---------------------------- #include <Rainman2.h> #include <wx/wizard.h> class NewPipelineProjectWizard : public wxWizard { public: NewPipelineProjectWizard(wxWindow* pParent, int iID = wxID_ANY); bool RunWizard(); class WelcomePage : public wxWizardPageSimple { public: WelcomePage(NewPipelineProjectWizard* pWizard); }; class GamePipelineSelect : public wxWizardPageSimple { public: GamePipelineSelect(NewPipelineProjectWizard* pWizard); enum { BTN_BROWSEPIPELINE = wxID_HIGHEST + 1, BTN_BROWSEGAMEFOLDER, CMB_PIPELINES, }; void onBrowsePipeline (wxCommandEvent& e); void onPipelineSelect (wxCommandEvent& e); void onBrowseGameFolder(wxCommandEvent& e); protected: wxComboBox *m_pPipelineFileList; wxTextCtrl *m_pGameFolder; static wxString _findGameFolder(wxString sPipelineFile); DECLARE_EVENT_TABLE(); }; };
[ "corsix@07142bc5-7355-0410-a98c-5fd2ca6e29ee" ]
[ [ [ 1, 79 ] ] ]
5056c90315c71e28bf80971fbb49289f1338795f
3187b0dd0d7a7b83b33c62357efa0092b3943110
/src/dlib/svm/kernel_abstract.h
265c386c065b0ae1f8c298313b9fc7279a57f89c
[ "BSL-1.0" ]
permissive
exi/gravisim
8a4dad954f68960d42f1d7da14ff1ca7a20e92f2
361e70e40f58c9f5e2c2f574c9e7446751629807
refs/heads/master
2021-01-19T17:45:04.106839
2010-10-22T09:11:24
2010-10-22T09:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,789
h
// Copyright (C) 2007 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_SVm_KERNEL_ABSTRACT_ #ifdef DLIB_SVm_KERNEL_ABSTRACT_ #include <cmath> #include <limits> #include <sstream> #include "../matrix/matrix_abstract.h" #include "../algs.h" #include "../serialize.h" namespace dlib { // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- /*!A Kernel_Function_Objects */ // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- /*! WHAT IS A KERNEL FUNCTION OBJECT? In the context of the dlib library documentation a kernel function object is an object with an interface with the following properties: - a public typedef named sample_type - a public typedef named scalar_type which should be a float, double, or long double type. - an overloaded operator() that operates on two items of sample_type and returns a scalar_type. (e.g. scalar_type val = kernel_function(sample(i),sample(j)); would be a valid expression) - a public typedef named mem_manager_type that is an implementation of dlib/memory_manager/memory_manager_kernel_abstract.h or dlib/memory_manager_global/memory_manager_global_kernel_abstract.h or dlib/memory_manager_stateless/memory_manager_stateless_kernel_abstract.h For examples of kernel functions see the following objects (e.g. the radial_basis_kernel). !*/ template < typename T > struct radial_basis_kernel { /*! REQUIREMENTS ON T T must be a dlib::matrix object WHAT THIS OBJECT REPRESENTS This object represents a radial basis function kernel !*/ typedef typename T::type scalar_type; typedef T sample_type; typedef typename T::mem_manager_type mem_manager_type; const scalar_type gamma; radial_basis_kernel( ); /*! ensures - #gamma == 0.1 !*/ radial_basis_kernel( const radial_basis_kernel& k ); /*! ensures - #gamma == k.gamma !*/ radial_basis_kernel( const scalar_type g ); /*! ensures - #gamma == g !*/ scalar_type operator() ( const sample_type& a, const sample_type& b ) const; /*! requires - a.nc() == 1 - b.nc() == 1 - a.nr() == b.nr() ensures - returns exp(-gamma * ||a-b||^2) !*/ radial_basis_kernel& operator= ( const radial_basis_kernel& k ); /*! ensures - #gamma = k.gamma - returns *this !*/ }; template < typename T > void serialize ( const radial_basis_kernel<T>& item, std::ostream& out ); /*! provides serialization support for radial_basis_kernel !*/ template < typename K > void deserialize ( radial_basis_kernel<T>& item, std::istream& in ); /*! provides deserialization support for radial_basis_kernel !*/ // ---------------------------------------------------------------------------------------- template < typename T > struct polynomial_kernel { /*! REQUIREMENTS ON T T must be a dlib::matrix object WHAT THIS OBJECT REPRESENTS This object represents a polynomial kernel !*/ typedef typename T::type scalar_type; typedef T sample_type; typedef typename T::mem_manager_type mem_manager_type; const scalar_type gamma; const scalar_type coef; const scalar_type degree; polynomial_kernel( ); /*! ensures - #gamma == 1 - #coef == 0 - #degree == 1 !*/ polynomial_kernel( const radial_basis_kernel& k ); /*! ensures - #gamma == k.gamma !*/ polynomial_kernel( const scalar_type g, const scalar_type c, const scalar_type d ); /*! ensures - #gamma == g - #coef == c - #degree == d !*/ scalar_type operator() ( const sample_type& a, const sample_type& b ) const; /*! requires - a.nc() == 1 - b.nc() == 1 - a.nr() == b.nr() ensures - returns pow(gamma*trans(a)*b + coef, degree) !*/ polynomial_kernel& operator= ( const polynomial_kernel& k ); /*! ensures - #gamma = k.gamma - #coef = k.coef - #degree = k.degree - returns *this !*/ }; template < typename T > void serialize ( const polynomial_kernel<T>& item, std::ostream& out ); /*! provides serialization support for polynomial_kernel !*/ template < typename K > void deserialize ( polynomial_kernel<T>& item, std::istream& in ); /*! provides deserialization support for polynomial_kernel !*/ // ---------------------------------------------------------------------------------------- template < typename T > struct linear_kernel { /*! REQUIREMENTS ON T T must be a dlib::matrix object WHAT THIS OBJECT REPRESENTS This object represents a linear function kernel !*/ typedef typename T::type scalar_type; typedef T sample_type; typedef typename T::mem_manager_type mem_manager_type; scalar_type operator() ( const sample_type& a, const sample_type& b ) const; /*! requires - a.nc() == 1 - b.nc() == 1 - a.nr() == b.nr() ensures - returns trans(a)*b !*/ }; template < typename T > void serialize ( const linear_kernel<T>& item, std::ostream& out ); /*! provides serialization support for linear_kernel !*/ template < typename K > void deserialize ( linear_kernel<T>& item, std::istream& in ); /*! provides deserialization support for linear_kernel !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_SVm_KERNEL_ABSTRACT_
[ [ [ 1, 292 ] ] ]
638dfae3ad1e2ed32af8e1e0dcf1dea5239cbb34
842997c28ef03f8deb3422d0bb123c707732a252
/src/moaicore/MOAIProp.h
ac209fffb5d3776305da342853fd0ea885789478
[]
no_license
bjorn/moai-beta
e31f600a3456c20fba683b8e39b11804ac88d202
2f06a454d4d94939dc3937367208222735dd164f
refs/heads/master
2021-01-17T11:46:46.018377
2011-06-10T07:33:55
2011-06-10T07:33:55
1,837,561
2
1
null
null
null
null
UTF-8
C++
false
false
2,143
h
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #ifndef MOAIPROP_H #define MOAIPROP_H #include <moaicore/MOAITransform.h> class MOAIPartition; class MOAIPartitionCell; class MOAIPartitionLayer; class MOAISurfaceSampler2D; //================================================================// // MOAIProp //================================================================// /** @name MOAIProp @text Base class for Props. */ class MOAIProp : public MOAITransform { private: friend class MOAIPartition; friend class MOAIPartitionCell; friend class MOAIPartitionLayer; MOAIPartition* mPartition; MOAIPartitionLayer* mLayer; MOAIPartitionCell* mCell; USLeanLink < MOAIProp* > mLinkInCell; MOAIProp* mNextResult; u32 mMask; USRect mBounds; float mCellSize; s32 mPriority; //----------------------------------------------------------------// static int _getPriority ( lua_State* L ); static int _setPriority ( lua_State* L ); //----------------------------------------------------------------// void SetBounds (); void SetBounds ( const USRect& bounds ); public: static const s32 UNKNOWN_PRIORITY = 0x80000000; enum { BOUNDS_EMPTY, BOUNDS_GLOBAL, BOUNDS_OK, }; enum { CAN_DRAW = 1 << 0x00, CAN_DRAW_DEBUG = 1 << 0x01, CAN_GATHER_SURFACES = 1 << 0x02, CAN_GET_OVERLAP_PRIM = 1 << 0x03, }; GET_SET ( u32, Mask, mMask ) GET ( s32, Priority, mPriority ) //----------------------------------------------------------------// virtual void Draw (); virtual void DrawDebug (); virtual void GatherSurfaces ( MOAISurfaceSampler2D& sampler ); MOAIPartition* GetPartitionTrait (); USRect GetBounds (); bool GetCellRect ( USRect* cellRect, USRect* paddedRect = 0 ); MOAIProp (); virtual ~MOAIProp (); void RegisterLuaClass ( USLuaState& state ); void RegisterLuaFuncs ( USLuaState& state ); void UpdateBounds ( u32 status ); void UpdateBounds ( const USRect& bounds, u32 status ); }; #endif
[ "Patrick@agile.(none)" ]
[ [ [ 1, 84 ] ] ]
677d810461901a619259b237ce3ce64ba0f4d926
0bea742434663bf4ddce7e60fe2703a05b1f1cd3
/JuceLibraryCode/juce_StandaloneFilterWindow.h
539fba98c65466c22cfba91079d3157ea6ef9522
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
rspindel/SoundFXMachine
84c593542484dbec9f7d264b11342d39adb32eea
d18fc8522104fe26540d89a39e93c49cf5d31ceb
refs/heads/master
2020-12-24T21:11:23.785667
2011-04-29T03:31:48
2011-04-29T03:31:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,407
h
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-10 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #ifndef __JUCE_STANDALONEFILTERWINDOW_JUCEHEADER__ #define __JUCE_STANDALONEFILTERWINDOW_JUCEHEADER__ #include "juce_AudioFilterStreamer.h" //============================================================================== /** A class that can be used to run a simple standalone application containing your filter. Just create one of these objects in your JUCEApplication::initialise() method, and let it do its work. It will create your filter object using the same createFilter() function that the other plugin wrappers use. */ class StandaloneFilterWindow : public DocumentWindow, public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug) { public: //============================================================================== StandaloneFilterWindow (const String& title, const Colour& backgroundColour); ~StandaloneFilterWindow(); //============================================================================== /** Deletes and re-creates the filter and its UI. */ void resetFilter(); /** Pops up a dialog letting the user save the filter's state to a file. */ void saveState(); /** Pops up a dialog letting the user re-load the filter's state from a file. */ void loadState(); /** Shows the audio properties dialog box modally. */ virtual void showAudioSettingsDialog(); /** Returns the property set to use for storing the app's last state. This will be used to store the audio set-up and the filter's last state. */ virtual PropertySet* getGlobalSettings(); //============================================================================== /** @internal */ void closeButtonPressed(); /** @internal */ void buttonClicked (Button*); /** @internal */ void resized(); private: ScopedPointer<AudioProcessor> filter; ScopedPointer<AudioFilterStreamingDeviceManager> deviceManager; TextButton optionsButton; void deleteFilter(); JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StandaloneFilterWindow); }; #endif // __JUCE_STANDALONEFILTERWINDOW_JUCEHEADER__
[ [ [ 1, 87 ] ] ]
d6706a00d51e8144da09ec7f30453b8c95561531
61fb1bf48c8eeeda8ecb2c40fcec1d3277ba6935
/patoBase/patouser.h
91f9be160bf6a81f19accce435efb32fa1b3d7a1
[]
no_license
matherthal/pato-scm
172497f3e5c6d71a2cbbd2db132282fb36ba4871
ba573dad95afa0c0440f1ae7d5b52a2736459b10
refs/heads/master
2020-05-20T08:48:12.286498
2011-11-25T11:05:23
2011-11-25T11:05:23
33,139,075
0
0
null
null
null
null
UTF-8
C++
false
false
336
h
#ifndef USER_H #define USER_H #include <string> class PatoUser { public: PatoUser(); void setId(int id); int getId(); void setName( std::string& name ); std::string getName( ); private: int m_idUser; std::string m_nameUser; }; #endif // USER_H
[ "rafael@Micro-Mariana" ]
[ [ [ 1, 22 ] ] ]
0f7d140719409a30d46ebfbe88af588b06992a4a
cfcd2a448c91b249ea61d0d0d747129900e9e97f
/thirdparty/OpenCOLLADA/COLLADAFramework/include/COLLADAFWTechnique.h
e69aa060ad4c54dfa61c460a493af860f4c5151e
[]
no_license
fire-archive/OgreCollada
b1686b1b84b512ffee65baddb290503fb1ebac9c
49114208f176eb695b525dca4f79fc0cfd40e9de
refs/heads/master
2020-04-10T10:04:15.187350
2009-05-31T15:33:15
2009-05-31T15:33:15
268,046
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,178
h
/* Copyright (c) 2008 NetAllied Systems GmbH This file is part of COLLADAStreamWriter. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #ifndef __COLLADAFRAMEWORK_TECHNIQUE_H__ #define __COLLADAFRAMEWORK_TECHNIQUE_H__ #include "COLLADAFWPrerequisites.h" #include "COLLADAFWAnnotate.h" #include "COLLADAFWInclude.h" #include "COLLADAFWCode.h" #include "COLLADAFWNewParam.h" #include "COLLADAFWSetParam.h" #include "COLLADAFWImage.h" #include "COLLADAFWShaderElement.h" #include "COLLADAFWPass.h" namespace COLLADAFW { /** Holds a description of the textures, samplers, shaders, parameters, and passes necessary for rendering this effect using one method. For <technique> in elements other than <profile_*>, see "<technique> (core)." Techniques hold all the necessary elements required to render an effect. Each effect can contain many techniques, each of which describes a different method for rendering that effect. There are three different scenarios for which techniques are commonly used: • One technique might describe a high-LOD version while a second technique describes a low-LOD version of the same effect. • Describe an effect in different ways and use validation tools in the FX Runtime to find the most efficient version of an effect for an unknown device that uses a standard API. • Describe an effect under different game states, for example, a daytime and a nighttime technique, a normal technique, and a "magic-is-enabled" technique. Child elements vary by profile. See the parent element main entries for details. The following list summarizes valid child elements. The child elements must appear in the following order if present, with the following exceptions: <code> and <include>; <newparam>, <setparam>, and <image> are choices, can appear in any order in that position; <blinn>, <constant>, <lambert>, <phong> are choices, can appear in any order in that position: */ class Technique { private: /** A text string containing the unique identifier of the element. This value must be unique within the instance document. Optional. */ String mId; /** A text string value containing the subidentifier of this element. This value must be unique within the scope of the parent element. Required. */ String mSid; /** Adds a strongly typed annotation remark to the parent object. No or multiple occurances. */ Array<Annotate> mAnnotateArray; /** Imports source code or precompiled binary shaders into the FX Runtime by referencing an external resource. No or multiple occurances. */ Array<Include> mIncludeArray; /** Provides an inline block of source code. No or multiple occurances. */ Array<Code> mCodeArray; /** Creates a new, named <param> (FX) object in the FX Runtime, and assigns it a type, an initial value, and additional attributes at declaration time. No or multiple occurances. */ Array<NewParam> mNewParamArray; /** Assigns a new value to a previously defined parameter. No or multiple occurances. */ Array<SetParam> mSetParamArray; /** Declares the storage for the graphical representation of an object. No or multiple occurances. */ Array<Image> mImageArray; /** blinn, constant, lambert, phong */ ShaderElement* mShaderElement; /** Provides a static declaration of all the render states, shaders, and settings for one rendering pipeline. One or more occurances. */ Array<Pass> mPassArray; /** Provides arbitrary additional information about or related to its parent element. No or multiple occurances. */ // Array<Extra> mExtraArray; public: /** Constructor that sets the stream the asset should be written to*/ Technique () {} /** Destructor. */ virtual ~Technique () {}; /** A text string containing the unique identifier of the element. This value must be unique within the instance document. Optional. */ const String getId () const { return mId; } /** A text string containing the unique identifier of the element. This value must be unique within the instance document. Optional. */ void setId ( const String Id ) { mId = Id; } /** A text string value containing the subidentifier of this element. This value must be unique within the scope of the parent element. Required. */ const String getSid () const { return mSid; } /** A text string value containing the subidentifier of this element. This value must be unique within the scope of the parent element. Required. */ void setSid ( const String Sid ) { mSid = Sid; } }; } //namespace COLLADAFW #endif //__COLLADAFRAMEWORK_TECHNIQUE_H__
[ [ [ 1, 124 ] ] ]
243fd1ec7da377adbda2ad1cad1f7f7da5acab9a
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Walkyrie Dx9/Valkyrie/Moteur/Fire.cpp
cab41a2260bf5c9c1949dfd9e15357cf78ac8d9b
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
UTF-8
C++
false
false
5,523
cpp
#include "Fire.h" HRESULT UpdatePariculeCustomFire(CParticleSystem* pParticleSystem,float fDeltatime) { Particle *pParticle; Particle **ppParticle; D3DXVECTOR3 vOldPosition; pParticleSystem->m_fDeltatime = fDeltatime; // Update our particle system timer... ppParticle = &pParticleSystem->m_pActiveList; // Start at the head of the active list //m_pTexParticle->UpdateTexture(m_fDeltatime); while( *ppParticle ) { pParticle = *ppParticle; // Set a pointer to the head pParticle->m_fTimePassed += pParticleSystem->m_fDeltatime; pParticleSystem->m_nCompteurParticule++; if( pParticle->m_fTimePassed >= pParticleSystem->m_fLifeCycle ) { // Time is up, put the particle back on the free list... *ppParticle = pParticle->m_pNext; pParticle->m_pNext = pParticleSystem->m_pFreeList; pParticleSystem->m_pFreeList = pParticle; --pParticleSystem->m_dwActiveCount; } else { // Update particle position and velocity // Update velocity with respect to Gravity (Constant Acceleration) pParticle->m_vCurVel += pParticleSystem->m_vGravity * pParticleSystem->m_fDeltatime; // Update velocity with respect to Wind (Acceleration based on // difference of vectors) if( pParticleSystem->m_bAirResistence == true ) pParticle->m_vCurVel += (pParticleSystem->m_vWind - pParticle->m_vCurVel) * pParticleSystem->m_fDeltatime; // Finally, update position with respect to velocity vOldPosition = pParticle->m_vCurPos; D3DXVECTOR3 vecTmp = pParticle->m_vCurVel * pParticleSystem->m_fDeltatime; pParticle->m_vCurPos += vecTmp; pParticle->m_fPourcentColor = (pParticleSystem->m_fLifeCycle-pParticle->m_fTimePassed)/pParticleSystem->m_fLifeCycle; pParticle->m_nIndiceTextureCurrentParticule = pParticleSystem->m_pTexPrincipale->GetIndiceTextureTime(pParticle->m_fTimePassed,0.0f,pParticleSystem->m_fLifeCycle); pParticle->m_eEtatParticule = EEtat_Principale; if(pParticle->m_fPourcentColor < 0.7f) pParticle->m_eEtatParticule = EEtat_Secondaire; /* if(pParticleSystem->m_fCoeffRotationParticule != 0.0f) { pParticle->m_fAngle += pParticleSystem->m_fCoeffRotationParticule; if(pParticle->m_fAngle > 360.0f) pParticle->m_fAngle = 0.0f; }*/ ppParticle = &pParticle->m_pNext; } } pParticleSystem->m_fLastUpdate += pParticleSystem->m_fDeltatime; if( pParticleSystem->m_fLastUpdate > pParticleSystem->m_fReleaseInterval ) { // Reset update timing... pParticleSystem->m_fLastUpdate = 0.0f; // Emit new particles at specified flow rate... for( DWORD i = 0; i < pParticleSystem->m_dwNumToRelease; ++i ) { // Do we have any free particles to put back to work? if( pParticleSystem->m_pFreeList ) { // If so, hand over the first free one to be reused. pParticle = pParticleSystem->m_pFreeList; // Then make the next free particle in the list next to go! pParticleSystem->m_pFreeList = pParticle->m_pNext; } else { // There are no free particles to recycle... // We'll have to create a new one from scratch! if( pParticleSystem->m_dwActiveCount < pParticleSystem->m_dwMaxParticles ) { if( NULL == ( pParticle = new Particle ) ) return E_OUTOFMEMORY; } } if( pParticleSystem->m_dwActiveCount < pParticleSystem->m_dwMaxParticles ) { pParticle->m_pNext = pParticleSystem->m_pActiveList; // Make it the new head... pParticleSystem->m_pActiveList = pParticle; // Set the attributes for our new particle... pParticle->m_vCurVel = pParticleSystem->m_vVelocity; if( pParticleSystem->m_fVelocityVar != 0.0f ) { D3DXVECTOR3 vRandomVec = CParticleSystem::getRandomVector(); pParticle->m_vCurVel += vRandomVec * pParticleSystem->m_fVelocityVar; } pParticle->m_eEtatParticule = EEtat_Principale; pParticle->m_fTimePassed = 0.0f; pParticle->m_vCurPos = pParticleSystem->m_vPosition; ++pParticleSystem->m_dwActiveCount; } } } return S_OK; } CFire::CFire(LPDIRECT3DDEVICE9 pD3DDevice) { m_pD3DDevice = pD3DDevice; m_pFire = new CParticleSystem(m_pD3DDevice); } CFire::~CFire() { delete m_pFire; } bool CFire::CreateAndInit(char **g_pTextNameFire , int nTailleFire,char **g_pTextNameSmoke , int nTailleSmoke) { if(nTailleFire > 1) m_pFire->SetMultiTexture(g_pTextNameFire,nTailleFire); else m_pFire->SetTexture(g_pTextNameFire[0]); if(nTailleSmoke > 1) m_pFire->SetMultiTextureSecondaire(g_pTextNameSmoke,nTailleSmoke); else m_pFire->SetTextureSecondaire(g_pTextNameSmoke[0]); m_pFire->SetMaxParticles( 1000 ); m_pFire->SetNumToRelease( 5 ); m_pFire->SetReleaseInterval( 0.01f ); m_pFire->SetLifeCycle( 2.0f ); m_pFire->SetSize( 0.6f ); m_pFire->SetColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f )); m_pFire->SetPosition( D3DXVECTOR3( 0.0f, -1.0f, 0.0f) ); m_pFire->SetVelocity( D3DXVECTOR3( 0.0f, 5.0f, 0.0f) ); m_pFire->SetGravity( D3DXVECTOR3( 0.0f, 0.0f, 0.0f) ); m_pFire->SetWind( D3DXVECTOR3( 0.0f, 0.0f, 0.0f) ); m_pFire->SetVelocityVar( 3.0f ); //m_pFire->SetCoeffRotationParticule(0.1f); m_pFire->SetFonctionUpdate(&UpdatePariculeCustomFire); m_pFire->Init(); return true; } void CFire::DestructionObjet() { m_pFire->Release(); } void CFire::Rendu3D() { m_pFire->Rendu3D(); } void CFire::Animation(float fDeltaTemps) { m_pFire->Update(fDeltaTemps); }
[ "Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 183 ] ] ]
071c4983e21be232a02f113416eb0a7727804641
5dc6c87a7e6459ef8e832774faa4b5ae4363da99
/vis_avs/r_onetone.cpp
f877a4456d2365b9e4c2297907b636eef8e52b02
[]
no_license
aidinabedi/avs4unity
407603d2fc44bc8b075b54cd0a808250582ee077
9b6327db1d092218e96d8907bd14d68b741dcc4d
refs/heads/master
2021-01-20T15:27:32.449282
2010-12-24T03:28:09
2010-12-24T03:28:09
90,773,183
5
2
null
null
null
null
UTF-8
C++
false
false
8,838
cpp
/* LICENSE ------- Copyright 2005 Nullsoft, Inc. 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 Nullsoft 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. */ #include "config.h" #include <windows.h> #include <stdlib.h> #include <vfw.h> #include <commctrl.h> #include "resource.h" #include "r_defs.h" #ifndef LASER #define MOD_NAME "Trans / Unique tone" #define C_THISCLASS C_OnetoneClass class C_THISCLASS : public C_RBASE { protected: public: C_THISCLASS(); virtual ~C_THISCLASS(); virtual int render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h); virtual char *get_desc() { return MOD_NAME; } virtual HWND conf(HINSTANCE hInstance, HWND hwndParent); virtual void load_config(unsigned char *data, int len); virtual int save_config(unsigned char *data); void RebuildTable(void); int __inline depthof(int c); int enabled; int invert; int color; unsigned char tabler[256]; unsigned char tableg[256]; unsigned char tableb[256]; int blend, blendavg; }; static C_THISCLASS *g_ConfigThis; // global configuration dialog pointer static HINSTANCE g_hDllInstance; // global DLL instance pointer (not needed in this example, but could be useful) C_THISCLASS::~C_THISCLASS() { } // configuration read/write C_THISCLASS::C_THISCLASS() // set up default configuration { color = 0xFFFFFF; invert=0; blend = 0; blendavg = 0; enabled=1; RebuildTable(); } #define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24)) void C_THISCLASS::load_config(unsigned char *data, int len) // read configuration of max length "len" from data. { int pos=0; if (len-pos >= 4) { enabled=GET_INT(); pos+=4; } if (len-pos >= 4) { color=GET_INT(); pos+=4; } if (len-pos >= 4) { blend=GET_INT(); pos+=4; } if (len-pos >= 4) { blendavg=GET_INT(); pos+=4; } if (len-pos >= 4) { invert=GET_INT(); pos+=4; } RebuildTable(); } #define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255 int C_THISCLASS::save_config(unsigned char *data) // write configuration to data, return length. config data should not exceed 64k. { int pos=0; PUT_INT(enabled); pos+=4; PUT_INT(color); pos+=4; PUT_INT(blend); pos+=4; PUT_INT(blendavg); pos+=4; PUT_INT(invert); pos+=4; return pos; } int __inline C_THISCLASS::depthof(int c) { int r= max(max((c & 0xFF), ((c & 0xFF00)>>8)), (c & 0xFF0000)>>16); return invert ? 255 - r : r; } void C_THISCLASS::RebuildTable(void) { int i; for (i=0;i<256;i++) tableb[i] = (unsigned char)((i / 255.0) * (float)(color & 0xFF)); for (i=0;i<256;i++) tableg[i] = (unsigned char)((i / 255.0) * (float)((color & 0xFF00) >> 8)); for (i=0;i<256;i++) tabler[i] = (unsigned char)((i / 255.0) * (float)((color & 0xFF0000) >> 16)); } // render function // render should return 0 if it only used framebuffer, or 1 if the new output data is in fbout. this is // used when you want to do something that you'd otherwise need to make a copy of the framebuffer. // w and h are the width and height of the screen, in pixels. // isBeat is 1 if a beat has been detected. // visdata is in the format of [spectrum:0,wave:1][channel][band]. int C_THISCLASS::render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h) { int i=w*h; int *p=framebuffer; int c,d; if (!enabled) return 0; if (isBeat&0x80000000) return 0; if (blend) { while (i--) { d = depthof(*p); c = tableb[d] | (tableg[d]<<8) | (tabler[d]<<16); *p++ = BLEND(*p, c); } } else if (blendavg) { while (i--) { d = depthof(*p); c = tableb[d] | (tableg[d]<<8) | (tabler[d]<<16); *p++ = BLEND_AVG(*p, c); } } else { while (i--) { d = depthof(*p); *p++ = tableb[d] | (tableg[d]<<8) | (tabler[d]<<16); } } return 0; } // configuration dialog stuff static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam,LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: if (g_ConfigThis->enabled) CheckDlgButton(hwndDlg,IDC_CHECK1,BST_CHECKED); if (g_ConfigThis->invert) CheckDlgButton(hwndDlg,IDC_INVERT,BST_CHECKED); if (g_ConfigThis->blend) CheckDlgButton(hwndDlg,IDC_ADDITIVE,BST_CHECKED); if (g_ConfigThis->blendavg) CheckDlgButton(hwndDlg,IDC_5050,BST_CHECKED); if (!g_ConfigThis->blend && !g_ConfigThis->blendavg) CheckDlgButton(hwndDlg,IDC_REPLACE,BST_CHECKED); return 1; case WM_DRAWITEM: { DRAWITEMSTRUCT *di=(DRAWITEMSTRUCT *)lParam; if (di->CtlID == IDC_DEFCOL) // paint nifty color button { int w=di->rcItem.right-di->rcItem.left; int _color=g_ConfigThis->color; _color = ((_color>>16)&0xff)|(_color&0xff00)|((_color<<16)&0xff0000); HPEN hPen,hOldPen; HBRUSH hBrush,hOldBrush; LOGBRUSH lb={BS_SOLID,_color,0}; hPen = (HPEN)CreatePen(PS_SOLID,0,_color); hBrush = CreateBrushIndirect(&lb); hOldPen=(HPEN)SelectObject(di->hDC,hPen); hOldBrush=(HBRUSH)SelectObject(di->hDC,hBrush); Rectangle(di->hDC,di->rcItem.left,di->rcItem.top,di->rcItem.right,di->rcItem.bottom); SelectObject(di->hDC,hOldPen); SelectObject(di->hDC,hOldBrush); DeleteObject(hBrush); DeleteObject(hPen); } } return 0; case WM_COMMAND: if ((LOWORD(wParam) == IDC_CHECK1) || (LOWORD(wParam) == IDC_ADDITIVE) || (LOWORD(wParam) == IDC_REPLACE) || (LOWORD(wParam) == IDC_5050) || (LOWORD(wParam) == IDC_INVERT)) { g_ConfigThis->enabled=IsDlgButtonChecked(hwndDlg,IDC_CHECK1)?1:0; g_ConfigThis->blend=IsDlgButtonChecked(hwndDlg,IDC_ADDITIVE)?1:0; g_ConfigThis->blendavg=IsDlgButtonChecked(hwndDlg,IDC_5050)?1:0; g_ConfigThis->invert=IsDlgButtonChecked(hwndDlg,IDC_INVERT)?1:0; } if (LOWORD(wParam) == IDC_DEFCOL) // handle clicks to nifty color button { int *a=&(g_ConfigThis->color); static COLORREF custcolors[16]; CHOOSECOLOR cs; cs.lStructSize = sizeof(cs); cs.hwndOwner = hwndDlg; cs.hInstance = 0; cs.rgbResult=((*a>>16)&0xff)|(*a&0xff00)|((*a<<16)&0xff0000); cs.lpCustColors = custcolors; cs.Flags = CC_RGBINIT|CC_FULLOPEN; if (ChooseColor(&cs)) { *a = ((cs.rgbResult>>16)&0xff)|(cs.rgbResult&0xff00)|((cs.rgbResult<<16)&0xff0000); g_ConfigThis->color = *a; g_ConfigThis->RebuildTable(); } InvalidateRect(GetDlgItem(hwndDlg,IDC_DEFCOL),NULL,TRUE); } } return 0; } HWND C_THISCLASS::conf(HINSTANCE hInstance, HWND hwndParent) // return NULL if no config dialog possible { g_ConfigThis = this; return CreateDialog(hInstance,MAKEINTRESOURCE(IDD_CFG_ONETONE),hwndParent,g_DlgProc); } // export stuff C_RBASE *R_Onetone(char *desc) // creates a new effect object if desc is NULL, otherwise fills in desc with description { if (desc) { strcpy(desc,MOD_NAME); return NULL; } return (C_RBASE *) new C_THISCLASS(); } #else C_RBASE *R_Onetone(char *desc) // creates a new effect object if desc is NULL, otherwise fills in desc with description { return NULL; } #endif
[ [ [ 1, 266 ] ] ]
0569b0c5c2d7af9f274a841faa4b13bb1e6b951a
d6bb7c9759be2d7117541affd05ad3147a0f9484
/ASEF_VS2010_sample/stdafx.cpp
8d70f93f84b028a6e771e9fb3972922b0116ebd6
[]
no_license
hejibo/ASEF
c97ca1587a3298a403a6a306a8f9b0fc87d6197d
ebf1fdbbf5f9624771785071d915998552ec860a
refs/heads/master
2021-01-16T17:40:22.991131
2011-05-09T14:21:20
2011-05-09T14:21:20
null
0
0
null
null
null
null
GB18030
C++
false
false
271
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // ASEF_filter.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ [ [ 1, 8 ] ] ]
c6691e11a9827f97cea228d450c8b7362952d615
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_hardware_native_Microsoft_SPOT_Hardware_HardwareProvider.h
5a4e4e4ebb934ecc33e535fd3d9e0f1d2f34ab4a
[ "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
3,030
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 _SPOT_HARDWARE_NATIVE_MICROSOFT_SPOT_HARDWARE_HARDWAREPROVIDER_H_ #define _SPOT_HARDWARE_NATIVE_MICROSOFT_SPOT_HARDWARE_HARDWAREPROVIDER_H_ namespace Microsoft { namespace SPOT { namespace Hardware { struct HardwareProvider { // Helper Functions to access fields of managed object // Declaration of stubs. These functions are implemented by Interop code developers static void NativeGetSerialPins( CLR_RT_HeapBlock* pMngObj, INT32 param0, UNSUPPORTED_TYPE * param1, UNSUPPORTED_TYPE param2, UNSUPPORTED_TYPE param3, UNSUPPORTED_TYPE * param4, HRESULT &hr ); static INT32 NativeGetSerialPortsCount( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ); static INT8 NativeSupportsNonStandardBaudRate( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ); static void NativeGetBaudRateBoundary( CLR_RT_HeapBlock* pMngObj, INT32 param0, UINT32 * param1, UINT32 * param2, HRESULT &hr ); static INT8 NativeIsSupportedBaudRate( CLR_RT_HeapBlock* pMngObj, INT32 param0, UINT32 * param1, HRESULT &hr ); static void NativeGetSpiPins( CLR_RT_HeapBlock* pMngObj, INT32 param0, UNSUPPORTED_TYPE * param1, UNSUPPORTED_TYPE param2, UNSUPPORTED_TYPE param3, HRESULT &hr ); static INT32 NativeGetSpiPortsCount( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ); static void NativeGetI2CPins( CLR_RT_HeapBlock* pMngObj, UNSUPPORTED_TYPE * param0, UNSUPPORTED_TYPE param1, HRESULT &hr ); static INT32 NativeGetPinsCount( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ); static void NativeGetPinsMap( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_UNSUPPORTED_TYPE param0, HRESULT &hr ); static UINT8 NativeGetPinUsage( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ); static UINT8 NativeGetSupportedResistorModes( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ); static UINT8 NativeGetSupportedInterruptModes( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ); static INT32 NativeGetButtonPins( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ); static void NativeGetLCDMetrics( CLR_RT_HeapBlock* pMngObj, INT32 * param0, INT32 * param1, INT32 * param2, INT32 * param3, HRESULT &hr ); }; } } } #endif //_SPOT_HARDWARE_NATIVE_MICROSOFT_SPOT_HARDWARE_HARDWAREPROVIDER_H_
[ [ [ 1, 46 ] ] ]
7bf53ec001e44afe0d48f9df08fb2ebc57bf09a0
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/core/type_mat2x2.inl
8476c41986a3f7b9ee85e9c340c78deb1dbf96ec
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
12,015
inl
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2005-01-16 // Updated : 2007-03-01 // Licence : This source is under MIT License // File : glm/core/type_mat2x2.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm{ namespace detail{ template <typename valType> typename tmat2x2<valType>::size_type tmat2x2<valType>::value_size() { return typename tmat2x2<valType>::size_type(2); } template <typename valType> typename tmat2x2<valType>::size_type tmat2x2<valType>::col_size() { return typename tmat2x2<valType>::size_type(2); } template <typename valType> typename tmat2x2<valType>::size_type tmat2x2<valType>::row_size() { return typename tmat2x2<valType>::size_type(2); } template <typename valType> bool tmat2x2<valType>::is_matrix() { return true; } ////////////////////////////////////// // Accesses template <typename valType> detail::tvec2<valType>& tmat2x2<valType>::operator[](typename tmat2x2<valType>::size_type i) { assert( i >= typename tmat2x2<valType>::size_type(0) && i < tmat2x2<valType>::col_size()); return value[i]; } template <typename valType> const detail::tvec2<valType>& tmat2x2<valType>::operator[](typename tmat2x2<valType>::size_type i) const { assert( i >= typename tmat2x2<valType>::size_type(0) && i < tmat2x2<valType>::col_size()); return value[i]; } ////////////////////////////////////////////////////////////// // mat2 constructors template <typename T> inline tmat2x2<T>::tmat2x2() { this->value[0] = detail::tvec2<T>(1, 0); this->value[1] = detail::tvec2<T>(0, 1); } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat2x2<T> & m) { this->value[0] = m.value[0]; this->value[1] = m.value[1]; } template <typename T> inline tmat2x2<T>::tmat2x2(const T f) { this->value[0] = detail::tvec2<T>(f, 0); this->value[1] = detail::tvec2<T>(0, f); } template <typename T> inline tmat2x2<T>::tmat2x2(const T x0, const T y0, const T x1, const T y1) { this->value[0] = detail::tvec2<T>(x0, y0); this->value[1] = detail::tvec2<T>(x1, y1); } template <typename T> inline tmat2x2<T>::tmat2x2(const detail::tvec2<T>& v0, const detail::tvec2<T>& v1) { this->value[0] = v0; this->value[1] = v1; } ////////////////////////////////////////////////////////////// // mat2 conversions template <typename T> template <typename U> inline tmat2x2<T>::tmat2x2(const tmat2x2<U>& m) { this->value[0] = detail::tvec2<T>(m[0]); this->value[1] = detail::tvec2<T>(m[1]); } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat3x3<T>& m) { this->value[0] = detail::tvec2<T>(m[0]); this->value[1] = detail::tvec2<T>(m[1]); } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat4x4<T>& m) { this->value[0] = detail::tvec2<T>(m[0]); this->value[1] = detail::tvec2<T>(m[1]); } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat2x3<T>& m) { this->value[0] = detail::tvec2<T>(m[0]); this->value[1] = detail::tvec2<T>(m[1]); } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat3x2<T>& m) { this->value[0] = m[0]; this->value[1] = m[1]; } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat2x4<T>& m) { this->value[0] = detail::tvec2<T>(m[0]); this->value[1] = detail::tvec2<T>(m[1]); } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat4x2<T>& m) { this->value[0] = m[0]; this->value[1] = m[1]; } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat3x4<T>& m) { this->value[0] = detail::tvec2<T>(m[0]); this->value[1] = detail::tvec2<T>(m[1]); } template <typename T> inline tmat2x2<T>::tmat2x2(const tmat4x3<T>& m) { this->value[0] = detail::tvec2<T>(m[0]); this->value[1] = detail::tvec2<T>(m[1]); } /* template <typename T> inline tmat2x2<T>::tmat2x2(const T* a) { this->value[0] = detail::tvec2<T>(a[0], a[1]); this->value[1] = detail::tvec2<T>(a[2], a[3]); } */ template <typename T> inline tmat2x2<T> tmat2x2<T>::_inverse() const { T Determinant = value[0][0] * value[1][1] - value[1][0] * value[0][1]; tmat2x2<T> Inverse( + value[1][1] / Determinant, - value[1][0] / Determinant, - value[0][1] / Determinant, + value[0][0] / Determinant); return Inverse; } ////////////////////////////////////////////////////////////// // mat3 operators // This function shouldn't required but it seems that VC7.1 have an optimisation bug if this operator wasn't declared template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator=(tmat2x2<T> const & m) { this->value[0] = m[0]; this->value[1] = m[1]; return *this; } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator+= (const T & s) { this->value[0] += s; this->value[1] += s; return *this; } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator+= (tmat2x2<T> const & m) { this->value[0] += m[0]; this->value[1] += m[1]; return *this; } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator-= (const T & s) { this->value[0] -= s; this->value[1] -= s; return *this; } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator-= (tmat2x2<T> const & m) { this->value[0] -= m[0]; this->value[1] -= m[1]; return *this; } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator*= (const T & s) { this->value[0] *= s; this->value[1] *= s; return *this; } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator*= (tmat2x2<T> const & m) { return (*this = *this * m); } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator/= (const T & s) { this->value[0] /= s; this->value[1] /= s; return *this; } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator/= (tmat2x2<T> const & m) { return (*this = *this / m); } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator++ () { ++this->value[0]; ++this->value[1]; return *this; } template <typename T> inline tmat2x2<T>& tmat2x2<T>::operator-- () { --this->value[0]; --this->value[1]; return *this; } ////////////////////////////////////////////////////////////// // Binary operators template <typename T> inline tmat2x2<T> operator+ (tmat2x2<T> const & m, const T & s) { return tmat2x2<T>( m[0] + s, m[1] + s); } template <typename T> inline tmat2x2<T> operator+ (const T & s, tmat2x2<T> const & m) { return tmat2x2<T>( m[0] + s, m[1] + s); } //template <typename T> //inline detail::tvec2<T> operator+ (tmat2x2<T> const & m, const detail::tvec2<T>& v) //{ //} //template <typename T> //inline detail::tvec2<T> operator+ (const detail::tvec2<T>& v, tmat2x2<T> const & m) //{ //} template <typename T> inline tmat2x2<T> operator+ (tmat2x2<T> const & m1, tmat2x2<T> const & m2) { return tmat2x2<T>( m1[0] + m2[0], m1[1] + m2[1]); } template <typename T> inline tmat2x2<T> operator- (tmat2x2<T> const & m, const T & s) { return tmat2x2<T>( m[0] - s, m[1] - s); } template <typename T> inline tmat2x2<T> operator- (const T & s, tmat2x2<T> const & m) { return tmat2x2<T>( s - m[0], s - m[1]); } //template <typename T> //inline tmat2x2<T> operator- (tmat2x2<T> const & m, const detail::tvec2<T>& v) //{ //} //template <typename T> //inline tmat2x2<T> operator- (const detail::tvec2<T>& v, tmat2x2<T> const & m) //{ //} template <typename T> inline tmat2x2<T> operator- (tmat2x2<T> const & m1, tmat2x2<T> const & m2) { return tmat2x2<T>( m1[0] - m2[0], m1[1] - m2[1]); } template <typename T> inline tmat2x2<T> operator* (tmat2x2<T> const & m, const T & s) { return tmat2x2<T>( m[0] * s, m[1] * s); } template <typename T> inline tmat2x2<T> operator* (const T & s, tmat2x2<T> const & m) { return tmat2x2<T>( m[0] * s, m[1] * s); } template <typename T> inline detail::tvec2<T> operator* (tmat2x2<T> const & m, const detail::tvec2<T>& v) { return detail::tvec2<T>( m[0][0] * v.x + m[1][0] * v.y, m[0][1] * v.x + m[1][1] * v.y); } template <typename T> inline detail::tvec2<T> operator* (const detail::tvec2<T>& v, tmat2x2<T> const & m) { return detail::tvec2<T>( m[0][0] * v.x + m[0][1] * v.y, m[1][0] * v.x + m[1][1] * v.y); } template <typename T> inline tmat2x2<T> operator* (tmat2x2<T> const & m1, tmat2x2<T> const & m2) { return tmat2x2<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1]); } template <typename T> inline tmat2x2<T> operator/ (tmat2x2<T> const & m, const T & s) { return tmat2x2<T>( m[0] / s, m[1] / s); } template <typename T> inline tmat2x2<T> operator/ (const T & s, tmat2x2<T> const & m) { return tmat2x2<T>( s / m[0], s / m[1]); } template <typename T> inline detail::tvec2<T> operator/ (tmat2x2<T> const & m, const detail::tvec2<T>& v) { return m._inverse() * v; } template <typename T> inline detail::tvec2<T> operator/ (const detail::tvec2<T>& v, tmat2x2<T> const & m) { return v * m._inverse(); } template <typename T> inline tmat2x2<T> operator/ (tmat2x2<T> const & m1, tmat2x2<T> const & m2) { return m1 * m2._inverse(); } // Unary constant operators template <typename valType> inline tmat2x2<valType> const operator- ( tmat2x2<valType> const & m ) { return tmat2x2<valType>( -m[0], -m[1]); } template <typename valType> inline tmat2x2<valType> const operator++ ( tmat2x2<valType> const & m, int ) { return tmat2x2<valType>( m[0] + valType(1), m[1] + valType(1)); } template <typename valType> inline tmat2x2<valType> const operator-- ( tmat2x2<valType> const & m, int ) { return tmat2x2<valType>( m[0] - valType(1), m[1] - valType(1)); } } //namespace detail } //namespace glm
[ [ [ 1, 463 ] ] ]
d7ec164f26180a9cf045860754a59b78e1f69f11
836523304390560c1b0b655888a4abef63a1b4a5
/util/TestSample.cpp
6aa187bcf1df9817da8946469d5513825ec479c2
[]
no_license
paranoiagu/UDSOnlineEditor
4675ed403fe5acf437ff034a17f3eaa932e7b780
7eaae6fef51a01f09d28021ca6e6f2affa7c9658
refs/heads/master
2021-01-11T03:19:59.238691
2011-10-03T06:02:35
2011-10-03T06:02:35
null
0
0
null
null
null
null
GB18030
C++
false
false
4,039
cpp
// TestSample.cpp : CTestSample 的实现 #include "stdafx.h" #include "TestSample.h" #include <stdio.h> #include <windows.h> #include <wincrypt.h> #include <atlstr.h> #include "PKIDtManager.h" #include "P11PinInputDlg.h" #include "comutil.h" #define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING) #define PROVIDER_NAME _T("HaiTai Cryptographic Service Provider") //"Rainbow iKey 1000 RSA Cryptographic Service Provider" void MyHandleError(char *s); // CTestSample STDMETHODIMP CTestSample::FindCerts(void) { /* HCRYPTPROV hCryptProv; BYTE pbData[1000]; // 1000 will hold the longest // key container name. DWORD cbData; WCHAR crContainer[1000]; if(CryptAcquireContext( &hCryptProv, NULL, PROVIDER_NAME, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { InfoMsgBox(_T("CryptAcquireContext")); } else { DWORD err = GetLastError(); InfoMsgBox(_T("CryptAcquireContext error")); } cbData = 0; memset(pbData, 0, sizeof(pbData)); CryptGetProvParam( hCryptProv, PP_ENUMCONTAINERS, pbData, &cbData, CRYPT_FIRST); memset(pbData, 0, sizeof(pbData)); if(CryptGetProvParam( hCryptProv, PP_ENUMCONTAINERS, pbData, &cbData, 0)) { memset(crContainer, 0, sizeof(crContainer)); MultiByteToWideChar(CP_ACP,0,(char *)pbData,strlen((char *)pbData),crContainer,1024); //wsprintf(crContainer, _T("count %s"), pbData); InfoMsgBox(crContainer); } else InfoMsgBox(_T("CryptGetProvParam error1")); CryptReleaseContext(hCryptProv, 0); */ /* CP11PinInputDlg pinDlg; if (pinDlg.DoModal() == IDOK) { //CString pin; //BSTR pin; //pinDlg.GetDlgControl(); //pinDlg.GetDlgItem(IDC_EDIT_PIN); //CT2A(pin.AllocSysString()); //InfoMsgBox(pin.AllocSysString()); InfoMsgBox(pinDlg.m_sz); } else { InfoMsgBox(_T("IDCANCEL")); }*/ PKIDtManager pkiDtManager; BYTE btContainer[1000]; char *pCertName = "admin"; char *pProvName = "HaiTai Cryptographic Service Provider"; if (pkiDtManager.GetContainers(btContainer, pCertName, pProvName)) { TCHAR containerName[1000]; MultiByteToWideChar(CP_ACP, 0, (char*)btContainer, 1000, containerName, 500); InfoMsgBox(containerName); } else { InfoMsgBox(_T("error")); } return S_OK; } void CTestSample::InfoMsgBox(TCHAR* szTip){ MessageBox(GetForegroundWindow(),szTip,_T("亿榕公文交换平台提示"),MB_OK|MB_ICONINFORMATION); } //------------------------------------------------------------------- // This example uses the function MyHandleError, a simple error // handling function, to print an error message to the // standard error (stderr) file and exit the program. // For most applications, replace this function with one // that does more extensive error reporting. void MyHandleError(char *s) { fprintf(stderr,"An error occurred in running the program. \n"); fprintf(stderr,"%s\n",s); fprintf(stderr, "Error number %x.\n", GetLastError()); fprintf(stderr, "Program terminating. \n"); exit(1); } // End of MyHandleError STDMETHODIMP CTestSample::AddNums(BSTR* rtnum) { // TODO: 在此添加实现代码 num++; CString strNumber; strNumber.Format(_T("%d"), num); *rtnum = strNumber.AllocSysString(); return S_OK; } STDMETHODIMP CTestSample::FindCertByUser(BSTR cuser,BSTR* ccontainer) { // TODO: 在此添加实现代码 PKIDtManager pkiDtManager; char btContainer[1000]; char *pCertName = (char*)_com_util::ConvertBSTRToString(cuser); char *pProvName = "HaiTai Cryptographic Service Provider"; if (pkiDtManager.GetContainers((BYTE*)btContainer, pCertName, pProvName)) { //char containerName[1000]; //MultiByteToWideChar(CP_ACP, 0, (char*)btContainer, 1000, containerName, 500); //InfoMsgBox(containerName); *ccontainer = A2BSTR(btContainer); } else { InfoMsgBox(_T("error")); } if (pCertName) delete(pCertName); return S_OK; }
[ [ [ 1, 160 ] ] ]
b35e0fe4ffd6523c02f81e74ac75c9880ccfda7e
4d01363b089917facfef766868fb2b1a853605c7
/src/SceneObjects/Meshes/MeshOBJ.h
d2d0a6eaa522e43a4686374fb19ffc57740e3279
[]
no_license
FardMan69420/aimbot-57
2bc7075e2f24dc35b224fcfb5623083edcd0c52b
3f2b86a1f86e5a6da0605461e7ad81be2a91c49c
refs/heads/master
2022-03-20T07:18:53.690175
2009-07-21T22:45:12
2009-07-21T22:45:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,608
h
/* * Vertex / face format with texture coordinates and simple materials */ #ifndef meshobj_h #define meshobj_h #include <string> #include <sstream> #include "Mesh.h" #include "../../Input/Filenames.h" #include "../../Input/ImageReader.h" #include "../../Utils/Misc/Tokenizer.h" #include "../../Utils/Structures/Position2.h" #include "../../Utils/Structures/Vector3.h" using std::string; using std::fstream; using std::stringstream; // obj files indices start from 1 :C class TexFace : public Face { public: int texIndices[4]; TexFace(int a, int b, int c, int d, int e, int f, int g, int h) : Face(a -1, b - 1, c - 1, d - 1) { texIndices[0] = e - 1; texIndices[1] = f - 1; texIndices[2] = g - 1; texIndices[3] = h - 1; } TexFace(int a, int b, int c, int d, int e, int f) : Face(a - 1, b - 1, c - 1 ) { texIndices[0] = d - 1; texIndices[1] = e - 1; texIndices[2] = f - 1; } }; class MeshOBJ : public Mesh { private: vector<Position2> texCoords; vector<Vector3> normals; vector<TexFace> texFaces; vector<int> normIndices; float tx, ty; float x, y, z; int a, b, c, d; bool haveNormals; bool haveTexCoords; void processLine(const string& str) { string first; stringstream ss; ss << str; ss >> first; if (first == "v") { ss >> x >> y >> z; vertices.push_back(Position3(x, y, z)); } else if (first == "vt") { haveTexCoords = true; ss >> tx >> ty; texCoords.push_back(Position2(tx, ty)); } else if (first == "vn") { haveNormals = true; ss >> x >> y >> z; normals.push_back(Vector3(x, y, z)); } else if(first == "f") { static int num = 1 + int(haveNormals) + int(haveTexCoords); parseIndices(str, num); } } // face indices are in format: f v1/t1/n v2/t2/n v3/t3/n ... vi/ti/n void parseIndices(const string& str, int numCoordTypes) { Tokenizer tokens(str, " /"); //absorb the 'f' tokens.nextToken(); vector<int> ind = tokens.getInts(); int numVerts = ind.size() / numCoordTypes; if(numVerts == 3) { texFaces.push_back(TexFace( ind.at(numCoordTypes * 0), ind.at(numCoordTypes * 1), ind.at(numCoordTypes * 2), ind.at(numCoordTypes * 0 + 1), ind.at(numCoordTypes * 1 + 1), ind.at(numCoordTypes * 2 + 1))); normIndices.push_back(ind.at(2)); } else if(numVerts == 4) { texFaces.push_back(TexFace( ind.at(numCoordTypes * 0), ind.at(numCoordTypes * 1), ind.at(numCoordTypes * 2), ind.at(numCoordTypes * 3), ind.at(numCoordTypes * 0 + 1), ind.at(numCoordTypes * 1 + 1), ind.at(numCoordTypes * 2 + 1), ind.at(numCoordTypes * 3 + 1))); normIndices.push_back(ind.at(2)); } else { cout << "Irregular polygon of order " << numVerts << endl; } } public: int textureID; MeshOBJ() { haveNormals = false; haveTexCoords = false; } void read(const string& filename) { fstream in; string absFilename = Filenames::meshes + filename; in.open(absFilename.c_str(), std::ios::in); if (in.fail() || in.eof()) { cout << "Opening " << absFilename << " failed." << endl; return; } string line; while (getline(in, line)) processLine(line); } void loadTexture(const string& filename) { textureID = ImageReader::loadTexture(Filenames::textures + filename); } vector<TexFace>& getTexFaces() { return texFaces; } vector<Position2>& getTexCoords() { return texCoords; } }; #endif
[ "daven.hughes@92c3b6dc-493d-11de-82d9-516ade3e46db" ]
[ [ [ 1, 176 ] ] ]
a3229ed373e2b06ddb33fa0a264af2d5d764f387
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/SimRobotCore/OpenGL/ObjectRenderer.h
8a4c2e3d452c5d2a3674dd52d8cdbb4a93432312
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,924
h
#ifndef ObjectRenderer_H #define ObjectRenderer_H /* // Example usage of ObjectRenderer: class MyGLWidget : public QGLWidget { public: MyGLWidget(QWidget * parent, Simulation* simulation, const std::string& object) : QGLWidget(parent), objectRenderer(simulation, object) {} private: ObjectRenderer objectRenderer; void initializeGL() { objectRenderer.init(isSharing()); } void paintGL() { objectRenderer.draw(); } void resizeGL(int width, int height) { objectRenderer.setSize(width, height); } void setFovSlot(int fov) { objectRenderer.setFov(fov); } // ... }; //... Simulation simulation(); simulation.loadFile(...) //... MyGLWidget* myGLWidget = new MyGLWidget(parent, &simulation, "myobject"); */ #include "../Tools/SimMath.h" #include "../Simulation/APIDatatypes.h" class Simulation; class GraphicsManager; class SimObject; class ObjectRenderer { public: enum DragType { DRAG_NORMAL, DRAG_ROTATE }; ObjectRenderer(Simulation* simulation, const std::string& object); ~ObjectRenderer(); void init(bool hasSharedDisplayLists); /**< Initializes the OpenGL context. */ void draw(); void setFocus(bool hasFocus); bool hasFocus(); void setSize(unsigned int width, unsigned int height); void getSize(unsigned int& width, unsigned int& height); Simulation* getSimulation() const; void setSimulation(Simulation* simulation); void setObject(const std::string& object); Vector3d getObjectPos(); void setSurfaceStyle(VisualizationParameterSet::SurfaceStyle style); VisualizationParameterSet::SurfaceStyle getSurfaceStyle() const; void zoom(double change); void setCameraMode(VisualizationParameterSet::CameraMode mode); VisualizationParameterSet::CameraMode getCameraMode() const; void toggleCameraMode(); void resetCamera(); void fitCamera(); void setSnapToRoot(bool on); bool hasSnapToRoot() const; void setFovY(int fovY); int getFovY() const; void setDragPlane(DragAndDropPlane plane); DragAndDropPlane getDragPlane() const; void setDragMode(DragAndDropMode mode); DragAndDropMode getDragMode() const; bool startDrag(int x, int y, DragType type); bool moveDrag(int x, int y); bool releaseDrag(int x, int y); void setShowDetailSensors(bool show); bool hasShowDetailSensors() const; void setShowControllerDrawings(bool show); bool hasShowControllerDrawings() const; void setCamera(const Vector3d& pos, const Vector3d& target); void getCamera(Vector3d& pos, Vector3d& target); void precomputeSensorValues(); /** Renders the object into a buffer by using the offscreen renderer. * @param image The buffer to store the image to. This buffer should offer space for width * height * 4 bytes. * @return True on success. */ bool renderOffscreen(void* image); private: Simulation* simulation; GraphicsManager* graphicsManager; std::string object; SimObject* simObject; Vector3d cameraPos; Vector3d cameraTarget; Vector3d cameraUpVector; unsigned int width; unsigned int height; double fovy; VisualizationParameterSet visParams; int fbo_reg; bool focus; double presentationDistance; unsigned int presentationSpeed; unsigned int presentationCirclecounter; class Point { public: Point(int x, int y) : x(x), y(y) {} Point() : x(0), y(0) {} int x; int y; }; bool dragging; DragType dragType; InteractiveSelectionType dragSelection; Point dragStartPos; Point dragCurrentPos; DragAndDropPlane dragPlane; DragAndDropMode dragMode; void zoomTargetCam(double change); void zoomFreeCam(double change); void zoomPresentationCam(double change); void calculateUpVector(); void presentationCameraView(); }; #endif
[ "alon@rogue.(none)" ]
[ [ [ 1, 166 ] ] ]
2c7ca044deff3ac15868dbd12712a06b8cf18375
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/mitchell.h
c2456199bf43e60c441a353ed51d180fef09b4b8
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,882
h
/************************************************************************* Mitchell hardware *************************************************************************/ #include "sound/okim6295.h" class mitchell_state : public driver_device { public: mitchell_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config), m_audiocpu(*this, "audiocpu"), m_oki(*this, "oki") { } /* memory pointers */ UINT8 * m_videoram; UINT8 * m_colorram; size_t m_videoram_size; /* video-related */ tilemap_t *m_bg_tilemap; UINT8 *m_objram; /* Sprite RAM */ int m_flipscreen; int m_video_bank; int m_paletteram_bank; /* sound-related */ int m_sample_buffer; int m_sample_select; /* misc */ int m_input_type; int m_dial[2]; int m_dial_selected; int m_dir[2]; int m_keymatrix; /* devices */ optional_device<cpu_device> m_audiocpu; optional_device<okim6295_device> m_oki; UINT8 *m_nvram; size_t m_nvram_size; }; /*----------- defined in video/mitchell.c -----------*/ WRITE8_HANDLER( mgakuen_paletteram_w ); READ8_HANDLER( mgakuen_paletteram_r ); WRITE8_HANDLER( mgakuen_videoram_w ); READ8_HANDLER( mgakuen_videoram_r ); WRITE8_HANDLER( mgakuen_objram_w ); READ8_HANDLER( mgakuen_objram_r ); WRITE8_HANDLER( pang_video_bank_w ); WRITE8_HANDLER( pang_videoram_w ); READ8_HANDLER( pang_videoram_r ); WRITE8_HANDLER( pang_colorram_w ); READ8_HANDLER( pang_colorram_r ); WRITE8_HANDLER( pang_gfxctrl_w ); WRITE8_HANDLER( pangbl_gfxctrl_w ); WRITE8_HANDLER( pang_paletteram_w ); READ8_HANDLER( pang_paletteram_r ); WRITE8_HANDLER( mstworld_gfxctrl_w ); WRITE8_HANDLER( mstworld_video_bank_w ); VIDEO_START( pang ); SCREEN_UPDATE( pang );
[ "Mike@localhost" ]
[ [ [ 1, 71 ] ] ]
594d28fc6eeb356e2b37e8097a5146864424d98b
1c80a726376d6134744d82eec3129456b0ab0cbf
/Project/C++/C++/练习/MFC_记事本/stdafx.cpp
3d744384e7ba93f2eb93965007abe5a57a94e0e2
[]
no_license
dabaopku/project_pku
338a8971586b6c4cdc52bf82cdd301d398ad909f
b97f3f15cdc3f85a9407e6bf35587116b5129334
refs/heads/master
2021-01-19T11:35:53.500533
2010-09-01T03:42:40
2010-09-01T03:42:40
null
0
0
null
null
null
null
GB18030
C++
false
false
174
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // MFC_记事本.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "[email protected]@592586dc-1302-11df-8689-7786f20063ad" ]
[ [ [ 1, 7 ] ] ]
fbe7793051ae6840f181903ca0b7fac51ae5c8b0
74388fdac3615e98665c61031afe602829bb95f9
/tags/MainProject/widget/glwidget.h
fcae8d34fac849147a433314fd550ca045cae5f0
[]
no_license
mvm9289/vig-qp2010
4bc78bce61970e1f67a53ca1a98ba7e10871615d
2005d0870f53a0a8c78bafad711a3b7f7e11ba4b
refs/heads/master
2020-03-27T22:55:51.934313
2010-09-23T21:15:11
2010-09-23T21:15:11
32,334,738
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,575
h
#ifndef _GLWIDGET_H_ #define _GLWIDGET_H_ #include <QtOpenGL/qgl.h> #include <QKeyEvent> #include <iostream> #include <qstring.h> #include <qfiledialog.h> #include <qtimer.h> #include <QtDesigner/QDesignerExportWidget> #include "material_lib.h" #include "point.h" #include "scene.h" #include "llum.h" #include "finestraLlums.h" #include <list> #define ROTATION_FACTOR 0.2 #define ZOOM_FACTOR 0.1 #define PAN_FACTOR 0.03 #define DEFAULT_FOVY 60.0 #define FPV_FOVY 90.0 class QDESIGNER_WIDGET_EXPORT GLWidget : public QGLWidget { Q_OBJECT public: GLWidget(QWidget * parent); signals: void carOpened(bool); void dialValueChanged(int); void activateAnimation(QString); void activateFirstPersonView(bool); public slots: // help - Ajuda per la terminal des de la que hem engegat el programa. void help(void); // Afegiu aquí la declaració dels slots que necessiteu // Reestablir la camera per defecte void setDefaultCamera(); // Obrir un dialeg per seleccionar un model pel vehicle i carregar-lo void openCar(); // Establir una novia orientación pel vehicle void orientCar(int alpha); void timerDone(); void setCarSpeed(int speed); void configureLight(llum* light); void showLightsWindow(); void activeSmooth(bool active); void activeLocalViewer(bool active); void activeCullFace(bool active); void activeFirstPersonView(bool active); void setFPVzFar(int value); void activeCarLampposts(bool active); protected: // initializeGL() - Aqui incluim les inicialitzacions del contexte grafic. virtual void initializeGL(); // paintGL - Mètode cridat cada cop que cal refrescar la finestra. // Tot el que es dibuixa es dibuixa aqui. virtual void paintGL( void ); // resizeGL() - Es cridat quan canvi la mida del widget virtual void resizeGL (int width, int height); // keyPressEvent() - Cridat quan es prem una tecla virtual void keyPressEvent(QKeyEvent *e); // mousePressEvent() i mouseReleaseEvent() virtual void mousePressEvent( QMouseEvent *e); virtual void mouseReleaseEvent( QMouseEvent *); // mouseMoveEvent() - Cridat quan s'arrosega el ratoli amb algun botó premut. virtual void mouseMoveEvent(QMouseEvent *e); // Calcular el parametres de la camera per defecte void computeDefaultCamera(); // Configurar la matriu modelview segons els parametres de la camera void setModelview(); // Configurar la matriu de projecció segons els parametres de la camera void setProjection(); // Recalcular els plans de retallat de l'escena void computeCuttingPlanes(); void saveCurrentCamera(); void restoreOldCamera(); // Configuracio dels llums void initializeLights(); void configure(llum* light); void updateLightsPosition(); void onOffLamppost(int xClick, int yClick); // Realitza el proces de seleccio i tractament del fanal seleccionat per l'usuari int getSelectedLamppost(int xClick, int yClick); // Retorna el fanal seleccionat per l'usuari mes proper al obs void onOffCarLampposts(); // Realitza el proces de seleccio i tractament dels fanals visibles pel vehicle list<int> getVisibleLampposts(); // Retorna com a maxim 4 fanals, els mes propers i visibles pel vehicle void updateModelView(); private: // interaccio typedef enum {NONE, ROTATE, ZOOM, PAN} InteractiveAction; InteractiveAction DoingInteractive; int xClick, yClick; Scene scene; // Escena a representar en el widget // Afegiu els atributs que necessiteu QTimer* timer; llum* L[8]; finestraLlums lightsWindow; double fovy; double aspect; double initialZNear; double initialZNearLast; double zNear; double zNearLast; double zNearAux; double zNearAuxLast; double initialZFar; double initialZFarLast; double zFar; double zFarLast; double zFarAux; double zFarAuxLast; double maxFPVzFar; double zFarFPV; Point VRP; Point VRPLast; Point OBS; Point OBSLast; Vector UP; Vector UPLast; double distOBS; double distOBSLast; bool carLoaded; bool firstPersonView; int NLampposts; list<int> onLampposts; // Llista amb els fanals encesos per l'usuario en el moment actual list<int> onCarLampposts; // Llista amb els fanals encesos davant del vehicle (no inclou els encesos manualment) bool carLampposts; // Indica si cal o no activar els fanals automatics davant del vehicle }; #endif
[ "mvm9289@58588aa8-722a-b9c2-831f-873cbd2be5b1" ]
[ [ [ 1, 166 ] ] ]
6cf7c4fb759f61e70452689c6ee572682da03528
0b1111e870b496aae0d6210806eebf1c942c9d3a
/Periodic/FFTTest.cpp
e648a818f9828de8af7e0e4d6a42e0fd246d4041
[ "WTFPL" ]
permissive
victorliu/Templated-Numerics
8ca3fabd79435fa40e95e9c8c944ecba42a0d8db
35ca6bb719615d5498a450a2d58e2aa2bb7ef5f9
refs/heads/master
2016-09-05T16:32:22.250276
2009-12-30T07:48:03
2009-12-30T07:48:03
318,857
3
1
null
null
null
null
UTF-8
C++
false
false
720
cpp
#include "FFT.hpp" #include <complex> #include <iostream> typedef std::complex<double> complex_t; int main(){ const size_t N = 14; complex_t *data = new complex_t[N]; for(size_t i = 0; i < N; ++i){ data[i] = i; } std::cout << "Original:" << std::endl; for(size_t i = 0; i < N; ++i){ std::cout << data[i] << std::endl; } FFT::Transform(N, data, data, FFT::FORWARD); std::cout << "Transformed:" << std::endl; for(size_t i = 0; i < N; ++i){ std::cout << data[i] << std::endl; } FFT::Transform(N, data, data, FFT::INVERSE); std::cout << "Inversed:" << std::endl; for(size_t i = 0; i < N; ++i){ std::cout << data[i] << std::endl; } delete [] data; return 0; }
[ "victor@onyx.(none)" ]
[ [ [ 1, 32 ] ] ]
7379530a7d5cd191a3f1cbd39e27508b77833347
672d939ad74ccb32afe7ec11b6b99a89c64a6020
/Graph/GraphStudio/GraphStudio-wCJLib/CaptureBitmap.h
12b738ae080695d5cf4c5fba844c9f1065240540
[]
no_license
cloudlander/legacy
a073013c69e399744de09d649aaac012e17da325
89acf51531165a29b35e36f360220eeca3b0c1f6
refs/heads/master
2022-04-22T14:55:37.354762
2009-04-11T13:51:56
2009-04-11T13:51:56
256,939,313
1
0
null
null
null
null
UTF-8
C++
false
false
955
h
// CaptureBitmap.h: interface for the CCaptureBitmap class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_CAPTUREBITMAP_H__5EDECB3D_5873_4DBF_AED4_74CB2FE0FBC5__INCLUDED_) #define AFX_CAPTUREBITMAP_H__5EDECB3D_5873_4DBF_AED4_74CB2FE0FBC5__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CCaptureBitmap : public CBitmap { public: DECLARE_DYNAMIC( CCaptureBitmap ) CCaptureBitmap(); virtual ~CCaptureBitmap(); void Capture( CRect &rect,CDC& dcMem ); void SaveBitmapEx( CString sFile ); // Implementation public : // Attributes int m_nWidth ; int m_nHeight; // Operations private : CPalette *GetPalette(){return m_pPalette;}; HANDLE CreateDIB( BITMAPINFOHEADER& bi,int *pbmData = NULL); CPalette *m_pPalette; }; #endif // !defined(AFX_CAPTUREBITMAP_H__5EDECB3D_5873_4DBF_AED4_74CB2FE0FBC5__INCLUDED_)
[ "xmzhang@5428276e-be0b-f542-9301-ee418ed919ad" ]
[ [ [ 1, 30 ] ] ]
ba86720547359735534ff61acf46329b11595022
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/src/Engine/Script/ExposeIEntity.h
cfcc3708bcc5ff40fa79992ef7b430dd2736138c
[]
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
1,056
h
#pragma once #include <LuaPlus/LuaPlus.h> namespace Engine { class CoreMgr; class IEntity; class ExposeEntityManager; class ExposePropertyContainer; class ExposeComponentContainer; class ExposeIEntity { public: ExposeIEntity(CoreMgr *coreMgr, ExposeEntityManager *exopsedEntityMgr, IEntity *entity); ~ExposeIEntity(); IEntity *getEntity() const { return entity; } LuaPlus::LuaObject getLEntity() const { return lEntity; } LuaPlus::LuaObject getLMeta() const { return lMeta; } protected: void init(); void SendCommand(LuaPlus::LuaObject lSelf, LuaPlus::LuaObject lCommand); void SendEvent(LuaPlus::LuaObject lSelf, LuaPlus::LuaObject lEventType, LuaPlus::LuaObject lEventArg); LuaPlus::LuaObject HasComponent(LuaPlus::LuaObject lSelf, LuaPlus::LuaObject lName); CoreMgr *coreMgr; ExposeEntityManager *exposedEntityMgr; IEntity *entity; LuaPlus::LuaObject lEntity; LuaPlus::LuaObject lMeta; ExposePropertyContainer *exposedPropContainer; ExposeComponentContainer *exposedCompContainer; }; }
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 41 ] ] ]
7e68a2765963b56fa392faffe20eaf1187b398e4
6c8c4728e608a4badd88de181910a294be56953a
/RexLogicModule/Avatar/AvatarAppearance.h
05a194154441c5cf9f00fbd36f83acf6e2075b50
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,046
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_RexLogic_AvatarAppearance_h #define incl_RexLogic_AvatarAppearance_h #include "EntityComponent/EC_AvatarAppearance.h" class QDomDocument; namespace Ogre { class Bone; class Entity; class Node; class Vector3; class Quaternion; } namespace HttpUtilities { class HttpTask; typedef boost::shared_ptr<HttpTask> HttpTaskPtr; } namespace RexLogic { class RexLogicModule; class AvatarExporter; class AvatarExporterRequest; typedef boost::shared_ptr<AvatarExporter> AvatarExporterPtr; typedef boost::shared_ptr<AvatarExporterRequest> AvatarExporterRequestPtr; //! Handles setting up and updating avatars' appearance. Owned by RexLogicModule::Avatar. class AvatarAppearance { //! States of inventory-based export. Must go input-first enum InventoryExportState { Idle = 0, Assets, Avatar }; public: AvatarAppearance(RexLogicModule *rexlogicmodule); ~AvatarAppearance(); //! Reads default appearance of avatar from file to xml document void ReadDefaultAppearance(const std::string& filename); //! Reads an avatar's appearance from avatar storage /*! The storage address should be set beforehand in the EC_OpensimAvatar component. \param entity Avatar entity \param use_default Whether to reset to default appearance if there is no storage url, default false */ void DownloadAppearance(Scene::EntityPtr entity, bool use_default = false); //! Reads an avatar's appearance from a file /*! \param entity Avatar entity \param filename Path/filename to load from. Note: can either be an xml or mesh file \return true if successful */ bool LoadAppearance(Scene::EntityPtr entity, const std::string& filename); //! Sets up an avatar entity's default appearance. void SetupDefaultAppearance(Scene::EntityPtr entity); //! Sets up an avatar entity's appearance with data from the appearance EC. /*! Since this involves deserializing the appearance description XML & (re)creating the mesh entity, should only be called when the whole appearance changes. Calls also SetupDynamicAppearance(). */ void SetupAppearance(Scene::EntityPtr entity); //! Sets ups the dynamic part of an avatar's appearance. This includes morphs & bone modifiers. void SetupDynamicAppearance(Scene::EntityPtr entity); //! Adjusts (possibly dynamic) height offset of avatar void AdjustHeightOffset(Scene::EntityPtr entity); //! Performs frame-based update. void Update(f64 frametime); //! Handles resource event bool HandleResourceEvent(event_id_t event_id, Foundation::EventDataInterface* data); //! Handles asset event bool HandleAssetEvent(event_id_t event_id, Foundation::EventDataInterface* data); //! Handles inventory event bool HandleInventoryEvent(event_id_t event_id, Foundation::EventDataInterface* data); //! Exports avatar to an authentication/avatar storage server account void ExportAvatar(Scene::EntityPtr entity, const std::string& account, const std::string& authserver, const std::string& password); //! Exports avatar to inventory void InventoryExportAvatar(Scene::EntityPtr entity); //! Exports avatar to inventory, finalization (after assets uploaded) void InventoryExportAvatarFinalize(Scene::EntityPtr entity); //! Resets avatar export state void InventoryExportReset(); //! Changes a material on an avatar. Filename can either be image or material. bool ChangeAvatarMaterial(Scene::EntityPtr entity, uint index, const std::string& filename); //! Adds an attachment on the avatar. Filename is the xml attachment description. bool AddAttachment(Scene::EntityPtr entity, const std::string& filename); private: //! Sets up an avatar mesh void SetupMeshAndMaterials(Scene::EntityPtr entity); //! Sets up avatar morphs void SetupMorphs(Scene::EntityPtr entity); //! Sets up avatar bone modifiers void SetupBoneModifiers(Scene::EntityPtr entity); //! Sets up avatar attachments void SetupAttachments(Scene::EntityPtr entity); //! Resets mesh entity bones to initial transform from the mesh original skeleton void ResetBones(Scene::EntityPtr entity); //! Applies a bone modifier void ApplyBoneModifier(Scene::EntityPtr entity, const BoneModifier& modifier, Real value); //! Hides vertices from an entity's mesh. Mesh should be cloned from the base mesh and this must not be called more than once for the entity. void HideVertices(Ogre::Entity*, std::set<uint> vertices_to_hide); //! Processes appearance downloads void ProcessAppearanceDownloads(); //! Processes avatar export (result from the avatar exporter threadtask) void ProcessAvatarExport(); //! Processes an avatar appearance download result void ProcessAppearanceDownload(Scene::EntityPtr entity, const u8* data, uint size); //! Processes an avatar appearance asset (inventory based avatar) void ProcessInventoryAppearance(Scene::EntityPtr entity, const u8* data, uint size); //! Requests needed avatar resouces uint RequestAvatarResources(Scene::EntityPtr entity, const AvatarAssetMap& assets, bool inventorymode = false); //! Fixes up avatar resource references after downloading of all avatar assets complete void FixupResources(Scene::EntityPtr entity); //! Fixes up a generic resource, whose type is known void FixupResource(AvatarAsset& asset, const AvatarAssetMap& asset_map, const std::string& resource_type); //! Fixes up avatar material (material script/texture resources) void FixupMaterial(AvatarMaterial& mat, const AvatarAssetMap& asset_map); //! Prepares new avatar appearance using xml as the main file bool PrepareAppearanceFromXml(Scene::EntityPtr entity, const std::string& filename); //! Prepares new avatar appearance using mesh as the main file, with optional xml file bool PrepareAppearanceFromMesh(Scene::EntityPtr entity, const std::string& filename); //! Guesses avatar asset resource type from human-readable asset name static const std::string& GetResourceTypeFromName(const std::string& name, bool inventorymode = false); //! Adds avatar assets to the export request void GetAvatarAssetsForExport(AvatarExporterRequestPtr request, EC_AvatarAppearance& appearance, bool inventorymode = false); //! Adds an avatar asset to the export request /*! \return true if added successfully */ bool GetAvatarAssetForExport(AvatarExporterRequestPtr request, const AvatarAsset& appearance, bool replace_spaces = false, bool inventorymode = false); //! Adds an avatar asset to the export request /*! \return true if added successfully */ bool GetAvatarMaterialForExport(AvatarExporterRequestPtr request, const AvatarMaterial& material, bool inventorymode = false); //! Gets a bone safely from the avatar skeleton /*! \return Pointer to bone, or 0 if does not exist */ Ogre::Bone* GetAvatarBone(Scene::EntityPtr entity, const std::string& bone_name); //! Gets initial derived transform of a bone. This is something Ogre can't give us automatically void GetInitialDerivedBonePosition(Ogre::Node* bone, Ogre::Vector3& position); //! Adds a directory as a temporary Ogre resource directory, group name "Avatar" /*! Each time this is called, the previously set temp directory will be removed from the resource system. */ void AddTempResourceDirectory(const std::string& dirname); //! Default avatar appearance xml document boost::shared_ptr<QDomDocument> default_appearance_; //! Thread tasks for avatar appearance downloads std::map<entity_id_t, HttpUtilities::HttpTaskPtr> appearance_downloaders_; //! Avatar resource request tags associated to entity std::map<request_tag_t, entity_id_t> avatar_resource_tags_; //! Avatar appearance xml asset request tags associated to entity, for inventory based appearance std::map<request_tag_t, entity_id_t> avatar_appearance_tags_; //! Amount of pending avatar resource requests. When hits 0, should be able to build avatar std::map<entity_id_t, uint> avatar_pending_requests_; //! Legacy storage avatar exporter task AvatarExporterPtr avatar_exporter_; //! Progress of inventory based export InventoryExportState inv_export_state_; //! Temp assetmap for inventory based export AvatarAssetMap inv_export_assetmap_; //! Dummy request to collect assets for inventory based export AvatarExporterRequestPtr inv_export_request_; //! Entity that is being used for inventory based export Scene::EntityWeakPtr inv_export_entity_; RexLogicModule *rexlogicmodule_; }; } #endif
[ "jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3", "cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 35 ], [ 44, 80 ], [ 82, 83 ], [ 87, 87 ], [ 89, 93 ], [ 101, 102 ], [ 104, 124 ], [ 126, 127 ], [ 129, 136 ], [ 141, 141 ], [ 145, 160 ], [ 162, 163 ], [ 165, 168 ], [ 170, 173 ], [ 175, 192 ], [ 194, 195 ], [ 200, 201 ], [ 203, 203 ], [ 205, 206 ], [ 216, 220 ] ], [ [ 36, 43 ], [ 81, 81 ], [ 84, 86 ], [ 88, 88 ], [ 94, 100 ], [ 103, 103 ], [ 125, 125 ], [ 128, 128 ], [ 137, 140 ], [ 142, 144 ], [ 161, 161 ], [ 164, 164 ], [ 169, 169 ], [ 174, 174 ], [ 193, 193 ], [ 196, 199 ], [ 202, 202 ], [ 204, 204 ], [ 207, 215 ] ] ]
955807207d382087adac9527103064169563fd36
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/Code/Tools/Tests/EmptyTestProcess.h
fa1d1401fc53f7288a086c2a9aac847858037975
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,852
h
//---------------------------------------------------------------------------------- // CEmptyTestProcess class // Author: Enric Vergara // // Description: // Test para probar el funcionamiento del reproductor de videos AVI. //---------------------------------------------------------------------------------- #pragma once #ifndef INC_EMPTY_TEST_PROCESS_H_ #define INC_EMPTY_TEST_PROCESS_H_ #include <string> //---Engine Includes---- #include "Core/Core.h" #include "Core/Process.h" //----------------------- //--Forward Declaration-- class CRenderManager; class CObject3D; class CInputManager; //----------------------- class CEmptyTestProcess: public CProcess { public: //---Init and End protocols CEmptyTestProcess(const std::string& processName): CProcess(processName), m_pObject3D(NULL) {} virtual ~CEmptyTestProcess(void) {Done();} //----CProcess Interface--------------------------------------- virtual bool Init (); virtual bool Start () {m_bStart = true; return true;} //---Update and Render function virtual void Update (float elapsedTime); virtual void RenderScene (CRenderManager* renderManager, CFontManager* fm); virtual uint32 RenderDebugInfo (CRenderManager* renderManager, CFontManager* fm, float fps); //-------------------------------------------------------------- private: //----CProcess Interface--------------------------------------- virtual void Release (); //-------------------------------------------------------------- void UpdateInputActions (CInputManager* inputManager); private: CObject3D* m_pObject3D; }; static CEmptyTestProcess* GetEmptyTest() {return static_cast<CEmptyTestProcess*>(CORE->GetProcess());} #endif //INC_EMPTY_TEST_PROCESS_H_
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 60 ] ] ]
cc55635072ae464551bbc97f9a87c8ddd43ac808
bca24d0199ee30ff3bcea994131758eda0c4482e
/MeshScintillator.h
d48ca167c7002d0e773f8a4970db22dc55c2f061
[]
no_license
abarendregt/Scint_Cell
bbde8d3a10e50d554f84add3a5bb83e6f100578c
3fa0b042ab9874a78b6241033b0824315cf07ab4
refs/heads/master
2020-03-28T19:40:05.918048
2011-04-26T03:19:05
2011-04-26T03:19:05
1,189,271
1
1
null
null
null
null
UTF-8
C++
false
false
902
h
#ifndef MESHSCINTILLATOR_H #define MESHSCINTILLATOR_H #include <fstream> #include <iostream> #include <string> #include <sstream> #include <cstdlib> #include <math.h> enum PT {null,Tri_Plain,Tri_Isect,RPP_Plain,RPP_Isect}; class MeshScintillator { double xMin, xMax, yMin, yMax; PT PartType; public: //This section defines each member of the class void setPT(PT pt) {this->PartType=pt;} void setxMin(double xMn) {this->xMin = xMn;} void setxMax(double xMx) {this->xMax = xMx;} void setyMin(double yMn) {this->yMin = yMn;} void setyMax(double yMx) {this->yMax = yMx;} //This section calls each member of the class for use PT getPT(void) {return this->PartType;} double getxMin(void) {return this->xMin;} double getxMax(void) {return this->xMax;} double getyMin(void) {return this->yMin;} double getyMax(void) {return this->yMax;} }; #endif
[ "highlander@highlander-desktop.(none)" ]
[ [ [ 1, 36 ] ] ]
b5e428e9df919f5bc4d51f23741cecbcacc2f4b0
94d9e8ec108a2f79068da09cb6ac903c16b77730
/shared/mtrand.h
2be7feceae00b914f867eec1ff96c2edcc6489a5
[]
no_license
kiyoya/sociarium
d375c0e5abcce11ae4b087930677483d74864d09
b26c2c9cbd23c2f8ef219d0059e42370294865d1
refs/heads/master
2021-01-25T07:28:25.862346
2009-10-22T05:57:42
2009-10-22T05:57:42
318,115
1
0
null
null
null
null
UTF-8
C++
false
false
2,115
h
// mtrand.h // HASHIMOTO, Yasuhiro (E-mail: hy @ sys.t.u-tokyo.ac.jp) /* Copyright (c) 2005-2009, HASHIMOTO, Yasuhiro, All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the University of Tokyo nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef INCLUDE_GUARD_SHARED_MTRAND_H #define INCLUDE_GUARD_SHARED_MTRAND_H #include <boost/random.hpp> namespace { namespace mt { unsigned long seed = 1; boost::mt19937 generator(seed); boost::uniform_real<> distribution(0.0, 1.0); boost::variate_generator<boost::mt19937, boost::uniform_real<> > rand(generator, distribution); } } #endif // INCLUDE_GUARD_SHARED_MTRAND_H
[ [ [ 1, 46 ] ] ]
4be1ba40ba28e29378bf40c8b340892570a28c5f
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/064.cpp
73bce17c9c54c71233ec955096440272d431167b
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
4,947
cpp
#ifdef _NES_MAPPER_CPP_ ///////////////////////////////////////////////////////////////////// // Mapper 64 void NES_mapper64_Init() { g_NESmapper.Reset = NES_mapper64_Reset; g_NESmapper.MemoryWrite = NES_mapper64_MemoryWrite; g_NESmapper.HSync = NES_mapper64_HSync; } void NES_mapper64_Reset() { // set CPU bank pointers g_NESmapper.set_CPU_bank4(g_NESmapper.num_8k_ROM_banks-1); g_NESmapper.set_CPU_bank5(g_NESmapper.num_8k_ROM_banks-1); g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-1); g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1); // set PPU bank pointers if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7); } g_NESmapper.Mapper64.irq_latch = 0; g_NESmapper.Mapper64.irq_counter = 0; g_NESmapper.Mapper64.irq_enabled = 0; g_NESmapper.Mapper64.regs[0] = 0; g_NESmapper.Mapper64.regs[1] = 0; g_NESmapper.Mapper64.regs[2] = 0; } void NES_mapper64_MemoryWrite(uint32 addr, uint8 data) { switch(addr & 0xF003) { case 0x8000: { g_NESmapper.Mapper64.regs[0] = data & 0x0F; g_NESmapper.Mapper64.regs[1] = data & 0x40; g_NESmapper.Mapper64.regs[2] = data & 0x80; } break; case 0x8001: { switch(g_NESmapper.Mapper64.regs[0]) { case 0x00: { if(g_NESmapper.Mapper64.regs[2]) { g_NESmapper.set_PPU_bank4(data+0); g_NESmapper.set_PPU_bank5(data+1); } else { g_NESmapper.set_PPU_bank0(data+0); g_NESmapper.set_PPU_bank1(data+1); } } break; case 0x01: { if(g_NESmapper.Mapper64.regs[2]) { g_NESmapper.set_PPU_bank6(data+0); g_NESmapper.set_PPU_bank7(data+1); } else { g_NESmapper.set_PPU_bank2(data+0); g_NESmapper.set_PPU_bank3(data+1); } } break; case 0x02: { if(g_NESmapper.Mapper64.regs[2]) { g_NESmapper.set_PPU_bank0(data); } else { g_NESmapper.set_PPU_bank4(data); } } break; case 0x03: { if(g_NESmapper.Mapper64.regs[2]) { g_NESmapper.set_PPU_bank1(data); } else { g_NESmapper.set_PPU_bank5(data); } } break; case 0x04: { if(g_NESmapper.Mapper64.regs[2]) { g_NESmapper.set_PPU_bank2(data); } else { g_NESmapper.set_PPU_bank6(data); } } break; case 0x05: { if(g_NESmapper.Mapper64.regs[2]) { g_NESmapper.set_PPU_bank3(data); } else { g_NESmapper.set_PPU_bank7(data); } } break; case 0x06: { if(g_NESmapper.Mapper64.regs[1]) { g_NESmapper.set_CPU_bank5(data); } else { g_NESmapper.set_CPU_bank4(data); } } break; case 0x07: { if(g_NESmapper.Mapper64.regs[1]) { g_NESmapper.set_CPU_bank6(data); } else { g_NESmapper.set_CPU_bank5(data); } } break; case 0x08: { //if(g_NESmapper.Mapper64.regs[2]) //{ // set_PPU_bank5(data); //} //else { g_NESmapper.set_PPU_bank1(data); } } break; case 0x09: { //if(g_NESmapper.Mapper64.regs[2]) //{ // set_PPU_bank7(data); //} //else { g_NESmapper.set_PPU_bank3(data); } } break; case 0x0F: { if(g_NESmapper.Mapper64.regs[1]) { g_NESmapper.set_CPU_bank4(data); } else { g_NESmapper.set_CPU_bank6(data); } } break; } } break; case 0xA000: { if(!(data & 0x01)) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT); } else { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } } break; case 0xC000: { g_NESmapper.Mapper64.irq_latch = data; g_NESmapper.Mapper64.irq_counter = g_NESmapper.Mapper64.irq_latch; } break; case 0xC001: { g_NESmapper.Mapper64.irq_counter = g_NESmapper.Mapper64.irq_latch; } break; case 0xE000: { g_NESmapper.Mapper64.irq_enabled = 0; g_NESmapper.Mapper64.irq_counter = g_NESmapper.Mapper64.irq_latch; } break; case 0xE001: { g_NESmapper.Mapper64.irq_enabled = 1; g_NESmapper.Mapper64.irq_counter = g_NESmapper.Mapper64.irq_latch; } break; } } void NES_mapper64_HSync(uint32 scanline) { if(g_NESmapper.Mapper64.irq_enabled) { if((scanline >= 0) && (scanline <= 239)) { if(NES_PPU_spr_enabled() || NES_PPU_bg_enabled()) { if(!(--g_NESmapper.Mapper64.irq_counter)) { g_NESmapper.Mapper64.irq_counter = g_NESmapper.Mapper64.irq_latch; NES6502_DoIRQ(); } } } } } ///////////////////////////////////////////////////////////////////// #endif
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 262 ] ] ]
e594f6d3223bdc2cddab83189c9fba10a68f0043
6f8721dafe2b841f4eb27237deead56ba6e7a55b
/src/WorldOfAnguis/Graphics/DirectX/Units/Player/DXPlayerView.cpp
b6003e43a80b2ec59bff350307d094db31d1fab2
[]
no_license
worldofanguis/WoA
dea2abf6db52017a181b12e9c0f9989af61cfa2a
161c7bb4edcee8f941f31b8248a41047d89e264b
refs/heads/master
2021-01-19T10:25:57.360015
2010-02-19T16:05:40
2010-02-19T16:05:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,245
cpp
/* * ___ ___ __ * \ \ / / / \ * \ \ / / / \ * \ \ /\ / /___ / /\ \ * \ \/ \/ /| | / ____ \ * \___/\___/ |___|/__/ \__\ * World Of Anguis * */ #include "DXPlayerView.h" DXPlayerView::DXPlayerView() { pTexture = NULL; AnimationFrame = 0; LoadTexture(1); // Player<ID>.bmp // } DXPlayerView::~DXPlayerView() { SAFE_RELEASE(pTexture); } void DXPlayerView::LoadTexture(int TextureID) { if(pTexture != NULL) return; char File[MAX_PATH]; sprintf_s(File,sizeof(File),"..\\..\\pic\\Player\\Player%d.bmp",TextureID); D3DXCreateTextureFromFileEx(DXPlayerView::pDevice, // Device File, 20, // Width 30, // Height 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255,0,255), // pink = transparent NULL, NULL, &pTexture); } void DXPlayerView::Draw(int X,int Y,bool FaceRight,bool Jumping) { if(pTexture == NULL || pSprite == NULL) return; D3DXVECTOR3 v(X,Y,0); pSprite->Draw(pTexture,NULL,NULL,&v,0xFFFFFFFF); }
[ [ [ 1, 57 ] ] ]
cb4bcf7c7e17563488cd7e7342112f6a976ce79f
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/coreLibrary_200/source/physics/dgCollisionEllipse.cpp
4f8730570a353594e86370dbc6ad03ed1267a836
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
UTF-8
C++
false
false
9,212
cpp
/* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "dgPhysicsStdafx.h" #include "dgBody.h" #include "dgContact.h" #include "dgCollisionEllipse.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// dgCollisionEllipse::dgCollisionEllipse(dgMemoryAllocator* const allocator, dgUnsigned32 signature, dgFloat32 rx, dgFloat32 ry, dgFloat32 rz, const dgMatrix& offsetMatrix) : dgCollisionSphere(allocator, signature, dgFloat32(1.0f), offsetMatrix), m_scale( rx, ry, rz, dgFloat32(0.0f)), m_invScale(dgFloat32(1.0f) / rx, dgFloat32(1.0f) / ry, dgFloat32(1.0f) / rz, dgFloat32(0.0f)) { m_rtti |= dgCollisionEllipse_RTTI; m_collsionId = m_ellipseCollision; } dgCollisionEllipse::dgCollisionEllipse(dgWorld* const world, dgDeserialize deserialization, void* const userData) : dgCollisionSphere(world, deserialization, userData) { dgVector size; m_rtti |= dgCollisionEllipse_RTTI; deserialization(userData, &m_scale, sizeof(dgVector)); m_invScale.m_x = dgFloat32(1.0f) / m_scale.m_x; m_invScale.m_y = dgFloat32(1.0f) / m_scale.m_y; m_invScale.m_z = dgFloat32(1.0f) / m_scale.m_z; m_invScale.m_w = dgFloat32(0.0f); } dgCollisionEllipse::~dgCollisionEllipse() { } dgInt32 dgCollisionEllipse::CalculateSignature() const { dgUnsigned32 buffer[2 * sizeof(dgMatrix) / sizeof(dgInt32)]; memset(buffer, 0, sizeof(buffer)); buffer[0] = m_ellipseCollision; buffer[1] = Quantize(m_scale.m_x); buffer[2] = Quantize(m_scale.m_y); buffer[3] = Quantize(m_scale.m_z); memcpy(&buffer[4], &m_offset, sizeof(dgMatrix)); return dgInt32(MakeCRC(buffer, sizeof(buffer))); } void dgCollisionEllipse::SetCollisionBBox(const dgVector& p0__, const dgVector& p1__) { _ASSERTE(0); } void dgCollisionEllipse::CalcAABB(const dgMatrix &matrix, dgVector &p0, dgVector &p1) const { dgMatrix mat(matrix); mat.m_front = mat.m_front.Scale(m_scale.m_x); mat.m_up = mat.m_up.Scale(m_scale.m_y); mat.m_right = mat.m_right.Scale(m_scale.m_z); dgCollisionConvex::CalcAABB(mat, p0, p1); } void dgCollisionEllipse::CalcAABBSimd(const dgMatrix &matrix, dgVector& p0, dgVector& p1) const { dgMatrix mat(matrix); mat.m_front = mat.m_front.Scale(m_scale.m_x); mat.m_up = mat.m_up.Scale(m_scale.m_y); mat.m_right = mat.m_right.Scale(m_scale.m_z); dgCollisionConvex::CalcAABBSimd(mat, p0, p1); #if 0 dgVector xxx0; dgVector xxx1; CalcAABB (matrix, xxx0, xxx1); _ASSERTE (dgAbsf(xxx0.m_x - p0.m_x) < 1.0e-3f); _ASSERTE (dgAbsf(xxx0.m_y - p0.m_y) < 1.0e-3f); _ASSERTE (dgAbsf(xxx0.m_z - p0.m_z) < 1.0e-3f); _ASSERTE (dgAbsf(xxx1.m_x - p1.m_x) < 1.0e-3f); _ASSERTE (dgAbsf(xxx1.m_y - p1.m_y) < 1.0e-3f); _ASSERTE (dgAbsf(xxx1.m_z - p1.m_z) < 1.0e-3f); #endif } dgVector dgCollisionEllipse::SupportVertex(const dgVector& dir) const { _ASSERTE((dir % dir) > dgFloat32 (0.999f)); dgVector dir1(dir.m_x * m_scale.m_x, dir.m_y * m_scale.m_y, dir.m_z * m_scale.m_z, dgFloat32(0.0f)); dir1 = dir1.Scale(dgRsqrt (dir1 % dir1)); dgVector p(dgCollisionSphere::SupportVertex(dir1)); return dgVector(p.m_x * m_scale.m_x, p.m_y * m_scale.m_y, p.m_z * m_scale.m_z, dgFloat32(0.0f)); } dgVector dgCollisionEllipse::SupportVertexSimd(const dgVector& dir) const { #ifdef DG_BUILD_SIMD_CODE _ASSERTE((dir % dir) > dgFloat32 (0.999f)); _ASSERTE((dgUnsigned64(&dir) & 0x0f) == 0); _ASSERTE((dgUnsigned64(&m_scale) & 0x0f) == 0); dgVector dir1; simd_type n; simd_type tmp; simd_type mag2; // dir1 = dgVector (dir.m_x * m_scale.m_x, dir.m_y * m_scale.m_y, dir.m_z * m_scale.m_z, dgFloat32 (0.0f)); n = simd_mul_v (*(simd_type*)&dir, *(simd_type*)&m_scale); // dir1 = dir1.Scale (dgRsqrt (dir1 % dir1)); mag2 = simd_mul_v (n, n); mag2 = simd_add_s (simd_add_v (mag2, simd_move_hl_v (mag2, mag2)), simd_permut_v (mag2, mag2, PURMUT_MASK (3,3,3,1))); tmp = simd_rsqrt_s(mag2); mag2 = simd_mul_s (simd_mul_s(*(simd_type*)&m_nrh0p5, tmp), simd_mul_sub_s (*(simd_type*)&m_nrh3p0, simd_mul_s (mag2, tmp), tmp)); (*(simd_type*) &dir1) = simd_mul_v (n, simd_permut_v (mag2, mag2, PURMUT_MASK (3,0,0,0))); dgVector p(dgCollisionSphere::SupportVertexSimd(dir1)); return dgVector(p.m_x * m_scale.m_x, p.m_y * m_scale.m_y, p.m_z * m_scale.m_z, dgFloat32(0.0f)); #else return dgVector (dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f)); #endif } dgInt32 dgCollisionEllipse::CalculatePlaneIntersection(const dgVector& normal, const dgVector& point, dgVector* const contactsOut) const { _ASSERTE((normal % normal) > dgFloat32 (0.999f)); // contactsOut[0] = point; dgVector n(normal.m_x * m_scale.m_x, normal.m_y * m_scale.m_y, normal.m_z * m_scale.m_z, dgFloat32(0.0f)); n = n.Scale((normal % point) / (n % n)); contactsOut[0] = dgVector(n.m_x * m_scale.m_x, n.m_y * m_scale.m_y, n.m_z * m_scale.m_z, dgFloat32(0.0f)); return 1; } dgInt32 dgCollisionEllipse::CalculatePlaneIntersectionSimd( const dgVector& normal, const dgVector& point, dgVector* const contactsOut) const { #ifdef DG_BUILD_SIMD_CODE _ASSERTE((normal % normal) > dgFloat32 (0.999f)); dgVector n(normal.m_x * m_scale.m_x, normal.m_y * m_scale.m_y, normal.m_z * m_scale.m_z, dgFloat32(0.0f)); n = n.Scale((normal % point) / (n % n)); contactsOut[0] = dgVector(n.m_x * m_scale.m_x, n.m_y * m_scale.m_y, n.m_z * m_scale.m_z, dgFloat32(0.0f)); return 1; #else return 0; #endif } void dgCollisionEllipse::DebugCollision(const dgMatrix& matrixPtr, OnDebugCollisionMeshCallback callback, void* const userData) const { dgMatrix mat(GetOffsetMatrix() * matrixPtr); mat.m_front = mat.m_front.Scale(m_scale.m_x); mat.m_up = mat.m_up.Scale(m_scale.m_y); mat.m_right = mat.m_right.Scale(m_scale.m_z); mat = GetOffsetMatrix().Inverse() * mat; dgCollisionSphere::DebugCollision(mat, callback, userData); } dgFloat32 dgCollisionEllipse::RayCast(const dgVector& p0, const dgVector& p1, dgContactPoint& contactOut, OnRayPrecastAction preFilter, const dgBody* const body, void* const userData) const { dgFloat32 t; if (PREFILTER_RAYCAST (preFilter, body, this, userData)) { return dgFloat32(1.2f); } dgVector q0(p0.m_x * m_invScale.m_x, p0.m_y * m_invScale.m_y, p0.m_z * m_invScale.m_z, dgFloat32(0.0f)); dgVector q1(p1.m_x * m_invScale.m_x, p1.m_y * m_invScale.m_y, p1.m_z * m_invScale.m_z, dgFloat32(0.0f)); t = dgCollisionSphere::RayCast(q0, q1, contactOut, NULL, NULL, NULL); return t; } dgFloat32 dgCollisionEllipse::RayCastSimd(const dgVector& p0, const dgVector& p1, dgContactPoint& contactOut, OnRayPrecastAction preFilter, const dgBody* const body, void* const userData) const { dgFloat32 t; if (PREFILTER_RAYCAST (preFilter, body, this, userData)) { return dgFloat32(1.2f); } dgVector q0(p0.m_x * m_invScale.m_x, p0.m_y * m_invScale.m_y, p0.m_z * m_invScale.m_z, dgFloat32(0.0f)); dgVector q1(p1.m_x * m_invScale.m_x, p1.m_y * m_invScale.m_y, p1.m_z * m_invScale.m_z, dgFloat32(0.0f)); t = dgCollisionSphere::RayCastSimd(q0, q1, contactOut, NULL, NULL, NULL); return t; } dgFloat32 dgCollisionEllipse::CalculateMassProperties(dgVector& inertia, dgVector& crossInertia, dgVector& centerOfMass) const { return dgCollisionConvex::CalculateMassProperties(inertia, crossInertia, centerOfMass); } void dgCollisionEllipse::GetCollisionInfo(dgCollisionInfo* info) const { dgCollisionConvex::GetCollisionInfo(info); info->m_sphere.m_r0 = m_scale.m_x; info->m_sphere.m_r1 = m_scale.m_y; info->m_sphere.m_r2 = m_scale.m_z; info->m_offsetMatrix = GetOffsetMatrix(); // strcpy (info->m_collisionType, "sphere"); info->m_collisionType = m_sphereCollision; } void dgCollisionEllipse::Serialize(dgSerialize callback, void* const userData) const { dgCollisionSphere::Serialize(callback, userData); callback(userData, &m_scale, sizeof(dgVector)); }
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 266 ] ] ]
b916109fb579babf269b2d93e1980cede1ca17de
4e8581b6eaaabdd58b1151201d64b45c7147dac7
/src/AlignedSequence.h
19fe6b78a28dd8155b7ae7dd4d97153a9f2593c8
[]
no_license
charmingbrew/bioinformatics-mscd-2011
c4a390bf25d2197d4e912d7976619cb02c666587
04d81d0f05001d3ed82911459cff6dddb3c7f252
refs/heads/master
2020-05-09T12:56:08.625451
2011-05-17T05:55:14
2011-05-17T05:55:14
33,334,714
0
1
null
null
null
null
UTF-8
C++
false
false
476
h
/** * @file AlignedSequence.h * @class AlignedSequence * @brief Holds a sequence string after it is aligned */ #ifndef _ALIGNEDSEQUENCE_H #define _ALIGNEDSEQUENCE_H #include <string> using namespace std; class AlignedSequence { private: string aligned_genotype; int score; public: void SetAlignedGenotype(string aligned_genotype); string GetAlignedGenotype(); void SetScore(int score); int GetScore(); }; #endif
[ "[email protected]@e9cc6749-363d-4b58-5071-845f21bc09f4", "millardfillmoreesquire@e9cc6749-363d-4b58-5071-845f21bc09f4", "[email protected]@e9cc6749-363d-4b58-5071-845f21bc09f4", "[email protected]@e9cc6749-363d-4b58-5071-845f21bc09f4" ]
[ [ [ 1, 1 ], [ 3, 6 ] ], [ [ 2, 2 ], [ 8, 8 ], [ 14, 14 ], [ 16, 17 ], [ 19, 19 ], [ 23, 23 ], [ 25, 25 ] ], [ [ 7, 7 ], [ 9, 9 ], [ 12, 13 ], [ 15, 15 ], [ 18, 18 ], [ 20, 22 ], [ 24, 24 ] ], [ [ 10, 11 ] ] ]
e93382f17a8e406e8c729429843d13889ed5c290
259319e5fe06036972de9036f0078b8f5faba86e
/records/StudentRecord.cpp
9b9eb617920366a7c7d62e8a3f5d9ba327189155
[]
no_license
ferromera/sancus
652d05fc2a28987ac37309b9293cbd7f92448186
0f5d9b2e0bf1b6e099ade36edcf75e9640788589
refs/heads/master
2021-01-01T16:56:39.380388
2011-12-04T01:01:55
2011-12-04T01:01:55
32,414,828
0
0
null
null
null
null
UTF-8
C++
false
false
2,683
cpp
#include "StudentRecord.h" #include <cstring> using namespace std; StudentRecord::StudentRecord():idNumber_(0),name_(string()){ key_=new Key; buffer= new char[260]; } StudentRecord::StudentRecord(const StudentRecord & sr): idNumber_(sr.idNumber_),name_(sr.name_){ key_=new Key((uint16_t) idNumber_); buffer= new char[260]; } StudentRecord::StudentRecord(char ** input){ key_= new Key(); buffer= new char[260]; read(input); } StudentRecord::StudentRecord(uint16_t idNumber,const string & name) :idNumber_(idNumber),name_(name){ key_= new Key(idNumber); buffer= new char[260]; } const StudentRecord::Key & StudentRecord::getKey()const{ //Key * k= dynamic_cast<Key *>(key_); //return (*k); return * ( (StudentRecord::Key *) key_ ); } void StudentRecord::setKey(const StudentRecord::Key & k){ //const Key & ak=dynamic_cast<const Key &>(k); delete key_; key_=new Key(k); idNumber_=k.getKey(); } void StudentRecord::setKey(int16_t k){ delete key_; key_=new Key(k); idNumber_=k; } void StudentRecord::read(char ** input){ char * buffCurr=buffer; memcpy(buffCurr,*input,2); memcpy(&idNumber_,*input,2); delete key_; key_=new Key(idNumber_); (*input)+=2; buffCurr+=2; uint8_t nameSize; memcpy(buffCurr,*input,1); memcpy(&nameSize,*input,1); buffCurr++; (*input)++; char * c_str=new char[nameSize+1]; memcpy(buffCurr,*input,nameSize); memcpy(c_str,*input,nameSize); (*input)+=nameSize; c_str[nameSize]='\0'; name_=c_str; delete c_str; } void StudentRecord::write(char ** output){ update(); memcpy(*output,buffer,size()); (*output)+=size(); } void StudentRecord::update(){ //write back to the buffer char * buffCurr=buffer; memcpy(buffCurr,&idNumber_,2); buffCurr+=2; uint8_t nameSize=name_.size(); memcpy(buffCurr,&nameSize,1); buffCurr++; memcpy(buffCurr,name_.c_str(),nameSize); } unsigned int StudentRecord::size()const{ return sizeof(idNumber_)+1+name_.size(); } uint16_t StudentRecord::idNumber()const{ return idNumber_; } const string & StudentRecord::name()const{ return name_; } void StudentRecord::idNumber(uint16_t p){ setKey(p); } void StudentRecord::name(const string & n){ name_=n; } StudentRecord& StudentRecord::operator=(const StudentRecord& rec){ if(this==&rec) return *this; idNumber_=rec.idNumber_; name_=rec.name_; key_=new Key((uint16_t) idNumber_); buffer= new char[260]; return *this; } StudentRecord::~StudentRecord(){ delete buffer; }
[ "[email protected]@b06ae71c-7d8b-23a7-3f8b-8cb8ce3c93c2" ]
[ [ [ 1, 118 ] ] ]
4450cc257a739bb94923c9183cbdebf5cd984099
084767fd7ed36a5ecebf3c60cca04e4ef7dbb27d
/Escr_NG.h
5a7cd962f3ed6a9b9ab1e955ad91c18c3370a8cd
[]
no_license
ricehiroko/alien
0ea7e06d180f2556cda5f5aa2da8aa88c6ffc166
863283b7081b1b7afef59c33843cc1467c320d0a
refs/heads/master
2021-05-27T16:37:10.619332
2011-08-02T17:56:07
2011-08-02T17:56:07
114,732,151
0
1
null
2017-12-19T07:16:13
2017-12-19T07:16:12
null
ISO-8859-13
C++
false
false
3,249
h
! Escr_NG.h ! Presenta un vector de cadenas en pantalla. ! Hace una pausa tras cada cadena. ! Visualiza cada cadena caracter a caracter. System_file; #ifndef ESCR_LIB; Constant ESCR_LIB; Message "Compilando librerķa de escritura letra a letra. Baltasar, el arquero."; Constant MAX_TAM_BUFFER = 310; Array escr_buffer_lib --> MAX_TAM_BUFFER; #ifdef TARGET_GLULX; Constant ESCR_PRIMERA_LETRA 4; #endif; #ifdef TARGET_ZCODE; Constant ESCR_PRIMERA_LETRA 2; #endif; ! Tipos de mensaje: Constant POR_LETRA = 0; Constant POR_MENSAJE = 1; ! Tipos de pausa: Constant PAUSA_NORMAL = 0; Constant SIN_PAUSA = 1; Constant ESPERAR_TECLA = 2; Constant PAUSA_DOBLE = 3; ! Tipos de letra: Constant LETRA_NORMAL = $$00001; Constant LETRA_NEGRITA = $$00010; Constant LETRA_CURSIVA = $$00100; Constant LETRA_FIJA = $$01000; Constant LETRA_INVERSA = $$10000; class Escritura class Vector private sonido 0, volumen 0, with hazPausaLetra [; if ( self.pausaLetra > -1 ) { EsperarTecla(0, self.pausaLetra); } ], hazPausaMensaje [; if ( self.pausaMensaje > -1 ) { EsperarTecla(0, self.pausaMensaje); } ], hazPausaDobleMensaje [; if ( self.pausaMensaje > -1 ) { EsperarTecla(0, self.pausaMensaje * 2); } ], pausaLetra 1, pausaMensaje 150, visualiza [ n p lon tipo_mensaje tipo_letra tipo_pausa; escr_buffer_lib-->0 = MAX_TAM_BUFFER - ESCR_PRIMERA_LETRA; ! Para cada cadena a visualizar for (n = 0 : n < self.longitud() : n++) { ! Para cada una de las cadenas ! Convertirlas a vector lon = PrintAnyToArray(escr_buffer_lib + WORDSIZE, MAX_TAM_BUFFER, (self.elemento(n))); ! lon = (self.elemento(n)).print_to_array(escr_buffer_lib); tipo_mensaje = self.elemento(n + 1); tipo_letra = self.elemento(n + 2); tipo_pausa = self.elemento(n + 3); if (tipo_letra & LETRA_NORMAL) style roman; if (tipo_letra & LETRA_NEGRITA) style bold; if (tipo_letra & LETRA_CURSIVA) style underline; if (tipo_letra & LETRA_FIJA) style fixed; if (tipo_letra & LETRA_INVERSA) style reverse; if (tipo_mensaje == POR_MENSAJE) { print (string) self.elemento(n); } else { ! Visualizar las letras una a una for (p = ESCR_PRIMERA_LETRA : p < (lon + ESCR_PRIMERA_LETRA) : p++) { print (char) escr_buffer_lib->p; #ifdef TARGET_GLULX; ! Tocar un sonido, esperar a pulsar una tecla o que pase un tiempo if ( self.sonido ~= 0 ) { EfectosSonoros.ActivarEfecto(Teletipo_ogg, 1, CANAL_COMPUTADORA); } self.hazPausaLetra(); #endif; #ifdef TARGET_ZCODE; self.hazPausaLetra(); #endif; } } switch (tipo_pausa) { ESPERAR_TECLA: EsperarTecla(); PAUSA_NORMAL: self.hazPausaMensaje(); PAUSA_DOBLE: self.hazPausaDobleMensaje(); } style roman; n = n + 3; } ]; #endif;
[ [ [ 1, 115 ] ] ]
da6498b977f6fe8f87d36a1a4bb6cb7721bd734a
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qprintpreviewwidget.h
7b849a0d85f2e959ba5e2f00643dfb0318f798cb
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,976
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPRINTPREVIEWWIDGET_H #define QPRINTPREVIEWWIDGET_H #include <QtGui/qwidget.h> #include <QtGui/qprinter.h> #ifndef QT_NO_PRINTPREVIEWWIDGET QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) class QPrintPreviewWidgetPrivate; class Q_GUI_EXPORT QPrintPreviewWidget : public QWidget { Q_OBJECT Q_DECLARE_PRIVATE(QPrintPreviewWidget) public: enum ViewMode { SinglePageView, FacingPagesView, AllPagesView }; enum ZoomMode { CustomZoom, FitToWidth, FitInView }; explicit QPrintPreviewWidget(QPrinter *printer, QWidget *parent = 0, Qt::WindowFlags flags = 0); explicit QPrintPreviewWidget(QWidget *parent = 0, Qt::WindowFlags flags = 0); ~QPrintPreviewWidget(); qreal zoomFactor() const; QPrinter::Orientation orientation() const; ViewMode viewMode() const; ZoomMode zoomMode() const; int currentPage() const; int numPages() const; void setVisible(bool visible); public Q_SLOTS: void print(); void zoomIn(qreal zoom = 1.1); void zoomOut(qreal zoom = 1.1); void setZoomFactor(qreal zoomFactor); void setOrientation(QPrinter::Orientation orientation); void setViewMode(ViewMode viewMode); void setZoomMode(ZoomMode zoomMode); void setCurrentPage(int pageNumber); void fitToWidth(); void fitInView(); void setLandscapeOrientation(); void setPortraitOrientation(); void setSinglePageViewMode(); void setFacingPagesViewMode(); void setAllPagesViewMode(); void updatePreview(); Q_SIGNALS: void paintRequested(QPrinter *printer); void previewChanged(); private: QPrintPreviewWidgetPrivate *d_ptr; Q_PRIVATE_SLOT(d_func(), void _q_fit()) Q_PRIVATE_SLOT(d_func(), void _q_updateCurrentPage()) }; QT_END_NAMESPACE QT_END_HEADER #endif // QT_NO_PRINTPREVIEWWIDGET #endif // QPRINTPREVIEWWIDGET_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 124 ] ] ]
6d22e0d8a632fc45f12bbe6f3159bbe450a2419c
40e58042e635ea2a61a6216dc3e143fd3e14709c
/chopshop11/SonarTask.h
ea8f64bb3a7b770b2caea2b875fe438cd85c3bff
[]
no_license
chopshop-166/frc-2011
005bb7f0d02050a19bdb2eb33af145d5d2916a4d
7ef98f84e544a17855197f491fc9f80247698dd3
refs/heads/master
2016-09-05T10:59:54.976527
2011-10-20T22:50:17
2011-10-20T22:50:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,387
h
/******************************************************************************* * Project : Chopshop11 * File Name : SonarTask.h * Owner : Software Group (FIRST Chopshop Team 166) * File Description : Task to get front and side sonar distances *******************************************************************************/ /*----------------------------------------------------------------------------*/ /* Copyright (c) MHS Chopshop Team 166, 2011. All Rights Reserved. */ /*----------------------------------------------------------------------------*/ #pragma once #include "WPILib.h" #include "Robot.h" // // This constant defines how often we want this task to run in the form // of miliseconds. Max allowed time is 999 miliseconds. #define SONAR_CYCLE_TIME (20) // 20ms #define AVERAGESIZE (100) //Store 10 values #define SONARINPERVOLT (81.0) //Number of inches per 1 volt of change class SonarTask : public Team166Task { public: // task constructor SonarTask(void); // task destructor virtual ~SonarTask(void); // Main function of the task virtual int Main(int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10); private: Proxy *proxy; // Handle to proxy Robot *lHandle; // Local handle AnalogChannel SonarCenter, SonarLeft, SonarRight; };
[ "[email protected]", "devnull@localhost", "[email protected]" ]
[ [ [ 1, 2 ], [ 4, 7 ], [ 9, 18 ], [ 20, 21 ], [ 23, 29 ], [ 31, 38 ], [ 43, 43 ] ], [ [ 3, 3 ] ], [ [ 8, 8 ], [ 19, 19 ], [ 22, 22 ], [ 30, 30 ], [ 39, 42 ] ] ]
7923a1a9ec8c0ae906b4d68f1be9815a7c534768
9d6d89a97c85abbfce7e2533d133816480ba8e11
/src/Engine/EventEngine/EventEngine.h
a92485debada5c3241a18e499da34fda3af9a09b
[]
no_license
polycraft/Bomberman-like-reseau
1963b79b9cf5d99f1846a7b60507977ba544c680
27361a47bd1aa4ffea972c85b3407c3c97fe6b8e
refs/heads/master
2020-05-16T22:36:22.182021
2011-06-09T07:37:01
2011-06-09T07:37:01
1,564,502
1
2
null
null
null
null
UTF-8
C++
false
false
1,042
h
#ifndef EVENTENGINE_H #define EVENTENGINE_H #include <vector> #include <map> #include <SDL/SDL.h> #include "IEventListener.h" using namespace std; namespace Engine { class EventEngine { public: EventEngine(); virtual ~EventEngine(); /** Met à jours les evenements **/ bool update(); /** Appel les écouteurs d'evenements **/ void callListener(); /** Ajoute un écouteur **/ void addListener(IEventListener *listener); /** Retire un écouteur **/ void removeListener(IEventListener *listener); private: /** Tableau des écouteurs **/ vector<IEventListener*> listener; /** Status des événements **/ stateEvent event; }; } #endif // EVENTENGINE_H
[ [ [ 1, 1 ], [ 10, 11 ], [ 14, 17 ], [ 23, 23 ], [ 33, 38 ], [ 48, 51 ] ], [ [ 2, 9 ], [ 12, 13 ], [ 18, 22 ], [ 24, 32 ], [ 39, 47 ] ] ]
855fbd37c5cc66eee753613493577b3c8db46b3c
daef491056b6a9e227eef3e3b820e7ee7b0af6b6
/Tags/0.1.4/code/lib/platform/ut_input.cpp
ccd21aac20b03249e91f4c533267ab4caf533494
[ "BSD-3-Clause" ]
permissive
BackupTheBerlios/gut-svn
de9952b8b3e62cedbcfeb7ccba0b4d267771dd95
0981d3b37ccfc1ff36cd79000f6c6be481ea4546
refs/heads/master
2021-03-12T22:40:32.685049
2006-07-07T02:18:38
2006-07-07T02:18:38
40,725,529
0
0
null
null
null
null
UTF-8
C++
false
false
4,758
cpp
/********************************************************************** * GameGut - ut_input.cpp * Copyright (c) 1999-2005 Jason Perkins. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the BSD-style license that is * included with this library in the file LICENSE.txt. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * files LICENSE.txt for more details. **********************************************************************/ #include "core/core.h" #include "platform/platform.h" /* Keep track of the state of every object on every device */ struct MyInputDevice { int type; int* buttons; int numButtons; }; /* Lists of all input devices connected to the system */ static utxArray<MyInputDevice*> my_keyboards; static utxArray<MyInputDevice*> my_mice; static utxArray<MyInputDevice*> my_controllers; /**************************************************************************** * Functions to query device states ****************************************************************************/ int utNumControllers() { return my_controllers.size(); } int utNumKeyboards() { return my_keyboards.size(); } int utNumMice() { return my_mice.size(); } /**************************************************************************** * Called by the platform-specific input system initialization; adds a new * device to the master lists that are managed here. ****************************************************************************/ int utxRegisterInputDevice(int type, int numBtns) { MyInputDevice* device = utALLOCT(MyInputDevice); device->type = type; device->buttons = (int*)utALLOC(sizeof(int) * numBtns); device->numButtons = numBtns; memset(device->buttons, 0, sizeof(int) * numBtns); switch (type) { case UT_DEVICE_KEYBOARD: my_keyboards.push_back(device); break; case UT_DEVICE_MOUSE: my_mice.push_back(device); break; case UT_DEVICE_CONTROLLER: my_controllers.push_back(device); break; } return true; } /**************************************************************************** * Called by the platform-specific input system during shutdown; release * all of the input device objects and the memory associated with them. ****************************************************************************/ void utxReleaseInputDevice(MyInputDevice* device) { utFREE(device->buttons); utFREE(device); } int utxReleaseAllInputDevices() { int i; for (i = 0; i < my_keyboards.size(); ++i) utxReleaseInputDevice(my_keyboards[i]); my_keyboards.clear(); for (i = 0; i < my_mice.size(); ++i) utxReleaseInputDevice(my_mice[i]); my_mice.clear(); for (i = 0; i < my_controllers.size(); ++i) utxReleaseInputDevice(my_controllers[i]); my_controllers.clear(); return true; } /**************************************************************************** * Called by mySetActiveWindow() in ut_window.cpp whenever the active * window has changed. ****************************************************************************/ static utWindow my_window = NULL; static void myReleaseButtons(utxArray<MyInputDevice*>& devices, utEvent* event) { for (int ixDev = 0; ixDev < devices.size(); ++ixDev) { event->arg0 = ixDev; int* buttons = devices[ixDev]->buttons; int count = devices[ixDev]->numButtons; for (int ixBtn = 0; ixBtn < count; ++ixBtn) { if (buttons[ixBtn]) { event->arg1 = ixBtn; utxSendInputEvent(event); } } } } int utxInputFocusChanged(utWindow window) { if (window == NULL) { utEvent event; event.window = my_window; event.when = utGetTimer(); event.arg2 = 0; /* Release any buttons that are marked as down, since I won't be * notified if the user releases them while in the other app */ event.what = UT_EVENT_KEY; myReleaseButtons(my_keyboards, &event); /* Let the platform layer clean up as well */ utxResetInputPlatform(); } my_window = window; return true; } /**************************************************************************** * Called by the platform-specific input system rather than utSendEvent(). * Updates the input device state stored here. ****************************************************************************/ int utxSendInputEvent(utEvent* event) { int* state; switch (event->what) { case UT_EVENT_KEY: state = &(my_keyboards[event->arg0]->buttons[event->arg1]); if (*state == event->arg2) return 1; *state = event->arg2; break; } return utSendEvent(event); }
[ "starkos@5eb1f239-c603-0410-9f17-9cbfe04d0a06" ]
[ [ [ 1, 185 ] ] ]
65d30fd6d8f2ee516b12e16cf672a211e172525f
8bb0a1d6c74f3a17d90c64d9ee40ae5153d15acb
/ cs191-nds-project/splash_screen/CS191_Project/include/Sprites/MarioAnimations/CMarioIdle.h
81301a2db98cc7045fd3e999b21d2511eb37e262
[]
no_license
btuduri/cs191-nds-project
9b12382316c0a59d4e48acd7f40ed55c5c4cde41
146b2218cc53f960a034d053238a4cf111726279
refs/heads/master
2020-03-30T19:13:10.122474
2008-05-19T02:26:19
2008-05-19T02:26:19
32,271,764
0
0
null
null
null
null
UTF-8
C++
false
false
427
h
#ifndef CMARIOIDLE_H_ #define CMARIOIDLE_H_ #pragma once #include "ProjectLib.h" #include "CAnimation.h" //#include "../graphics/mario_idle.h" #include "../graphics/mario_sprites.h" class CMarioIdle : public CAnimation { public: CMarioIdle(); virtual ~CMarioIdle(); void update(CSprite *sprite); void load(CSprite *sprite); private: u16 nextImage; u16 curImage; }; #endif /*CMARIOIDLE_H_*/
[ "kingofcode@67d8362a-e844-0410-8493-f333cf7aaa27" ]
[ [ [ 1, 24 ] ] ]
97c947bbffe83b1c6e5610e952486b529b54cbce
1ef66085a12fa4476f44b7faa6828a08170d9e51
/meshdeformer/3rdparty/assimp/.svn/text-base/NullLogger.h.svn-base
e1f5802d2ad2f4e3c382414db7e1a7d24e579fbb
[]
no_license
porpaew/dreamstuff
73ad03e0308882e68c9c7b5c9f9eded6a4e90bed
f24d5aab1d4fbc87de012a7205b68d63255c0be3
refs/heads/master
2021-01-18T19:26:41.303411
2010-08-21T05:37:54
2010-08-21T05:37:54
40,980,385
0
0
null
null
null
null
UTF-8
C++
false
false
3,317
/* Open Asset Import Library (ASSIMP) ---------------------------------------------------------------------- Copyright (c) 2006-2008, ASSIMP Development Team All rights reserved. Redistribution and use of this software 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 ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. 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. ---------------------------------------------------------------------- */ /** @file NullLogger.h * @brief Dummy logger */ #ifndef INCLUDED_AI_NULLLOGGER_H #define INCLUDED_AI_NULLLOGGER_H #include "Logger.h" namespace Assimp { // --------------------------------------------------------------------------- /** @brief CPP-API: Empty logging implementation. * * Does nothing! Used by default if the application hasn't requested a * custom logger via #DefaultLogger::set() or #DefaultLogger::create(); */ class ASSIMP_API NullLogger : public Logger { public: /** @brief Logs a debug message */ void OnDebug(const char* message) { (void)message; //this avoids compiler warnings } /** @brief Logs an info message */ void OnInfo(const char* message) { (void)message; //this avoids compiler warnings } /** @brief Logs a warning message */ void OnWarn(const char* message) { (void)message; //this avoids compiler warnings } /** @brief Logs an error message */ void OnError(const char* message) { (void)message; //this avoids compiler warnings } /** @brief Detach a still attached stream from logger */ bool attachStream(LogStream *pStream, unsigned int severity) { (void)pStream; (void)severity; //this avoids compiler warnings return false; } /** @brief Detach a still attached stream from logger */ bool detatchStream(LogStream *pStream, unsigned int severity) { (void)pStream; (void)severity; //this avoids compiler warnings return false; } private: }; } #endif // !! AI_NULLLOGGER_H_INCLUDED
[ "lai.jingwen2008@21fd095a-c762-11de-9e96-3193d784f102" ]
[ [ [ 1, 95 ] ] ]
16129e84615c3d39c7f6b894dcfe634fc4c54412
0466568120485fcabdba5aa22a4b0fea13068b8b
/opencv/samples/gpu/cascadeclassifier_nvidia_api.cpp
b33b447fec1513652f6d4ab25865d08ee2419b4c
[]
no_license
coapp-packages/opencv
be25a9aec58d9ac890fc764932ba67914add078d
c78981e0d8f602fde523a82c3a7e2c3fef1f39bc
refs/heads/master
2020-05-17T12:11:25.406742
2011-07-14T17:13:01
2011-07-14T17:13:01
2,048,483
3
0
null
null
null
null
UTF-8
C++
false
false
13,943
cpp
#if _MSC_VER >= 1400 #pragma warning( disable : 4201 4408 4127 4100) #endif #include "cvconfig.h" #include <iostream> #include <iomanip> #include "opencv2/opencv.hpp" #include "opencv2/gpu/gpu.hpp" #ifdef HAVE_CUDA #include "NCVHaarObjectDetection.hpp" #endif using namespace std; using namespace cv; #if !defined(HAVE_CUDA) int main( int argc, const char** argv ) { cout << "Please compile the library with CUDA support" << endl; return -1; } #else const Size2i preferredVideoFrameSize(640, 480); const string wndTitle = "NVIDIA Computer Vision :: Haar Classifiers Cascade"; void matPrint(Mat &img, int lineOffsY, Scalar fontColor, const string &ss) { int fontFace = FONT_HERSHEY_DUPLEX; double fontScale = 0.8; int fontThickness = 2; Size fontSize = cv::getTextSize("T[]", fontFace, fontScale, fontThickness, 0); Point org; org.x = 1; org.y = 3 * fontSize.height * (lineOffsY + 1) / 2; putText(img, ss, org, fontFace, fontScale, CV_RGB(0,0,0), 5*fontThickness/2, 16); putText(img, ss, org, fontFace, fontScale, fontColor, fontThickness, 16); } void displayState(Mat &canvas, bool bHelp, bool bGpu, bool bLargestFace, bool bFilter, double fps) { Scalar fontColorRed = CV_RGB(255,0,0); Scalar fontColorNV = CV_RGB(118,185,0); ostringstream ss; ss << "FPS = " << setprecision(1) << fixed << fps; matPrint(canvas, 0, fontColorRed, ss.str()); ss.str(""); ss << "[" << canvas.cols << "x" << canvas.rows << "], " << (bGpu ? "GPU, " : "CPU, ") << (bLargestFace ? "OneFace, " : "MultiFace, ") << (bFilter ? "Filter:ON" : "Filter:OFF"); matPrint(canvas, 1, fontColorRed, ss.str()); if (bHelp) { matPrint(canvas, 2, fontColorNV, "Space - switch GPU / CPU"); matPrint(canvas, 3, fontColorNV, "M - switch OneFace / MultiFace"); matPrint(canvas, 4, fontColorNV, "F - toggle rectangles Filter"); matPrint(canvas, 5, fontColorNV, "H - toggle hotkeys help"); } else { matPrint(canvas, 2, fontColorNV, "H - toggle hotkeys help"); } } NCVStatus process(Mat *srcdst, Ncv32u width, Ncv32u height, NcvBool bFilterRects, NcvBool bLargestFace, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &d_haarStages, NCVVector<HaarClassifierNode128> &d_haarNodes, NCVVector<HaarFeature64> &d_haarFeatures, NCVVector<HaarStage64> &h_haarStages, INCVMemAllocator &gpuAllocator, INCVMemAllocator &cpuAllocator, cudaDeviceProp &devProp) { ncvAssertReturn(!((srcdst == NULL) ^ gpuAllocator.isCounting()), NCV_NULL_PTR); NCVStatus ncvStat; NCV_SET_SKIP_COND(gpuAllocator.isCounting()); NCVMatrixAlloc<Ncv8u> d_src(gpuAllocator, width, height); ncvAssertReturn(d_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv8u> h_src(cpuAllocator, width, height); ncvAssertReturn(h_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<NcvRect32u> d_rects(gpuAllocator, 100); ncvAssertReturn(d_rects.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCV_SKIP_COND_BEGIN for (Ncv32u i=0; i<(Ncv32u)srcdst->rows; i++) { memcpy(h_src.ptr() + i * h_src.stride(), srcdst->ptr(i), srcdst->cols); } ncvStat = h_src.copySolid(d_src, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR); NCV_SKIP_COND_END NcvSize32u roi; roi.width = d_src.width(); roi.height = d_src.height(); Ncv32u numDetections; ncvStat = ncvDetectObjectsMultiScale_device( d_src, roi, d_rects, numDetections, haar, h_haarStages, d_haarStages, d_haarNodes, d_haarFeatures, haar.ClassifierSize, (bFilterRects || bLargestFace) ? 4 : 0, 1.2f, 1, (bLargestFace ? NCVPipeObjDet_FindLargestObject : 0) | NCVPipeObjDet_VisualizeInPlace, gpuAllocator, cpuAllocator, devProp, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR); NCV_SKIP_COND_BEGIN ncvStat = d_src.copySolid(h_src, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR); for (Ncv32u i=0; i<(Ncv32u)srcdst->rows; i++) { memcpy(srcdst->ptr(i), h_src.ptr() + i * h_src.stride(), srcdst->cols); } NCV_SKIP_COND_END return NCV_SUCCESS; } int main(int argc, const char** argv) { cout << "OpenCV / NVIDIA Computer Vision" << endl; cout << "Face Detection in video and live feed" << endl; cout << "Syntax: exename <cascade_file> <image_or_video_or_cameraid>" << endl; cout << "=========================================" << endl; ncvAssertPrintReturn(cv::gpu::getCudaEnabledDeviceCount() != 0, "No GPU found or the library is compiled without GPU support", -1); ncvAssertPrintReturn(argc == 3, "Invalid number of arguments", -1); string cascadeName = argv[1]; string inputName = argv[2]; NCVStatus ncvStat; NcvBool bQuit = false; VideoCapture capture; Size2i frameSize; //open content source Mat image = imread(inputName); Mat frame; if (!image.empty()) { frameSize.width = image.cols; frameSize.height = image.rows; } else { if (!capture.open(inputName)) { int camid = -1; istringstream ss(inputName); int x = 0; ss >> x; ncvAssertPrintReturn(capture.open(camid) != 0, "Can't open source", -1); } capture >> frame; ncvAssertPrintReturn(!frame.empty(), "Empty video source", -1); frameSize.width = frame.cols; frameSize.height = frame.rows; } NcvBool bUseGPU = true; NcvBool bLargestObject = false; NcvBool bFilterRects = true; NcvBool bHelpScreen = false; CascadeClassifier classifierOpenCV; ncvAssertPrintReturn(classifierOpenCV.load(cascadeName) != 0, "Error (in OpenCV) opening classifier", -1); int devId; ncvAssertCUDAReturn(cudaGetDevice(&devId), -1); cudaDeviceProp devProp; ncvAssertCUDAReturn(cudaGetDeviceProperties(&devProp, devId), -1); cout << "Using GPU: " << devId << "(" << devProp.name << "), arch=" << devProp.major << "." << devProp.minor << endl; //============================================================================== // // Load the classifier from file (assuming its size is about 1 mb) // using a simple allocator // //============================================================================== NCVMemNativeAllocator gpuCascadeAllocator(NCVMemoryTypeDevice, devProp.textureAlignment); ncvAssertPrintReturn(gpuCascadeAllocator.isInitialized(), "Error creating cascade GPU allocator", -1); NCVMemNativeAllocator cpuCascadeAllocator(NCVMemoryTypeHostPinned, devProp.textureAlignment); ncvAssertPrintReturn(cpuCascadeAllocator.isInitialized(), "Error creating cascade CPU allocator", -1); Ncv32u haarNumStages, haarNumNodes, haarNumFeatures; ncvStat = ncvHaarGetClassifierSize(cascadeName, haarNumStages, haarNumNodes, haarNumFeatures); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error reading classifier size (check the file)", -1); NCVVectorAlloc<HaarStage64> h_haarStages(cpuCascadeAllocator, haarNumStages); ncvAssertPrintReturn(h_haarStages.isMemAllocated(), "Error in cascade CPU allocator", -1); NCVVectorAlloc<HaarClassifierNode128> h_haarNodes(cpuCascadeAllocator, haarNumNodes); ncvAssertPrintReturn(h_haarNodes.isMemAllocated(), "Error in cascade CPU allocator", -1); NCVVectorAlloc<HaarFeature64> h_haarFeatures(cpuCascadeAllocator, haarNumFeatures); ncvAssertPrintReturn(h_haarFeatures.isMemAllocated(), "Error in cascade CPU allocator", -1); HaarClassifierCascadeDescriptor haar; ncvStat = ncvHaarLoadFromFile_host(cascadeName, haar, h_haarStages, h_haarNodes, h_haarFeatures); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error loading classifier", -1); NCVVectorAlloc<HaarStage64> d_haarStages(gpuCascadeAllocator, haarNumStages); ncvAssertPrintReturn(d_haarStages.isMemAllocated(), "Error in cascade GPU allocator", -1); NCVVectorAlloc<HaarClassifierNode128> d_haarNodes(gpuCascadeAllocator, haarNumNodes); ncvAssertPrintReturn(d_haarNodes.isMemAllocated(), "Error in cascade GPU allocator", -1); NCVVectorAlloc<HaarFeature64> d_haarFeatures(gpuCascadeAllocator, haarNumFeatures); ncvAssertPrintReturn(d_haarFeatures.isMemAllocated(), "Error in cascade GPU allocator", -1); ncvStat = h_haarStages.copySolid(d_haarStages, 0); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1); ncvStat = h_haarNodes.copySolid(d_haarNodes, 0); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1); ncvStat = h_haarFeatures.copySolid(d_haarFeatures, 0); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1); //============================================================================== // // Calculate memory requirements and create real allocators // //============================================================================== NCVMemStackAllocator gpuCounter(devProp.textureAlignment); ncvAssertPrintReturn(gpuCounter.isInitialized(), "Error creating GPU memory counter", -1); NCVMemStackAllocator cpuCounter(devProp.textureAlignment); ncvAssertPrintReturn(cpuCounter.isInitialized(), "Error creating CPU memory counter", -1); ncvStat = process(NULL, frameSize.width, frameSize.height, false, false, haar, d_haarStages, d_haarNodes, d_haarFeatures, h_haarStages, gpuCounter, cpuCounter, devProp); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error in memory counting pass", -1); NCVMemStackAllocator gpuAllocator(NCVMemoryTypeDevice, gpuCounter.maxSize(), devProp.textureAlignment); ncvAssertPrintReturn(gpuAllocator.isInitialized(), "Error creating GPU memory allocator", -1); NCVMemStackAllocator cpuAllocator(NCVMemoryTypeHostPinned, cpuCounter.maxSize(), devProp.textureAlignment); ncvAssertPrintReturn(cpuAllocator.isInitialized(), "Error creating CPU memory allocator", -1); printf("Initialized for frame size [%dx%d]\n", frameSize.width, frameSize.height); //============================================================================== // // Main processing loop // //============================================================================== namedWindow(wndTitle, 1); Mat gray, frameDisp; do { Mat gray; cvtColor((image.empty() ? frame : image), gray, CV_BGR2GRAY); // // process // NcvSize32u minSize = haar.ClassifierSize; if (bLargestObject) { Ncv32u ratioX = preferredVideoFrameSize.width / minSize.width; Ncv32u ratioY = preferredVideoFrameSize.height / minSize.height; Ncv32u ratioSmallest = min(ratioX, ratioY); ratioSmallest = max((Ncv32u)(ratioSmallest / 2.5f), (Ncv32u)1); minSize.width *= ratioSmallest; minSize.height *= ratioSmallest; } Ncv32f avgTime; NcvTimer timer = ncvStartTimer(); if (bUseGPU) { ncvStat = process(&gray, frameSize.width, frameSize.height, bFilterRects, bLargestObject, haar, d_haarStages, d_haarNodes, d_haarFeatures, h_haarStages, gpuAllocator, cpuAllocator, devProp); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error in memory counting pass", -1); } else { vector<Rect> rectsOpenCV; classifierOpenCV.detectMultiScale( gray, rectsOpenCV, 1.2f, bFilterRects ? 4 : 0, (bLargestObject ? CV_HAAR_FIND_BIGGEST_OBJECT : 0) | CV_HAAR_SCALE_IMAGE, Size(minSize.width, minSize.height)); for (size_t rt = 0; rt < rectsOpenCV.size(); ++rt) rectangle(gray, rectsOpenCV[rt], Scalar(255)); } avgTime = (Ncv32f)ncvEndQueryTimerMs(timer); cvtColor(gray, frameDisp, CV_GRAY2BGR); displayState(frameDisp, bHelpScreen, bUseGPU, bLargestObject, bFilterRects, 1000.0f / avgTime); imshow(wndTitle, frameDisp); //handle input switch (cvWaitKey(3)) { case ' ': bUseGPU = !bUseGPU; break; case 'm': case 'M': bLargestObject = !bLargestObject; break; case 'f': case 'F': bFilterRects = !bFilterRects; break; case 'h': case 'H': bHelpScreen = !bHelpScreen; break; case 27: bQuit = true; break; } // For camera and video file, capture the next image if (capture.isOpened()) { capture >> frame; if (frame.empty()) { break; } } } while (!bQuit); cvDestroyWindow(wndTitle.c_str()); return 0; } #endif //!defined(HAVE_CUDA)
[ "vp153@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08", "anatoly@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08", "anton@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08", "alexeys@73c94f0f-984f-4a5f-82bc-2d8db8d8ee08" ]
[ [ [ 1, 1 ], [ 3, 3 ], [ 8, 9 ] ], [ [ 2, 2 ], [ 4, 5 ], [ 12, 12 ], [ 14, 14 ], [ 16, 18 ], [ 21, 21 ], [ 24, 24 ], [ 26, 27 ], [ 30, 32 ], [ 42, 45 ], [ 54, 54 ], [ 60, 60 ], [ 64, 67 ], [ 71, 71 ], [ 76, 77 ], [ 79, 120 ], [ 122, 144 ], [ 147, 147 ], [ 152, 152 ], [ 155, 155 ], [ 158, 158 ], [ 163, 163 ], [ 168, 168 ], [ 171, 171 ], [ 173, 173 ], [ 177, 177 ], [ 181, 181 ], [ 184, 184 ], [ 187, 187 ], [ 190, 191 ], [ 200, 203 ], [ 206, 219 ], [ 221, 230 ], [ 232, 278 ], [ 281, 284 ], [ 286, 291 ], [ 293, 295 ], [ 298, 304 ], [ 306, 307 ], [ 309, 321 ], [ 324, 333 ], [ 336, 336 ], [ 339, 340 ], [ 346, 346 ], [ 350, 350 ], [ 354, 359 ], [ 369, 375 ] ], [ [ 6, 7 ], [ 15, 15 ], [ 19, 20 ], [ 22, 23 ], [ 25, 25 ], [ 28, 29 ], [ 33, 41 ], [ 46, 53 ], [ 55, 59 ], [ 61, 63 ], [ 68, 70 ], [ 72, 75 ], [ 78, 78 ], [ 121, 121 ], [ 145, 146 ], [ 148, 151 ], [ 153, 154 ], [ 156, 157 ], [ 159, 162 ], [ 164, 167 ], [ 169, 170 ], [ 172, 172 ], [ 174, 176 ], [ 178, 180 ], [ 182, 183 ], [ 185, 186 ], [ 188, 189 ], [ 192, 199 ], [ 204, 205 ], [ 220, 220 ], [ 231, 231 ], [ 279, 280 ], [ 285, 285 ], [ 292, 292 ], [ 296, 297 ], [ 305, 305 ], [ 308, 308 ], [ 322, 323 ], [ 334, 335 ], [ 337, 337 ], [ 341, 345 ], [ 347, 349 ], [ 351, 353 ], [ 360, 368 ], [ 376, 376 ] ], [ [ 10, 11 ], [ 13, 13 ], [ 338, 338 ] ] ]
0690b7c628db25455755e76989d428ed85988d47
9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab
/tests/jrtp/Sender/Sender.h
2df901c1369f47e185d7e15c799c6132037a7296
[]
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
1,324
h
// Sender.h : main header file for the SENDER application // #if !defined(AFX_SENDER_H__A4DDF36E_C9E3_4A38_B541_3B8918A99518__INCLUDED_) #define AFX_SENDER_H__A4DDF36E_C9E3_4A38_B541_3B8918A99518__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 ///////////////////////////////////////////////////////////////////////////// // CSenderApp: // See Sender.cpp for the implementation of this class // class CSenderApp : public CWinApp { public: CSenderApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSenderApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CSenderApp) // 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_SENDER_H__A4DDF36E_C9E3_4A38_B541_3B8918A99518__INCLUDED_)
[ "yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd" ]
[ [ [ 1, 49 ] ] ]
a1fe852748f042f5c42d1b614ecf6bc47eea894a
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/CUuenc.cpp
9ad1eb093fd1984211a84a7c06debff5001a666b
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
5,492
cpp
/* CUuenc.cpp Classe per la codifica/decodifica in formato UUENC (CRT). Luca Piergentili, 21/11/96 [email protected] */ #include "env.h" #include "pragma.h" #pragma warning (disable:4135) // conversione tipi #pragma warning (disable:4244) // conversione tipi #include "macro.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "CUuenc.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT //#define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /* uuENC() */ static unsigned char uuENC(unsigned char outbyte) { static const char UUEncodeTable[] = { "`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" }; return(UUEncodeTable[(outbyte & 0x3f)]); } /* uuDEC() */ static unsigned char uuDEC(unsigned char inbyte) { return((inbyte - ' ') & 0x3f); } /* Encode() Codifica in UUENC il file di input nel file di output. Restituisce 0 per conversione effettuata, -1 se non puo' aprire il file di input, -2 se non puo' aprire il file di output. */ int CUuenc::Encode(const char *lpcszInputFileName,const char *lpcszOutputFileName) { int nNumRead; int nCurPos; unsigned char cCurByte; unsigned char szCurLine[64]; unsigned char szEncodedLine[512]; unsigned char* pPtrEncodedLine = szEncodedLine; FILE* fpDecodedFile; FILE* fpEncodedFile; if((fpDecodedFile = fopen(lpcszInputFileName,"rb"))==(FILE*)NULL) return(-1); if((fpEncodedFile = fopen(lpcszOutputFileName,"wb"))==(FILE*)NULL) { fclose(fpDecodedFile); return(-2); } while(!feof(fpDecodedFile)) { memset(szCurLine,'\0',sizeof(szCurLine)); memset(szEncodedLine,'\0',sizeof(szEncodedLine)); pPtrEncodedLine = szEncodedLine; nNumRead = 0; while(nNumRead < 45 && !feof(fpDecodedFile)) { cCurByte = fgetc(fpDecodedFile); nNumRead++; szCurLine[nNumRead] = cCurByte; } *pPtrEncodedLine++ = uuENC((char)nNumRead); nCurPos = 1; while(nCurPos <= (nNumRead-2)) { cCurByte = (szCurLine[nCurPos] >> 2); *pPtrEncodedLine++ = uuENC(cCurByte); cCurByte = (szCurLine[nCurPos] << 4) | (szCurLine[nCurPos+1] >> 4); *pPtrEncodedLine++ = uuENC(cCurByte); cCurByte = (szCurLine[nCurPos+1] << 2) | (szCurLine[nCurPos+2] >> 6); *pPtrEncodedLine++ = uuENC(cCurByte); cCurByte = (szCurLine[nCurPos+2] & 0x3f); *pPtrEncodedLine++ = uuENC(cCurByte); nCurPos += 3; } if(nCurPos < nNumRead) { cCurByte = (szCurLine[nCurPos] >> 2); *pPtrEncodedLine++ = uuENC(cCurByte); if(nCurPos==(nNumRead-1)) { cCurByte = ((szCurLine[nCurPos] << 4) & 0x30); *pPtrEncodedLine++ = uuENC(cCurByte); } else { cCurByte = (((szCurLine[nCurPos] << 4) & 0x30) | ((szCurLine[nCurPos+1] >> 4) & 0x0f)); *pPtrEncodedLine++ = uuENC(cCurByte); cCurByte = ((szCurLine[nCurPos+1] << 2) & 0x3c); } *pPtrEncodedLine++ = uuENC(cCurByte); } fprintf(fpEncodedFile,"%s\r\n",szEncodedLine); } fclose(fpEncodedFile); fclose(fpDecodedFile); return(0); } /* Decode() Decodifica il file di input nel file di output. Restituisce 0 per conversione effettuata, -1 se non puo' aprire il file di input, -2 se non puo' aprire il file di output. */ int CUuenc::Decode(const char *lpcszInputFileName,const char *lpcszOutputFileName) { int NumChars; int nCurPos; char szCurLine[64]; char cCurChar; FILE* fpEncodedFile; FILE* fpDecodedFile; if((fpEncodedFile = fopen(lpcszInputFileName,"rt"))==(FILE*)NULL) return(-1); if((fpDecodedFile = fopen(lpcszOutputFileName,"wb"))==(FILE*)NULL) { fclose(fpEncodedFile); return(-2); } while(!feof(fpEncodedFile)) { if(fgets(szCurLine,sizeof(szCurLine)-1,fpEncodedFile)) { NumChars = (int)uuDEC(szCurLine[0]); if(NumChars < 45) NumChars--; if(NumChars > 0) { nCurPos = 1; while(NumChars > 0) { if(NumChars >= 3) { cCurChar = ((uuDEC(szCurLine[nCurPos]) << 2) | (uuDEC(szCurLine[nCurPos+1]) >> 4)); fputc(cCurChar,fpDecodedFile); cCurChar = ((uuDEC(szCurLine[nCurPos+1]) << 4) | (uuDEC(szCurLine[nCurPos+2]) >> 2)); fputc(cCurChar,fpDecodedFile); cCurChar = ((uuDEC(szCurLine[nCurPos+2]) << 6) | (uuDEC(szCurLine[nCurPos+3]))); fputc(cCurChar,fpDecodedFile); } else { if(NumChars >= 1) { cCurChar = ((uuDEC(szCurLine[nCurPos]) << 2) | (uuDEC(szCurLine[nCurPos+1]) >> 4)); fputc(cCurChar,fpDecodedFile); } if(NumChars >= 2) { cCurChar = ((uuDEC(szCurLine[nCurPos+1]) << 4) | (uuDEC(szCurLine[nCurPos+2]) >> 2)); fputc(cCurChar,fpDecodedFile); } } NumChars -= 3; nCurPos += 4; } } } } fclose(fpEncodedFile); fclose(fpDecodedFile); return(0); } #pragma warning (default:4135) // conversione tipi #pragma warning (default:4244) // conversione tipi
[ [ [ 1, 225 ] ] ]
905625bd28b6052432681bcd0408b43a8b7a51ba
f6a8ffe1612a9a39fc1daa4e7849cad56ec351f0
/uebung1/uebung1/ImageLoader.cpp
e1079b89b6f991571837941be862a38741cb8a1a
[]
no_license
comebackfly/c-plusplus-programming
03e097ec5b85a4bf1d8fdd47041a82d7b6ca0753
d9b2fb3caa60459fe459cacc5347ccc533b4b1ec
refs/heads/master
2021-01-01T18:12:09.667814
2011-07-18T22:30:31
2011-07-18T22:30:31
35,753,632
0
0
null
null
null
null
UTF-8
C++
false
false
685
cpp
#include "StdAfx.h" #include "ImageLoader.h" #include "ImageObject.h" #include <string> #include <iostream> ImageObject ImageLoader::loadImage(int w, int h, int bpp, std::string path){ const char* fileName = path.c_str(); unsigned char *pix = (unsigned char *)htwOpenImage( &fileName, &w, &h, &bpp ); ImageObject image*; if( !pix ){ // Bild konnte nicht geladen werden }else if( bpp==1 ){ // Graustufenbild in eigene Struktur kopieren }else if( bpp==3 ){ // Farbbild in eigene Struktur kopieren std::cout << "in :" << std::endl; image = new ImageObject(pix, w, h, bpp); } //Destruktor htwDeleteImage( pix ); return image; }
[ "[email protected]@5f9f56c3-fb77-04ef-e3c5-e71eb3e36737" ]
[ [ [ 1, 28 ] ] ]
625c82b379f5652e406c73ab673a65272e3bcd46
5e61787e7adba6ed1c2b5e40d38098ebdf9bdee8
/sans/models/c_models/CCoreFourShellModel.cpp
071b066fa53af4a04ce8fa1973fb6ec7733faf23
[]
no_license
mcvine/sansmodels
4dcba43d18c930488b0e69e8afb04139e89e7b21
618928810ee7ae58ec35bbb839eba2a0117c4611
refs/heads/master
2021-01-22T13:12:22.721492
2011-09-30T14:01:06
2011-09-30T14:01:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,494
cpp
/** This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. If you use DANSE applications to do scientific research that leads to publication, we ask that you acknowledge the use of the software with the following sentence: "This work benefited from DANSE software developed under NSF award DMR-0520547." copyright 2008, University of Tennessee */ /** CCoreFourShellModel * * C extension * * WARNING: THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY * DO NOT MODIFY THIS FILE, MODIFY corefourshell.h * AND RE-RUN THE GENERATOR SCRIPT * */ #define NO_IMPORT_ARRAY #define PY_ARRAY_UNIQUE_SYMBOL PyArray_API_sans extern "C" { #include <Python.h> #include <arrayobject.h> #include "structmember.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "corefourshell.h" } #include "models.hh" #include "dispersion_visitor.hh" /// Error object for raised exceptions static PyObject * CCoreFourShellModelError = NULL; // Class definition typedef struct { PyObject_HEAD /// Parameters PyObject * params; /// Dispersion parameters PyObject * dispersion; /// Underlying model object CoreFourShellModel * model; /// Log for unit testing PyObject * log; } CCoreFourShellModel; static void CCoreFourShellModel_dealloc(CCoreFourShellModel* self) { Py_DECREF(self->params); Py_DECREF(self->dispersion); Py_DECREF(self->log); delete self->model; self->ob_type->tp_free((PyObject*)self); } static PyObject * CCoreFourShellModel_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { CCoreFourShellModel *self; self = (CCoreFourShellModel *)type->tp_alloc(type, 0); return (PyObject *)self; } static int CCoreFourShellModel_init(CCoreFourShellModel *self, PyObject *args, PyObject *kwds) { if (self != NULL) { // Create parameters self->params = PyDict_New(); self->dispersion = PyDict_New(); self->model = new CoreFourShellModel(); // Initialize parameter dictionary PyDict_SetItemString(self->params,"thick_shell4",Py_BuildValue("d",10.000000000000)); PyDict_SetItemString(self->params,"sld_shell4",Py_BuildValue("d",0.000004000000)); PyDict_SetItemString(self->params,"scale",Py_BuildValue("d",1.000000000000)); PyDict_SetItemString(self->params,"sld_shell2",Py_BuildValue("d",0.000002000000)); PyDict_SetItemString(self->params,"thick_shell1",Py_BuildValue("d",10.000000000000)); PyDict_SetItemString(self->params,"thick_shell2",Py_BuildValue("d",10.000000000000)); PyDict_SetItemString(self->params,"sld_shell1",Py_BuildValue("d",0.000001000000)); PyDict_SetItemString(self->params,"thick_shell3",Py_BuildValue("d",10.000000000000)); PyDict_SetItemString(self->params,"sld_core0",Py_BuildValue("d",0.000006400000)); PyDict_SetItemString(self->params,"background",Py_BuildValue("d",0.001000000000)); PyDict_SetItemString(self->params,"rad_core0",Py_BuildValue("d",60.000000000000)); PyDict_SetItemString(self->params,"sld_solv",Py_BuildValue("d",0.000006400000)); PyDict_SetItemString(self->params,"sld_shell3",Py_BuildValue("d",0.000003000000)); // Initialize dispersion / averaging parameter dict DispersionVisitor* visitor = new DispersionVisitor(); PyObject * disp_dict; disp_dict = PyDict_New(); self->model->rad_core0.dispersion->accept_as_source(visitor, self->model->rad_core0.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "rad_core0", disp_dict); disp_dict = PyDict_New(); self->model->thick_shell1.dispersion->accept_as_source(visitor, self->model->thick_shell1.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "thick_shell1", disp_dict); disp_dict = PyDict_New(); self->model->thick_shell2.dispersion->accept_as_source(visitor, self->model->thick_shell2.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "thick_shell2", disp_dict); disp_dict = PyDict_New(); self->model->thick_shell3.dispersion->accept_as_source(visitor, self->model->thick_shell3.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "thick_shell3", disp_dict); disp_dict = PyDict_New(); self->model->thick_shell4.dispersion->accept_as_source(visitor, self->model->thick_shell4.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "thick_shell4", disp_dict); // Create empty log self->log = PyDict_New(); } return 0; } static PyMemberDef CCoreFourShellModel_members[] = { {"params", T_OBJECT, offsetof(CCoreFourShellModel, params), 0, "Parameters"}, {"dispersion", T_OBJECT, offsetof(CCoreFourShellModel, dispersion), 0, "Dispersion parameters"}, {"log", T_OBJECT, offsetof(CCoreFourShellModel, log), 0, "Log"}, {NULL} /* Sentinel */ }; /** Read double from PyObject @param p PyObject @return double */ double CCoreFourShellModel_readDouble(PyObject *p) { if (PyFloat_Check(p)==1) { return (double)(((PyFloatObject *)(p))->ob_fval); } else if (PyInt_Check(p)==1) { return (double)(((PyIntObject *)(p))->ob_ival); } else if (PyLong_Check(p)==1) { return (double)PyLong_AsLong(p); } else { return 0.0; } } /** * Function to call to evaluate model * @param args: input numpy array q[] * @return: numpy array object */ static PyObject *evaluateOneDim(CoreFourShellModel* model, PyArrayObject *q){ PyArrayObject *result; // Check validity of array q , q must be of dimension 1, an array of double if (q->nd != 1 || q->descr->type_num != PyArray_DOUBLE) { //const char * message= "Invalid array: q->nd=%d,type_num=%d\n",q->nd,q->descr->type_num; //PyErr_SetString(PyExc_ValueError , message); return NULL; } result = (PyArrayObject *)PyArray_FromDims(q->nd, (int *)(q->dimensions), PyArray_DOUBLE); if (result == NULL) { const char * message= "Could not create result "; PyErr_SetString(PyExc_RuntimeError , message); return NULL; } for (int i = 0; i < q->dimensions[0]; i++){ double q_value = *(double *)(q->data + i*q->strides[0]); double *result_value = (double *)(result->data + i*result->strides[0]); *result_value =(*model)(q_value); } return PyArray_Return(result); } /** * Function to call to evaluate model * @param args: input numpy array [x[],y[]] * @return: numpy array object */ static PyObject * evaluateTwoDimXY( CoreFourShellModel* model, PyArrayObject *x, PyArrayObject *y) { PyArrayObject *result; int i,j, x_len, y_len, dims[1]; //check validity of input vectors if (x->nd != 1 || x->descr->type_num != PyArray_DOUBLE || y->nd != 1 || y->descr->type_num != PyArray_DOUBLE || y->dimensions[0] != x->dimensions[0]){ const char * message= "evaluateTwoDimXY expect 2 numpy arrays"; PyErr_SetString(PyExc_ValueError , message); return NULL; } if (PyArray_Check(x) && PyArray_Check(y)) { x_len = dims[0]= x->dimensions[0]; y_len = dims[0]= y->dimensions[0]; // Make a new double matrix of same dims result=(PyArrayObject *) PyArray_FromDims(1,dims,NPY_DOUBLE); if (result == NULL){ const char * message= "Could not create result "; PyErr_SetString(PyExc_RuntimeError , message); return NULL; } /* Do the calculation. */ for ( i=0; i< x_len; i++) { double x_value = *(double *)(x->data + i*x->strides[0]); double y_value = *(double *)(y->data + i*y->strides[0]); double *result_value = (double *)(result->data + i*result->strides[0]); *result_value = (*model)(x_value, y_value); } return PyArray_Return(result); }else{ PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.evaluateTwoDimXY couldn't run."); return NULL; } } /** * evalDistribution function evaluate a model function with input vector * @param args: input q as vector or [qx, qy] where qx, qy are vectors * */ static PyObject * evalDistribution(CCoreFourShellModel *self, PyObject *args){ PyObject *qx, *qy; PyArrayObject * pars; int npars ,mpars; // Get parameters // Reader parameter dictionary self->model->thick_shell4 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell4") ); self->model->sld_shell4 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell4") ); self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") ); self->model->sld_shell2 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell2") ); self->model->thick_shell1 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell1") ); self->model->thick_shell2 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell2") ); self->model->sld_shell1 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell1") ); self->model->thick_shell3 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell3") ); self->model->sld_core0 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_core0") ); self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") ); self->model->rad_core0 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rad_core0") ); self->model->sld_solv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_solv") ); self->model->sld_shell3 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell3") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "rad_core0"); self->model->rad_core0.dispersion->accept_as_destination(visitor, self->model->rad_core0.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell1"); self->model->thick_shell1.dispersion->accept_as_destination(visitor, self->model->thick_shell1.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell2"); self->model->thick_shell2.dispersion->accept_as_destination(visitor, self->model->thick_shell2.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell3"); self->model->thick_shell3.dispersion->accept_as_destination(visitor, self->model->thick_shell3.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell4"); self->model->thick_shell4.dispersion->accept_as_destination(visitor, self->model->thick_shell4.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.evalDistribution expects a q value."); return NULL; } // Check params if(PyArray_Check(pars)==1) { // Length of list should 1 or 2 npars = pars->nd; if(npars==1) { // input is a numpy array if (PyArray_Check(pars)) { return evaluateOneDim(self->model, (PyArrayObject*)pars); } }else{ PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.evalDistribution expect numpy array of one dimension."); return NULL; } }else if( PyList_Check(pars)==1) { // Length of list should be 2 for I(qx,qy) mpars = PyList_GET_SIZE(pars); if(mpars!=2) { PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.evalDistribution expects a list of dimension 2."); return NULL; } qx = PyList_GET_ITEM(pars,0); qy = PyList_GET_ITEM(pars,1); if (PyArray_Check(qx) && PyArray_Check(qy)) { return evaluateTwoDimXY(self->model, (PyArrayObject*)qx, (PyArrayObject*)qy); }else{ PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.evalDistribution expect 2 numpy arrays in list."); return NULL; } } PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.evalDistribution couln't be run."); return NULL; } /** * Function to call to evaluate model * @param args: input q or [q,phi] * @return: function value */ static PyObject * run(CCoreFourShellModel *self, PyObject *args) { double q_value, phi_value; PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->thick_shell4 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell4") ); self->model->sld_shell4 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell4") ); self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") ); self->model->sld_shell2 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell2") ); self->model->thick_shell1 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell1") ); self->model->thick_shell2 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell2") ); self->model->sld_shell1 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell1") ); self->model->thick_shell3 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell3") ); self->model->sld_core0 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_core0") ); self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") ); self->model->rad_core0 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rad_core0") ); self->model->sld_solv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_solv") ); self->model->sld_shell3 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell3") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "rad_core0"); self->model->rad_core0.dispersion->accept_as_destination(visitor, self->model->rad_core0.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell1"); self->model->thick_shell1.dispersion->accept_as_destination(visitor, self->model->thick_shell1.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell2"); self->model->thick_shell2.dispersion->accept_as_destination(visitor, self->model->thick_shell2.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell3"); self->model->thick_shell3.dispersion->accept_as_destination(visitor, self->model->thick_shell3.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell4"); self->model->thick_shell4.dispersion->accept_as_destination(visitor, self->model->thick_shell4.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.run expects a q value."); return NULL; } // Check params if( PyList_Check(pars)==1) { // Length of list should be 2 for I(q,phi) npars = PyList_GET_SIZE(pars); if(npars!=2) { PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.run expects a double or a list of dimension 2."); return NULL; } // We have a vector q, get the q and phi values at which // to evaluate I(q,phi) q_value = CCoreFourShellModel_readDouble(PyList_GET_ITEM(pars,0)); phi_value = CCoreFourShellModel_readDouble(PyList_GET_ITEM(pars,1)); // Skip zero if (q_value==0) { return Py_BuildValue("d",0.0); } return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value)); } else { // We have a scalar q, we will evaluate I(q) q_value = CCoreFourShellModel_readDouble(pars); return Py_BuildValue("d",(*(self->model))(q_value)); } } /** * Function to call to calculate_ER * @return: effective radius value */ static PyObject * calculate_ER(CCoreFourShellModel *self) { PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->thick_shell4 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell4") ); self->model->sld_shell4 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell4") ); self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") ); self->model->sld_shell2 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell2") ); self->model->thick_shell1 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell1") ); self->model->thick_shell2 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell2") ); self->model->sld_shell1 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell1") ); self->model->thick_shell3 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell3") ); self->model->sld_core0 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_core0") ); self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") ); self->model->rad_core0 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rad_core0") ); self->model->sld_solv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_solv") ); self->model->sld_shell3 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell3") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "rad_core0"); self->model->rad_core0.dispersion->accept_as_destination(visitor, self->model->rad_core0.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell1"); self->model->thick_shell1.dispersion->accept_as_destination(visitor, self->model->thick_shell1.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell2"); self->model->thick_shell2.dispersion->accept_as_destination(visitor, self->model->thick_shell2.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell3"); self->model->thick_shell3.dispersion->accept_as_destination(visitor, self->model->thick_shell3.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell4"); self->model->thick_shell4.dispersion->accept_as_destination(visitor, self->model->thick_shell4.dispersion, disp_dict); return Py_BuildValue("d",(*(self->model)).calculate_ER()); } /** * Function to call to evaluate model in cartesian coordinates * @param args: input q or [qx, qy]] * @return: function value */ static PyObject * runXY(CCoreFourShellModel *self, PyObject *args) { double qx_value, qy_value; PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->thick_shell4 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell4") ); self->model->sld_shell4 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell4") ); self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") ); self->model->sld_shell2 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell2") ); self->model->thick_shell1 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell1") ); self->model->thick_shell2 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell2") ); self->model->sld_shell1 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell1") ); self->model->thick_shell3 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "thick_shell3") ); self->model->sld_core0 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_core0") ); self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") ); self->model->rad_core0 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rad_core0") ); self->model->sld_solv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_solv") ); self->model->sld_shell3 = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sld_shell3") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "rad_core0"); self->model->rad_core0.dispersion->accept_as_destination(visitor, self->model->rad_core0.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell1"); self->model->thick_shell1.dispersion->accept_as_destination(visitor, self->model->thick_shell1.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell2"); self->model->thick_shell2.dispersion->accept_as_destination(visitor, self->model->thick_shell2.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell3"); self->model->thick_shell3.dispersion->accept_as_destination(visitor, self->model->thick_shell3.dispersion, disp_dict); disp_dict = PyDict_GetItemString(self->dispersion, "thick_shell4"); self->model->thick_shell4.dispersion->accept_as_destination(visitor, self->model->thick_shell4.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.run expects a q value."); return NULL; } // Check params if( PyList_Check(pars)==1) { // Length of list should be 2 for I(qx, qy)) npars = PyList_GET_SIZE(pars); if(npars!=2) { PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.run expects a double or a list of dimension 2."); return NULL; } // We have a vector q, get the qx and qy values at which // to evaluate I(qx,qy) qx_value = CCoreFourShellModel_readDouble(PyList_GET_ITEM(pars,0)); qy_value = CCoreFourShellModel_readDouble(PyList_GET_ITEM(pars,1)); return Py_BuildValue("d",(*(self->model))(qx_value,qy_value)); } else { // We have a scalar q, we will evaluate I(q) qx_value = CCoreFourShellModel_readDouble(pars); return Py_BuildValue("d",(*(self->model))(qx_value)); } } static PyObject * reset(CCoreFourShellModel *self, PyObject *args) { return Py_BuildValue("d",0.0); } static PyObject * set_dispersion(CCoreFourShellModel *self, PyObject *args) { PyObject * disp; const char * par_name; if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) { PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.set_dispersion expects a DispersionModel object."); return NULL; } void *temp = PyCObject_AsVoidPtr(disp); DispersionModel * dispersion = static_cast<DispersionModel *>(temp); // Ugliness necessary to go from python to C // TODO: refactor this if (!strcmp(par_name, "rad_core0")) { self->model->rad_core0.dispersion = dispersion; } else if (!strcmp(par_name, "thick_shell1")) { self->model->thick_shell1.dispersion = dispersion; } else if (!strcmp(par_name, "thick_shell2")) { self->model->thick_shell2.dispersion = dispersion; } else if (!strcmp(par_name, "thick_shell3")) { self->model->thick_shell3.dispersion = dispersion; } else if (!strcmp(par_name, "thick_shell4")) { self->model->thick_shell4.dispersion = dispersion; } else { PyErr_SetString(CCoreFourShellModelError, "CCoreFourShellModel.set_dispersion expects a valid parameter name."); return NULL; } DispersionVisitor* visitor = new DispersionVisitor(); PyObject * disp_dict = PyDict_New(); dispersion->accept_as_source(visitor, dispersion, disp_dict); PyDict_SetItemString(self->dispersion, par_name, disp_dict); return Py_BuildValue("i",1); } static PyMethodDef CCoreFourShellModel_methods[] = { {"run", (PyCFunction)run , METH_VARARGS, "Evaluate the model at a given Q or Q, phi"}, {"runXY", (PyCFunction)runXY , METH_VARARGS, "Evaluate the model at a given Q or Qx, Qy"}, {"calculate_ER", (PyCFunction)calculate_ER , METH_VARARGS, "Evaluate the model at a given Q or Q, phi"}, {"evalDistribution", (PyCFunction)evalDistribution , METH_VARARGS, "Evaluate the model at a given Q or Qx, Qy vector "}, {"reset", (PyCFunction)reset , METH_VARARGS, "Reset pair correlation"}, {"set_dispersion", (PyCFunction)set_dispersion , METH_VARARGS, "Set the dispersion model for a given parameter"}, {NULL} }; static PyTypeObject CCoreFourShellModelType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "CCoreFourShellModel", /*tp_name*/ sizeof(CCoreFourShellModel), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)CCoreFourShellModel_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "CCoreFourShellModel objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ CCoreFourShellModel_methods, /* tp_methods */ CCoreFourShellModel_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)CCoreFourShellModel_init, /* tp_init */ 0, /* tp_alloc */ CCoreFourShellModel_new, /* tp_new */ }; //static PyMethodDef module_methods[] = { // {NULL} //}; /** * Function used to add the model class to a module * @param module: module to add the class to */ void addCCoreFourShellModel(PyObject *module) { PyObject *d; if (PyType_Ready(&CCoreFourShellModelType) < 0) return; Py_INCREF(&CCoreFourShellModelType); PyModule_AddObject(module, "CCoreFourShellModel", (PyObject *)&CCoreFourShellModelType); d = PyModule_GetDict(module); CCoreFourShellModelError = PyErr_NewException("CCoreFourShellModel.error", NULL, NULL); PyDict_SetItemString(d, "CCoreFourShellModelError", CCoreFourShellModelError); }
[ [ [ 1, 645 ] ] ]
5b768536b37c2b868d088cd8cbad8229576bec41
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlEdgeKey.inl
d3e371ffdaab0f0a5e09896fdfda61919afca952
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
1,081
inl
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. //---------------------------------------------------------------------------- inline EdgeKey::EdgeKey (int iV0, int iV1) { if ( iV0 < iV1 ) { // v0 is minimum V[0] = iV0; V[1] = iV1; } else { // v1 is minimum V[0] = iV1; V[1] = iV0; } } //---------------------------------------------------------------------------- inline bool EdgeKey::operator< (const EdgeKey& rkKey) const { if ( V[1] < rkKey.V[1] ) return true; if ( V[1] > rkKey.V[1] ) return false; return V[0] < rkKey.V[0]; } //----------------------------------------------------------------------------
[ [ [ 1, 36 ] ] ]
78c4859b1ed66a9ce777871b099973956e6d9db7
ef8e875dbd9e81d84edb53b502b495e25163725c
/litewiz/src/items/item.h
344c38d25e2d92cd8cfdc6948b23f39dcfda874e
[]
no_license
panone/litewiz
22b9d549097727754c9a1e6286c50c5ad8e94f2d
e80ed9f9d845b08c55b687117acb1ed9b6e9a444
refs/heads/master
2021-01-10T19:54:31.146153
2010-10-01T13:29:38
2010-10-01T13:29:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
933
h
/******************************************************************************* *******************************************************************************/ #ifndef ITEM_H #define ITEM_H /******************************************************************************/ #include "file_cluster.h" /******************************************************************************/ class QString; /******************************************************************************* *******************************************************************************/ class Item : public FileCluster { public: Item ( QString const & name, QString const & stem, QList< FileCluster * > const & collection ); }; /******************************************************************************/ #endif /* ITEM_H */
[ [ [ 1, 31 ] ] ]
e5d55fd9b7e4286ebb2a909ac9045ccf5bd9125b
81e051c660949ac0e89d1e9cf286e1ade3eed16a
/quake3ce/code/qcommon/cvar.cpp
da8822c932b121e76dfd344fe00367edbc87cbf0
[]
no_license
crioux/q3ce
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
5e724f55940ac43cb25440a65f9e9e12220c9ada
refs/heads/master
2020-06-04T10:29:48.281238
2008-11-16T15:00:38
2008-11-16T15:00:38
32,103,416
5
0
null
null
null
null
UTF-8
C++
false
false
19,739
cpp
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // cvar.c -- dynamic variable tracking #include"common_pch.h" cvar_t *cvar_vars; cvar_t *cvar_cheats; int cvar_modifiedFlags; #define MAX_CVARS 1024 cvar_t cvar_indexes[MAX_CVARS]; int cvar_numIndexes; #define FILE_HASH_SIZE 256 static cvar_t* cvar_hashTable[FILE_HASH_SIZE]; cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force); /* ================ return a hash value for the filename ================ */ static long generateHashValue( const char *fname ) { int i; long hash; char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower(fname[i]); hash+=(long)(letter)*(i+119); i++; } hash &= (FILE_HASH_SIZE-1); return hash; } /* ============ Cvar_ValidateString ============ */ static qboolean Cvar_ValidateString( const char *s ) { if ( !s ) { return qfalse; } if ( strchr( s, '\\' ) ) { return qfalse; } if ( strchr( s, '\"' ) ) { return qfalse; } if ( strchr( s, ';' ) ) { return qfalse; } return qtrue; } /* ============ Cvar_FindVar ============ */ static cvar_t *Cvar_FindVar( const char *var_name ) { cvar_t *var; long hash; hash = generateHashValue(var_name); for (var=cvar_hashTable[hash] ; var ; var=var->hashNext) { if (!Q_stricmp(var_name, var->name)) { return var; } } return NULL; } /* ============ Cvar_VariableValue ============ */ lfixed Cvar_VariableValue( const char *var_name ) { cvar_t *var; var = Cvar_FindVar (var_name); if (!var) return LFIXED_0; return var->value; } /* ============ Cvar_VariableFixedValue ============ */ gfixed Cvar_VariableFixedValue( const char *var_name ) { cvar_t *var; var = Cvar_FindVar (var_name); if (!var) return GFIXED_0; return MAKE_GFIXED(var->value); } /* ============ Cvar_VariableIntegerValue ============ */ int Cvar_VariableIntegerValue( const char *var_name ) { cvar_t *var; var = Cvar_FindVar (var_name); if (!var) return 0; return var->integer; } /* ============ Cvar_VariableString ============ */ const char *Cvar_VariableString( const char *var_name ) { cvar_t *var; var = Cvar_FindVar (var_name); if (!var) return ""; return var->string; } /* ============ Cvar_VariableStringBuffer ============ */ void Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) { cvar_t *var; var = Cvar_FindVar (var_name); if (!var) { *buffer = 0; } else { Q_strncpyz( buffer, var->string, bufsize ); } } /* ============ Cvar_CommandCompletion ============ */ void Cvar_CommandCompletion( void(*callback)(const char *s) ) { cvar_t *cvar; for ( cvar = cvar_vars ; cvar ; cvar = cvar->next ) { callback( cvar->name ); } } /* ============ Cvar_Get If the variable already exists, the value will not be set unless CVAR_ROM The flags will be or'ed in if the variable exists. ============ */ cvar_t *Cvar_Get( const char *var_name, const char *var_value, int flags ) { cvar_t *var; long hash; if ( !var_name || ! var_value ) { Com_Error( ERR_FATAL, "Cvar_Get: NULL parameter" ); } if ( !Cvar_ValidateString( var_name ) ) { Com_Printf("invalid cvar name string: %s\n", var_name ); var_name = "BADNAME"; } #if 0 // FIXME: values with backslash happen if ( !Cvar_ValidateString( var_value ) ) { Com_Printf("invalid cvar value string: %s\n", var_value ); var_value = "BADVALUE"; } #endif var = Cvar_FindVar (var_name); if ( var ) { // if the C code is now specifying a variable that the user already // set a value for, take the new value as the reset value if ( ( var->flags & CVAR_USER_CREATED ) && !( flags & CVAR_USER_CREATED ) && var_value[0] ) { var->flags &= ~CVAR_USER_CREATED; Z_Free( var->resetString ); var->resetString = CopyString( var_value ); // ZOID--needs to be set so that cvars the game sets as // SERVERINFO get sent to clients cvar_modifiedFlags |= flags; } var->flags |= flags; // only allow one non-empty reset string without a warning if ( !var->resetString[0] ) { // we don't have a reset string yet Z_Free( var->resetString ); var->resetString = CopyString( var_value ); } else if ( var_value[0] && strcmp( var->resetString, var_value ) ) { Com_DPrintf( "Warning: cvar \"%s\" given initial values: \"%s\" and \"%s\"\n", var_name, var->resetString, var_value ); } // if we have a latched string, take that value now if ( var->latchedString ) { char *s; s = var->latchedString; var->latchedString = NULL; // otherwise cvar_set2 would free it Cvar_Set2( var_name, s, qtrue ); Z_Free( s ); } // use a CVAR_SET for rom sets, get won't override #if 0 // CVAR_ROM always overrides if ( flags & CVAR_ROM ) { Cvar_Set2( var_name, var_value, qtrue ); } #endif return var; } // // allocate a new cvar // if ( cvar_numIndexes >= MAX_CVARS ) { Com_Error( ERR_FATAL, "MAX_CVARS" ); } var = &cvar_indexes[cvar_numIndexes]; cvar_numIndexes++; var->name = CopyString (var_name); var->string = CopyString (var_value); var->modified = qtrue; var->modificationCount = 1; var->value = MAKE_LFIXED(atof(var->string)); var->integer = atoi(var->string); var->resetString = CopyString( var_value ); // link the variable in var->next = cvar_vars; cvar_vars = var; var->flags = flags; hash = generateHashValue(var_name); var->hashNext = cvar_hashTable[hash]; cvar_hashTable[hash] = var; return var; } /* ============ Cvar_Set2 ============ */ cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force ) { cvar_t *var; Com_DPrintf( "Cvar_Set2: %s %s\n", var_name, value ); if ( !Cvar_ValidateString( var_name ) ) { Com_Printf("invalid cvar name string: %s\n", var_name ); var_name = "BADNAME"; } #if 0 // FIXME if ( value && !Cvar_ValidateString( value ) ) { Com_Printf("invalid cvar value string: %s\n", value ); var_value = "BADVALUE"; } #endif var = Cvar_FindVar (var_name); if (!var) { if ( !value ) { return NULL; } // create it if ( !force ) { return Cvar_Get( var_name, value, CVAR_USER_CREATED ); } else { return Cvar_Get (var_name, value, 0); } } if (!value ) { value = var->resetString; } if (!strcmp(value,var->string)) { return var; } // note what types of cvars have been modified (userinfo, archive, serverinfo, systeminfo) cvar_modifiedFlags |= var->flags; if (!force) { if (var->flags & CVAR_ROM) { Com_Printf ("%s is read only.\n", var_name); return var; } if (var->flags & CVAR_INIT) { Com_Printf ("%s is write protected.\n", var_name); return var; } if (var->flags & CVAR_LATCH) { if (var->latchedString) { if (strcmp(value, var->latchedString) == 0) return var; Z_Free (var->latchedString); } else { if (strcmp(value, var->string) == 0) return var; } Com_Printf ("%s will be changed upon restarting.\n", var_name); var->latchedString = CopyString(value); var->modified = qtrue; var->modificationCount++; return var; } if ( (var->flags & CVAR_CHEAT) && !cvar_cheats->integer ) { Com_Printf ("%s is cheat protected.\n", var_name); return var; } } else { if (var->latchedString) { Z_Free (var->latchedString); var->latchedString = NULL; } } if (!strcmp(value, var->string)) return var; // not changed var->modified = qtrue; var->modificationCount++; Z_Free (var->string); // free the old value string var->string = CopyString(value); var->value = MAKE_LFIXED(atof(var->string)); var->integer = atoi (var->string); return var; } /* ============ Cvar_Set ============ */ void Cvar_Set( const char *var_name, const char *value) { Cvar_Set2 (var_name, value, qtrue); } /* ============ Cvar_SetLatched ============ */ void Cvar_SetLatched( const char *var_name, const char *value) { Cvar_Set2 (var_name, value, qfalse); } /* ============ Cvar_SetValue ============ */ void Cvar_SetValue( const char *var_name, lfixed value) { char val[32]; if ( value == FIXED_SNAP(value) ) { Com_sprintf (val, sizeof(val), "%i",FIXED_TO_INT(value)); } else { Com_sprintf (val, sizeof(val), "%f",FIXED_TO_DOUBLE(value)); } Cvar_Set (var_name, val); } /* ============ Cvar_SetValue ============ */ void Cvar_SetIntegerValue( const char *var_name, int value) { char val[32]; Com_sprintf (val, sizeof(val), "%i",value); Cvar_Set (var_name, val); } /* ============ Cvar_Reset ============ */ void Cvar_Reset( const char *var_name ) { Cvar_Set2( var_name, NULL, qfalse ); } /* ============ Cvar_SetCheatState Any testing variables will be reset to the safe values ============ */ void Cvar_SetCheatState( void ) { cvar_t *var; // set all default vars to the safe value for ( var = cvar_vars ; var ; var = var->next ) { if ( var->flags & CVAR_CHEAT ) { // the CVAR_LATCHED|CVAR_CHEAT vars might escape the reset here // because of a different var->latchedString if (var->latchedString) { Z_Free(var->latchedString); var->latchedString = NULL; } if (strcmp(var->resetString,var->string)) { Cvar_Set( var->name, var->resetString ); } } } } /* ============ Cvar_Command Handles variable inspection and changing from the console ============ */ qboolean Cvar_Command( void ) { cvar_t *v; // check variables v = Cvar_FindVar (Cmd_Argv(0)); if (!v) { return qfalse; } // perform a variable print or set if ( Cmd_Argc() == 1 ) { Com_Printf ("\"%s\" is:\"%s" S_COLOR_WHITE "\" default:\"%s" S_COLOR_WHITE "\"\n", v->name, v->string, v->resetString ); if ( v->latchedString ) { Com_Printf( "latched: \"%s\"\n", v->latchedString ); } return qtrue; } // set the value if forcing isn't required Cvar_Set2 (v->name, Cmd_Argv(1), qfalse); return qtrue; } /* ============ Cvar_Toggle_f Toggles a cvar for easy single key binding ============ */ void Cvar_Toggle_f( void ) { int v; if ( Cmd_Argc() != 2 ) { Com_Printf ("usage: toggle <variable>\n"); return; } v = Cvar_VariableIntegerValue( Cmd_Argv( 1 ) ); v = !v; Cvar_Set2 (Cmd_Argv(1), va("%i", v), qfalse); } /* ============ Cvar_Set_f Allows setting and defining of arbitrary cvars from console, even if they weren't declared in C code. ============ */ void Cvar_Set_f( void ) { int i, c, l, len; char combined[MAX_STRING_TOKENS]; c = Cmd_Argc(); if ( c < 3 ) { Com_Printf ("usage: set <variable> <value>\n"); return; } combined[0] = 0; l = 0; for ( i = 2 ; i < c ; i++ ) { len = strlen ( Cmd_Argv( i ) + 1 ); if ( l + len >= MAX_STRING_TOKENS - 2 ) { break; } strcat( combined, Cmd_Argv( i ) ); if ( i != c-1 ) { strcat( combined, " " ); } l += len; } Cvar_Set2 (Cmd_Argv(1), combined, qfalse); } /* ============ Cvar_SetU_f As Cvar_Set, but also flags it as userinfo ============ */ void Cvar_SetU_f( void ) { cvar_t *v; if ( Cmd_Argc() != 3 ) { Com_Printf ("usage: setu <variable> <value>\n"); return; } Cvar_Set_f(); v = Cvar_FindVar( Cmd_Argv( 1 ) ); if ( !v ) { return; } v->flags |= CVAR_USERINFO; } /* ============ Cvar_SetS_f As Cvar_Set, but also flags it as userinfo ============ */ void Cvar_SetS_f( void ) { cvar_t *v; if ( Cmd_Argc() != 3 ) { Com_Printf ("usage: sets <variable> <value>\n"); return; } Cvar_Set_f(); v = Cvar_FindVar( Cmd_Argv( 1 ) ); if ( !v ) { return; } v->flags |= CVAR_SERVERINFO; } /* ============ Cvar_SetA_f As Cvar_Set, but also flags it as archived ============ */ void Cvar_SetA_f( void ) { cvar_t *v; if ( Cmd_Argc() != 3 ) { Com_Printf ("usage: seta <variable> <value>\n"); return; } Cvar_Set_f(); v = Cvar_FindVar( Cmd_Argv( 1 ) ); if ( !v ) { return; } v->flags |= CVAR_ARCHIVE; } /* ============ Cvar_Reset_f ============ */ void Cvar_Reset_f( void ) { if ( Cmd_Argc() != 2 ) { Com_Printf ("usage: reset <variable>\n"); return; } Cvar_Reset( Cmd_Argv( 1 ) ); } /* ============ Cvar_WriteVariables Appends lines containing "set variable value" for all variables with the archive flag set to qtrue. ============ */ void Cvar_WriteVariables( fileHandle_t f ) { cvar_t *var; char buffer[1024]; for (var = cvar_vars ; var ; var = var->next) { if( Q_stricmp( var->name, "cl_cdkey" ) == 0 ) { continue; } if( var->flags & CVAR_ARCHIVE ) { // write the latched value, even if it hasn't taken effect yet if ( var->latchedString ) { Com_sprintf (buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->latchedString); } else { Com_sprintf (buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->string); } FS_Printf (f, "%s", buffer); } } } /* ============ Cvar_List_f ============ */ void Cvar_List_f( void ) { cvar_t *var; int i; const char *match; if ( Cmd_Argc() > 1 ) { match = Cmd_Argv( 1 ); } else { match = NULL; } i = 0; for (var = cvar_vars ; var ; var = var->next, i++) { if (match && !Com_Filter(match, var->name, qfalse)) continue; if (var->flags & CVAR_SERVERINFO) { Com_Printf("S"); } else { Com_Printf(" "); } if (var->flags & CVAR_USERINFO) { Com_Printf("U"); } else { Com_Printf(" "); } if (var->flags & CVAR_ROM) { Com_Printf("R"); } else { Com_Printf(" "); } if (var->flags & CVAR_INIT) { Com_Printf("I"); } else { Com_Printf(" "); } if (var->flags & CVAR_ARCHIVE) { Com_Printf("A"); } else { Com_Printf(" "); } if (var->flags & CVAR_LATCH) { Com_Printf("L"); } else { Com_Printf(" "); } if (var->flags & CVAR_CHEAT) { Com_Printf("C"); } else { Com_Printf(" "); } Com_Printf (" %s \"%s\"\n", var->name, var->string); } Com_Printf ("\n%i total cvars\n", i); Com_Printf ("%i cvar indexes\n", cvar_numIndexes); } /* ============ Cvar_Restart_f Resets all cvars to their hardcoded values ============ */ void Cvar_Restart_f( void ) { cvar_t *var; cvar_t **prev; prev = &cvar_vars; while ( 1 ) { var = *prev; if ( !var ) { break; } // don't mess with rom values, or some inter-module // communication will get broken (com_cl_running, etc) if ( var->flags & ( CVAR_ROM | CVAR_INIT | CVAR_NORESTART ) ) { prev = &var->next; continue; } // throw out any variables the user created if ( var->flags & CVAR_USER_CREATED ) { *prev = var->next; if ( var->name ) { Z_Free( var->name ); } if ( var->string ) { Z_Free( var->string ); } if ( var->latchedString ) { Z_Free( var->latchedString ); } if ( var->resetString ) { Z_Free( var->resetString ); } // clear the var completely, since we // can't remove the index from the list Com_Memset( var, 0, sizeof( var ) ); continue; } Cvar_Set( var->name, var->resetString ); prev = &var->next; } } /* ===================== Cvar_InfoString ===================== */ char *Cvar_InfoString( int bit ) { static char info[MAX_INFO_STRING]; cvar_t *var; info[0] = 0; for (var = cvar_vars ; var ; var = var->next) { if (var->flags & bit) { Info_SetValueForKey (info, var->name, var->string); } } return info; } /* ===================== Cvar_InfoString_Big handles large info strings ( CS_SYSTEMINFO ) ===================== */ char *Cvar_InfoString_Big( int bit ) { static char info[BIG_INFO_STRING]; cvar_t *var; info[0] = 0; for (var = cvar_vars ; var ; var = var->next) { if (var->flags & bit) { Info_SetValueForKey_Big (info, var->name, var->string); } } return info; } /* ===================== Cvar_InfoStringBuffer ===================== */ void Cvar_InfoStringBuffer( int bit, char* buff, int buffsize ) { Q_strncpyz(buff,Cvar_InfoString(bit),buffsize); } /* ===================== Cvar_Register basically a slightly modified Cvar_Get for the interpreted modules ===================== */ void Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags ) { cvar_t *cv; cv = Cvar_Get( varName, defaultValue, flags ); if ( !vmCvar ) { return; } vmCvar->handle = cv - cvar_indexes; vmCvar->modificationCount = -1; Cvar_Update( vmCvar ); } /* ===================== Cvar_Register updates an interpreted modules' version of a cvar ===================== */ void Cvar_Update( vmCvar_t *vmCvar ) { cvar_t *cv = NULL; // bk001129 assert(vmCvar); // bk if ( (unsigned)vmCvar->handle >= cvar_numIndexes ) { Com_Error( ERR_DROP, "Cvar_Update: handle out of range" ); } cv = cvar_indexes + vmCvar->handle; if ( cv->modificationCount == vmCvar->modificationCount ) { return; } if ( !cv->string ) { return; // variable might have been cleared by a cvar_restart } vmCvar->modificationCount = cv->modificationCount; // bk001129 - mismatches. if ( strlen(cv->string)+1 > MAX_CVAR_VALUE_STRING ) Com_Error( ERR_DROP, "Cvar_Update: src %s length %d exceeds MAX_CVAR_VALUE_STRING", cv->string, strlen(cv->string), sizeof(vmCvar->string) ); // bk001212 - Q_strncpyz guarantees zero padding and dest[MAX_CVAR_VALUE_STRING-1]==0 // bk001129 - paranoia. Never trust the destination string. // bk001129 - beware, sizeof(char*) is always 4 (for cv->string). // sizeof(vmCvar->string) always MAX_CVAR_VALUE_STRING //Q_strncpyz( vmCvar->string, cv->string, sizeof( vmCvar->string ) ); // id Q_strncpyz( vmCvar->string, cv->string, MAX_CVAR_VALUE_STRING ); vmCvar->value = cv->value; vmCvar->integer = cv->integer; } /* ============ Cvar_Init Reads in all archived cvars ============ */ void Cvar_Init (void) { cvar_cheats = Cvar_Get("sv_cheats", "1", CVAR_ROM | CVAR_SYSTEMINFO ); Cmd_AddCommand ("toggle", Cvar_Toggle_f); Cmd_AddCommand ("set", Cvar_Set_f); Cmd_AddCommand ("sets", Cvar_SetS_f); Cmd_AddCommand ("setu", Cvar_SetU_f); Cmd_AddCommand ("seta", Cvar_SetA_f); Cmd_AddCommand ("reset", Cvar_Reset_f); Cmd_AddCommand ("cvarlist", Cvar_List_f); Cmd_AddCommand ("cvar_restart", Cvar_Restart_f); }
[ "jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac", "crioux@684fc592-8442-0410-8ea1-df6b371289ac" ]
[ [ [ 1, 149 ], [ 151, 690 ], [ 692, 932 ] ], [ [ 150, 150 ], [ 691, 691 ] ] ]
98034d769ace00df7df2294cd24d934e2c9dda0c
b957e10ed5376dbe85c07bdef1f510f641984a1a
/Object.cpp
9061d37946b70f34c44618f7f3c89fc005a968c3
[]
no_license
alexjshank/motors
063245c206df936a886f72a22f0f15c78e1129cb
7193b729466d8caece267f0b8ddbf16d99c13f8a
refs/heads/master
2016-09-10T15:47:20.906269
2009-11-04T18:41:21
2009-11-04T18:41:21
33,394,870
0
0
null
null
null
null
UTF-8
C++
false
false
25
cpp
#include ".\object.h"
[ "alexjshank@0c9e2a0d-1447-0410-93de-f5a27bb8667b" ]
[ [ [ 1, 2 ] ] ]
991c51949cccb9115e996fa745fa06fc387f8d10
465943c5ffac075cd5a617c47fd25adfe496b8b4
/LANDMARS.H
ab44619a57cd4d65f50c8f2b5515a54c4ce51384
[]
no_license
paulanthonywilson/airtrafficcontrol
7467f9eb577b24b77306709d7b2bad77f1b231b7
6c579362f30ed5f81cabda27033f06e219796427
refs/heads/master
2016-08-08T00:43:32.006519
2009-04-09T21:33:22
2009-04-09T21:33:22
172,292
1
0
null
null
null
null
UTF-8
C++
false
false
1,430
h
/* Class to describe landmarks to initilise beacons,gates and airports in the arena Simon Hall ver 1.0 03-04-96*/ #ifndef _LANDMARKS_H #define _LANDMARKS_H #include <assert.h> #include "gate.h" #include "beacon.h" #include "airport.h" #include "flightpa.h" class Landmarks { private : Gate *AllGates_c[9]; Beacon *AllBeacons_c[9]; Airport *AllAirports_c[9]; FlightPath *AllFlightPaths_c[9]; int NoOfGates_c, NoOfBeacons_c; int NoOfAirports_c, NoOfFlightPaths_c; LandmarkTypeId DestChoice_c; public : Landmarks(){ NoOfGates_c=0; NoOfBeacons_c=0; NoOfAirports_c=0; NoOfFlightPaths_c=0; } ~Landmarks(); int NoOfGates(void){ return NoOfGates_c; } int NoOfBeacons(void){ return NoOfBeacons_c; } int NoOfAirports(void){ return NoOfAirports_c; } int NoOfFlightPaths(void){ return NoOfFlightPaths_c; } void AddGate( Gate * ); void AddBeacon( Beacon * ); void AddAirport( Airport * ); void AddFlightPath( FlightPath * ); Gate ** AllGates(void){ return AllGates_c; } Beacon ** AllBeacons(void){ return AllBeacons_c; } Airport ** AllAirports(void){ return AllAirports_c; } FlightPath ** AllFlightPaths(void){ return AllFlightPaths_c; } Destination *PickDestination(); LandmarkTypeId DestChoice(){ return DestChoice_c; } Airport *PickAirport(); Gate *PickGate(); void ChooseDestType(); }; # endif _LANDMARKS_H
[ [ [ 1, 73 ] ] ]
01758cc6146ccb50799cfc6b6095cfbdeaeffae3
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/operational/PathSmoother/PathSmoother/shape.h
0b0ed0e656ed266dfcfa41be99717bccac3f02de
[]
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
1,186
h
#ifndef _SHAPE_H #define _SHAPE_H #ifdef __cplusplus_cli #pragma managed(push,off) #endif #include "coords/dpvector2.h" #include "ref_obj.h" enum intersection_mode { im_min, im_max, im_min_abs, im_max_abs }; class shape : public ref_obj { public: static int shape_count; shape() { shape_count++; } virtual ~shape() { shape_count--; } // tests for intersection of the shape with the search vector starting at p width direction u as well as testing // for the closest point to the line segment defined by p, u' and d // p - path point // u - search vector // d - distance of line segment to look for intersection, direction is u' virtual bool intersect(const dpvector2& p, const dpvector2& u, const double d, const intersection_mode im, dpvector2& t) const = 0; }; inline bool intersect_helper(const dpvector2& p, const dpvector2& u, const dpvector2& s, const dpvector2& v, dpvector2& t) { dpmatrix2 A( u.x(), -v.x(), u.y(), -v.y() ); if (abs(A.inv()) > 1e-4) { t = A*(s-p); return (t.y() >= 0 && t.y() < 1); } else { return false; } } #ifdef __cplusplus_cli #pragma managed(pop) #endif #endif
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 54 ] ] ]
a16647abf12a19a042f3677c3609f47c00b6f622
0b085287d26e47bff407677479600132abf42728
/libqz7/core/RingBuffer.cpp
6e7a92f1aa3de75f38d419f0ab6056cfd2ed3a5f
[]
no_license
bks/qz7
ee717626f111c5bf301e41732f2badf37e6272fa
85493103def2959c2c3a68da9b48f9cf74791cc3
refs/heads/master
2021-01-22T03:39:22.364142
2008-12-09T00:35:38
2008-12-09T00:35:38
75,379
1
0
null
null
null
null
UTF-8
C++
false
false
561
cpp
#include "qz7/RingBuffer.h" #include "qz7/Error.h" #include "qz7/Stream.h" #include <string.h> namespace qz7 { void RingBuffer::flush() { if (!mStream->write(mBuffer, mPos)) throw WriteError(mStream); // if we're flushing in the middle, we need to rearrange the buffer if (mPos != mSize) { quint8 temp[mSize]; ::memcpy(temp, &mBuffer[mPos], mSize - mPos); ::memcpy(&temp[mSize - mPos], mBuffer, mPos); ::memcpy(mBuffer, temp, mSize); } mPos = 0; } }
[ "bks@yochanan.(none)" ]
[ [ [ 1, 27 ] ] ]
254a5ff052c1771a1baa2acd10429104042c3b7e
b799c972367cd014a1ffed4288a9deb72f590bec
/project/NetServices/services/http/client/data/HTTPMap.cpp
49b0cfa916d363ceb64bc3c350f00ff5fc8a5795
[]
no_license
intervigilium/csm213a-embedded
647087de8f831e3c69e05d847d09f5fa12b468e6
ae4622be1eef8eb6e4d1677a9b2904921be19a9e
refs/heads/master
2021-01-13T02:22:42.397072
2011-12-11T22:50:37
2011-12-11T22:50:37
2,832,079
2
1
null
null
null
null
UTF-8
C++
false
false
4,273
cpp
/* Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "HTTPMap.h" #include "../../util/url.h" //#define __DEBUG #include "dbg/dbg.h" HTTPMap::HTTPMap(const string& keyValueSep /*= "="*/, const string& pairSep /*= "&"*/) : HTTPData(), Dictionary(), m_buf(), m_len(0), m_chunked(false), m_keyValueSep(keyValueSep), m_pairSep(pairSep) { } HTTPMap::~HTTPMap() { } void HTTPMap::clear() { m_buf.clear(); } int HTTPMap::read(char* buf, int len) { memcpy( (void*)buf, (void*)m_buf.data(), len ); m_buf.erase(0, len); //Erase these chars return len; } int HTTPMap::write(const char* buf, int len) { m_buf.append( buf, len ); if( ( m_chunked && !len ) || ( !m_chunked && ( m_buf.length() >= m_len ) ) ) //Last chunk or EOF { parseString(); } return len; } string HTTPMap::getDataType() //Internet media type for Content-Type header { return "application/x-www-form-urlencoded"; } void HTTPMap::setDataType(const string& type) //Internet media type from Content-Type header { //Do not really care here } int HTTPMap::getDataLen() //For Content-Length header { //This will be called before any read occurs, so let's generate our string object //Generate string generateString(); return m_len; } bool HTTPMap::getIsChunked() //For Transfer-Encoding header { return false; //We don't want to chunk this } void HTTPMap::setIsChunked(bool chunked) //From Transfer-Encoding header { m_chunked = chunked; } void HTTPMap::setDataLen(int len) //From Content-Length header, or if the transfer is chunked, next chunk length { m_len += len; //Useful so that we can parse string when last byte is written if not chunked m_buf.reserve( m_len ); } void HTTPMap::generateString() { Dictionary::iterator it; bool first = true; while( !Dictionary::empty() ) { if(!first) { m_buf.append( m_pairSep ); } else { first = false; } it = Dictionary::begin(); m_buf.append( Url::encode( (*it).first ) ); m_buf.append( m_keyValueSep ); m_buf.append( Url::encode( (*it).second ) ); Dictionary::erase(it); //Free memory as we process data } m_len = m_buf.length(); DBG("\r\nData [len %d]:\r\n%s\r\n", m_len, m_buf.c_str()); } void HTTPMap::parseString() { string key; string value; int pos = 0; int key_pos; int key_len; int value_pos; int value_len; bool eof = false; while(!eof) { key_pos = pos; value_pos = m_buf.find(m_keyValueSep, pos); if(value_pos < 0) { //Parse error, break break; } key_len = value_pos - key_pos; value_pos+= m_keyValueSep.length(); pos = m_buf.find( m_pairSep, value_pos ); if(pos < 0) //Not found { pos = m_buf.length(); eof = true; } value_len = pos - value_pos; pos += m_pairSep.length(); //Append elenent Dictionary::operator[]( Url::decode( m_buf.substr(key_pos, key_len) ) ) = Url::decode( m_buf.substr(value_pos, value_len) ); } m_buf.clear(); //Free data }
[ [ [ 1, 167 ] ] ]
8bba36355cfca084641158c9051caf33c5dbaf0c
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/code/BaseImporter.cpp
4f16a72707b9e7ebeea6ba92d2595f1f52dd503b
[ "BSD-3-Clause" ]
permissive
spring/assimp
fb53b91228843f7677fe8ec18b61d7b5886a6fd3
db29c9a20d0dfa9f98c8fd473824bba5a895ae9e
refs/heads/master
2021-01-17T23:19:56.511185
2011-11-08T12:15:18
2011-11-08T12:15:18
2,017,841
1
1
null
null
null
null
UTF-8
C++
false
false
15,928
cpp
/* --------------------------------------------------------------------------- Open Asset Import Library (ASSIMP) --------------------------------------------------------------------------- Copyright (c) 2006-2010, ASSIMP Development Team All rights reserved. Redistribution and use of this software 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 ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. 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. --------------------------------------------------------------------------- */ /** @file BaseImporter.cpp * @brief Implementation of BaseImporter */ #include "AssimpPCH.h" #include "BaseImporter.h" #include "FileSystemFilter.h" #include "Importer.h" using namespace Assimp; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer BaseImporter::BaseImporter() : progress() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Destructor, private as well BaseImporter::~BaseImporter() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Imports the given file and returns the imported data. aiScene* BaseImporter::ReadFile(const Importer* pImp, const std::string& pFile, IOSystem* pIOHandler) { progress = pImp->GetProgressHandler(); ai_assert(progress); // Gather configuration properties for this run SetupProperties( pImp ); // Construct a file system filter to improve our success ratio at reading external files FileSystemFilter filter(pFile,pIOHandler); // create a scene object to hold the data ScopeGuard<aiScene> sc(new aiScene()); // dispatch importing try { InternReadFile( pFile, sc, &filter); } catch( const std::exception& err ) { // extract error description mErrorText = err.what(); DefaultLogger::get()->error(mErrorText); return NULL; } // return what we gathered from the import. sc.dismiss(); return sc; } // ------------------------------------------------------------------------------------------------ void BaseImporter::SetupProperties(const Importer* /*pImp*/) { // the default implementation does nothing } // ------------------------------------------------------------------------------------------------ /*static*/ bool BaseImporter::SearchFileHeaderForToken(IOSystem* pIOHandler, const std::string& pFile, const char** tokens, unsigned int numTokens, unsigned int searchBytes /* = 200 */) { ai_assert(NULL != tokens && 0 != numTokens && 0 != searchBytes); if (!pIOHandler) return false; boost::scoped_ptr<IOStream> pStream (pIOHandler->Open(pFile)); if (pStream.get() ) { // read 200 characters from the file boost::scoped_array<char> _buffer (new char[searchBytes+1 /* for the '\0' */]); char* buffer = _buffer.get(); const unsigned int read = pStream->Read(buffer,1,searchBytes); if (!read) return false; for (unsigned int i = 0; i < read;++i) buffer[i] = ::tolower(buffer[i]); // It is not a proper handling of unicode files here ... // ehm ... but it works in most cases. char* cur = buffer,*cur2 = buffer,*end = &buffer[read]; while (cur != end) { if (*cur) *cur2++ = *cur; ++cur; } *cur2 = '\0'; for (unsigned int i = 0; i < numTokens;++i) { ai_assert(NULL != tokens[i]); if (::strstr(buffer,tokens[i])) { DefaultLogger::get()->debug(std::string("Found positive match for header keyword: ") + tokens[i]); return true; } } } return false; } // ------------------------------------------------------------------------------------------------ // Simple check for file extension /*static*/ bool BaseImporter::SimpleExtensionCheck (const std::string& pFile, const char* ext0, const char* ext1, const char* ext2) { std::string::size_type pos = pFile.find_last_of('.'); // no file extension - can't read if( pos == std::string::npos) return false; const char* ext_real = & pFile[ pos+1 ]; if( !ASSIMP_stricmp(ext_real,ext0) ) return true; // check for other, optional, file extensions if (ext1 && !ASSIMP_stricmp(ext_real,ext1)) return true; if (ext2 && !ASSIMP_stricmp(ext_real,ext2)) return true; return false; } // ------------------------------------------------------------------------------------------------ // Get file extension from path /*static*/ std::string BaseImporter::GetExtension (const std::string& pFile) { std::string::size_type pos = pFile.find_last_of('.'); // no file extension at all if( pos == std::string::npos) return ""; std::string ret = pFile.substr(pos+1); std::transform(ret.begin(),ret.end(),ret.begin(),::tolower); // thanks to Andy Maloney for the hint return ret; } // ------------------------------------------------------------------------------------------------ // Check for magic bytes at the beginning of the file. /* static */ bool BaseImporter::CheckMagicToken(IOSystem* pIOHandler, const std::string& pFile, const void* _magic, unsigned int num, unsigned int offset, unsigned int size) { ai_assert(size <= 16 && _magic); if (!pIOHandler) { return false; } union { const char* magic; const uint16_t* magic_u16; const uint32_t* magic_u32; }; magic = reinterpret_cast<const char*>(_magic); boost::scoped_ptr<IOStream> pStream (pIOHandler->Open(pFile)); if (pStream.get() ) { // skip to offset pStream->Seek(offset,aiOrigin_SET); // read 'size' characters from the file union { char data[16]; uint16_t data_u16[8]; uint32_t data_u32[4]; }; if(size != pStream->Read(data,1,size)) { return false; } for (unsigned int i = 0; i < num; ++i) { // also check against big endian versions of tokens with size 2,4 // that's just for convinience, the chance that we cause conflicts // is quite low and it can save some lines and prevent nasty bugs if (2 == size) { uint16_t rev = *magic_u16; ByteSwap::Swap(&rev); if (data_u16[0] == *magic_u16 || data_u16[0] == rev) { return true; } } else if (4 == size) { uint32_t rev = *magic_u32; ByteSwap::Swap(&rev); if (data_u32[0] == *magic_u32 || data_u32[0] == rev) { return true; } } else { // any length ... just compare if(!memcmp(magic,data,size)) { return true; } } magic += size; } } return false; } #include "../contrib/ConvertUTF/ConvertUTF.h" // ------------------------------------------------------------------------------------------------ void ReportResult(ConversionResult res) { if(res == sourceExhausted) { DefaultLogger::get()->error("Source ends with incomplete character sequence, transformation to UTF-8 fails"); } else if(res == sourceIllegal) { DefaultLogger::get()->error("Source contains illegal character sequence, transformation to UTF-8 fails"); } } // ------------------------------------------------------------------------------------------------ // Convert to UTF8 data void BaseImporter::ConvertToUTF8(std::vector<char>& data) { ConversionResult result; if(data.size() < 8) { throw DeadlyImportError("File is too small"); } // UTF 8 with BOM if((uint8_t)data[0] == 0xEF && (uint8_t)data[1] == 0xBB && (uint8_t)data[2] == 0xBF) { DefaultLogger::get()->debug("Found UTF-8 BOM ..."); std::copy(data.begin()+3,data.end(),data.begin()); data.resize(data.size()-3); return; } // UTF 32 BE with BOM if(*((uint32_t*)&data.front()) == 0xFFFE0000) { // swap the endianess .. for(uint32_t* p = (uint32_t*)&data.front(), *end = (uint32_t*)&data.back(); p <= end; ++p) { AI_SWAP4P(p); } } // UTF 32 LE with BOM if(*((uint32_t*)&data.front()) == 0x0000FFFE) { DefaultLogger::get()->debug("Found UTF-32 BOM ..."); const uint32_t* sstart = (uint32_t*)&data.front()+1, *send = (uint32_t*)&data.back()+1; char* dstart,*dend; std::vector<char> output; do { output.resize(output.size()?output.size()*3/2:data.size()/2); dstart = &output.front(),dend = &output.back()+1; result = ConvertUTF32toUTF8((const UTF32**)&sstart,(const UTF32*)send,(UTF8**)&dstart,(UTF8*)dend,lenientConversion); } while(result == targetExhausted); ReportResult(result); // copy to output buffer. const size_t outlen = (size_t)(dstart-&output.front()); data.assign(output.begin(),output.begin()+outlen); return; } // UTF 16 BE with BOM if(*((uint16_t*)&data.front()) == 0xFFFE) { // swap the endianess .. for(uint16_t* p = (uint16_t*)&data.front(), *end = (uint16_t*)&data.back(); p <= end; ++p) { ByteSwap::Swap2(p); } } // UTF 16 LE with BOM if(*((uint16_t*)&data.front()) == 0xFEFF) { DefaultLogger::get()->debug("Found UTF-16 BOM ..."); const uint16_t* sstart = (uint16_t*)&data.front()+1, *send = (uint16_t*)(&data.back()+1); char* dstart,*dend; std::vector<char> output; do { output.resize(output.size()?output.size()*3/2:data.size()*3/4); dstart = &output.front(),dend = &output.back()+1; result = ConvertUTF16toUTF8((const UTF16**)&sstart,(const UTF16*)send,(UTF8**)&dstart,(UTF8*)dend,lenientConversion); } while(result == targetExhausted); ReportResult(result); // copy to output buffer. const size_t outlen = (size_t)(dstart-&output.front()); data.assign(output.begin(),output.begin()+outlen); return; } } // ------------------------------------------------------------------------------------------------ void BaseImporter::TextFileToBuffer(IOStream* stream, std::vector<char>& data) { ai_assert(NULL != stream); const size_t fileSize = stream->FileSize(); if(!fileSize) { throw DeadlyImportError("File is empty"); } data.reserve(fileSize+1); data.resize(fileSize); if(fileSize != stream->Read( &data[0], 1, fileSize)) { throw DeadlyImportError("File read error"); } ConvertToUTF8(data); // append a binary zero to simplify string parsing data.push_back(0); } // ------------------------------------------------------------------------------------------------ namespace Assimp { // Represents an import request struct LoadRequest { LoadRequest(const std::string& _file, unsigned int _flags,const BatchLoader::PropertyMap* _map, unsigned int _id) : file(_file), flags(_flags), refCnt(1),scene(NULL), loaded(false), id(_id) { if (_map) map = *_map; } const std::string file; unsigned int flags; unsigned int refCnt; aiScene* scene; bool loaded; BatchLoader::PropertyMap map; unsigned int id; bool operator== (const std::string& f) { return file == f; } }; } // ------------------------------------------------------------------------------------------------ // BatchLoader::pimpl data structure struct Assimp::BatchData { BatchData() : next_id(0xffff) {} // IO system to be used for all imports IOSystem* pIOSystem; // Importer used to load all meshes Importer* pImporter; // List of all imports std::list<LoadRequest> requests; // Base path std::string pathBase; // Id for next item unsigned int next_id; }; // ------------------------------------------------------------------------------------------------ BatchLoader::BatchLoader(IOSystem* pIO) { ai_assert(NULL != pIO); data = new BatchData(); data->pIOSystem = pIO; data->pImporter = new Importer(); data->pImporter->SetIOHandler(data->pIOSystem); } // ------------------------------------------------------------------------------------------------ BatchLoader::~BatchLoader() { // delete all scenes wthat have not been polled by the user for (std::list<LoadRequest>::iterator it = data->requests.begin();it != data->requests.end(); ++it) { delete (*it).scene; } data->pImporter->SetIOHandler(NULL); /* get pointer back into our posession */ delete data->pImporter; delete data; } // ------------------------------------------------------------------------------------------------ unsigned int BatchLoader::AddLoadRequest (const std::string& file, unsigned int steps /*= 0*/, const PropertyMap* map /*= NULL*/) { ai_assert(!file.empty()); // check whether we have this loading request already std::list<LoadRequest>::iterator it; for (it = data->requests.begin();it != data->requests.end(); ++it) { // Call IOSystem's path comparison function here if (data->pIOSystem->ComparePaths((*it).file,file)) { if (map) { if (!((*it).map == *map)) continue; } else if (!(*it).map.empty()) continue; (*it).refCnt++; return (*it).id; } } // no, we don't have it. So add it to the queue ... data->requests.push_back(LoadRequest(file,steps,map,data->next_id)); return data->next_id++; } // ------------------------------------------------------------------------------------------------ aiScene* BatchLoader::GetImport (unsigned int which) { for (std::list<LoadRequest>::iterator it = data->requests.begin();it != data->requests.end(); ++it) { if ((*it).id == which && (*it).loaded) { aiScene* sc = (*it).scene; if (!(--(*it).refCnt)) { data->requests.erase(it); } return sc; } } return NULL; } // ------------------------------------------------------------------------------------------------ void BatchLoader::LoadAll() { // no threaded implementation for the moment for (std::list<LoadRequest>::iterator it = data->requests.begin();it != data->requests.end(); ++it) { // force validation in debug builds unsigned int pp = (*it).flags; #ifdef _DEBUG pp |= aiProcess_ValidateDataStructure; #endif // setup config properties if necessary data->pImporter->pimpl->mFloatProperties = (*it).map.floats; data->pImporter->pimpl->mIntProperties = (*it).map.ints; data->pImporter->pimpl->mStringProperties = (*it).map.strings; if (!DefaultLogger::isNullLogger()) { DefaultLogger::get()->info("%%% BEGIN EXTERNAL FILE %%%"); DefaultLogger::get()->info("File: " + (*it).file); } data->pImporter->ReadFile((*it).file,pp); (*it).scene = const_cast<aiScene*>(data->pImporter->GetOrphanedScene()); (*it).loaded = true; DefaultLogger::get()->info("%%% END EXTERNAL FILE %%%"); } }
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f", "kimmi@67173fc5-114c-0410-ac8e-9d2fd5bffc1f", "ulfjorensen@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 46 ], [ 48, 51 ], [ 57, 57 ], [ 71, 71 ], [ 73, 81 ], [ 83, 83 ], [ 88, 94 ], [ 98, 99 ], [ 101, 375 ], [ 377, 377 ], [ 380, 380 ], [ 387, 387 ], [ 395, 395 ], [ 401, 529 ] ], [ [ 47, 47 ], [ 52, 56 ], [ 58, 70 ], [ 72, 72 ], [ 82, 82 ], [ 84, 87 ], [ 95, 97 ], [ 100, 100 ] ], [ [ 376, 376 ], [ 378, 379 ], [ 381, 386 ], [ 388, 394 ], [ 396, 400 ] ] ]
7a6161beae98a5c683024a9004ebd3eaa00573af
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/CxxParser/Debug/test.h
46f28cbeae262d651da4063e5fca2d7a907d5202
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
105
h
template <class T, class B> struct TagEntry { class TagEntry::SimpleClass { } virtual foo(); }
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 6 ] ] ]
cf51a4727e99b4aa84b4c859168324d128827c1a
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Util/alcommon/include/altimeval.h
2610c991bdd3d8fcb8fe4ea2466e2c8f527c4a0d
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,376
h
/** * @author Aldebaran Robotics * Aldebaran Robotics (c) 2007 All Rights Reserved - This file is confidential.\n * * Version : $Id$ */ #ifndef AL_TIMEVAL_HH #define AL_TIMEVAL_HH #ifdef _WIN32 #include <sys/timeb.h> #include <sys/types.h> #include <winsock.h> // for timeval // #include "alh.h" int gettimeofday(struct timeval* t,void* timezone); #else #include <sys/time.h> #endif #include <ostream> /* * ALTimeval.h and ALTimeval.cpp contain a set of utility functions that * manipulate timestamps easily. * This is mostly about operator overloading and basic functions. * ALTimeval should be cross-platform, and implements gettimeofday on * Windows. */ // reset time to 0,0 inline void reset( struct timeval & t ) { t.tv_sec = 0; t.tv_usec = 0; } // is time set to (0,0) ? inline bool isNull( struct timeval & t ) { return t.tv_sec == 0 && t.tv_usec == 0; } void AddMicroSec( struct timeval & t, unsigned int pnTimeInMicroSec ); struct timeval operator+( const struct timeval & t1, const struct timeval & t2 ); struct timeval operator+( const struct timeval & t1, long t2 ); // WARNING: t2 is in second !!!!! struct timeval operator-( const struct timeval & t1, const struct timeval & t2 ); struct timeval operator-( const struct timeval & t1, long t2 ); // WARNING: t2 is in second !!!!! bool operator==( const struct timeval & t1, const struct timeval & t2 ); bool operator< ( const struct timeval & t1, const struct timeval & t2 ); bool operator> ( const struct timeval & t1, const struct timeval & t2 ); bool operator<=( const struct timeval & t1, const struct timeval & t2 ); bool operator>=( const struct timeval & t1, const struct timeval & t2 ); struct timeval now( void ); struct timeval epoch( void ); void printtv( const struct timeval & t ); std::ostream &operator<<( std::ostream& os, const struct timeval & st ); std::string toString( const struct timeval & t ); typedef struct timeval ALTimeval; /** * \brief give duration time between two dates (in micro seconds) * * Take 2 dates and return the duration between then is us. * * @param begin starting date * @param end ending date * * @return duration between the two dates */ int duration( const struct timeval & begin, const struct timeval & end ); #endif // AL_TIMEVAL_HH
[ [ [ 1, 81 ] ] ]
4691ea39b40591ab54a3c9ff27602f402b18f0a2
51d0aa420c539ad087ed1d32aa123d8fcefe2cb9
/src/luanode_dns.cpp
d9d5ef49a6f32aab501319c163d67e483ada7f83
[ "MIT" ]
permissive
Sciumo/LuaNode
1aae81a44d9ff1948499b2103b56c175e97d89da
0611b4d5496bf67d336ac24e903a91e5d28f6f83
refs/heads/master
2021-01-18T00:01:13.841566
2011-08-01T22:15:50
2011-08-01T22:15:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,075
cpp
#include "stdafx.h" #include "luanode.h" #include "luanode_dns.h" #include "blogger.h" #include <boost/asio/placeholders.hpp> #include <boost/bind.hpp> using namespace LuaNode::Dns; const char* Resolver::className = "Resolver"; const Resolver::RegType Resolver::methods[] = { { "Lookup", &Resolver::Lookup }, {0} }; const Resolver::RegType Resolver::setters[] = { {0} }; const Resolver::RegType Resolver::getters[] = { {0} }; static unsigned long s_resolverCount = 0; Resolver::Resolver(lua_State* L) : m_L( LuaNode::GetLuaVM() ), m_resolver( LuaNode::GetIoService() ) { s_resolverCount++; LogDebug("Constructing Resolver (%p). Current resolver count = %d", this, s_resolverCount); } Resolver::~Resolver(void) { s_resolverCount--; LogDebug("Destructing Resolver (%p). Current resolver count = %d", this, s_resolverCount); } ////////////////////////////////////////////////////////////////////////// /// int Resolver::Lookup(lua_State* L) { int callback; std::string domain = luaL_checkstring(L, 2); std::string service = luaL_checkstring(L, 3); luaL_checktype(L, 4, LUA_TFUNCTION); lua_pushvalue(L, 4); callback = luaL_ref(L, LUA_REGISTRYINDEX); bool enumerateAll = lua_toboolean(L, 5); /*if(lua_type(L, 3) == LUA_TSTRING) { service = lua_tostring(L, 3); } else if(lua_type(L, 3) == LUA_TFUNCTION) { lua_pushvalue(L, 3); callback = luaL_ref(L, LUA_REGISTRYINDEX); } else { luaL_error(L, "A callback must be supplied"); }*/ boost::asio::ip::tcp::resolver::query query(domain, service); // TODO: No hacer que esto sea una clase, sino un par de funciones estáticas // No pasar el this en el handler (el resolver podría ser gc'ed mientras hay un async_resolve flying... // o sino, guardo una ref en la registry mientras tanto... m_resolver.async_resolve(query, boost::bind(&Resolver::HandleResolve, this, callback, domain, enumerateAll, boost::asio::placeholders::error, boost::asio::placeholders::iterator) ); return 0; } ////////////////////////////////////////////////////////////////////////// /// void Resolver::HandleResolve(int callback, std::string domain, bool enumerateAll, const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iter) { lua_State* L = LuaNode::GetLuaVM(); lua_rawgeti(L, LUA_REGISTRYINDEX, callback); luaL_unref(L, LUA_REGISTRYINDEX, callback); if(error) { lua_pushstring(L, error.message().c_str()); lua_call(L, 1, LUA_MULTRET); lua_settop(L, 0); return; } boost::asio::ip::tcp::resolver::iterator end; if(iter == end) { lua_pushstring(L, "did not resolve to anything?"); // TODO: proper error message :D lua_call(L, 1, LUA_MULTRET); lua_settop(L, 0); return; } lua_pushnil(L); // enumerateAll will push an array of endpoints instead of just the first one if(enumerateAll) { lua_newtable(L); int table = lua_gettop(L); int i = 0; while(iter != end) { boost::asio::ip::tcp::endpoint endpoint = *iter++; EndpointToLua(L, endpoint); lua_rawseti(L, table, ++i); } } else { boost::asio::ip::tcp::endpoint endpoint = *iter++; EndpointToLua(L, endpoint); } lua_pushlstring(L, domain.c_str(), domain.size()); lua_call(L, 3, LUA_MULTRET); lua_settop(L, 0); } ////////////////////////////////////////////////////////////////////////// /// Pushes to Lua the data of the endpoint void Resolver::EndpointToLua(lua_State* L, const boost::asio::ip::tcp::endpoint& endpoint) { const boost::asio::ip::address& address = endpoint.address(); std::string s = endpoint.address().to_string(); lua_newtable(L); lua_pushstring(L, address.to_string().c_str()); lua_setfield(L, -2, "address"); lua_pushnumber(L, endpoint.port()); lua_setfield(L, -2, "port"); if(endpoint.address().is_v6()) { lua_pushnumber(L, 6); } else if(endpoint.address().is_v4()) { lua_pushnumber(L, 4); } else { lua_pushliteral(L, "unknown"); } lua_setfield(L, -2, "family"); }
[ [ [ 1, 147 ] ] ]
df9840d3a39d03662fa5121386d9ee31adb98bdc
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_using_decl_overld_pass.cpp
4e815a996c50e7aa214d6b95724c71a8a4ee4ebc
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,379
cpp
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004, // by libs/config/tools/generate // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE // This file should compile, if it does not then // BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE needs to be defined. // see boost_no_using_decl_overld.ipp for more details // Do not edit this file, it was generated automatically by // ../tools/generate from boost_no_using_decl_overld.ipp on // Sun Jul 25 11:47:49 GMTDT 2004 // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifndef BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE #include "boost_no_using_decl_overld.ipp" #else namespace boost_no_using_declaration_overloads_from_typename_base = empty_boost; #endif int main( int, char *[] ) { return boost_no_using_declaration_overloads_from_typename_base::test(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 39 ] ] ]
49052f968ef06c325f38d918ffa02055439fefcd
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Scene Estimator 2/Track.h
e6f2d454b67e8533e0f41d4c62a6928477c5a4b8
[]
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
6,018
h
#ifndef TRACK_H #define TRACK_H #include "Cluster.h" #include "MatrixIndex.h" #include "PosteriorPosePosition.h" #include "RoadGraph.h" #include "RoadPartition.h" #include "RoadPoint.h" #include "SceneEstimatorConstants.h" #include "SceneEstimatorFunctions.h" #include "Target.h" #include "VehicleOdometry.h" #include <FLOAT.H> #include <MATH.H> #include <STDIO.H> #include <STDLIB.H> #ifdef __cplusplus_cli #pragma managed(push,off) #endif //track invalid ID #define T_INVALIDID -1 //track status flags #define T_STATUSACTIVE 1 #define T_STATUSFULLOCCLUDED 2 #define T_STATUSPARTOCCLUDED 3 #define T_STATUSDELETED -99 //track occlusion types: no occlusion, partial occlusion, full occlusion #define T_OCCLUSIONNONE 0 #define T_OCCLUSIONPART 10 #define T_OCCLUSIONFULL 20 //number of states in the track #define T_NUMSTATES 5 //number of position measurements made for the track #define T_NUMTPMEAS 3 //number of states in the auxiliary velocity estimator #define T_NUMAVESTATES 4 //number of measurements for the auxiliary velocity estimator #define T_NUMAVEMEAS 2 class Track; class Track { //The track class. Stores one persistent obstacle track. private: //TRACK FLAGS AND DATA //persistent and unique track ID int mID; //track status flag (active, occluded, deleted) int mStatusFlag; //time since the track was last updated (NOTE: this gets reset to 0 every time the track is occluded) double mTimeSinceLastUpdate; //absolute time since the track was last updated (NOTE: this doesn't get reset when the track is occluded) double mAbsoluteTimeSinceLastUpdate; //time since the target has been created double mTimeSinceCreation; //number of measurements the track has received int mNumMeasurements; //closest partition in the RNDF RoadPartition* mClosestPartition; //whether the track has been initialized with data bool mIsInitialized; //TRACK STATES //XY location of the track anchor point, in ego-vehicle coordinates double mX; double mY; //orientation angle for transforming tracks from object storage to vehicle frame double mOrientation; //ground speed (m/s) double mSpeed; //track heading relative to ego vehicle heading double mHeading; //TRACK STATE COVARIANCE MATRIX double mCovariance[T_NUMSTATES*T_NUMSTATES]; //TRACK PROBABILITIES //probability that the track is a car (based on object size)) double mCarProbability; //probability that the track is currently stopped (not moving) double mStoppedProbability; //TRACK POINTS //number of points stored for the class int mNumTrackPoints; //the track points stored for the class, in object storage frame double* mTrackPoints; //THE TRACK POSITION MEASUREMENT //flag whether the measurement is accurate at the present time bool mtpmIsCurrent; //counter-clockwise and clockwise occlusion bearings (rad.) double mtpmBCCW; double mtpmBCW; //closest range double mtpmRMIN; //measurement variance double mtpmR[T_NUMTPMEAS*T_NUMTPMEAS]; //measurement-state covariance double mtpmPHt[T_NUMSTATES*T_NUMTPMEAS]; //THE TRACK AUXILIARY VELOCITY ESTIMATOR //state of the auxiliary velocity estimator (X, Y, S, H) double maveState[T_NUMAVESTATES]; //covariance of the auxiliary velocity estimator double maveCovariance[T_NUMAVESTATES*T_NUMAVESTATES]; public: //elements for implementing a linked list of tracks Track* PrevTrack; Track* NextTrack; //accessor methods double AbsoluteTimeSinceLastUpdate() {return mAbsoluteTimeSinceLastUpdate;} double CarProbability() {return mCarProbability;} RoadPartition* ClosestPartition() {return mClosestPartition;} double Covariance(int r, int c) {return mCovariance[midx(r, c, T_NUMSTATES)];} double Heading() {return mHeading;} int ID() {return mID;} bool IsInitialized() {return mIsInitialized;} int NumMeasurements() {return mNumMeasurements;} int NumTrackPoints() {return mNumTrackPoints;} double Orientation() {return mOrientation;} double Speed() {return mSpeed;} int StatusFlag() {return mStatusFlag;} double StoppedProbability() {return mStoppedProbability;} double TimeSinceCreation() {return mTimeSinceCreation;} double TimeSinceLastUpdate() {return mTimeSinceLastUpdate;} double TrackPoints(int r, int c) {return mTrackPoints[midx(r, c, mNumTrackPoints)];} double X() {return mX;} double Y() {return mY;} //accessor methods for track position measurement bool tpmIsCurrent() {return mtpmIsCurrent;} double tpmBCCW() {return mtpmBCCW;} double tpmBCW() {return mtpmBCW;} double tpmRMIN() {return mtpmRMIN;} double tpmR(int r, int c) {return mtpmR[midx(r, c, T_NUMTPMEAS)];} double tpmPHt(int r, int c) {return mtpmPHt[midx(r, c, T_NUMSTATES)];} //accessor methods for auxiliary velocity estimator double aveX() {return maveState[0];} double aveY() {return maveState[1];} double aveSpeed() {return maveState[2];} double aveHeading() {return maveState[3];} double aveCovariance(int r, int c) {return maveCovariance[midx(r, c, T_NUMAVESTATES)];} //constructors and destructor Track(int iID); Track(Track* iTrackToCopy); ~Track(); //track member functions bool CanBeAssociated(Target* iTarget); bool HeadingIsValid(); bool IsNearStopline(PosteriorPosePosition* iPosteriorPosePosition); bool IsOccluded(); double Likelihood(double& oPMDist, double& oSHMDist, Target* iTarget); void MaintainTrack(); void MarkForDeletion() {mStatusFlag = T_STATUSDELETED; return;} void MarkForOcclusion(int iOcclusionType); void Predict(double iPredictDt, VehicleOdometry* iVehicleOdometry, PosteriorPosePosition* iPosteriorPosePosition, RoadGraph* iRoadGraph); void SetTrackPositionMeasurement(); bool SpeedIsValid(); Cluster TrackPointsCluster(); void Update(Target* iTarget, PosteriorPosePosition* iPosteriorPosePosition, RoadGraph* iRoadGraph); }; #ifdef __cplusplus_cli #pragma managed(pop) #endif #endif //TRACK_H
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 185 ] ] ]
621a28dd728425cd86df4a77e698b5fa6f7d5820
8a8873b129313b24341e8fa88a49052e09c3fa51
/inc/GradeDialog.h
c8af7f220e8659af9f213c4f8e3a95feed32854d
[]
no_license
flaithbheartaigh/wapbrowser
ba09f7aa981d65df810dba2156a3f153df071dcf
b0d93ce8517916d23104be608548e93740bace4e
refs/heads/master
2021-01-10T11:29:49.555342
2010-03-08T09:36:03
2010-03-08T09:36:03
50,261,329
1
0
null
null
null
null
UTF-8
C++
false
false
1,650
h
/* ============================================================================ Name : GradeDialog.h Author : Version : Copyright : Your copyright notice Description : CGradeDialog declaration ============================================================================ */ #ifndef GRADEDIALOG_H #define GRADEDIALOG_H // INCLUDES #include "Control.h" class CMainEngine; class MGradeObserver; class CScreenLayout; class CBitmapFactory; // CLASS DECLARATION /** * CGradeDialog * */ class CGradeDialog : public CControl { public: // Constructors and destructor ~CGradeDialog(); static CGradeDialog* NewL(MGradeObserver& aObserver,CMainEngine& aMainEngine); static CGradeDialog* NewLC(MGradeObserver& aObserver,CMainEngine& aMainEngine); private: CGradeDialog(MGradeObserver& aObserver,CMainEngine& aMainEngine); void ConstructL(); public://From CControl virtual void Draw(CGraphic& aGraphic) const; virtual TBool KeyEventL(TInt aKeyCode); virtual TBool HandleCommandL(TInt aCommand); virtual void SizeChanged(const TRect& aScreenRect); virtual const TDesC& LeftButton() const; virtual const TDesC& RightButton() const; public: void SetTitle(const TDesC& aTitle); void SetGradeNum(TInt aNum); private: void InitBitmaps(); private: CFbsBitmap* iDialogBmp; MGradeObserver& iObserver; CMainEngine& iMainEngine; const CScreenLayout& iScreenLayout; CBitmapFactory& iBitmapFactory; TInt iGradeNum; TBuf<20> iTitle; TSize iDialogSize; TSize iIconSize; TPoint iStartPoint; TPoint iIconPoint; }; #endif // GRADEDIALOG_H
[ "sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f" ]
[ [ [ 1, 74 ] ] ]
75a6994c82c9b6b02bef1a658e5e3cb2b76086a8
96f796a966025265020459ca2a38346c3c292b1e
/Ansoply/TextObject.h
968c577d1af06b9ee89a5b50c57a40f55fcbf8e1
[]
no_license
shanewfx/ansoply
222979843662ddb98fb444ce735d607e3033dd5e
99e91008048d0c1afbf80152d0dc173a15e068ee
refs/heads/master
2020-05-18T15:53:46.618329
2009-06-17T01:04:47
2009-06-17T01:04:47
32,243,359
1
0
null
null
null
null
UTF-8
C++
false
false
1,615
h
#pragma once #include "ansoplyobject.h" #include "project.h" class CTextObject : public CAnsoplyObject { friend class CMultiSAP; public: CTextObject(); ~CTextObject(void); void SetDDSFontCache(IDirectDrawSurface7*); IDirectDrawSurface7* GetDDSFontCache(); void SetLogFont(const LOGFONT * logFont); LONG SetText( ULONG uX, ULONG uY, LPCTSTR sText, LPCTSTR sFaceName, ULONG uItalic, ULONG uBold, ULONG uUnderLine, ULONG uWidth, ULONG uHeight, ULONG uColor); LOGFONT& GetFont(); LPCTSTR GetText(); LPCTSTR GetFaceName(); ULONG GetTextLen(); ULONG GetXCoordinate(); ULONG GetYCoordinate(); ULONG GetColor(); ULONG GetItalic() { return m_uItalic; } ULONG GetBold() { return m_uBold; } ULONG GetUnderLine() { return m_uUnderLine; } ULONG GetWidth() { return m_uWidth; } ULONG GetHeight() { return m_uHeight; } void SetAlphaBlt(CAlphaBlt * pAlphaBlt) { m_pAlphaBlt = pAlphaBlt; } virtual void Draw(); ULONG m_uSurfaceWidth; ULONG m_uSurfaceHeight; ULONG m_uRegionWidth; ULONG m_uRegionHeight; protected: IDirectDrawSurface7* m_pDDSFontCache; LOGFONT m_logFont; TCHAR* m_text; // hold the text TCHAR m_facename[32]; ULONG m_cx; ULONG m_cy; ULONG m_uItalic; ULONG m_uBold; ULONG m_uUnderLine; ULONG m_uWidth; ULONG m_uHeight; ULONG m_uColor; CMultiSAP * m_pMultiSAP; CAlphaBlt* m_pAlphaBlt; }; inline IDirectDrawSurface7* CTextObject::GetDDSFontCache() { return m_pDDSFontCache; }
[ "Gmagic10@26f92a05-6149-0410-981d-7deb1f891687", "gmagic10@26f92a05-6149-0410-981d-7deb1f891687" ]
[ [ [ 1, 2 ], [ 4, 7 ], [ 9, 47 ], [ 53, 65 ], [ 69, 76 ] ], [ [ 3, 3 ], [ 8, 8 ], [ 48, 52 ], [ 66, 68 ] ] ]
7a2cff04950878d477159f43d006e7d7e5cb156b
8a3fce9fb893696b8e408703b62fa452feec65c5
/AutoBall/AutoBall/stdafx.cpp
b541be6e3d43ace73607fff6d940824bb8f10290
[]
no_license
win18216001/tpgame
bb4e8b1a2f19b92ecce14a7477ce30a470faecda
d877dd51a924f1d628959c5ab638c34a671b39b2
refs/heads/master
2021-04-12T04:51:47.882699
2011-03-08T10:04:55
2011-03-08T10:04:55
42,728,291
0
2
null
null
null
null
GB18030
C++
false
false
268
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // AutoBall.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ [ [ 1, 8 ] ] ]
3ebe03d088d6a836a3ea203db4b528035dcc7215
967868cbef4914f2bade9ef8f6c300eb5d14bc57
/Security/SspiAuth.hpp
b04317ebdbf25eee170af7339c30ec1568e281b9
[]
no_license
saminigod/baseclasses-001
159c80d40f69954797f1c695682074b469027ac6
381c27f72583e0401e59eb19260c70ee68f9a64c
refs/heads/master
2023-04-29T13:34:02.754963
2009-10-29T11:22:46
2009-10-29T11:22:46
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,333
hpp
/* © Vestris Inc., Geneva Switzerland http://www.vestris.com, 1998, All Rights Reserved __________________________________________________ written by Daniel Doubrovkine - [email protected] */ #ifndef BASECLASSES_SSPI_AUTHENTICATION_HPP #define BASECLASSES_SSPI_AUTHENTICATION_HPP #include <platform/include.hpp> #ifdef _WIN32 #include <String/String.hpp> #include "Win32SecInterface.hpp" #include "State.hpp" class CSspiAuthenticator : public CAuthenticator { property(CString, Package); property(CredHandle, Credentials); property(CtxtHandle, Context); property(bool, HaveCredentials); property(bool, HaveContext); private_property(DWORD, MaxTokenSize); protected: static CWin32SecInterface m_SecInterface; void Initialize(void); void UnInitialize(void); bool Context(const CString& ServerBuffer, CString * AuthResponse); bool Chalenge(CString * AuthResponse); bool Response(const CString& AuthHeader, CString * AuthResponse); public: virtual bool ChalengeResponse(const CString& AuthHeader, CString * AuthResponse); bool AcquireCredentials(void); bool QueryMaxToken(void); CSspiAuthenticator(CAuthenticationType AuthType, const CString& Package); ~CSspiAuthenticator(void); }; #endif #endif
[ [ [ 1, 45 ] ] ]
5dbfcfb5442cbc3422b49953df293052a7611d54
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Utilities/Deprecated/H1Group/hkpGroupCollisionFilter.h
bd90f0159159ee0a0f1f0ec2fe65c6fc090b7534
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,524
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_UTILITIES2_GROUP_COLLISION_FILTER_H #define HK_UTILITIES2_GROUP_COLLISION_FILTER_H #include <Physics/Collide/Filter/hkpCollisionFilter.h> extern const hkClass hkpGroupCollisionFilterClass; /// The group collision filter. There are 32 possible collision groups, and /// each entity can be assigned to any number of groups /// (one group is defined by one bit in a 32 bit integer). /// You can then disable or enable collisions between these groups. /// Objects that have not been assigned to a collision group have a collision group value of 0. /// Note: this code is deprecated, please do not use it /// Collision group 32 is reserved for use as a disable all collision filter, any bodies in that group /// will not collide with anything class hkpGroupCollisionFilter : public hkpCollisionFilter { public: HK_DECLARE_REFLECTION(); /// hkpGroupCollisionFilter(); /// Enables collisions between the specified collision groups. If one of the parameters passed to this function is 0, /// the m_noGroupCollisionEnabled flag is set to true. /// This is a flag that indicates whether objects that are not assigned to any group can collide with objects that are group members. /// By default, it is set to true. void enableCollisionGroups(hkUint32 groupBitsA, hkUint32 groupBitsB); /// Disables collisions between the specified collision groups. If one of the parameters passed to this function is 0, /// the m_noGroupCollisionEnabled flag is set to false. void disableCollisionGroups(hkUint32 groupBitsA, hkUint32 groupBitsB); /// Returns true if the specified groups A and B have collisions enabled. /// The special cases of (0,X) or (X,0) always return the m_noGroupCollisionEnabled value. hkBool isCollisionEnabled(hkUint32 groupBitsA, hkUint32 groupBitsB) const; /// hkpCollisionFilter interface implementation which returns true if the objects are enabled to collide, based on their collision groups. /// The implementation calls isCollisionEnabled( a->getOwner()->getCollisionFilterInfo() ... ) virtual hkBool isCollisionEnabled(const hkpCollidable& a, const hkpCollidable& b ) const; // hkpShapeCollectionFilter interface forwarding virtual hkBool isCollisionEnabled( const hkpCollisionInput& input, const hkpCdBody& a, const hkpCdBody& b, const hkpShapeContainer& bContainer, hkpShapeKey bKey ) const; // hkpShapeCollectionFilter interface forwarding virtual hkBool isCollisionEnabled( const hkpCollisionInput& input, const hkpCdBody& collectionBodyA, const hkpCdBody& collectionBodyB, const HK_SHAPE_CONTAINER& containerShapeA, const HK_SHAPE_CONTAINER& containerShapeB, hkpShapeKey keyA, hkpShapeKey keyB ) const; // hkpRayShapeCollectionFilter interface forwarding virtual hkBool isCollisionEnabled( const hkpShapeRayCastInput& aInput, const hkpShape& shape, const hkpShapeContainer& bContainer, hkpShapeKey bKey ) const; // hkpRayCollidableFilter interface forwarding virtual hkBool isCollisionEnabled( const hkpWorldRayCastInput& a, const hkpCollidable& collidableB ) const; public: hkBool m_noGroupCollisionEnabled; hkUint32 m_collisionGroups[32]; public: hkpGroupCollisionFilter(hkFinishLoadedObjectFlag f) {} }; #endif // HK_DYNAMICS2_GROUP_COLLISION_FILTER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 93 ] ] ]
ef6c749ecc7afa6aa5ab28996b1ce5539ed68bbd
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/test/sockets.cpp
ace417b5467b7a2b1e442baa7a1cc1e491d415c1
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
6,758
cpp
// Copyright (C) 2006 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <dlib/sockets.h> #include <dlib/server.h> #include <dlib/misc_api.h> #include "tester.h" namespace { using namespace test; using namespace dlib; using namespace std; dlib::mutex gm; dlib::signaler gs(gm); const char magic_num = 42; const int min_bytes_sent = 10000; int assigned_port; logger dlog("test.sockets"); // ---------------------------------------------------------------------------------------- class serv : public server::kernel_1a_c { public: serv ( ) : error_occurred (false), got_connections(false) {} void on_listening_port_assigned ( ) { auto_mutex M(gm); assigned_port = get_listening_port(); gs.broadcast(); } void on_connect ( connection& con ) { dlog << LINFO << "in serv::on_connect(): got new connection"; int status; int count = 0; char buf[100]; while ((status = con.read(buf,sizeof(buf))) > 0) { for (int i = 0; i < status; ++i) { if (buf[i] != magic_num) { tag = 4.0; error_occurred = true; } } count += status; } if (count != min_bytes_sent) { tag = 5.0; error_occurred = true; } got_connections = true; dlog << LINFO << "in serv::on_connect(): on_connect ending"; } bool error_occurred; bool got_connections; double tag; }; // ---------------------------------------------------------------------------------------- class thread_container : public multithreaded_object { public: serv& srv; thread_container ( serv& srv_ ) : srv(srv_) { for (int i = 0; i < 10; ++i) register_thread(*this, &thread_container::thread_proc); // start up the threads start(); } ~thread_container () { // wait for all threads to terminate wait(); } void thread_proc ( ) { try { dlog << LTRACE << "enter thread"; { auto_mutex M(gm); while (assigned_port == 0) gs.wait(); } int status; scoped_ptr<connection> con; string hostname; string ip; status = get_local_hostname(hostname); if (status) { srv.tag = 1.0; srv.error_occurred = true; srv.clear(); dlog << LERROR << "leaving thread, line: " << __LINE__; dlog << LERROR << "get_local_hostname() failed"; return; } status = hostname_to_ip(hostname,ip); if (status) { srv.tag = 2.0; srv.error_occurred = true; srv.clear(); dlog << LERROR << "leaving thread, line: " << __LINE__; dlog << LERROR << "hostname_to_ip() failed"; return; } dlog << LTRACE << "try to connect to the server at port " << srv.get_listening_port(); status = create_connection(con,srv.get_listening_port(),ip); if (status) { srv.tag = 3.0; srv.error_occurred = true; srv.clear(); dlog << LERROR << "leaving thread, line: " << __LINE__; dlog << LERROR << "create_connection() failed"; return; } dlog << LTRACE << "sending magic_num to server"; int i; for (i = 0; i < min_bytes_sent; ++i) { con->write(&magic_num,1); } dlog << LTRACE << "shutting down connection to server"; close_gracefully(con); dlog << LTRACE << "finished calling close_gracefully() on the connection"; } catch (exception& e) { srv.error_occurred = true; dlog << LERROR << "exception thrown in thread_proc(): " << e.what(); cout << "exception thrown in thread_proc(): " << e.what(); } dlog << LTRACE << "exit thread"; } }; void run_server(serv* srv) { dlog << LTRACE << "calling srv.start()"; srv->start(); dlog << LTRACE << "srv.start() just ended."; } void sockets_test ( ) /*! requires - sockets is an implementation of sockets/sockets_kernel_abstract.h is instantiated with int ensures - runs tests on sockets for compliance with the specs !*/ { dlog << LTRACE << "starting test"; serv srv; assigned_port = 0; dlog << LTRACE << "spawning threads"; thread_container stuff(srv); thread_function thread2(run_server, &srv); // wait until all the sending threads have ended stuff.wait(); if (srv.error_occurred) { dlog << LDEBUG << "tag: " << srv.tag; } srv.clear(); dlog << LTRACE << "ending successful test"; DLIB_CASSERT( !srv.error_occurred,""); DLIB_CASSERT( srv.got_connections,""); } // ---------------------------------------------------------------------------------------- class sockets_tester : public tester { public: sockets_tester ( ) : tester ("test_sockets", "Runs tests on the sockets component.") {} void perform_test ( ) { sockets_test(); } } a; }
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 245 ] ] ]
6319bd5e84e837fa93b3dc619ff1697c01676085
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_sfinae_pass.cpp
ec36a0ed667d4f6a44444dc4e30acc5cea2e5a42
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004, // by libs/config/tools/generate // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_NO_SFINAE // This file should compile, if it does not then // BOOST_NO_SFINAE needs to be defined. // see boost_no_sfinae.ipp for more details // Do not edit this file, it was generated automatically by // ../tools/generate from boost_no_sfinae.ipp on // Sun Jul 25 11:47:49 GMTDT 2004 // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifndef BOOST_NO_SFINAE #include "boost_no_sfinae.ipp" #else namespace boost_no_sfinae = empty_boost; #endif int main( int, char *[] ) { return boost_no_sfinae::test(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 39 ] ] ]
ad2e1d932241ad0f6808762835aec4f11db20aa1
24bc1634133f5899f7db33e5d9692ba70940b122
/src/ammo/game/server.hpp
e6d107ec2941c37f95ae1d36439b8402223327e1
[]
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
481
hpp
#ifndef SERVER_H_INCLUDED #define SERVER_H_INCLUDED #include "ammo/game/game.hpp" #include "RakNetTypes.h" #include "ammo/game/gameobjects/playerobject.hpp" namespace ammo { class Server : public Game { public: Server(unsigned short portNum, unsigned int maxConns); ~Server(); void Draw(float deltaTime); void Update(float deltaTime); private: std::map<SystemAddress,ammo::PlayerObject*> _players; }; } #endif
[ "PhillipSpiess@d8b90d80-bb63-11dd-bed2-db724ec49875", "j.nick.terry@d8b90d80-bb63-11dd-bed2-db724ec49875" ]
[ [ [ 1, 25 ] ], [ [ 26, 27 ] ] ]
21eee15b4bfd19bf7fb9559a362b2c3e14ad5ddf
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/inl/QxDao/QxDao_CreateTable.inl
a4cf60415dd423acc169d9c20b52b3d841e2aa15
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
1,698
inl
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** 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. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ namespace qx { namespace dao { namespace detail { template <class T> struct QxDao_CreateTable { static QSqlError createTable(QSqlDatabase * pDatabase) { T t; Q_UNUSED(t); qx::dao::detail::QxDao_Helper<T> dao(t, pDatabase, "create table"); if (! dao.isValid()) { return dao.error(); } QString sql = dao.builder().createTable().getSqlQuery(); if (sql.isEmpty()) { return dao.errEmpty(); } if (! dao.query().exec(sql)) { return dao.errFailed(); } return dao.error(); } }; } // namespace detail } // namespace dao } // namespace qx
[ [ [ 1, 51 ] ] ]
a03a2590c8b073ff9e16a4ac17600eeaf0409f0c
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/OggVorbisLib/symbian/oggvorbisfile/OggVorbisFile.h
1aa74cf233ff5384daca3c17ce434e18a7c997b0
[ "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
WINDOWS-1252
C++
false
false
1,764
h
// OggVorbisFile.h // // Copyright © Symbian Software Ltd 2004. All rights reserved. // #ifndef __OGGVORBISFILE_H #define __OGGVORBISFILE_H class COggVorbisFile : public CBase, public MDataSource { class CBody; public: IMPORT_C static COggVorbisFile* NewL(TUid aPlayUid); IMPORT_C ~COggVorbisFile(); IMPORT_C void OpenL(CMMFClip& aClip); // open and verify IMPORT_C TBool IsOpen(); IMPORT_C TTimeIntervalMicroSeconds Duration(); IMPORT_C void PCMOutL(CMMFDataBuffer& aBuffer); IMPORT_C TInt GetDecoderPositionL(); IMPORT_C void SetPositionL(TTimeIntervalMicroSeconds aPos); IMPORT_C TInt GetNumberOfMetaDataEntries(); IMPORT_C CMMFMetaDataEntry* GetMetaDataEntryL(TInt aIndex); IMPORT_C void ResetL(); IMPORT_C void SetSink(MDataSink* aSink); // from MDataSource: virtual TFourCC SourceDataTypeCode(TMediaId aMediaId); virtual void FillBufferL(CMMFBuffer* aBuffer, MDataSink* aConsumer,TMediaId aMediaId); virtual void BufferEmptiedL(CMMFBuffer* aBuffer); virtual TBool CanCreateSourceBuffer(); virtual CMMFBuffer* CreateSourceBufferL(TMediaId aMediaId, TBool &aReference); virtual void ConstructSourceL( const TDesC8& aInitData ); //informational: IMPORT_C TInt SampleRate(); IMPORT_C TInt Channels(); IMPORT_C TInt BytesPerWord(); IMPORT_C TInt BitRate(); IMPORT_C void DbgSetHeapFail(RHeap::TAllocFail aType, TInt aWhen); IMPORT_C void DbgHeapMark(); IMPORT_C void DbgHeapMarkEnd(); private: COggVorbisFile(TUid aPlayUid); void ConstructL(); private: CBody* iBody; }; #endif
[ [ [ 1, 64 ] ] ]
faedc9f10c7b7d5a81e5b0c2afff26ec3a73eb98
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-10-27/pcbnew/router.cpp
9e3d65d11736fc345798e50dc822e0bfe330fb23
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-2
C++
false
false
15,494
cpp
/****************************************/ /* EDITEUR de PCB: Menus d'AUTOROUTAGE: */ /****************************************/ // #define ROUTER #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #include "autorout.h" #include "cell.h" #include "trigo.h" #include "protos.h" #define ROUTER #define PSCALE 1 /* routines externes */ int ReadListeSegmentDescr(wxDC * DC, FILE * File, TRACK * PtSegm,DrawStructureType ItemType, int * LineNum, int NumSegm); /* routines internes */ static void Out_Pads(BOARD * Pcb, FILE * outfile); static int GenEdges(BOARD * Pcb, FILE * outfile); static void GenExistantTracks(BOARD * Pcb, FILE *outfile, int current_net_code, int type); static void ReturnNbViasAndTracks(BOARD * Pcb, int netcode, int * nb_vias, int *nb_tracks); /* variables locales */ static int min_layer, max_layer; /******************************************/ void WinEDA_PcbFrame::GlobalRoute(wxDC * DC) /******************************************/ { #ifdef ROUTER FILE * outfile; wxString FullFileName, ExecFileName, msg; char Line[1024]; int ii; int net_number; #ifdef __UNIX__ ExecFileName = FindKicadFile("anneal"); #else ExecFileName = FindKicadFile("anneal.exe"); #endif /* test de la presence du fichier et execution si present */ if( ! wxFileExists(ExecFileName) ) { sprintf(Line,"routeur <%s> not found", ExecFileName .GetData()); DisplayError(this, Line, 20) ; return; } /* Calcule du nom du fichier intermediaire de communication */ FullFileName = m_CurrentScreen->m_FileName; ChangeFileNameExt(FullFileName,".ipt"); if( (outfile = fopen(FullFileName.GetData(), "wt")) == NULL ) { msg = _("Unable to create temporary file ") + FullFileName; DisplayError(this, msg,20); return; } msg = _("Create temporary file ") + FullFileName; SetStatusText(msg); /* calcul ratsnest */ m_Pcb->m_Status_Pcb = 0 ; Compile_Ratsnest(DC, TRUE); m_Pcb->ComputeBoundaryBox(); // Sortie de la dimension hors tout du pcb (dimensions + marge + pas_route) #define B_MARGE 1000 // en 1/10000 inch fprintf(outfile,"j %d %d %d %d", (-B_MARGE - pas_route + m_Pcb->m_BoundaryBox.GetX() )/PSCALE, (-B_MARGE - pas_route + m_Pcb->m_BoundaryBox.GetY() )/PSCALE, (B_MARGE + pas_route + m_Pcb->m_BoundaryBox.GetRight() )/PSCALE, (B_MARGE + pas_route + m_Pcb->m_BoundaryBox.GetBottom() )/PSCALE); /* calcul du nombre de couches cuivre */ min_layer = 1; /* -> couche soudure = min layer */ max_layer = m_Pcb->m_BoardSettings->m_CopperLayerCount; fprintf(outfile," %d %d", min_layer, max_layer); net_number = m_Pcb->m_NbNets; fprintf(outfile," %d", net_number); fprintf(outfile," %d", pas_route / PSCALE); fprintf(outfile," %d %d %d", /* isolation Pad, track, via */ g_DesignSettings.m_TrackClearence/PSCALE, g_DesignSettings.m_TrackClearence/PSCALE, g_DesignSettings.m_TrackClearence/PSCALE ); fprintf(outfile," 0"); /* via type */ fprintf(outfile," %d", g_DesignSettings.m_CurrentViaSize/PSCALE); /* via diam */ fprintf(outfile," n"); /* via enterree non permise */ fprintf(outfile," 0"); /* unused */ fprintf(outfile," %d", g_DesignSettings.m_CurrentTrackWidth /PSCALE); /* default track width */ fprintf(outfile," 0"); /* unused */ fprintf(outfile," 0 0 0\n"); /* unused */ fprintf(outfile,"k 0 0 0 0 0 0 0 0 0 0\n"); /* spare record */ fprintf(outfile,"m 0 0 0 0 0 0 0 0 0 0\n"); /* cost record */ for ( ii = min_layer; ii <= max_layer; ii++ ) { int dir; dir = 3; /* horizontal */ if (ii & 1 ) dir = 1; /* vertical */ fprintf(outfile,"l %d %d\n", ii, dir); /* layer direction record */ } Out_Pads(m_Pcb, outfile); GenEdges(m_Pcb, outfile); fclose( outfile ); ExecFileName += " " + FullFileName; Affiche_Message(ExecFileName); wxExecute(ExecFileName); #else wxMessageBox("En cours de developpement, non disponible actuellement", "Bientot disponible!"); #endif } /************************************************/ static void Out_Pads(BOARD * Pcb, FILE * outfile) /************************************************/ { D_PAD * pt_pad ; //MODULE * Module; int netcode, mod_num, nb_pads, plink; LISTE_PAD * pt_liste_pad, * pt_start_liste, * pt_end_liste, * pt_liste_pad_limite; int pin_min_layer, pin_max_layer; int no_conn = Pcb->m_NbPads+1; /* valeur incrementee pour indiquer que le pad n'est pas deja connecte a une piste*/ pt_liste_pad = pt_start_liste = Pcb->m_Pads; pt_liste_pad_limite = pt_start_liste + Pcb->m_NbPads; if( pt_liste_pad == NULL ) return; netcode = (*pt_liste_pad)->m_NetCode; nb_pads = 1; plink = 0; for ( ; pt_liste_pad < pt_liste_pad_limite ; ) { /* Recherche de la fin de la liste des pads du net courant */ for( pt_end_liste = pt_liste_pad + 1 ; ; pt_end_liste++) { if (pt_end_liste >= pt_liste_pad_limite ) break ; if ((*pt_end_liste)->m_NetCode != netcode ) break ; nb_pads++; } /* fin de liste trouvee : */ if( netcode > 0 ) { int nb_vias, nb_tracks; ReturnNbViasAndTracks(Pcb, netcode, &nb_vias, &nb_tracks); if ( nb_pads < 2 ) { char Line[256]; EQUIPOT * equipot = GetEquipot(Pcb, netcode); sprintf(Line,"Warning: %d pad, net %s", nb_pads, equipot->m_Netname.GetData()); DisplayError(NULL, Line,20); } fprintf(outfile,"r %d %d %d %d %d %d 1 1\n", netcode, nb_pads, nb_vias+nb_pads, nb_tracks, 0, g_DesignSettings.m_CurrentTrackWidth /PSCALE); } for( ;pt_liste_pad < pt_end_liste ; pt_liste_pad++) { pt_pad = *pt_liste_pad; netcode = pt_pad->m_NetCode; plink = pt_pad->m_physical_connexion; /* plink = numero unique si pad non deja connecte a une piste */ if (plink <= 0 ) plink = no_conn++; if( netcode <= 0 ) /* pad non connecte */ fprintf(outfile,"u 0"); else fprintf(outfile,"p %d", netcode); /* position */ fprintf(outfile," %d %d", pt_pad->m_Pos.x/PSCALE, pt_pad->m_Pos.y/PSCALE); /* layers */ pin_min_layer = 0; pin_max_layer = max_layer; if( (pt_pad->m_Masque_Layer & ALL_CU_LAYERS) == CUIVRE_LAYER ) pin_min_layer = pin_max_layer = min_layer; else if( (pt_pad->m_Masque_Layer & ALL_CU_LAYERS) == CMP_LAYER ) pin_min_layer = pin_max_layer = max_layer; fprintf(outfile," %d %d", pin_min_layer, pin_min_layer); /* link */ fprintf(outfile," %d", plink); /* type of device (1 = IC, 2 = edge conn, 3 = discret, 4 = other */ switch (pt_pad->m_Attribut) { case STANDARD: case SMD: fprintf(outfile," %d", 1); break; case CONN: fprintf(outfile," %d", 2); break; case P_HOLE: case MECA: fprintf(outfile," %d", 4); break; } /* pin number */ fprintf(outfile," %ld", (long)(pt_pad->m_Padname)); /* layer size number (tj = 1) */ fprintf(outfile," %d", 1); /* device number */ mod_num = 1; /* A CHANGER */ fprintf(outfile," %d", mod_num); /* orientations pins 1 et 2 */ fprintf(outfile," x"); /* spare */ fprintf(outfile," 0 0\n"); /* output layer size record */ fprintf(outfile,"q"); switch (pt_pad->m_PadShape) /* out type, dims */ { case CIRCLE: fprintf(outfile," c 0 %d 0", pt_pad->m_Size.x/PSCALE ); break; case OVALE: case RECT: case TRAPEZE: int lmax = pt_pad->m_Size.x; int lmin = pt_pad->m_Size.y; int angle = pt_pad->m_Orient/10; while (angle < 0 ) angle += 180; while (angle > 180 ) angle -= 180; while (angle > 135 ) { angle -= 90; EXCHG(lmax,lmin); } fprintf(outfile," r %d %d %d", angle, lmax /PSCALE, lmin/PSCALE ); break; } /* layers */ fprintf(outfile," %d %d\n", pin_min_layer, pin_max_layer); } /* fin generation liste pads pour 1 net */ if(netcode) { GenExistantTracks(Pcb, outfile, netcode, TYPEVIA); GenExistantTracks(Pcb, outfile, netcode, TYPETRACK); } nb_pads = 1; pt_liste_pad = pt_start_liste = pt_end_liste; if(pt_start_liste < pt_liste_pad_limite) netcode = (*pt_start_liste)->m_NetCode ; } } /**************************************************************************/ /* void ReturnNbViasAndTracks(int netcode, int * nb_vias, int *nb_tracks) */ /**************************************************************************/ /* calcule le nombre de vias et segments de pistes pour le net netcode */ static void ReturnNbViasAndTracks(BOARD * Pcb, int netcode, int * nb_vias, int *nb_tracks) { TRACK * track; *nb_vias = 0; *nb_tracks = 0; track = Pcb->m_Track; if( track == NULL ) return; for ( ; track != NULL ; track = (TRACK*) track->Pnext ) { if( track->m_NetCode > netcode ) return; if( track->m_NetCode != netcode ) continue; if(track->m_StructType == TYPEVIA ) (*nb_vias)++; if(track->m_StructType == TYPETRACK ) (*nb_tracks)++; } } /************************************************/ /* static void GenExistantTracks(FILE *outfile) */ /************************************************/ /* generation des pistes existantes */ static void GenExistantTracks(BOARD * Pcb, FILE *outfile, int current_net_code, int type) { int netcode, plink; int via_min_layer, via_max_layer; TRACK * track; track = Pcb->m_Track; if( track == NULL ) return; for ( ; track != NULL ; track = (TRACK*) track->Pnext ) { netcode = track->m_NetCode; if( netcode > current_net_code ) return; if( netcode != current_net_code ) continue; plink = track->m_Sous_Netcode; via_min_layer = track->m_Layer; if(track->m_StructType != type ) continue; if(track->m_StructType == TYPEVIA ) { via_min_layer &= 15; via_max_layer = (track->m_Layer >> 4) & 15; if (via_min_layer == via_max_layer) { track->m_Layer = 0xF; via_min_layer = 0; via_max_layer = 15; } if( via_max_layer < via_min_layer ) EXCHG(via_max_layer,via_min_layer); if(via_max_layer == CMP_N) via_max_layer = max_layer; else via_max_layer++; if(via_min_layer == CUIVRE_N) via_min_layer = min_layer; else via_min_layer++; fprintf(outfile,"v 0 "); fprintf(outfile," %d %d", track->m_Start.x/PSCALE, track->m_Start.y/PSCALE); fprintf(outfile," %d %d", via_min_layer, via_max_layer); fprintf(outfile," %d", plink); fprintf(outfile," %d\n", 1); /* layer size record */ fprintf(outfile,"q c 0 %d 0 0 0\n", track->m_Width/PSCALE ); } if(track->m_StructType == TYPETRACK ) { fprintf(outfile,"t 0 %d", track->m_Width/PSCALE); fprintf(outfile," %d %d", track->m_Start.x/PSCALE, track->m_Start.y/PSCALE); fprintf(outfile," %d %d", track->m_End.x/PSCALE, track->m_End.y/PSCALE); if(via_min_layer == CMP_N) via_min_layer = max_layer; else via_min_layer++; fprintf(outfile," %d", via_min_layer); fprintf(outfile," %d\n", 1); /*Number of corners */ /* output corner */ fprintf(outfile,"c"); fprintf(outfile," %d %d\n", track->m_End.x/PSCALE, track->m_End.y/PSCALE); } } } /***********************************************/ static int GenEdges(BOARD * Pcb, FILE * outfile) /***********************************************/ /* Generation des contours (edges). Il sont générés comme des segments de piste placés sur chaque couche routable. */ { #define NB_CORNERS 4 EDA_BaseStruct * PtStruct; DRAWSEGMENT * PtDrawSegment; int ii; int dx, dy, width, angle; int ox, oy, fx, fy; wxPoint lim[4]; int NbItems = 0; /* impression des contours */ for ( PtStruct = Pcb->m_Drawings; PtStruct != NULL; PtStruct = PtStruct->Pnext) { if( PtStruct->m_StructType != TYPEDRAWSEGMENT ) continue; PtDrawSegment = (DRAWSEGMENT *) PtStruct; if( PtDrawSegment->m_Layer != EDGE_N) continue; fx = PtDrawSegment->m_End.x;ox = PtDrawSegment->m_Start.x; fy = PtDrawSegment->m_End.y; oy = PtDrawSegment->m_Start.y; dx = fx - ox; dy = fy - oy; if( (dx == 0) && (dy == 0) ) continue; /* elimination des segments non horizontaux, verticaux ou 45 degres, non gérés par l'autorouteur */ if( (dx != 0) && (dy != 0) && (abs(dx) != abs(dy)) ) continue; NbItems++; if( outfile == NULL ) continue; /* car simple decompte des items */ /* generation de la zone interdite */ if( dx < 0 ) { EXCHG(ox,fx); EXCHG(oy,fy); dx = -dx; dy = -dy; } if( (dx == 0) && (dy < 0 ) ) { EXCHG(oy,fy);dy = -dy; } width = PtDrawSegment->m_Width; width += pas_route; angle = - ArcTangente(dy, dx); if (angle % 450)/* not H, V or X */ { wxBell(); continue; } /* 1er point */ dx = -width; dy = - width; RotatePoint(&dx, &dy, angle); lim[0].x = ox + dx; lim[0].y = oy + dy; /* 2eme point */ RotatePoint(&dx, &dy, -900); lim[1].x = fx + dx; lim[1].y = fy + dy; /* 3eme point */ RotatePoint(&dx, &dy, -900); lim[2].x = fx + dx; lim[2].y = fy + dy; /* 4eme point */ RotatePoint(&dx, &dy, -900); lim[3].x = ox + dx; lim[3].y = oy + dy; if ( angle % 900 ) { } /* mise a l'echelle */ for( ii = 0; ii < 4; ii++ ) { lim[ii].x = (int)( ( (double)lim[ii].x + 0.5) / PSCALE); lim[ii].y = (int)( ( (double)lim[ii].y + 0.5) / PSCALE); } /* sortie du 1er point */ fprintf(outfile,"n %d %d %ld %ld %d\n", 0, /* layer number, 0 = all layers */ 0, /* -1 (no via), 0 (no via no track), 1 (no track) */ (long)lim[0].x, (long)lim[0].y, NB_CORNERS); /* sortie des autres points */ for( ii = 1; ii < 4; ii++ ) { fprintf(outfile,"c %ld %ld\n", (long)lim[ii].x, (long)lim[ii].y); } } return NbItems; } /****************************************************/ void WinEDA_PcbFrame::ReadAutoroutedTracks(wxDC * DC) /****************************************************/ { char Line[1024]; wxString FullFileName, msg; int LineNum = 0, nbtracks, NbTrack = 0; FILE * File; /* Calcule du nom du fichier intermediaire de communication */ FullFileName = m_CurrentScreen->m_FileName; ChangeFileNameExt(FullFileName, ".trc"); if( (File = fopen(FullFileName.GetData(),"rt")) == NULL ) { msg = "Impossible de trouver le fichier de routage " + FullFileName; DisplayError(this, msg, 20); return; } else { msg = _("Lecture fichier de routage ") + FullFileName; Affiche_Message(msg); } nbtracks = 0; while( GetLine(File, Line, &LineNum ) != NULL ) { if(strnicmp(Line,"$EndPCB",6) == 0) break; if(strnicmp(Line,"$TRACK",6) == 0) { TRACK * StartTrack = m_Pcb->m_Track; for( ;StartTrack != NULL; StartTrack = (TRACK*)StartTrack->Pnext) { if( StartTrack->Pnext == NULL ) break; } nbtracks = ReadListeSegmentDescr(DC, File, StartTrack, TYPETRACK, &LineNum, NbTrack); m_Pcb->m_NbSegmTrack += nbtracks; break; } } fclose(File); if( nbtracks == 0 ) DisplayError(this, "Warning: No tracks", 10); else { m_Pcb->m_Status_Pcb = 0; m_CurrentScreen->SetModify(); } Compile_Ratsnest(DC, TRUE); if( nbtracks ) m_CurrentScreen->SetRefreshReq(); }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 573 ] ] ]
182e746a1342bf341c0752eb4cc9203c85f7360b
5da9d428805218901d7c039049d7e13a1a2b1c4c
/Vivian/Geometry.h
eef604b2432f48e9c1b94e49585f6056a347192c
[]
no_license
SakuraSinojun/vivianmage
840be972f14e17bb76241ba833318c13cf2b00a4
7a82ee5c5f37d98b86e8d917d9bb20c96a2d6c7f
refs/heads/master
2021-01-22T20:44:33.191391
2010-12-11T15:26:15
2010-12-11T15:26:15
32,322,907
0
0
null
null
null
null
BIG5
C++
false
false
8,890
h
// // SIZE, POINT, RECT 的Wrapper // // #ifndef __Geomtry_h__ #define __Geomtry_h__ class CSize; class CPoint; class CRect; // // CSize class(SIZE的Wrapper) // class CSize: public tagSIZE { public: CSize(); CSize(int cx, int cy); CSize(SIZE size); CSize(DWORD size); BOOL operator==(SIZE size) const; BOOL operator!=(SIZE size) const; void operator+=(SIZE size); void operator-=(SIZE size); CSize operator+(SIZE size) const; CSize operator-(SIZE size) const; CSize operator-() const; } ; // // CPoint class(POINT的Wrapper) // class CPoint: public tagPOINT { public: CPoint(); CPoint(int x, int y); CPoint(POINT point); CPoint(DWORD point); void Offset(int offx, int offy); void Offset(POINT point); void Offset(SIZE size); BOOL operator==(POINT point) const; BOOL operator!=(POINT point) const; void operator+=(SIZE size); void operator-=(SIZE size); void operator+=(POINT point); void operator-=(POINT point); CPoint operator+(SIZE size) const; CPoint operator-(SIZE size) const; CPoint operator-() const; CPoint operator+(POINT point) const; CSize operator-(POINT point) const; } ; // // CRect class(RECT的Wrapper) // #ifdef _GNU_H_WINDOWS32_STRUCTURES class CRect: public _RECT { #else class CRect: public tagRECT { #endif public: CRect(); CRect(int x1, int y1, int x2, int y2); CRect(const RECT &rect); CRect(CPoint point,CSize size); int Width() const; int Height() const; CSize Size() const; CPoint &TopLeft(); CPoint &BottomRight(); const CPoint &TopLeft() const; const CPoint &BottomRight() const; BOOL IsRectEmpty() const; BOOL IsRectNull() const; BOOL PtInRect(POINT point) const; void SetRect(int x1, int y1, int x2, int y2); void SetRectEmpty(); void InflateRect(int x, int y); void InflateRect(SIZE size); void OffsetRect(int x, int y); void OffsetRect(SIZE size); void OffsetRect(POINT point); void NormalizeRect(); void operator=(const RECT &rect); BOOL operator==(const RECT &rect) const; BOOL operator!=(const RECT &rect) const; void operator+=(POINT point); void operator+=(SIZE size); void operator+=(const RECT &rect); void operator-=(POINT point); void operator-=(SIZE size); void operator-=(const RECT &rect); void operator&=(const RECT &rect); void operator|=(const RECT &rect); CRect operator+(POINT point) const; CRect operator-(POINT point) const; CRect operator+(SIZE size) const; CRect operator-(SIZE size) const; CRect operator&(const RECT &rect) const; CRect operator|(const RECT &rect) const; } ; // inline成員函式 inline CSize::CSize() { } inline CSize::CSize(int _cx, int _cy) { cx = _cx; cy = _cy; } inline CSize::CSize(SIZE size) { *(SIZE *)this = size; } inline CSize::CSize(DWORD size) { cx = (short)LOWORD(size); cy = (short)HIWORD(size); } inline BOOL CSize::operator==(SIZE size) const { return (cx == size.cx && cy == size.cy); } inline BOOL CSize::operator!=(SIZE size) const { return (cx != size.cx || cy != size.cy); } inline void CSize::operator+=(SIZE size) { cx += size.cx; cy += size.cy; } inline void CSize::operator-=(SIZE size) { cx -= size.cx; cy -= size.cy; } inline CSize CSize::operator+(SIZE size) const { return CSize(cx + size.cx, cy + size.cy); } inline CSize CSize::operator-(SIZE size) const { return CSize(cx - size.cx, cy - size.cy); } inline CSize CSize::operator-() const { return CSize(-cx, -cy); } inline CPoint::CPoint() { } inline CPoint::CPoint(int _x, int _y) { x = _x; y = _y; } inline CPoint::CPoint(POINT point) { *(POINT *)this = point; } inline CPoint::CPoint(DWORD point) { x = (short)LOWORD(point); y = (short)HIWORD(point); } inline void CPoint::Offset(int offx, int offy) { x += offx; y += offy; } inline void CPoint::Offset(POINT point) { x += point.x; y += point.y; } inline void CPoint::Offset(SIZE size) { x += size.cx; y += size.cy; } inline BOOL CPoint::operator==(POINT point) const { return (x == point.x && y == point.y); } inline BOOL CPoint::operator!=(POINT point) const { return (x != point.x || y != point.y); } inline void CPoint::operator+=(SIZE size) { x += size.cx; y += size.cy; } inline void CPoint::operator-=(SIZE size) { x -= size.cx; y -= size.cy; } inline void CPoint::operator+=(POINT point) { x += point.x; y += point.y; } inline void CPoint::operator-=(POINT point) { x -= point.x; y -= point.y; } inline CPoint CPoint::operator+(SIZE size) const { return CPoint(x + size.cx, y + size.cy); } inline CPoint CPoint::operator-(SIZE size) const { return CPoint(x - size.cx, y - size.cy); } inline CPoint CPoint::operator-() const { return CPoint(-x, -y); } inline CPoint CPoint::operator+(POINT point) const { return CPoint(x + point.x, y + point.y); } inline CSize CPoint::operator-(POINT point) const { return CSize(x - point.x, y - point.y); } inline CRect::CRect() { } inline CRect::CRect(int x1, int y1, int x2, int y2) { left = x1; top = y1; right = x2; bottom = y2; } inline CRect::CRect(const RECT &rect) { left = rect.left; top = rect.top; right = rect.right; bottom = rect.bottom; } inline CRect::CRect (CPoint point,CSize size) { left=point.x; top=point.y; right=point.x+size.cx; bottom=point.y+size.cy; } inline int CRect::Width() const { return right - left; } inline int CRect::Height() const { return bottom - top; } inline CSize CRect::Size() const { return CSize(right - left, bottom - top); } inline CPoint &CRect::TopLeft() { return *((CPoint *)this); } inline CPoint &CRect::BottomRight() { return *((CPoint *)this + 1); } inline const CPoint &CRect::TopLeft() const { return *((CPoint *)this); } inline const CPoint &CRect::BottomRight() const { return *((CPoint *)this + 1); } inline BOOL CRect::IsRectEmpty() const { return (left == right || top == bottom); } inline BOOL CRect::IsRectNull() const { return (left == 0 && right == 0 && top == 0 && bottom == 0); } inline BOOL CRect::PtInRect(POINT point) const { return ::PtInRect(this, point); } inline void CRect::SetRect(int x1, int y1, int x2, int y2) { left = x1; top = y1; right = x2; bottom = y2; } inline void CRect::SetRectEmpty() { left = top = right = bottom = 0; } inline void CRect::InflateRect(int x, int y) { ::InflateRect(this, x, y); } inline void CRect::InflateRect(SIZE size) { ::InflateRect(this, size.cx, size.cy); } inline void CRect::OffsetRect(int x, int y) { ::OffsetRect(this, x, y); } inline void CRect::OffsetRect(POINT point) { ::OffsetRect(this, point.x, point.y); } inline void CRect::OffsetRect(SIZE size) { ::OffsetRect(this, size.cx, size.cy); } inline void CRect::operator=(const RECT &srcRect) { ::CopyRect(this, &srcRect); } inline BOOL CRect::operator==(const RECT &rect) const { return ::EqualRect(this, &rect); } inline BOOL CRect::operator!=(const RECT &rect) const { return !::EqualRect(this, &rect); } inline void CRect::operator+=(POINT point) { ::OffsetRect(this, point.x, point.y); } inline void CRect::operator+=(SIZE size) { ::OffsetRect(this, size.cx, size.cy); } inline void CRect::operator+=(const RECT &rect) { left += rect.left; top += rect.top; right += rect.right; bottom += rect.bottom; } inline void CRect::operator-=(POINT point) { ::OffsetRect(this, -point.x, -point.y); } inline void CRect::operator-=(SIZE size) { ::OffsetRect(this, -size.cx, -size.cy); } inline void CRect::operator-=(const RECT &rect) { left -= rect.left; top -= rect.top; right -= rect.right; bottom -= rect.bottom; } inline void CRect::operator&=(const RECT &rect) { ::IntersectRect(this, this, &rect); } inline void CRect::operator|=(const RECT &rect) { ::UnionRect(this, this, &rect); } inline CRect CRect::operator+(POINT pt) const { CRect rect(*this); ::OffsetRect(&rect, pt.x, pt.y); return rect; } inline CRect CRect::operator-(POINT pt) const { CRect rect(*this); ::OffsetRect(&rect, -pt.x, -pt.y); return rect; } inline CRect CRect::operator+(SIZE size) const { CRect rect(*this); ::OffsetRect(&rect, size.cx, size.cy); return rect; } inline CRect CRect::operator-(SIZE size) const { CRect rect(*this); ::OffsetRect(&rect, -size.cx, -size.cy); return rect; } inline CRect CRect::operator&(const RECT &rect2) const { CRect rect; ::IntersectRect(&rect, this, &rect2); return rect; } inline CRect CRect::operator|(const RECT &rect2) const { CRect rect; ::UnionRect(&rect, this, &rect2); return rect; } #endif
[ "SakuraSinojun@c9cc3ed0-94a9-11de-b6d4-8762f465f3f9" ]
[ [ [ 1, 494 ] ] ]
efbc869a0cd6b3fec55c33f10675c7bf943ed0f2
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SRC/DRIVERS/DISPLAY/DISPLAY_DRV/dispmode.cpp
20801ef4ffcbc010d35cb0008520985f7f5ef0a5
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
4,128
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this source code is subject to the terms of the Microsoft end-user // license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. // If you did not accept the terms of the EULA, you are not authorized to use // this source code. For a copy of the EULA, please see the LICENSE.RTF on your // install media. // // Copyright (c) Samsung Electronics. Co. LTD. All rights reserved. /*++ THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Module Name: dispmode.cpp Abstract: This module implement the main class that derived from DDGPE of display driver to support DirectDraw In this part, there are codes related with Display Mode Functions: DrvGetMask, SetMode, GetModeInfoEx, ... Notes: --*/ #include "precomp.h" #if (LCD_BPP == 16) ULONG gBitMasks[] = {0xF800, 0x07E0, 0x001F}; #elif (LCD_BPP == 32) ULONG gBitMasks[] = {0x00FF0000, 0x0000FF00, 0x000000FF}; #else #error LCD_BPP_UNDEFINED #endif ULONG * APIENTRY DrvGetMasks( DHPDEV dhpdev ) { return gBitMasks; } SCODE S3C6410Disp::SetMode (INT modeId, HPALETTE *palette) { SCODE scRet = S_OK; RETAILMSG(DISP_ZONE_ENTER, (_T("[DISPDRV] ++%s(%d)\n\r"), _T(__FUNCTION__), modeId)); if (modeId == 0) { m_dwPhysicalModeID = m_pMode->modeId; // Create Palette if (palette) { *palette = EngCreatePalette(PAL_BITFIELDS, 0, NULL, gBitMasks[0], gBitMasks[1], gBitMasks[2]); } } else { RETAILMSG(DISP_ZONE_ERROR, (_T("[DISPDRV:ERR] %s() : modeId = %d, Driver Support Only Mode 0\n\r"), _T(__FUNCTION__), modeId)); scRet = E_INVALIDARG; } RETAILMSG(DISP_ZONE_ENTER,(_T("[DISPDRV] --%s()\n\r"), _T(__FUNCTION__))); return scRet; } SCODE S3C6410Disp::GetModeInfo(GPEMode *mode, int modeNo) { if (modeNo != 0) { RETAILMSG(DISP_ZONE_ERROR, (_T("[DISPDRV:ERR] GetModeInfo() : modeNo = %d, Driver Support Only Mode 0\n\r"), modeNo)); return E_INVALIDARG; } *mode = *m_pMode; return S_OK; } SCODE S3C6410Disp::GetModeInfoEx(GPEModeEx *pModeEx, int modeNo) { if (modeNo != 0) { RETAILMSG(DISP_ZONE_ERROR, (_T("[DISPDRV:ERR] GetModeInfoEx() : modeNo = %d, Driver Support Only Mode 0\n\r"), modeNo)); return E_INVALIDARG; } *pModeEx = *m_pModeEx; return S_OK; } int S3C6410Disp::NumModes() { return MAX_SUPPORT_MODE; } void S3C6410Disp::InitializeDisplayMode() { //Setup ModeInfoEx, ModeInfo m_pModeEx = &m_ModeInfoEx; m_pMode = &m_ModeInfoEx.modeInfo; memset(m_pModeEx, 0, sizeof(GPEModeEx)); #if (LCD_BPP == 16) m_pModeEx->ePixelFormat = ddgpePixelFormat_565; #elif (LCD_BPP == 32) m_pModeEx->ePixelFormat = ddgpePixelFormat_8888; #endif // Fill GPEMode modeInfo m_pMode->modeId = 0; m_pMode->width = m_nScreenWidth; m_pMode->height = m_nScreenHeight; m_pMode->format = EDDGPEPixelFormatToEGPEFormat[m_pModeEx->ePixelFormat]; m_pMode->Bpp = EGPEFormatToBpp[m_pMode->format]; m_pMode->frequency = 60; // Usually LCD Panel require 60Hz // Fill DDGPEStandardHeader m_pModeEx->dwSize = sizeof(GPEModeEx); m_pModeEx->dwVersion = GPEMODEEX_CURRENTVERSION; // Fill ModeInfoEX m_pModeEx->dwPixelFourCC = 0; // Should be Zero m_pModeEx->dwPixelFormatData = 0; // Don't care m_pModeEx->lPitch = m_dwDeviceScreenWidth*(m_pMode->Bpp/8); m_pModeEx->dwFlags = 0; // Should be Zero m_pModeEx->dwRBitMask = gBitMasks[0]; m_pModeEx->dwGBitMask = gBitMasks[1]; m_pModeEx->dwBBitMask = gBitMasks[2]; m_pModeEx->dwAlphaBitMask = 0x00000000; }
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 154 ] ] ]
19f898dbff16bd33fed2eddbdd962d99505a1b4e
90c0655f3ad1e3ce9f0822eda11bd6be58a29f57
/src/Cliente.cpp
76347a95adcd26f570bd5806f526c35c5c90e7a8
[]
no_license
rocanaan/proj-aguiar-2011
46cb8f68f6701bd7f499f21687ce8d0e3d6d111a
fcb13adcca01c1472c53caffe22c0f3ebafe9a10
refs/heads/master
2021-01-01T16:39:05.692522
2011-07-05T03:31:41
2011-07-05T03:31:41
34,010,824
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,111
cpp
#include "include\Cliente.h" #include <iostream> #include <cstdlib> #include <string> using namespace std; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //-----------------------------------Contrutores ----------------------------------------------------------------// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Cliente::Cliente() { this->id = 0; this->fila = 0; this->interrompido = 0; } Cliente::Cliente(int pid,double instante_chegada, int pfila, int rodada_atual) { this->id = pid; this->fila = pfila; this->interrompido = false; this->instante_chegada1 = instante_chegada; this->direto_ao_servidor = false; this->rodada_pertencente = rodada_atual; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------Funções Membro-------------------------------------------------------// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int Cliente::GetFila() { return fila; } int Cliente::SetFila(int pfila) { this->fila = pfila; } double Cliente::GetTempoRestante() { return tempo_restante; } double Cliente::SetTempoRestante(double ptempo_restante) { this->tempo_restante = ptempo_restante; } bool Cliente::VerificaInterrompido() { return interrompido; } void Cliente::Interromper() { this->interrompido = true; } void Cliente::SetInstanteChegada2(double t) { this->instante_chegada2=t; } void Cliente::SetDuracaoPrimeiroServico(double duracao) { this->duracao_primeiro_servico=duracao; } void Cliente::SetDuracaoSegundoServico(double duracao) { this->duracao_segundo_servico=duracao; } void Cliente::SetInstanteSaida(double t) { this->instante_saida=t; } int Cliente::GetID() { return id; } void Cliente::SetDiretoAoServidor(bool pbool) { this->direto_ao_servidor = pbool; } bool Cliente::GetDiretoAoServidor() { return direto_ao_servidor; } int Cliente::GetRodadaPertencente() { return rodada_pertencente; } double Cliente::W1() { return instante_chegada2 - instante_chegada1 - duracao_primeiro_servico; } double Cliente::T1() { return instante_chegada2 - instante_chegada1; } double Cliente::W2() { return instante_saida - instante_chegada2 - duracao_segundo_servico; } double Cliente::T2() { return instante_saida - instante_chegada2; }
[ "[email protected]@cedf45fa-8354-0ca4-fa20-ed59a3261951", "[email protected]@cedf45fa-8354-0ca4-fa20-ed59a3261951", "[email protected]@cedf45fa-8354-0ca4-fa20-ed59a3261951" ]
[ [ [ 1, 12 ], [ 21, 21 ], [ 28, 28 ], [ 30, 36 ], [ 102, 106 ] ], [ [ 13, 13 ] ], [ [ 14, 20 ], [ 22, 27 ], [ 29, 29 ], [ 37, 101 ], [ 107, 125 ] ] ]
3b8a22a973116a92866b29368efa6993c9599780
c7fd308ee062c23e1b036b84bbf890c3f7e74fc4
/UtahTeapot/main.cpp
adf293e6e8a6d03644b0a838ad40138791c2a90e
[]
no_license
truenite/truenite-opengl
805881d06a5f6ef31c32235fb407b9a381a59ed9
157b0e147899f95445aed8f0d635848118fce8b6
refs/heads/master
2021-01-10T01:59:35.796094
2011-05-06T02:03:16
2011-05-06T02:03:16
53,160,700
0
0
null
null
null
null
UTF-8
C++
false
false
2,486
cpp
#include <windows.h> #include <GL/glut.h> float rotationX=0.0; float rotationY=0.0; float prevX=0.0; float prevY=0.0; bool mouseDown=false; float viewer[]= {0.0, 0.0, 3.0}; float angle=0.0; int displayMode=1; void teapot(void){ glPushMatrix(); glRotatef(angle,0,1,0); if(displayMode==1) glutWireTeapot(0.5); else glutSolidTeapot(0.5); glPopMatrix(); } void display(void){ glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(viewer[0],viewer[1],viewer[2],0,0,0,0,1,0); glRotatef(rotationX,1,0,0); glRotatef(rotationY,0,1,0); teapot(); glutSwapBuffers(); } void reshape(int w, int h){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, (GLdouble)w/(GLdouble)h, 1.0, 100.0); glViewport(0,0,w,h); } void idle(){ angle += 1; glutPostRedisplay(); } void mouse(int button, int state, int x, int y){ if(button == GLUT_LEFT_BUTTON && state==GLUT_DOWN){ mouseDown = true; prevX = x - rotationY; prevY = y - rotationX; }else{ mouseDown = false; } } void mouseMotion(int x, int y){ if(mouseDown){ rotationX = y - prevY; rotationY = x - prevX; glutPostRedisplay(); } } void key(unsigned char key, int x, int y) { if(key == 'x') viewer[0]-= 0.1; if(key == 'X') viewer[0]+= 0.1; if(key == 'y') viewer[1]-= 0.1; if(key == 'Y') viewer[1]+= 0.1; if(key == 'z') viewer[2]-= 0.1; if(key == 'Z') viewer[2]+= 0.1; glutPostRedisplay(); } void menu(int val){ displayMode=val; glutPostRedisplay(); } int addMenu(){ int mainMenu, subMenu1; mainMenu = glutCreateMenu(menu); subMenu1 = glutCreateMenu(menu); glutSetMenu(mainMenu); glutAddSubMenu("Display mode", subMenu1); glutSetMenu(subMenu1); glutAddMenuEntry("Wireframe", 1); glutAddMenuEntry("Solid", 2); glutSetMenu(mainMenu); glutAttachMenu(GLUT_RIGHT_BUTTON); } int main(int argc, char **argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutCreateWindow("Utah Teapot"); glutInitWindowSize(500,500); glutDisplayFunc(display); glutReshapeFunc(reshape); glutIdleFunc(idle) ; glutMouseFunc(mouse); glutMotionFunc(mouseMotion); glutKeyboardFunc(key); addMenu(); glutMainLoop(); }
[ [ [ 1, 112 ] ] ]
5f3a42348f7f1f34256f48fedaef26f78444a355
216e2f8055a0bc2c5a08bb0cbb208a84c6b22baa
/src/glfMultiples/glfMultiples/Main.cpp
62dcc38f0f306a46617cc244f40efccc0756b835
[]
no_license
hagax8/statgen
014aae02f892ffd8f927259b70899a8d4f26c40f
1052ccdaae88787b616f67d436a0ec0be3a1b92e
refs/heads/master
2021-05-27T00:42:59.468450
2011-03-01T21:38:45
2011-03-01T21:38:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,120
cpp
/* * Copyright (C) 2008-2011 Regents of the University of Michigan * * 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, see <http://www.gnu.org/licenses/>. */ #include "BaseQualityHelper.h" #include "GlfLikelihoods.h" #include "StringArray.h" #include "StringAlias.h" #include "Parameters.h" #include "Pedigree.h" #include "Error.h" #include <math.h> #include <time.h> FILE * baseCalls = NULL; void ReportDate(FILE * output) { if (output == NULL) return; time_t systemTime; time(&systemTime); tm * digestedTime; digestedTime = gmtime(&systemTime); fprintf(output, "##filedate=%04d%02d%02d\n", digestedTime->tm_year + 1900, digestedTime->tm_mon + 1, digestedTime->tm_mday); } void DumpDetails(glfHandler * glf, int n, int position, int refBase) { char alleles[] = { 0, 'a', 'c', 'g', 't' }; int firstGlf = 0; while (glf[firstGlf].isStub) firstGlf++; printf("Dump for section %s, position %d [%c]\n", (const char *) glf[firstGlf].label, position, alleles[refBase]); printf("Depth"); for (int i = 0; i < n; i++) printf("\t%d", glf[i].GetDepth(position)); printf("\n"); printf("MapQ"); for (int i = 0; i < n; i++) printf("\t%d", glf[i].GetMapQuality(position)); printf("\n"); for (int i = 1, index = 0; i <= 4; i++) for (int j = i; j <= 4; j++, index++) { printf("%c/%c", alleles[i], alleles[j]); for (int k = 0; k < n; k++) printf("\t%d", glf[k].GetLogLikelihoods(position)[index]); printf("\n"); } } int GetBestGenotype(const double likelihoods[], const double priors[]) { int best = 0; for (int i = 1; i < 10; i++) if (likelihoods[i] * priors[i] > likelihoods[best] * priors[best]) best = i; return best; } const char * GetBestGenotypeLabel(const double likelihoods[], const double priors[]) { const char * genotypeLabel[10] = {"A/A", "A/C", "A/G", "A/T", "C/C", "C/G", "C/T", "G/G", "G/T", "T/T"}; return genotypeLabel[GetBestGenotype(likelihoods, priors)]; } int GetBestRatio(const double likelihoods[], const double priors[]) { double sum = 0.0; int best = 0; for (int i = 1; i < 10; i++) if (likelihoods[i] * priors[i] > likelihoods[best] * priors[best]) best = i; for (int i = 0; i < 10; i++) sum += likelihoods[i] * priors[i]; double error = 1.0 - likelihoods[best] * priors[best]/sum; if (error < 0.0000000001) return 100; return int (-log10(error) * 10 + 0.5); } void ReportGenotypes(GenotypeLikelihood & lk, glfHandler * glf, int n, int position, int refAllele, int al1, int al2) { if (baseCalls == NULL) return; double priors[10]; lk.GetPriors(priors, lk.min); int geno11 = glfHandler::GenotypeIndex(al1, al1); int geno12 = glfHandler::GenotypeIndex(al1, al2); int geno22 = glfHandler::GenotypeIndex(al2, al2); int label1 = al1 == refAllele ? 0 : 1; int label2 = al2 == refAllele ? 0 : al1 == al2 ? label1 : label1 + 1; int genoRR = 0; int genoR1 = 0; int genoR2 = 0; if (label2 == 2) { genoRR = glfHandler::GenotypeIndex(refAllele, refAllele); genoR1 = glfHandler::GenotypeIndex(refAllele, al1); genoR2 = glfHandler::GenotypeIndex(refAllele, al2); } String label11, label12, label22; label11.printf("%d/%d", label1, label1); label12.printf("%d/%d", label1, label2); label22.printf("%d/%d", label2, label2); // fprintf(baseCalls, "\t%.3f", lk.min); for (int i = 0; i < n; i++) { // Report on the best genotype for the current SNP model int quality = GetBestRatio(glf[i].GetLikelihoods(position), priors); int best = GetBestGenotype(glf[i].GetLikelihoods(position), priors); fprintf(baseCalls, "\t%s:%d:%d", (const char *) (best == geno11 ? label11 : best == geno12 ? label12 : label22), glf[i].GetDepth(position), quality); if (label1 == 0 && label2 == 0) continue; if (label2 < 2) fprintf(baseCalls, ":%d,%d,%d", glf[i].GetLogLikelihoods(position)[geno11], glf[i].GetLogLikelihoods(position)[geno12], glf[i].GetLogLikelihoods(position)[geno22]); else fprintf(baseCalls, ":%d,%d,%d,%d,%d,%d", glf[i].GetLogLikelihoods(position)[genoRR], glf[i].GetLogLikelihoods(position)[genoR1], glf[i].GetLogLikelihoods(position)[geno11], glf[i].GetLogLikelihoods(position)[genoR2], glf[i].GetLogLikelihoods(position)[geno12], glf[i].GetLogLikelihoods(position)[geno22]); } fprintf(baseCalls, "\n"); } void ReportSNP(glfHandler * glf, int n, int position, int refBase, int allele1, int allele2, const char * filter, int totalCoverage, int averageMapQuality, double posterior) { if (baseCalls == NULL) return; if (allele2 == refBase) { int swap = allele1; allele1 = allele2; allele2 = swap; } char alleles[] = { 0, 'a', 'c', 'g', 't' }; // Find the location of the first non-stub glf int firstGlf = 0; while (glf[firstGlf].isStub) firstGlf++; // #Chrom Pos Id fprintf(baseCalls, "%s\t%d\t.\t", (const char *) glf[firstGlf].label, position + 1); // Reference allele int nalleles = 1; fprintf(baseCalls, "%c\t", alleles[refBase]); // Other alleles if (allele1 != refBase) fprintf(baseCalls, "%c", alleles[allele1]), nalleles++; if (allele2 != refBase && allele2 != allele1) fprintf(baseCalls, "%s%c", nalleles > 1 ? "," : "", alleles[allele2]), nalleles++; if (nalleles == 1) fprintf(baseCalls, "."); fprintf(baseCalls, "\t"); int quality = posterior > 0.9999999999 ? 100 : -10 * log10(1.0 - posterior); // Quality for this call fprintf(baseCalls, "%d\t", quality); // Filter for this call fprintf(baseCalls, "%s\t", filter == NULL || filter[0] == 0 ? "PASS" : filter); GenotypeLikelihood lk; // Find best frequency lk.glf = glf; lk.n = n; lk.position = position; lk.SetAlleles(allele1, allele2); lk.OptimizeFrequency(); double af = 1.0 - lk.min; // Information for this call fprintf(baseCalls, "depth=%d;mapQ=%d;", totalCoverage, averageMapQuality); if (allele1 != refBase) fprintf(baseCalls, "AF=%.6lf,%.6lf\t", 1.0 - af, af); else fprintf(baseCalls, "AF=%.6lf\t", af); // Format for this call fprintf(baseCalls, "GT:DP:GQ"); if ((allele2 != refBase) || (allele1 != refBase)) { fprintf(baseCalls, ":PL%s", allele1 == refBase ? "" : "3"); } ReportGenotypes(lk, glf, n, position, refBase, allele1, allele2); } double FilteringLikelihood (glfHandler * glf, int n, int position, int refAllele) { FilterLikelihood lk; lk.glf = glf; lk.n = n; lk.position = position; lk.SetReferenceAllele(refAllele); lk.OptimizeFrequency(); return -lk.fmin; } double PolymorphismLikelihood (glfHandler * glf, int n, int position, int refAllele, int mutAllele) { GenotypeLikelihood lk; lk.glf = glf; lk.n = n; lk.position = position; lk.SetAlleles(refAllele, mutAllele); lk.OptimizeFrequency(); return -lk.fmin; } double SinkLikelihood (glfHandler * glf, int n, int position) { double lk = 0.0; double scale = -log(10.0) / 10; for (int r = 1; r <= 4; r++) for (int m = r + 1; m <= 4; m++) { int geno = glfHandler::GenotypeIndex(r, m); double partial = log(1.0 / 6.0); for (int i = 0; i < n; i++) partial += glf[i].GetLogLikelihoods(position)[geno] * scale; if (lk == 0.0) { lk = partial; continue; } double max = partial > lk ? partial : lk; double min = partial > lk ? lk : partial; if (max - min > 50) lk = max; else lk = log(exp(partial - min) + exp(lk - min)) + min; } return lk; } int main(int argc, char ** argv) { printf("glfMultiples -- SNP calls based on .glf or .glz files\n"); printf("(c) 2008-2011 Goncalo Abecasis, Sebastian Zoellner, Yun Li\n\n"); String pedfile; String positionfile; String callfile; String glfAliases; String glfPrefix; String glfSuffix; ParameterList pl; double posterior = 0.50; int mapQuality = 60; int minTotalDepth = 1; int maxTotalDepth = 1000; bool verbose = false; bool mapQualityStrict = false; bool hardFilter = false; bool smartFilter = false; bool softFilter = true; bool robustPrior = true; bool uniformPrior = false; String xLabel("X"), yLabel("Y"), mitoLabel("MT"); int xStart = 2699520, xStop = 154931044; BEGIN_LONG_PARAMETERS(longParameters) LONG_PARAMETER_GROUP("Pedigree File") LONG_STRINGPARAMETER("ped", &pedfile) LONG_PARAMETER_GROUP("Map Quality Filter") LONG_INTPARAMETER("minMapQuality", &mapQuality) LONG_PARAMETER("strict", &mapQualityStrict) LONG_PARAMETER_GROUP("Total Depth Filter") LONG_INTPARAMETER("minDepth", &minTotalDepth) LONG_INTPARAMETER("maxDepth", &maxTotalDepth) LONG_PARAMETER_GROUP("Position Filter") LONG_STRINGPARAMETER("positionFile", &positionfile) LONG_PARAMETER_GROUP("Chromosome Labels") LONG_STRINGPARAMETER("xChr", &xLabel) LONG_STRINGPARAMETER("yChr", &yLabel) LONG_STRINGPARAMETER("mito", &mitoLabel) LONG_INTPARAMETER("xStart", &xStart) LONG_INTPARAMETER("xStop", &xStop) LONG_PARAMETER_GROUP("Filtering Options") EXCLUSIVE_PARAMETER("hardFilter", &hardFilter) EXCLUSIVE_PARAMETER("smartFilter", &smartFilter) EXCLUSIVE_PARAMETER("softFilter", &softFilter) LONG_PARAMETER_GROUP("Prior Options") EXCLUSIVE_PARAMETER("uniformPrior", &uniformPrior) EXCLUSIVE_PARAMETER("robustPrior", &robustPrior) LONG_PARAMETER_GROUP("Output") LONG_PARAMETER("verbose", &verbose) LONG_PARAMETER_GROUP("Sample Names") LONG_STRINGPARAMETER("glfAliases", &glfAliases) LONG_PARAMETER_GROUP("Prefixes and Suffixes") LONG_STRINGPARAMETER("glfPrefix",&glfPrefix) LONG_STRINGPARAMETER("glfSuffix",&glfSuffix) END_LONG_PARAMETERS(); pl.Add(new StringParameter('b', "Base Call File", callfile)); pl.Add(new DoubleParameter('p', "Posterior Threshold", posterior)); pl.Add(new LongParameters("Additional Options", longParameters)); int argstart = pl.ReadWithTrailer(argc, argv) + 1; pl.Status(); if (posterior < 0.50) error("Posterior threshold for genotype calls (-p option) must be > 0.50."); time_t t; time(&t); printf("Analysis started on %s\n", ctime(&t)); fflush(stdout); int n = argc - argstart; argv += argstart; Pedigree ped; if (!pedfile.IsEmpty()) { ped.pd.AddStringColumn("glfFile"); ped.Load(pedfile); n = ped.count; } else if (n == 0) error("No pedigree file present and no glf files listed at the end of command line\n"); // Prior for finding difference from the reference at a particular site double prior = 0.0; for (int i = 1; i <= 2 * n; i++) prior += 1.0 / i; prior *= 0.001; glfHandler * glf = new glfHandler[n]; bool firstGlf = n; if (ped.count) { bool warn = false; for (int i = n - 1; i > 0; i++) { if (!glf[i].Open(ped[i].strings[0])) { printf("Failed to open genotype likelihood file [%s] for individual %s:%s\n", (const char *) ped[i].strings[0], (const char *) ped[i].famid, (const char *) ped[i].pid); glf[i].OpenStub(); firstGlf = i; } if (warn) printf("\n"); if (firstGlf == n) error("No genotype likelihood files could be opened"); } } else { for (int i = firstGlf = 0; i < n; i++) { String glfName = glfPrefix + String(argv[i]) + glfSuffix; if (!glf[i].Open(glfName)) error("Failed to open genotype likelihood file [%s]\n", glfName.c_str()); } } StringAlias aliases; aliases.ReadFromFile(glfAliases); printf("Calling genotypes for files ...\n"); for (int i = 0; i < n; i++) printf("%s\n", ped.count ? (const char *) ped[i].strings[0] : argv[i]); printf("\n"); baseCalls = fopen(callfile, "wt"); if (baseCalls != NULL) { fprintf(baseCalls, "##fileformat=VCFv4.0\n"); ReportDate(baseCalls); fprintf(baseCalls, "##source=glfMultiples\n"); fprintf(baseCalls, "##minDepth=%d\n", minTotalDepth); fprintf(baseCalls, "##maxDepth=%d\n", maxTotalDepth); fprintf(baseCalls, "##minMapQuality=%d\n", mapQuality); fprintf(baseCalls, "##minPosterior=%.4f\n", posterior); fprintf(baseCalls, "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Total Depth\">\n"); fprintf(baseCalls, "##INFO=<ID=AF,Number=.,Type=Float,Description=\"Alternate Allele Frequency\">\n"); fprintf(baseCalls, "##INFO=<ID=mapQ,Number=1,Type=Integer,Description=\"Root Mean Squared Mapping Quality\">\n"); fprintf(baseCalls, "##FILTER=<ID=mapQ,Description=\"Mapping Quality Below Threshold\">\n"); fprintf(baseCalls, "##FILTER=<ID=depth,Description=\"Read Depth Too High or Too Low\">\n"); fprintf(baseCalls, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Most Likely Genotype\">\n"); fprintf(baseCalls, "##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Call Quality\">\n"); fprintf(baseCalls, "##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth\">\n"); fprintf(baseCalls, "##FORMAT=<ID=PL,Number=3,Type=Integer,\"Genotype Likelihoods for Genotypes 0/0,0/1,1/1\">\n"); fprintf(baseCalls, "##FORMAT=<ID=PL3,Number=6,Type=Integer,\"Genotype Likelihoods for Genotypes 0/0,0/1,1/1,0/2,1/2,2/2\">\n"); fprintf(baseCalls, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT"); for (int i = 0; i < n; i++) fprintf(baseCalls, "\t%s", ped.count ? (const char *) (ped[i].famid + ":" + ped[i].pid) : (const char *) aliases.GetAlias(argv[i])); fprintf(baseCalls, "\n"); } StringArray buffer, tokens; StringHash positions; buffer.Read(positionfile); for (int i = 0; i < buffer.Length(); i++) { tokens.ReplaceTokens(buffer[i], " \t:"); if (tokens.Length() != 2) continue; positions.Add(tokens[0] + ":" + (int(tokens[1].AsInteger() - 1))); } int chromosomeType = 0; while (glf[firstGlf].NextSection()) { for (int i = firstGlf + 1; i < n; i++) { if (glf[i].isStub) continue; glf[i].NextSection(); if (glf[firstGlf].maxPosition != glf[i].maxPosition || glf[firstGlf].label != glf[i].label) { error("Genotype files '%s' and '%s' are not compatible ...\n" " File '%s' has section %s with %d entries ...\n" " File '%s' section %s with %d entries ...\n", ped.count ? (const char *) ped[firstGlf].strings[0] : argv[firstGlf], ped.count ? (const char *) ped[i].strings[0] : argv[i], ped.count ? (const char *) ped[firstGlf].strings[0] : argv[firstGlf], (const char *) glf[firstGlf].label, glf[firstGlf].maxPosition, ped.count ? (const char *) ped[i].strings[0] : argv[i], (const char *) glf[i].label, glf[i].maxPosition); } } chromosomeType = CT_AUTOSOME; if (ped.count) { if (glf[firstGlf].label == xLabel) chromosomeType = CT_CHRX; if (glf[firstGlf].label == yLabel) chromosomeType = CT_CHRY; if (glf[firstGlf].label == mitoLabel) chromosomeType = CT_MITO; } printf("Processing section %s with %d entries\n", (const char *) glf[firstGlf].label, glf[firstGlf].maxPosition); int refBase = 0; int position = 0; int mapQualityFilter = 0; int depthFilter = 0; int homozygousReference = 0; int transitions = 0; int transversions = 0; int otherPolymorphisms = 0; int sinkFilter = 0; int smartFilterHits = 0; int baseCounts[5] = {0, 0, 0, 0, 0}; String filter; while (true) { if (position > 0) { // Check whether we have reached the end of the current chromosome bool done = true; for (int i = 0; i < n; i++) if (glf[i].data.recordType != 0) done = false; if (done) break; } // Advance to the next position where needed for (int i = 0; i < n; i++) if (glf[i].position == position) glf[i].NextBaseEntry(); // Figure out the current analysis position refBase = glf[0].data.refBase; position = glf[0].position; for (int i = 1; i < n; i++) if (position > glf[i].position) { position = glf[i].position; refBase = glf[i].data.refBase; } // Avoid alignments that extend past the end of the chromosome if (position >= glf[firstGlf].maxPosition) break; baseCounts[refBase]++; // These lines can be uncommented for debugging purposes // for (int i = 0; i < n; i++) // printf("GLF %d : position %d, refBase %d\n", i, position, refBase); // printf("Position: %d, refBase: %d\n", position, refBase); if (positions.Entries()) { filter = glf[firstGlf].label + ":" + position; if (positions.Find(filter) < 0) continue; } if (refBase == 0) continue; // Corrected calculation of root-mean-square Map Quality score // and check if we have at least one sample with good quality data int currentDepth = 0, totalDepth = 0, numCovered = 0; double currentQuality = 0.0, averageMapQuality = 0.0; bool passMapQualityFilter = false; for (int i = 0; i < n; i++) { currentDepth = glf[i].GetDepth(position); if (currentDepth != 0) { totalDepth += currentDepth; numCovered++; // not currently used -- will be "NS" currentQuality = glf[i].GetMapQuality(position); averageMapQuality += currentDepth * currentQuality * currentQuality; if (currentQuality >= mapQuality) passMapQualityFilter = true; } } averageMapQuality = sqrt(averageMapQuality / totalDepth); filter.Clear(); if (!passMapQualityFilter) { if (filter.Length() == 0) mapQualityFilter++; if (hardFilter) continue; filter.catprintf("%smapQ<%d", filter.Length() ? ";" : "", mapQuality); } if (totalDepth < minTotalDepth) { if (filter.Length() == 0) depthFilter++; if (hardFilter) continue; filter.catprintf("%sdepth<=%d", filter.Length() ? ";" : "", totalDepth); } if (totalDepth > maxTotalDepth) { if (filter.Length() == 0) depthFilter++; if (hardFilter) continue; filter.catprintf("%sdepth>=%d", filter.Length() ? ";" : "", totalDepth); } // Create convenient aliases for each base unsigned char transition = (((refBase - 1) ^ 2) + 1); unsigned char transvers1 = (((refBase - 1) ^ 3) + 1); unsigned char transvers2 = (((refBase - 1) ^ 1) + 1); int homRef = glf[0].GenotypeIndex(refBase, refBase); // Calculate likelihood assuming every is homozygous for the reference double lRef = log(1.0 - prior); for (int i = 0; i < n; i++) lRef += log(glf[i].GetLikelihoods(position)[homRef]); // Figure out the correct type of analysis // int cType = chromosomeType != CT_CHRX ? chromosomeType : // position >= xStart && position <= xStop ? CT_CHRX : CT_AUTOSOME; // Calculate maximum likelihood for a variant if (smartFilter) { double anyVariant = log(prior) + FilteringLikelihood(glf, n, position, refBase); if (exp(lRef - anyVariant) > (1.0 - posterior)/posterior) { smartFilterHits++; continue; } } double pTs = uniformPrior ? 1./3. : 2./3.; double pTv = uniformPrior ? 1./3. : 1./6.; // Calculate likelihoods for the most likelily SNP configurations double refTransition = log(prior * pTs) + PolymorphismLikelihood(glf, n, position, refBase, transition); double refTransvers1 = log(prior * pTv) + PolymorphismLikelihood(glf, n, position, refBase, transvers1); double refTransvers2 = log(prior * pTv) + PolymorphismLikelihood(glf, n, position, refBase, transvers2); // Calculate likelihoods for less likely SNP configurations double transitiontv1 = log(prior * 0.001) + PolymorphismLikelihood(glf, n, position, transition, transvers1); double transitiontv2 = log(prior * 0.001) + PolymorphismLikelihood(glf, n, position, transition, transvers2); double transvers1tv2 = log(prior * 0.001) + PolymorphismLikelihood(glf, n, position, transvers1, transvers2); // Calculate the likelihood for unusual configurations where everyone is heterozygous ... double sink = n > 10 ? log(prior * 1e-8) + SinkLikelihood(glf, n, position) : -1e100; double lmax = max( max(max(lRef, refTransition),max(refTransvers1, refTransvers2)), max(max(transitiontv1, transitiontv2), max(transvers1tv2, sink))); double sum = exp(lRef - lmax) + exp(refTransition -lmax) + exp(refTransvers1 - lmax) + exp(refTransvers2 - lmax) + exp(transitiontv1 - lmax) + exp(transitiontv2 - lmax) + exp(transvers1tv2 - lmax) + exp(sink - lmax); if (sum == 0.0) continue; if (exp(lRef - lmax)/sum > 1.0 - prior) { if (filter.Length() == 0) homozygousReference++; if (positions.Entries()) ReportSNP(glf, n, position, refBase, refBase, refBase, filter, totalDepth, averageMapQuality, lRef / sum); continue; } double quality = 1.0 - exp(lRef - lmax) / sum; if (verbose) { DumpDetails(glf, n, position, refBase); printf("%.3f %.3f %.3f %.3f %.3f %.3f %.3f\n", lRef, refTransition, refTransvers1, refTransvers2, transitiontv1, transitiontv2, transvers1tv2); } if (exp(refTransition - lmax)/sum > posterior) { ReportSNP(glf, n, position, refBase, refBase, transition, filter, totalDepth, averageMapQuality, quality /* refTransition/sum */); if (filter.Length() == 0) transitions++; } else if (exp(refTransvers1 - lmax)/sum > posterior) { ReportSNP(glf, n, position, refBase, refBase, transvers1, filter, totalDepth, averageMapQuality, quality /* refTransvers1/sum */); if (filter.Length() == 0) transversions++; } else if (exp(refTransvers2 - lmax)/sum > posterior) { ReportSNP(glf, n, position, refBase, refBase, transvers2, filter, totalDepth, averageMapQuality, quality /* refTransvers2/sum */); if (filter.Length() == 0) transversions++; } else if (exp(transitiontv1 - lmax)/sum > posterior) { ReportSNP(glf, n, position, refBase, transition, transvers1, filter, totalDepth, averageMapQuality, quality /* transitiontv1/sum */); if (filter.Length() == 0) otherPolymorphisms++; } else if (exp(transitiontv2 - lmax)/sum > posterior) { ReportSNP(glf, n, position, refBase, transition, transvers2, filter, totalDepth, averageMapQuality, quality /* transitiontv2/sum */); if (filter.Length() == 0) otherPolymorphisms++; } else if (exp(transvers1tv2 - lmax)/sum > posterior) { ReportSNP(glf, n, position, refBase, transvers1, transvers2, filter, totalDepth, averageMapQuality, quality /* transvers1tv2/sum */); if (filter.Length() == 0) otherPolymorphisms++; } else if (exp(sink - lmax)/sum > posterior) sinkFilter++; } int actualBases = glf[firstGlf].maxPosition - baseCounts[0]; printf(" Missing bases = %9d (%.3f%%)\n", baseCounts[0], baseCounts[0] * 100. / glf[firstGlf].maxPosition); printf(" Reference bases = %9d (%.3f%%)\n", glf[firstGlf].maxPosition - baseCounts[0], (glf[firstGlf].maxPosition - baseCounts[0]) * 100. / glf[firstGlf].maxPosition); printf(" A/T bases = %9d (%.3f%%, %d A, %d T)\n", baseCounts[1] + baseCounts[4], (baseCounts[1] + baseCounts[4]) * 100. / actualBases, baseCounts[1], baseCounts[4]); printf(" G/C bases = %9d (%.3f%%, %d G, %d C)\n", baseCounts[3] + baseCounts[2], (baseCounts[3] + baseCounts[2]) * 100. / actualBases, baseCounts[3], baseCounts[2]); printf(" Depth Filter = %9d bases (%.3f%%)\n", depthFilter, depthFilter * 100. / actualBases); printf(" Map Quality Filter = %9d bases (%.3f%%)\n", mapQualityFilter, mapQualityFilter * 100. / actualBases); printf(" Non-Polymorphic = %9d bases (%.3f%%)\n", homozygousReference, homozygousReference * 100. / actualBases); printf(" Transitions = %9d bases (%.3f%%)\n", transitions, transitions * 100. / actualBases); printf(" Transversions = %9d bases (%.3f%%)\n", transversions, transversions * 100. / actualBases); printf(" Other Polymorphisms = %9d bases (%.3f%%)\n", otherPolymorphisms, otherPolymorphisms * 100. / actualBases); if (n > 10) printf(" Homology Sink = %9d bases (%.3f%%)\n", sinkFilter, sinkFilter * 100. / actualBases); if (smartFilter) printf(" Smart Filter = %9d bases (%.3f%%)\n", smartFilterHits, smartFilterHits * 100. / actualBases); int noCalls = actualBases - homozygousReference - transitions - transversions - otherPolymorphisms - sinkFilter; printf(" No call = %9d bases (%.3f%%)\n", noCalls, noCalls * 100. / actualBases); fflush(stdout); } if (baseCalls != NULL) fclose(baseCalls); time(&t); printf("\nAnalysis completed on %s\n", ctime(&t)); fflush(stdout); }
[ [ [ 1, 820 ] ] ]
9b35b10a742c90d1abcc1a5b50e21f288c34caf4
3affbb81deebe2f45e2efa4582cb45b2fb142303
/cob_driver/cob_camera_sensors/common/include/cob_camera_sensors/AVTPikeCam.h
7dec163d8643a7eb1cca22a4c8e902168b1e07cc
[]
no_license
cool-breeze/care-o-bot
38ad558e14f400a28bc0e0a788aff62ac0b89e05
bb6999df19f717574113fc75ffb1c5ec5b8e83a6
refs/heads/master
2021-01-16T19:12:30.842596
2010-04-29T06:58:50
2010-04-29T06:58:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,527
h
/**************************************************************** * * Copyright (c) 2010 * * Fraunhofer Institute for Manufacturing Engineering * and Automation (IPA) * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Project name: care-o-bot * ROS stack name: cob3_driver * ROS package name: cob_camera_sensors * Description: Interface to AVTPikeCam Firewire Camera. * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Author: Jan Fischer, email:[email protected] * Supervised by: Jan Fischer, email:[email protected] * * Date of creation: Nov 2008 * ToDo: * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * 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 Fraunhofer Institute for Manufacturing * Engineering and Automation (IPA) nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License LGPL 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 Lesser General Public License LGPL for more details. * * You should have received a copy of the GNU Lesser General Public * License LGPL along with this program. * If not, see <http://www.gnu.org/licenses/>. * ****************************************************************/ /// @file AVTPikeCam.h /// Interface to AVTPikeCam Firewire Camera. /// @author Jan Fischer /// @date Novemeber, 2008 #ifndef __AVT_PIKE_CAM_H__ #define __AVT_PIKE_CAM_H__ #ifdef __COB_ROS__ #include "cob_camera_sensors/AbstractColorCamera.h" #else #include "cob_driver/cob_camera_sensors/common/include/cob_camera_sensors/AbstractColorCamera.h" #endif #include <vector> #include <iostream> #include <cstdlib> using namespace std; #ifndef __LINUX__ #include <fgcamera.h> #ifdef __MINGW__ typedef unsigned char UINT8; #endif #endif #define UINT8P_CAST(x) reinterpret_cast<UINT8*>(x) #ifdef __LINUX__ #include <dc1394/dc1394.h> typedef struct { unsigned long Low; unsigned long High; }UINT32HL; #define UINT32 unsigned long #define _UINT32HL #endif #ifdef SWIG %module Sensors %include "Source/Vision/CameraSensors/AbstractColorCamera.h" %{ #include "AVTPikeCam.h" %} #endif namespace ipa_CameraSensors { /// @ingroup CameraSensorDriver /// Interface developed for AVT PIKE 145C camera. /// Interface should also fit to other IEEE 1394 cameras. class AVTPikeCam : public AbstractColorCamera { private: /// Camera specific parameters bool m_operationMode_B; ///< FireWire A (400Mbit/s) or FireWire B (800Mbit/s). UINT32HL m_GUID; ///< GUID (worldwide unique identifier) of the IEEE1395 camera static bool m_CloseExecuted; ///< Trigger takes care, that AVT library is closed only once static bool m_OpenExecuted; ///< Trigger takes care, that AVT library is opend only once #ifdef __LINUX__ dc1394video_frame_t* m_Frame; dc1394_t* m_IEEE1394Info; ///< Hold information about IEEE1394 nodes, connected cameras and camera properties dc1394camera_list_t* m_IEEE1394Cameras; ///< List holds all available firewire cameras dc1394camera_t* m_cam; ///< Opened camera instance. dc1394video_modes_t m_availableVideoModes; ///< Struct holds all available video modes for the opened camera dc1394speed_t m_IsoSpeed; ///< ISO speed. dc1394framerate_t m_FrameRate; ///< Frame rate. dc1394video_mode_t m_VideoMode; ///< Comprise format and mode (i.e. DC1394_VIDEO_MODE_1280x960_RGB8 or DC1394_VIDEO_MODE_FORMAT7_0) dc1394color_coding_t m_ColorCoding; ///< Necessary for Format 7 video mode. Here the color coding is not specified through the video mode #endif #ifndef __LINUX__ CFGCamera m_cam; ///< The camera object for AVT FireGrab (part of AVT FirePackage) FGNODEINFO m_nodeInfo[5]; ///< Array holds information about all detected firewire nodes UINT32 m_NodeCnt; ///< Number of detected IEEE1394 nodes FGFRAME m_Frame; ///< The acquired latest frame from the camera #endif /// Parses the XML configuration file, that holds the camera settings /// @param filename The file name and path of the configuration file /// @param cameraIndex The index of the camera within the configuration file /// i.e. AVT_PIKE_CAM_0 or AVT_PIKE_CAM_1 /// @return Return value unsigned long LoadParameters(const char* filename, int cameraIndex); /// Parses the data extracted by <code>LoadParameters</code> and calls the /// corresponding <code>SetProperty</code> functions. /// @return Return code unsigned long SetParameters(); public: /// Constructor AVTPikeCam (); /// Destructor ~AVTPikeCam (); //******************************************************************************* // AbstractColorCamera interface implementation //******************************************************************************* unsigned long Init(std::string directory, int cameraIndex = 0); unsigned long Open(); unsigned long Close(); unsigned long GetColorImage(char* colorImageData, bool getLatestFrame); unsigned long GetColorImage(IplImage * Img, bool getLatestFrame); unsigned long GetColorImage2(IplImage ** Img, bool getLatestFrame); unsigned long SaveParameters(const char* filename); //speichert die Parameter in das File /// Sets the camera properties. /// The following parameters are admitted: ///<ol> /// <li> PROP_BRIGHTNESS: 0..1023 </li> /// <li> PROP_SHUTTER: 0..4095, VALUE_AUTO</li> /// <li> PROP_AUTO_EXPOSURE: 50..205</li> /// <li> PROP_WHITE_BALANCE_U: 0..568, VALUE_AUTO</li> /// <li> PROP_WHITE_BALANCE_V: 0..568, VALUE_AUTO</li> /// <li> PROP_HUE: 0..80</li> /// <li> PROP_SATURATION: 0..511</li> /// <li> PROP_GAMMA: 0..2</li> /// <li> PROP_GAIN: 0..680</li> /// <li> PROP_FRAME_RATE: 0..60</li> /// <li> PROP_FW_OPERATION_MODE: A / B</li> ///</ol> unsigned long SetProperty(t_cameraProperty* cameraProperty); unsigned long SetPropertyDefaults(); unsigned long GetProperty(t_cameraProperty* cameraProperty); /// Shows the camera's parameters information. /// Shows actual value, max and min value and auto mode for each parameter unsigned long PrintCameraInformation(); unsigned long TestCamera(const char* filename); //******************************************************************************* // Camera specific functions //******************************************************************************* }; } // end namespace ipa_CameraSensors #endif //__AVT_PIKE_CAM_H__
[ "jsf@jsf-laptop.(none)", "[email protected]", "[email protected]" ]
[ [ [ 1, 58 ], [ 63, 65 ], [ 67, 67 ], [ 96, 96 ] ], [ [ 59, 62 ], [ 68, 95 ], [ 97, 205 ] ], [ [ 66, 66 ] ] ]
94175c06b45bedc9d24179ea16abb0ca21fbf6d0
a5cc77a18ce104eefd5d117ac21a623461fe98ca
/rulesdockwidget.cpp
0a80d497917cafbaf01b378c82c28f7020e22605
[]
no_license
vinni-au/yax
7267ccaba9ce8e207a0a2ea60f3c61b2602895f9
122413eefc71a31f4e6700cc958406d244bf9a8f
refs/heads/master
2016-09-10T03:16:43.293156
2011-12-15T19:37:53
2011-12-15T19:37:53
32,195,604
0
0
null
null
null
null
UTF-8
C++
false
false
1,165
cpp
#include "rulesdockwidget.hpp" RulesWidget::RulesWidget(QWidget *parent) : QSplitter(parent) { setOrientation(Qt::Vertical); QSplitter* topSplitter = new QSplitter; m_rulesView = new QTreeView; m_btnRuleAdd = new QPushButton(tr("Добавить")); m_btnRuleDelete = new QPushButton(tr("Удалить")); m_btnRuleUp = new QPushButton(tr("Выше")); m_btnRuleDown = new QPushButton(tr("Ниже")); topSplitter->addWidget(m_rulesView); QWidget* trWidget = new QWidget; QVBoxLayout* trl = new QVBoxLayout; trWidget->setLayout(trl); trl->setSpacing(5); trl->addWidget(m_btnRuleAdd); trl->addWidget(m_btnRuleDelete); trl->addStretch(); trl->addWidget(m_btnRuleUp); trl->addWidget(m_btnRuleDown); topSplitter->addWidget(trWidget); addWidget(topSplitter); m_rulesView->setModel(YAXModels::instance()->rulesModel()); m_rulesView->setItemDelegate(new RulesDelegate); } RulesDockWidget::RulesDockWidget(QString title) : QDockWidget(title) { setWidget(m_widget = new RulesWidget); }
[ [ [ 1, 39 ] ] ]
ce98df1187e6494bbfd9353c24c7dbce33bf14d5
d411188fd286604be7670b61a3c4c373345f1013
/zomgame/ZGame/medical_item.cpp
d5b03475e287910ee9d715fb718894f593bc8c08
[]
no_license
kjchiu/zomgame
5af3e45caea6128e6ac41a7e3774584e0ca7a10f
1f62e569da4c01ecab21a709a4a3f335dff18f74
refs/heads/master
2021-01-13T13:16:58.843499
2008-09-13T05:11:16
2008-09-13T05:11:16
1,560,000
0
1
null
null
null
null
UTF-8
C++
false
false
677
cpp
#include "medical_item.h" MedicalItem::MedicalItem(){ setName("Bandage"); setHealPot(1); setDescription("You should be able to use this to heal your wounds"); setDisplayChar('+'); } MedicalItem::MedicalItem(string name, int nHealPotential){ setName(name); setHealPot(nHealPotential); setDescription("You should be able to use this to heal your wounds"); setDisplayChar('+'); } int MedicalItem::getHealPot(){ return healPotential; } void MedicalItem::setHealPot(int nHealPotential){ if (nHealPotential > 10){ healPotential = 10; } else if (nHealPotential < 1){ healPotential = 1; } else { healPotential = nHealPotential; } }
[ "nicholasbale@9b66597e-bb4a-0410-bce4-15c857dd0990" ]
[ [ [ 1, 30 ] ] ]
8b3c5647f4f2235c22e816121261c80fc915d892
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-world/DatabaseCleaner.cpp
434dbc12164b74b8581dd2c18d2184033658f9ba
[]
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
14,002
cpp
/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" initialiseSingleton(DatabaseCleaner); void DatabaseCleaner::Run() { Log.Error("DatabaseCleaner", "The method is unavailable."); return; /* Log.Notice("DatabaseCleaner", "Stage 1 of 3: Cleaning characters..."); CleanCharacters(); Log.Notice("DatabaseCleaner", "Stage 2 of 3: Cleaning world..."); CleanWorld(); Log.Notice("DatabaseCleaner", "Stage 3 of 3: Optimizing databases..."); Optimize(); */ } void DatabaseCleaner::CleanWorld() { } void DatabaseCleaner::Optimize() { } void DatabaseCleaner::CleanCharacters() { //TODO: Review this code... currently it would wipe almost the whole character database.. :D /* set<uint32> chr_guids; set<uint32> chr_guilds; set<uint32> chr_charters; Log.Notice("DatabaseCleaner", "Loading guids..."); QueryResult * result = CharacterDatabase.Query("SELECT guid, guildid, charterId FROM characters"); if(result) { do { chr_guids.insert(result->Fetch()[0].GetUInt32()); if(result->Fetch()[1].GetUInt32() != 0) chr_guilds.insert(result->Fetch()[1].GetUInt32()); if(result->Fetch()[2].GetUInt32() != 0) chr_guilds.insert(result->Fetch()[2].GetUInt32()); } while(result->NextRow()); delete result; } Log.Notice("DatabaseCleaner", "Got %u guids.", chr_guids.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning playeritems..."); result = CharacterDatabase.Query("SELECT ownerguid, guid FROM playeritems"); vector<uint64> tokill_items; if(result) { do { if(result->Fetch()[0].GetUInt32()!=0 && chr_guids.find(result->Fetch()[0].GetUInt32()) == chr_guids.end()) { tokill_items.push_back(result->Fetch()[1].GetUInt64()); } }while(result->NextRow()); delete result; } for(vector<uint64>::iterator itr = tokill_items.begin(); itr != tokill_items.end(); ++itr) { CharacterDatabase.WaitExecute("DELETE FROM playeritems WHERE guid = "I64FMTD, *itr); } Log.Notice("DatabaseCleaner", "Deleted %u item instances.", tokill_items.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning questlog..."); result = CharacterDatabase.Query("SELECT index, player_guid FROM questlog"); vector<uint32> tokill_quests; if(result) { do { if(chr_guids.find(result->Fetch()[1].GetUInt32()) == chr_guids.end()) tokill_quests.push_back(result->Fetch()[0].GetUInt32()); } while(result->NextRow()); delete result; } for(vector<uint32>::iterator itr = tokill_quests.begin(); itr != tokill_quests.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM questlog WHERE index = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u questlog entries.", tokill_quests.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning corpses..."); vector<uint32> tokill_corpses; result = CharacterDatabase.Query("SELECT * FROM corpses"); if(result) { do { Corpse * pCorpse = new Corpse(0, result->Fetch()[0].GetUInt32()); pCorpse->LoadValues(result->Fetch()[8].GetString()); pCorpse->SetUInt32Value(OBJECT_FIELD_GUID_01, 0); if(pCorpse->GetUInt32Value(CORPSE_FIELD_DISPLAY_ID) == 0 || pCorpse->GetUInt32Value(CORPSE_FIELD_OWNER) == 0 || chr_guids.find(pCorpse->GetUInt32Value(CORPSE_FIELD_OWNER)) == chr_guids.end()) { tokill_corpses.push_back(pCorpse->GetLowGUID()); } delete pCorpse; } while(result->NextRow()); delete result; } for(vector<uint32>::iterator itr = tokill_corpses.begin(); itr != tokill_corpses.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM corpses WHERE guid = %u", *itr); Log.Notice("DatabaseCleaner", "Removed %u corpses.", tokill_corpses.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning mailbox..."); result = CharacterDatabase.Query("SELECT message_id, player_guid FROM mailbox"); vector<uint32> tokill_mail; if(result) { do { if(chr_guids.find(result->Fetch()[1].GetUInt32()) == chr_guids.end()) tokill_mail.push_back(result->Fetch()[0].GetUInt32()); } while(result->NextRow()); delete result; } for(vector<uint32>::iterator itr = tokill_mail.begin(); itr != tokill_mail.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM mailbox WHERE message_id = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u mail messages.", tokill_mail.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning guilds table..."); result = CharacterDatabase.Query("SELECT guildId FROM guilds"); vector<uint32> tokill_guilds; if(result) { do { if(chr_guilds.find(result->Fetch()[0].GetUInt32()) == chr_guilds.end()) { tokill_guilds.push_back(result->Fetch()[0].GetUInt32()); } } while(result->NextRow()); delete result; } for(vector<uint32>::iterator itr = tokill_guilds.begin(); itr != tokill_guilds.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM guilds WHERE guildId = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u guilds.", tokill_guilds.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning guild_ranks table..."); result = CharacterDatabase.Query("SELECT guildId FROM guild_ranks"); set<uint32> tokill_guildranks; if(result) { do { if(chr_guilds.find(result->Fetch()[0].GetUInt32()) == chr_guilds.end()) { tokill_guildranks.insert(result->Fetch()[0].GetUInt32()); } } while(result->NextRow()); delete result; } for(set<uint32>::iterator itr = tokill_guildranks.begin(); itr != tokill_guildranks.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM guild_ranks WHERE guildId = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u guild rank rows.", tokill_guildranks.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning social table..."); result = CharacterDatabase.Query("SELECT * FROM social"); vector<pair<uint32,uint32> > tokill_social; if(result) { do { uint32 g1 = result->Fetch()[0].GetUInt32(); uint32 g2 = result->Fetch()[1].GetUInt32(); if(chr_guids.find(g1) == chr_guids.end() || chr_guids.find(g2) == chr_guids.end()) { pair<uint32,uint32> x; x.first = g1; x.second = g2; tokill_social.push_back(x); } } while(result->NextRow()); delete result; } for(vector<pair<uint32,uint32> >::iterator itr = tokill_social.begin(); itr != tokill_social.end(); ++itr) { CharacterDatabase.WaitExecute("DELETE FROM social WHERE guid = %u and socialguid = %u", itr->first, itr->second); } Log.Notice("DatabaseCleaner", "Deleted %u social entries.", tokill_social.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning cooldown tables..."); set<uint32> tokill_cool; vector<pair<uint32,uint32> > tokill_cool2; result = CharacterDatabase.Query("SELECT OwnerGuid, CooldownTimeStamp FROM playercooldownitems"); if(result) { uint32 t = getMSTime(); do { uint32 guid = result->Fetch()[0].GetUInt32(); uint32 cool = result->Fetch()[1].GetUInt32(); if(chr_guids.find(guid) == chr_guids.end()) tokill_cool.insert(guid); else if(t >= cool) tokill_cool2.push_back(make_pair(guid,cool)); } while(result->NextRow()); delete result; } for(vector<pair<uint32,uint32> >::iterator itr = tokill_cool2.begin(); itr != tokill_cool2.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM playercooldownitems WHERE OwnerGuid = %u AND CooldownTimeStamp = %u", itr->first, itr->second); for(set<uint32>::iterator itr = tokill_cool.begin(); itr != tokill_cool.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM playercooldownitems WHERE OwnerGuid = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u playercooldownitems.", tokill_cool.size() + tokill_cool2.size()); tokill_cool.clear(); tokill_cool2.clear(); result = CharacterDatabase.Query("SELECT OwnerGuid, TimeStamp FROM playercooldownsecurity"); if(result) { uint32 t = getMSTime(); do { uint32 guid = result->Fetch()[0].GetUInt32(); uint32 cool = result->Fetch()[1].GetUInt32(); if(chr_guids.find(guid) == chr_guids.end()) tokill_cool.insert(guid); else if(t >= cool) tokill_cool2.push_back(make_pair(guid,cool)); } while(result->NextRow()); delete result; } for(vector<pair<uint32,uint32> >::iterator itr = tokill_cool2.begin(); itr != tokill_cool2.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM playercooldownsecurity WHERE OwnerGuid = %u AND TimeStamp = %u", itr->first, itr->second); for(set<uint32>::iterator itr = tokill_cool.begin(); itr != tokill_cool.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM playercooldownsecurity WHERE OwnerGuid = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u playercooldownsecurities.", tokill_cool.size() + tokill_cool2.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning tutorials..."); vector<uint32> tokill_tutorials; result = CharacterDatabase.Query("SELECT playerId FROM tutorials"); if(result) { do { uint32 pi = result->Fetch()[0].GetUInt32(); if(chr_guids.find(pi) == chr_guids.end()) tokill_tutorials.push_back(pi); } while(result->NextRow()); delete result; } for(vector<uint32>::iterator itr = tokill_tutorials.begin(); itr != tokill_tutorials.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM tutorials WHERE playerId = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u tutorials.", tokill_tutorials.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning playerpets..."); set<uint32> tokill_pet; result = CharacterDatabase.Query("SELECT ownerguid, petnumber FROM playerpets"); if(result) { do { if(chr_guids.find( result->Fetch()[0].GetUInt32() ) == chr_guids.end()) tokill_pet.insert(result->Fetch()[0].GetUInt32()); } while(result->NextRow()); delete result; } for(set<uint32>::iterator itr = tokill_pet.begin(); itr != tokill_pet.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM playerpets WHERE ownerguid = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u pets.", tokill_pet.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning playersummonspells..."); set<uint32> tokill_ss; result = CharacterDatabase.Query("SELECT ownerguid FROM playersummonspells"); if(result) { do { if(chr_guids.find( result->Fetch()[0].GetUInt32() ) == chr_guids.end()) tokill_ss.insert(result->Fetch()[0].GetUInt32()); } while(result->NextRow()); delete result; } for(set<uint32>::iterator itr = tokill_ss.begin(); itr != tokill_ss.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM playersummonspells WHERE ownerguid = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u summonspells.", tokill_ss.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning playerpetspells..."); set<uint32> tokill_ps; result = CharacterDatabase.Query("SELECT ownerguid FROM playerpetspells"); if(result) { do { if(chr_guids.find( result->Fetch()[0].GetUInt32() ) == chr_guids.end()) tokill_ps.insert(result->Fetch()[0].GetUInt32()); } while(result->NextRow()); delete result; } for(set<uint32>::iterator itr = tokill_ps.begin(); itr != tokill_ps.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM playerpetspells WHERE ownerguid = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u petspells.", tokill_ps.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning gm_tickets..."); CharacterDatabase.WaitExecute("DELETE FROM gm_tickets WHERE playerGuid NOT IN (SELECT guid FROM characters)"); //TODO: Print out count of removed gm_tickets Log.Notice("DatabaseCleaner", "Deleted dead gm tickets."); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning charters..."); vector<uint32> tokill_charters; result = CharacterDatabase.Query("SELECT * FROM charters"); if(result) { do { if(chr_charters.find(result->Fetch()[0].GetUInt32()) == chr_charters.end() || chr_guids.find(result->Fetch()[1].GetUInt32()) == chr_guids.end()) { tokill_charters.push_back(result->Fetch()[0].GetUInt32()); } } while(result->NextRow()); delete result; } for(vector<uint32>::iterator itr = tokill_charters.begin(); itr != tokill_charters.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM charters WHERE charterId = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u charters.", tokill_charters.size()); Log.Line(); Log.Notice("DatabaseCleaner", "Cleaning charters..."); result = CharacterDatabase.Query("SELECT auctionId, owner FROM auctions"); vector<uint32> tokill_auct; if(result) { do { if(chr_guids.find(result->Fetch()[1].GetUInt32()) == chr_guids.end()) tokill_auct.push_back(result->Fetch()[0].GetUInt32()); } while(result->NextRow()); delete result; } for(vector<uint32>::iterator itr = tokill_auct.begin(); itr != tokill_auct.end(); ++itr) CharacterDatabase.WaitExecute("DELETE FROM auctions WHERE auctionId = %u", *itr); Log.Notice("DatabaseCleaner", "Deleted %u auctions.", tokill_auct.size()); Log.Notice("DatabaseCleaner", "Ending..."); Log.Line(); */ }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 5, 25 ], [ 30, 37 ], [ 39, 52 ], [ 56, 121 ], [ 123, 339 ], [ 343, 382 ], [ 384, 384 ] ], [ [ 2, 4 ], [ 26, 29 ], [ 38, 38 ], [ 53, 55 ], [ 122, 122 ], [ 340, 342 ], [ 383, 383 ] ] ]
0f0b10c1032c9b19a6ffdc7942a4e49f28c00401
6e5c32618b28d2c7a6175d2921e0baeb530183c1
/src/WCEngine/EventManager.cpp
3b5e9a1afcc521158caf6994e98e2fe50c3e89a2
[]
no_license
RoestVrijStaal/warehousepanic
79a26e97026b0184a10c4a631dff5df0be8918dc
16eeba14c7e38b2b0eeddd90e5ac6970b0bff9a9
refs/heads/master
2020-05-20T08:04:19.112773
2010-06-09T19:03:54
2010-06-09T19:03:54
35,184,762
0
0
null
null
null
null
UTF-8
C++
false
false
1,674
cpp
#include "EventManager.h" namespace gdn { // Easier constructors for typical events GameEvent GameEvent::ChangeSceneEvent( std::string newscene ) { return GameEvent( ChangeScene, newscene ); } GameEvent GameEvent::HighscoreEvent( int newscore ) { return GameEvent( Highscore, newscore ); } GameEvent GameEvent::ChangeLevelEvent( int nlevel ) { return GameEvent( ChangeLevel, nlevel ); } GameEvent GameEvent::ChangeScoreEvent( int newscore ) { return GameEvent( ChangeScore, newscore ); } GameEvent GameEvent::QuitEvent() { return GameEvent( Quit ); } EventManager* EventManager::instance = NULL; EventManager* EventManager::GetInstance() { if ( instance == NULL ) { instance = new EventManager(); } return instance; } EventManager::EventManager() { Initialize(); } EventManager::~EventManager() { if ( instance != NULL ) { delete instance; instance = NULL; } } void EventManager::Initialize() { for ( EVENT_RECEIVER i = (EVENT_RECEIVER)0; i < count; i = (EVENT_RECEIVER)(i + 1) ) { events[i]; } } void EventManager::PushEvent( EVENT_RECEIVER receiver, GameEvent event ) { std::list< GameEvent >& queue = events[receiver]; queue.push_back( event ); } bool EventManager::HasEvent( EVENT_RECEIVER receiver ) { std::list< GameEvent >& queue = events[receiver]; return queue.size() > 0; } GameEvent& EventManager::PeekEvent( EVENT_RECEIVER receiver ) { std::list< GameEvent >& queue = events[receiver]; return queue.front(); } void EventManager::PopEvent( EVENT_RECEIVER receiver ) { std::list< GameEvent >& queue = events[receiver]; queue.pop_front(); } }
[ "[email protected]@03d7b61e-2572-11df-92c5-9faf7978932a", "[email protected]@03d7b61e-2572-11df-92c5-9faf7978932a" ]
[ [ [ 1, 12 ], [ 14, 87 ] ], [ [ 13, 13 ] ] ]
d600ecd4cba9594fd6ce9ff12e13a2c229695fee
22b6d8a368ecfa96cb182437b7b391e408ba8730
/engine/include/qvIGuiView.h
705ee04bb4294ca2264e00a7491f3b827fcf3b29
[ "MIT" ]
permissive
drr00t/quanticvortex
2d69a3e62d1850b8d3074ec97232e08c349e23c2
b780b0f547cf19bd48198dc43329588d023a9ad9
refs/heads/master
2021-01-22T22:16:50.370688
2010-12-18T12:06:33
2010-12-18T12:06:33
85,525,059
0
0
null
null
null
null
UTF-8
C++
false
false
629
h
#ifndef __IGUIVIEW_H_ #define __IGUIVIEW_H_ #include "qvIElementView.h" namespace qv { namespace views { static const EVT_ELEMENT_VIEW_TYPE EVT_ELEMENT_VIEW_GUI("EVT_ELEMENT_VIEW_GUI"); class IGuiView: public IElementView { //public: // virtual const ElementViewID& getID()=0; // virtual const ElementViewType& getType()=0; // virtual bool getVisible()=0; //virtual void setVisible(bool visible)=0; // virtual void render(u32 currentTimeMs, u32 elapsedTimeMs)=0; // virtual void update( u32 elapsedTimeMs)=0; }; } } #endif
[ [ [ 1, 32 ] ] ]
bf82d26adaee3e755c68942052abbd8804e308f1
2a6a2adbc18d74e89152324dacd7ffe190fcd7cc
/old/B(n, k)/B(n, k)/Perm Test/Matrix.cpp
5fa1253163435b11c5ed499192fa0f14031476f2
[]
no_license
swenson/Tabloid-Terror
fcb848e2bd9817009f8e0d5312162bd0d7d44825
8880b2af2da6f0635a311105d80f8b94bd7cc072
refs/heads/master
2021-01-16T22:46:01.908023
2010-12-08T02:29:21
2010-12-08T02:29:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,949
cpp
// Matrix.cpp: implementation of the Matrix class. // ////////////////////////////////////////////////////////////////////// #include "Matrix.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Matrix::Matrix() { rownum = 0; colnum = 0; } Matrix::~Matrix() { } // this inserts x into row i col j where i, j >= 1 void Matrix::Set(const int i, const int j, const double x) { // Make sure (i, j) exists if ( (rownum < i) || (colnum < j) ) { cerr << "\nError in Set. Tried to set spot (" << i << "," << j <<")."; cerr << "When rownum=" << rownum << " and colnum=" << colnum; char ch = getchar(); exit(-1); } (data[i-1])[j-1] = x; } // this inserts col into the nth column note then n >= 1. so n != 0 void Matrix::ColumnSet(const int n, vector<double> col) { // Are there n cols yet? if(colnum >= n) { // make sure the number of rows is right if ( rownum != col.size()) { cerr << "\n Error in ColumnSet"; cerr << "\n tried to insert a column of size " << col.size(); cerr << "When the rownum = " << rownum; char ch = getchar(); exit(-1); } // set the col for(int j = 1; j <= rownum; j++) { Set(n, j, col[j-1]); } } else { // make sure there are at least n-1 columns if(colnum < n-1) { cerr << "\n Error in ColumnSet. Tried to insert column " << n; cerr << " when column " << n-1 << "doesn't exist"; char ch = getchar(); exit(-1); } //set the colnum colnum++; // we need to insert a number at the end of each row // if this is the first column we need to do something special int count = 0; if (n == 1) { rownum = col.size(); for( count = 0; count < col.size(); count++) { vector<double> temp; temp.push_back(col[count]); data.push_back(temp); } } else { for(vector< vector<double> >::iterator iter = data.begin(); iter != data.end(); ++iter) { (*iter).push_back(col[count]); count++; } } } } bool IsZero( vector<double> v) { bool flag = true; for(int i = 0; i < v.size(); i++) { if (v[i] != 0) { flag = false; break; } } return(flag); } void Matrix::RowSwap(const int i, const int j) { vector<double> temp; temp = data[i]; data[i] = data[j]; data[j] = temp; } void Matrix::RowMult(const int i, const double d) { for(int j = 0; j < colnum; j++) { (data[i])[j] *= d; } } // add d * Row i to row j void Matrix::RowAddMult(const int i, const int j, const double d) { for (int k = 0; k < colnum; k++) { (data[j])[k] += d*((data[i])[k]); } } Matrix RowReduce(Matrix N) { Matrix M = N; // we go down the rows int currentrow = 0; for (int currentcol = 0; currentcol < M.col(); currentcol++) { // look for a nonzero entry in the current column and below or at the current row int nonzero; bool found = false; for(nonzero = currentrow; nonzero < M.row(); nonzero++) { if ( M.Get(nonzero, currentcol) != 0) { found = true; break; } } if (!found) { // column is all zeroed out moveon } else { // is the nonzero entry in the current row? if(nonzero != currentrow) { // ok swap rows M.RowSwap(nonzero, currentrow); } // so now the current row has a nonzero entry in column currentcol // normalize double factor = 1.0/M.Get(currentrow,currentcol); M.RowMult(currentrow, factor); //now zero out beneath it for(int j = currentrow+1; j < M.row(); j++) { M.RowAddMult(currentrow, j, -1.0*M.Get(j,currentcol)); } } currentrow++; } return(M); } int Matrix::Rank(void) { Matrix M = RowReduce(*this); int Answer = 0;; for( int i = 0; i < rownum; i++) { if (!IsZero( (M.data)[i] )) { Answer++; } } return(Answer); }
[ "smaug@blue.(none)" ]
[ [ [ 1, 170 ] ] ]
fbb7eee287923b3d39124f2fc6e94441573eb997
24bc1634133f5899f7db33e5d9692ba70940b122
/extlibs/RakNet/include/ReplicaManager2.h
e9fdba21eea0cc21cda873ae109a362fe3f15e49
[]
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
60,299
h
/// \file /// \brief Contains the second iteration of the ReplicaManager class. This system automatically creates and destroys objects, downloads the world to new players, manages players, and automatically serializes as needed. /// /// 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. #ifndef __REPLICA_MANAGER_2_H #define __REPLICA_MANAGER_2_H #include "Export.h" #include "RakNetTypes.h" #include "DS_Map.h" #include "PluginInterface.h" #include "NetworkIDObject.h" #include "PacketPriority.h" #include "GetTime.h" #include "BitStream.h" #include "DS_Queue.h" namespace RakNet { class BitStream; class Replica2; class Connection_RM2; class Connection_RM2Factory; /// \defgroup REPLICA_MANAGER_2_GROUP ReplicaManager2 /// \ingroup PLUGINS_GROUP /// \brief These are the types of events that can cause network data to be transmitted. /// \ingroup REPLICA_MANAGER_2_GROUP typedef int SerializationType; enum { /// Serialization command initiated by the user SEND_SERIALIZATION_GENERIC_TO_SYSTEM, /// Serialization command initiated by the user BROADCAST_SERIALIZATION_GENERIC_TO_SYSTEM, /// Serialization command automatically called after sending construction of the object SEND_SERIALIZATION_CONSTRUCTION_TO_SYSTEM, /// Serialization command automatically called after sending construction of the object BROADCAST_SERIALIZATION_CONSTRUCTION_TO_SYSTEM, /// Automatic serialization of data, based on Replica2::AddAutoSerializeTimer SEND_AUTO_SERIALIZE_TO_SYSTEM, /// Automatic serialization of data, based on Replica2::AddAutoSerializeTimer BROADCAST_AUTO_SERIALIZE_TO_SYSTEM, /// Received a serialization command, relaying to systems other than the sender RELAY_SERIALIZATION_TO_SYSTEMS, /// If SetAutoAddNewConnections is true, this is the command sent when sending all game objects to new connections automatically SEND_CONSTRUCTION_SERIALIZATION_AUTO_INITIAL_DOWNLOAD_TO_SYSTEM, // Automatically sent message indicating if the replica is visible or not to a new connection SEND_VISIBILITY_AUTO_INITIAL_DOWNLOAD_TO_SYSTEM, /// The data portion of the game download, preceeded by SEND_CONSTRUCTION_SERIALIZATION_AUTO_INITIAL_DOWNLOAD_TO_SYSTEM SEND_DATA_SERIALIZATION_AUTO_INITIAL_DOWNLOAD_TO_SYSTEM, /// Default reason to send a destruction command SEND_DESTRUCTION_GENERIC_TO_SYSTEM, /// Triggered by ReplicaManager2::RecalculateVisibility - A replica is now never constructed, so needs to be destroyed SEND_DESTRUCTION_VISIBILITY_RECALCULATION_TO_SYSTEM, /// Triggered by Replica2::BroadcastDestruction BROADCAST_DESTRUCTION_GENERIC_TO_SYSTEM, /// Received destruction message, relaying to other systems RELAY_DESTRUCTION_TO_SYSTEMS, /// Default reason to send a construction command SEND_CONSTRUCTION_GENERIC_TO_SYSTEM, /// Triggered by ReplicaManager2::RecalculateVisibility - A replica is now always constructed, so needs to be created SEND_CONSTRUCTION_VISIBILITY_RECALCULATION_TO_SYSTEM, /// Triggered by Replica2::BroadcastConstruction() BROADCAST_CONSTRUCTION_GENERIC_TO_SYSTEM, /// Replica2::QueryIsConstructionAuthority()==false yet we called ReplicaManager2::SendConstruction() SEND_CONSTRUCTION_REQUEST_TO_SERVER, /// A non-authority object was created by a client, accepted, and is now relayed to all other connected systems BROADCAST_CONSTRUCTION_REQUEST_ACCEPTED_TO_SYSTEM, /// A non-authority object was created by a client, accepted SEND_CONSTRUCTION_REPLY_ACCEPTED_TO_CLIENT, /// A non-authority object was created by a client, denied SEND_CONSTRUCTION_REPLY_DENIED_TO_CLIENT, /// An object is visible SEND_VISIBILITY_TRUE_TO_SYSTEM, /// An object is visible BROADCAST_VISIBILITY_TRUE_TO_SYSTEM, /// An object is not visible SEND_VISIBILITY_FALSE_TO_SYSTEM, /// An object is not visible BROADCAST_VISIBILITY_FALSE_TO_SYSTEM, /// An object is visible, and we are telling other systems about this RELAY_VISIBILITY_TRUE_TO_SYSTEMS, /// An object is visible, and we are telling other systems about this RELAY_VISIBILITY_FALSE_TO_SYSTEMS, /// Calling Replica2::Serialize() for the purpose of reading memory to compare against later. This read will not be transmitted AUTOSERIALIZE_RESYNCH_ONLY, /// Calling Replica2::Serialize() to compare against a prior call. The serialization may be transmitted AUTOSERIALIZE_DEFAULT, /// Start your own reasons one unit past this enum UNDEFINED_REASON, }; /// \brief A management system for your game objects and players to make serialization, scoping, and object creation and destruction easier. /// /// Quick start: /// 1. Create a class that derives from Connection_RM2, implementing the Construct() function. Construct() is a factory function that should return instances of your game objects, given a user-defined identifier. /// 2. Create a class that derives from Connection_RM2Factory, implementing AllocConnection() and DeallocConnection() to return instances of the class from step 1. /// 3. Attach ReplicaManager2 as a plugin /// 4. Call ReplicaManager2::SetConnectionFactory with an instance of the class from step 2. /// 5. For each of your game classes that use this system, derive from Replica2 and implement SerializeConstruction(), Serialize(), Deserialize(). The output of SerializeConstruction() is sent to Connection_RM2::Construct() /// 6. When these classes are allocated, call Replica2::SetReplicaManager() with the instance of ReplicaManager2 class created in step 3 (this could be done automatically in the constructor) /// 7. Creation: Use Replica2::SendConstruction() to create the object remotely, Replica2::SendDestruction() to delete the object remotely. /// 8. Scoping: Override Replica2::QueryVisibility() and Replica2::QueryConstruction() to return BQR_YES or BQR_NO if an object should be visible and in scope to a given connection. Defaults to BQR_ALWAYS /// 9. Automatic serialization: Call Replica2::AddAutoSerializeTimer() to automatically call Replica2::Serialize() at intervals, compare this to the last value, and broadcast out the object when the serialized variables change. /// /// \pre Call RakPeer::SetNetworkIDManager() /// \pre This system is a server or peer: Call NetworkIDManager::SetIsNetworkIDAuthority(true). /// \pre This system is a client: Call NetworkIDManager::SetIsNetworkIDAuthority(false). /// \pre If peer to peer, set NetworkID::peerToPeerMode=true, and comment out NETWORK_ID_USE_PTR_TABLE in NetworkIDManager.h /// \ingroup REPLICA_MANAGER_2_GROUP class RAK_DLL_EXPORT ReplicaManager2 : public PluginInterface { public: /// Constructor ReplicaManager2(); /// Destructor virtual ~ReplicaManager2(); /// Sets the factory class used to allocate connection objects /// \param[in] factory A pointer to an instance of a class that derives from Connection_RM2Factory. This pointer it saved and not copied, so the object should remain in memory. void SetConnectionFactory(Connection_RM2Factory *factory); /// \param[in] Default ordering channel to use when passing -1 to a function that takes orderingChannel as a parameter void SetDefaultOrderingChannel(char def); /// \param[in] Default packet priority to use when passing NUMBER_OF_PRIORITIES to a function that takes priority as a parameter void SetDefaultPacketPriority(PacketPriority def); /// \param[in] Default packet reliability to use when passing NUMBER_OF_RELIABILITIES to a function that takes reliability as a parameter void SetDefaultPacketReliability(PacketReliability def); /// Auto scope will track the prior construction and serialization visibility of each registered Replica2 class, for each connection. /// Per-tick, as the visibility or construction status of a replica changes, it will be constructed, destroyed, or the visibility will change as appropriate. /// \param[in] construction If true, Connection_RM2::SetConstructionByReplicaQuery will be called once per PluginInterface::Update tick. This will call Replica2::QueryConstruction to return if an object should be exist on a particular connection /// \param[in] visibility If true, Connection_RM2::SetConstructionSerializationByReplicaQuery will be called once per PluginInterface::Update tick. This will call Replica2::QuerySerialization to return if an object should be visible to a particular connection or not. void SetAutoUpdateScope(bool construction, bool visibility); /// Autoadd will cause a Connection_RM2 instance to be allocated for every connection. /// Defaults to true. Set this to false if you have connections which do not participate in the game (master server, etc). /// \param[in] autoAdd If true, all incoming connections are added as ReplicaManager2 connections. void SetAutoAddNewConnections(bool autoAdd); /// If SetAutoAddNewConnections() is false, you need to add connections manually /// connections are also created implicitly if needed /// \param[in] systemAddress The address of the new system /// \return false if the connection already exists bool AddNewConnection(SystemAddress systemAddress); /// Remove an existing connection. Also done automatically on ID_DISCONNECTION_NOTIFICATION and ID_CONNECTION_LOST /// \param[in] systemAddress The address of the system to remove the connection for /// \return false if the connection does not exist bool RemoveConnection(SystemAddress systemAddress); /// Is this connection registered with the system? /// \param[in] systemAddress The address of the system to check /// \return true if this address is registered, false otherwise bool HasConnection(SystemAddress systemAddress); /// If true, autoserialize timers added with Replica2::AddAutoSerializeTimer() will automatically decrement. /// If false, you must call Replica2::ElapseAutoSerializeTimers() manually. /// Defaults to true /// \param[in] autoUpdate True to automatically call ElapseAutoSerializeTimers(). Set to false if you need to control these timers. void SetDoReplicaAutoSerializeUpdate(bool autoUpdate); /// Sends a construction command to one or more systems, which will be relayed throughout the network. /// Recipient(s) will allocate the connection via Connection_RM2Factory::AllocConnection() if it does not already exist. /// Will trigger a call on the remote system(s) to Connection_RM2::Construct() /// \note If using peer-to-peer, don't forget to set NetworkID::peerToPeerMode=true and comment out NETWORK_ID_USE_PTR_TABLE in NetworkIDManager.h. /// \note This is a low level function. Beginners may wish to use Replica2::SendConstruction() or Replica2::BroadcastConstruction(). You can also override Replica2::QueryConstruction() /// \param[in] replica The class to construct remotely /// \param[in] replicaData User-defined serialized data representing how to construct the class. Could be the name of the class, a unique identifier, or other methods /// \param[in] recipient Which system to send to. Use UNASSIGNED_SYSTEM_ADDRESS to send to all previously created connections. Connection_RM2Factory::AllocConnection will be called if this connection has not been previously used. /// \param[in] timestamp Timestamp to send with the message. Use 0 to not send a timestamp if you don't need it. /// \param[in] sendMessage True to actually send a network message. False to only register that the object exists on the remote system, useful for objects created outside ReplicaManager2, or objects that already existed in the world. /// \param[in] exclusionList Which systems to not send to. This list is carried with the messsage, and appended to at each node in the connection graph. This is used to prevent infinite cyclical sends. /// \param[in] localClientId If replica->QueryIsConstructionAuthority()==false, this number will be sent with SEND_CONSTRUCTION_REQUEST_TO_SERVER to the \a recipient. SEND_CONSTRUCTION_REPLY_ACCEPTED_TO_CLIENT or SEND_CONSTRUCTION_REPLY_DENIED_TO_CLIENT will be returned, and this number will be used to look up the local object in Replica2::clientPtrArray /// \param[in] type What kind of serialization operation this is. Use one of the pre-defined types, or create your own. This will be returned in \a type in Connection_RM2::Construct() /// \param[in] priority PacketPriority to send with. Use NUMBER_OF_PRIORITIES to use the default defined by SetDefaultPacketPriority(). /// \param[in] reliability PacketReliability to send with. Use NUMBER_OF_RELIABILITIES to use the default defined by SetDefaultPacketReliability(); /// \param[in] orderingChannel ordering channel to send on. Use -1 to use the default defined by SetDefaultOrderingChannel() /// \pre Call SetConnectionFactory() with a derived instance of Connection_RM2Factory. void SendConstruction(Replica2 *replica, BitStream *replicaData, SystemAddress recipient, RakNetTime timestamp, bool sendMessage, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList, unsigned char localClientId, SerializationType type=SEND_CONSTRUCTION_GENERIC_TO_SYSTEM, PacketPriority priority=NUMBER_OF_PRIORITIES, PacketReliability reliability=NUMBER_OF_RELIABILITIES, char orderingChannel=-1); /// Sends a destruction command to one or more systems, which will be relayed throughout the network. /// Recipient(s) will allocate the connection via Connection_RM2Factory::AllocConnection() if it does not already exist. /// Will trigger a call on the remote system(s) to Replica2::ReceiveDestruction() which in turn calls Replica2::DeserializeDestruction() with the value passed in \a replicaData /// Note: This is a low level function. Beginners may wish to use Replica2::SendDestruction() or Replica2::BroadcastDestruction(). /// \param[in] replica The class to destroy remotely /// \param[in] replicaData User-defined serialized data. Passed to Replica2::ReceiveDestruction() /// \param[in] recipient Which system to send to. Use UNASSIGNED_SYSTEM_ADDRESS to send to all previously created connections. Connection_RM2Factory::AllocConnection will be called if this connection has not been previously used. /// \param[in] timestamp Timestamp to send with the message. Use 0 to not send a timestamp if you don't need it. /// \param[in] sendMessage True to actually send a network message. False to only register that the object no longer exists on the remote system. /// \param[in] exclusionList Which systems to not send to. This list is carried with the messsage, and appended to at each node in the connection graph. This is used to prevent infinite cyclical sends. /// \param[in] type What kind of serialization operation this is. Use one of the pre-defined types, or create your own. This will be returned in \a type in Connection_RM2::Construct() /// \param[in] priority PacketPriority to send with. Use NUMBER_OF_PRIORITIES to use the default defined by SetDefaultPacketPriority(). /// \param[in] reliability PacketReliability to send with. Use NUMBER_OF_RELIABILITIES to use the default defined by SetDefaultPacketReliability(); /// \param[in] orderingChannel ordering channel to send on. Use -1 to use the default defined by SetDefaultOrderingChannel() /// \pre Replica::QueryIsDestructionAuthority() must return true /// \pre Call SetConnectionFactory() with a derived instance of Connection_RM2Factory. void SendDestruction(Replica2 *replica, BitStream *replicaData, SystemAddress recipient, RakNetTime timestamp, bool sendMessage, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList, SerializationType type=SEND_DESTRUCTION_GENERIC_TO_SYSTEM, PacketPriority priority=NUMBER_OF_PRIORITIES, PacketReliability reliability=NUMBER_OF_RELIABILITIES, char orderingChannel=-1); /// Sends a serialized object to one or more systems, which will be relayed throughout the network. /// Recipient(s) will allocate the connection via Connection_RM2Factory::AllocConnection() if it does not already exist. /// Will trigger a call on the remote system(s) to Replica2::ReceiveSerialization() which in turn calls Replica2::Deserialize() with the value passed in \a replicaData /// Note: This is a low level function. Beginners may wish to use Replica2::SendSerialize() or Replica2::BroadcastSerialize(). /// \param[in] replica The class to serialize /// \param[in] replicaData User-defined serialized data. Passed to Replica2::ReceiveSerialization() /// \param[in] recipient Which system to send to. Use UNASSIGNED_SYSTEM_ADDRESS to send to all previously created connections. Connection_RM2Factory::AllocConnection will be called if this connection has not been previously used. /// \param[in] timestamp Timestamp to send with the message. Use 0 to not send a timestamp if you don't need it. /// \param[in] exclusionList Which systems to not send to. This list is carried with the messsage, and appended to at each node in the connection graph. This is used to prevent infinite cyclical sends. /// \param[in] type What kind of serialization operation this is. Use one of the pre-defined types, or create your own. This will be returned in \a type in Connection_RM2::Construct() /// \param[in] priority PacketPriority to send with. Use NUMBER_OF_PRIORITIES to use the default defined by SetDefaultPacketPriority(). /// \param[in] reliability PacketReliability to send with. Use NUMBER_OF_RELIABILITIES to use the default defined by SetDefaultPacketReliability(); /// \param[in] orderingChannel ordering channel to send on. Use -1 to use the default defined by SetDefaultOrderingChannel() /// \pre Replica::QueryIsSerializationAuthority() must return true /// \pre Call SetConnectionFactory() with a derived instance of Connection_RM2Factory. void SendSerialize(Replica2 *replica, BitStream *replicaData, SystemAddress recipient, RakNetTime timestamp, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList, SerializationType type=SEND_SERIALIZATION_GENERIC_TO_SYSTEM, PacketPriority priority=NUMBER_OF_PRIORITIES, PacketReliability reliability=NUMBER_OF_RELIABILITIES, char orderingChannel=-1); /// Sets the visibility status of an object. which will be relayed throughout the network. /// Objects that are not visible should be hidden in the game world, and will not send AutoSerialize updates /// Recipient(s) will allocate the connection via Connection_RM2Factory::AllocConnection() if it does not already exist. /// Will trigger a call on the remote system(s) to Connection_RM2::ReceiveVisibility() /// Note: This is a low level function. Beginners may wish to use Connection_RM2::SendVisibility() or override Replica2::QueryVisibility() /// \param[in] objectList The objects to send to the system. /// \param[in] replicaData User-defined serialized data. Read in Connection_RM2::ReceiveVisibility() /// \param[in] recipient Which system to send to. Use UNASSIGNED_SYSTEM_ADDRESS to send to all previously created connections. Connection_RM2Factory::AllocConnection will be called if this connection has not been previously used. /// \param[in] timestamp Timestamp to send with the message. Use 0 to not send a timestamp if you don't need it. /// \param[in] sendMessage True to actually send a network message. False to only register that the objects exist on the remote system /// \param[in] type What kind of serialization operation this is. Use one of the pre-defined types, or create your own. This will be returned in \a type in Connection_RM2::Construct() /// \param[in] priority PacketPriority to send with. Use NUMBER_OF_PRIORITIES to use the default defined by SetDefaultPacketPriority(). /// \param[in] reliability PacketReliability to send with. Use NUMBER_OF_RELIABILITIES to use the default defined by SetDefaultPacketReliability(); /// \param[in] orderingChannel ordering channel to send on. Use -1 to use the default defined by SetDefaultOrderingChannel() /// \pre Replica::QueryIsConstructionAuthority() must return true /// \pre Call SetConnectionFactory() with a derived instance of Connection_RM2Factory. void SendVisibility(Replica2 *replica, BitStream *replicaData, SystemAddress recipient, RakNetTime timestamp, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList, SerializationType type=SEND_VISIBILITY_TRUE_TO_SYSTEM, PacketPriority priority=NUMBER_OF_PRIORITIES, PacketReliability reliability=NUMBER_OF_RELIABILITIES, char orderingChannel=-1); /// Returns how many Replica2 instances are registered. /// Replica2 instances are automatically registered when used, and unregistered when calling Deref (which is automatically done in the destructor). /// Used for GetReplicaAtIndex if you want to perform some object on all registered Replica objects. /// \return How many replica objects are in the list of replica objects unsigned GetReplicaCount(void) const; /// Returns a previously registered Replica2 *, from index 0 to GetReplicaCount()-1. /// Replica2* objects are returned in the order they were registered. /// \param[in] index An index, from 0 to GetReplicaCount()-1. /// \return A Replica2 pointer Replica2 *GetReplicaAtIndex(unsigned index); /// Returns the number of registered connections. /// Connections are registered implicitly when used. /// Connections are unregistered on disconnect. /// \return The number of registered connections unsigned GetConnectionCount(void) const; /// Returns a connection pointer previously implicitly added. /// \param[in] index An index, from 0 to GetConnectionCount()-1. /// \return A Connection_RM2 pointer Connection_RM2* GetConnectionAtIndex(unsigned index) const; /// Returns a connection pointer previously implicitly added. /// \param[in] systemAddress The system address of the connection to return /// \return A Connection_RM2 pointer Connection_RM2* GetConnectionBySystemAddress(SystemAddress systemAddress) const; /// Returns the index of a connection, by SystemAddress /// \param[in] systemAddress The system address of the connection index to return /// \return The connection index, or -1 if no such connection unsigned int GetConnectionIndexBySystemAddress(SystemAddress systemAddress) const; /// Call this when Replica2::QueryVisibility() or Replica2::QueryConstructionVisibility() changes from BQR_ALWAYS or BQR_NEVER to BQR_YES or BQR_NO /// Otherwise these two conditions are assumed to never change /// \param[in] Which replica to update void RecalculateVisibility(Replica2 *replica); /// \internal static int Replica2ObjectComp( RakNet::Replica2 * const &key, RakNet::Replica2 * const &data ); /// \internal static int Replica2CompByNetworkID( const NetworkID &key, RakNet::Replica2 * const &data ); /// \internal static int Connection_RM2CompBySystemAddress( const SystemAddress &key, RakNet::Connection_RM2 * const &data ); /// Given a replica instance, return all connections that are believed to have this replica instantiated. /// \param[in] replica Which replica is being refered to /// \param[out] output List of connections, ordered by system address void GetConnectionsWithReplicaConstructed(Replica2 *replica, DataStructures::OrderedList<SystemAddress, Connection_RM2*, ReplicaManager2::Connection_RM2CompBySystemAddress> &output); /// Given a replica instance, return all connections that are believed to have this replica visible /// \param[in] replica Which replica is being refered to /// \param[out] output List of connections, ordered by system address void GetConnectionsWithSerializeVisibility(Replica2 *replica, DataStructures::OrderedList<SystemAddress, Connection_RM2*, ReplicaManager2::Connection_RM2CompBySystemAddress> &output); /// Gets the instance of RakPeerInterface that this plugin was attached to /// \return The instance of RakPeerInterface that this plugin was attached to RakPeerInterface *GetRakPeer(void) const; /// Internally starts tracking this replica /// \internal void Reference(Replica2* replica, bool *newReference); /// Stops tracking this replica. Call before deleting the Replica. Done automatically in ~Replica() /// \internal void Dereference(Replica2 *replica); protected: // Plugin interface functions void OnAttach(RakPeerInterface *peer); PluginReceiveResult OnReceive(RakPeerInterface *peer, Packet *packet); void OnCloseConnection(RakPeerInterface *peer, SystemAddress systemAddress); void OnShutdown(RakPeerInterface *peer); void Update(RakPeerInterface *peer); PluginReceiveResult OnDownloadComplete(unsigned char *packetData, int packetDataLength, SystemAddress sender, RakNetTime timestamp); PluginReceiveResult OnDownloadStarted(unsigned char *packetData, int packetDataLength, SystemAddress sender, RakNetTime timestamp); PluginReceiveResult OnConstruction(unsigned char *packetData, int packetDataLength, SystemAddress sender, RakNetTime timestamp); PluginReceiveResult OnDestruction(unsigned char *packetData, int packetDataLength, SystemAddress sender, RakNetTime timestamp); PluginReceiveResult OnVisibilityChange(unsigned char *packetData, int packetDataLength, SystemAddress sender, RakNetTime timestamp); PluginReceiveResult OnSerialize(unsigned char *packetData, int packetDataLength, SystemAddress sender, RakNetTime timestamp); bool AddToAndWriteExclusionList(SystemAddress recipient, RakNet::BitStream *bs, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList); void WriteExclusionList(RakNet::BitStream *bs, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList); void CullByAndAddToExclusionList( DataStructures::OrderedList<SystemAddress, Connection_RM2*,ReplicaManager2::Connection_RM2CompBySystemAddress> &inputList, DataStructures::OrderedList<SystemAddress, Connection_RM2*,ReplicaManager2::Connection_RM2CompBySystemAddress> &culledOutput, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList); void ReadExclusionList(RakNet::BitStream *bs, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList); void Send(RakNet::BitStream *bs, SystemAddress recipient, PacketPriority priority, PacketReliability reliability, char orderingChannel); void Clear(void); void DownloadToNewConnection(Connection_RM2* connection, RakNetTime timestamp, PacketPriority priority, PacketReliability reliability, char orderingChannel); Connection_RM2* CreateConnectionIfDoesNotExist(SystemAddress systemAddress, bool *newConnection); Connection_RM2* AutoCreateConnection(SystemAddress systemAddress, bool *newConnection); void AddConstructionReference(Connection_RM2* connection, Replica2* replica); void AddVisibilityReference(Connection_RM2* connection, Replica2* replica); void RemoveVisibilityReference(Connection_RM2* connection, Replica2* replica); void WriteHeader(RakNet::BitStream *bs, MessageID type, RakNetTime timestamp); friend class Connection_RM2; friend class Replica2; RakPeerInterface *rakPeer; Connection_RM2Factory *connectionFactoryInterface; bool autoUpdateConstruction, autoUpdateVisibility; char defaultOrderingChannel; PacketPriority defaultPacketPriority; PacketReliability defaultPacketReliablity; bool autoAddNewConnections; bool doReplicaAutoUpdate; RakNetTime lastUpdateTime; DataStructures::List<Replica2*> fullReplicaUnorderedList; DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> fullReplicaOrderedList; DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> alwaysDoConstructReplicaOrderedList; DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> alwaysDoSerializeReplicaOrderedList; // Should only be in this list if QueryIsServer() is true DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> variableConstructReplicaOrderedList; DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> variableSerializeReplicaOrderedList; DataStructures::OrderedList<SystemAddress, Connection_RM2*, ReplicaManager2::Connection_RM2CompBySystemAddress> connectionList; }; /// \brief The result of various scope and construction queries /// \ingroup REPLICA_MANAGER_2_GROUP enum RAK_DLL_EXPORT BooleanQueryResult { /// The query is always true, for all systems. Certain optimizations are performed here, but you should not later return any other value without first calling ReplicaManager2::RecalculateVisibility BQR_ALWAYS, /// True BQR_YES, /// False BQR_NO, /// The query is never true, for all systems. Certain optimizations are performed here, but you should not later return any other value without first calling ReplicaManager2::RecalculateVisibility BQR_NEVER }; /// \brief Contextual information about serialization, passed to some functions in Replica2 /// \ingroup REPLICA_MANAGER_2_GROUP struct RAK_DLL_EXPORT SerializationContext { SerializationContext() {} ~SerializationContext() {} SerializationContext(SerializationType st, SystemAddress relay, SystemAddress recipient, RakNetTime _timestamp) {serializationType=st; relaySourceAddress=relay; recipientAddress=recipient; timestamp=_timestamp;} /// The system that sent the message to us. SystemAddress relaySourceAddress; /// The system that we are sending to. SystemAddress recipientAddress; /// Timestamp to send with the message. 0 means undefined. Set to non-zero to actually transmit using ID_TIMESTAMP RakNetTime timestamp; /// What type of serialization was performed SerializationType serializationType; /// General category of serialization static bool IsSerializationCommand(SerializationType r); /// General category of serialization static bool IsDownloadCommand(SerializationType r); /// General category of serialization static bool IsDestructionCommand(SerializationType r); /// General category of serialization static bool IsConstructionCommand(SerializationType r); /// General category of serialization static bool IsVisibilityCommand(SerializationType r); /// General category of serialization static bool IsVisible(SerializationType r); }; /// \brief Base class for game objects that use the ReplicaManager2 system /// All game objects that want to use the ReplicaManager2 functionality must inherit from Replica2. /// Generally you will want to implement at a minimum Serialize(), Deserialize(), and SerializeConstruction() /// \ingroup REPLICA_MANAGER_2_GROUP class RAK_DLL_EXPORT Replica2 : public NetworkIDObject { public: /// Constructor Replica2(); /// Destructor virtual ~Replica2(); /// Sets the replica manager to use with this Replica. /// Will also set the NetworkIDManager associated with RakPeerInterface::SetNetworkIDManager() /// Call this before using any of the functions below! /// \param[in] rm A pointer to your instance of ReplicaManager 2 void SetReplicaManager(ReplicaManager2* rm); /// Returns what was passed to SetReplicaManager(), or 0 if no value ever passed /// \return Registered instance of ReplicaManager2 ReplicaManager2* GetReplicaManager(void) const; /// Construct this object on other systems /// Triggers a call to SerializeConstruction() /// \note If using peer-to-peer, don't forget to set NetworkID::peerToPeerMode=true and comment out NETWORK_ID_USE_PTR_TABLE in NetworkIDManager.h /// \param[in] recipientAddress Which system to send to /// \param[in] serializationType What type of command this is. Use UNDEFINED_REASON to have a type chosen automatically virtual void SendConstruction(SystemAddress recipientAddress, SerializationType serializationType=UNDEFINED_REASON); /// Destroy this object on other systems /// Triggers a call to SerializeDestruction() /// \param[in] recipientAddress Which system to send to /// \param[in] serializationType What type of command this is. Use UNDEFINED_REASON to have a type chosen automatically virtual void SendDestruction(SystemAddress recipientAddress, SerializationType serializationType=UNDEFINED_REASON); /// Serialize this object to another system /// Triggers a call to Serialize() /// \param[in] recipientAddress Which system to send to /// \param[in] serializationType What type of command this is. Use UNDEFINED_REASON to have a type chosen automatically virtual void SendSerialize(SystemAddress recipientAddress, SerializationType serializationType=UNDEFINED_REASON); /// Update the visibility of this object on another system /// Triggers a call to SerializeVisibility() /// \param[in] recipientAddress Which system to send to /// \param[in] serializationType What type of command this is. Use UNDEFINED_REASON to have a type chosen automatically virtual void SendVisibility(SystemAddress recipientAddress, SerializationType serializationType=UNDEFINED_REASON); /// Construct this object on other systems /// \param[in] serializationContext Which system to send to, an input timestamp, and the SerializationType. 0 to use defaults, no timestamp. virtual void BroadcastConstruction(SerializationContext *serializationContext=0); /// Serialize this object to all current connections /// Triggers a call to SerializeConstruction() for each connection (you can serialize differently per connection). /// \param[in] serializationContext Which system to send to, an input timestamp, and the SerializationType. 0 to use defaults, no timestamp. virtual void BroadcastSerialize(SerializationContext *serializationContext=0); /// Destroy this object on all current connections /// Triggers a call to SerializeDestruction() for each connection (you can serialize differently per connection). /// \param[in] serializationContext Which system to send to, an input timestamp, and the SerializationType. 0 to use defaults, no timestamp. virtual void BroadcastDestruction(SerializationContext *serializationContext=0); /// Update the visibility state of this object on all other systems /// Use SEND_VISIBILITY_TRUE_TO_SYSTEM or SEND_VISIBILITY_FALSE_TO_SYSTEM in \a serializationContext::serializationType /// Triggers a call to SerializeVisibility() for each connection (you can serialize differently per connection). /// \param[in] serializationContext Which system to send to, an input timestamp, and the SerializationType. 0 to use defaults, no timestamp, true visibility virtual void BroadcastVisibility(bool isVisible, SerializationContext *serializationContext=0); /// CALLBACK: /// Override in order to write to \a bitStream data identifying this class for the class factory. Will be received by Connection_RM2::Construct() to create an instance of this class. /// \param[out] bitStream Data used to identify this class, along with any data you also want to send when constructing the class /// \param[in] serializationContext serializationType passed to Replica2::SendConstruction(), along with destination system, and a timestamp you can write to. /// \return Return false to cancel the construction, true to process virtual bool SerializeConstruction(RakNet::BitStream *bitStream, SerializationContext *serializationContext)=0; /// CALLBACK: /// Override in order to write to \a bitStream data to send along with destruction requests. Will be received by DeserializeDestruction() /// \param[out] bitStream Data to send /// \param[in] serializationContext Describes which system we are sending to, and a timestamp as an out parameter /// \return Return false to cancel the operation, true to process virtual bool SerializeDestruction(RakNet::BitStream *bitStream, SerializationContext *serializationContext); /// CALLBACK: /// Override in order to write to \a bitStream data to send as regular class serialization, for normal per-tick data. Will be received by Deserialize() /// \param[out] bitStream Data to send /// \param[in] serializationContext Describes which system we are sending to, and a timestamp as an out parameter /// \return Return false to cancel the operation, true to process virtual bool Serialize(RakNet::BitStream *bitStream, SerializationContext *serializationContext); /// CALLBACK: /// Override in order to write to \a bitStream data to send along with visibility changes. Will be received by DeserializeVisibility() /// \param[out] bitStream Data to send /// \param[in] serializationContext Describes which system we are sending to, and a timestamp as an out parameter /// \return Return false to cancel the operation, true to process virtual bool SerializeVisibility(RakNet::BitStream *bitStream, SerializationContext *serializationContext); /// CALLBACK: /// Receives data written by SerializeDestruction() /// \param[in] bitStream Data sent /// \param[in] serializationType SerializationContext::serializationType /// \param[in] sender Which system sent this message to us /// \param[in] timestamp If a timestamp was written, will be whatever was written adjusted to the local system time. 0 if not used. virtual void DeserializeDestruction(RakNet::BitStream *bitStream, SerializationType serializationType, SystemAddress sender, RakNetTime timestamp); /// CALLBACK: /// Receives data written by Serialize() /// \param[in] bitStream Data sent /// \param[in] serializationType SerializationContext::serializationType /// \param[in] sender Which system sent this message to us /// \param[in] timestamp If a timestamp was written, will be whatever was written adjusted to the local system time. 0 if not used. virtual void Deserialize(RakNet::BitStream *bitStream, SerializationType serializationType, SystemAddress sender, RakNetTime timestamp); /// CALLBACK: /// Receives data written by SerializeVisibility() /// \param[in] bitStream Data sent /// \param[in] serializationType SerializationContext::serializationType /// \param[in] sender Which system sent this message to us /// \param[in] timestamp If a timestamp was written, will be whatever was written adjusted to the local system time. 0 if not used. virtual void DeserializeVisibility(RakNet::BitStream *bitStream, SerializationType serializationType, SystemAddress sender, RakNetTime timestamp); /// CALLBACK: /// For a given connection, should this object exist? /// Checked every Update cycle if ReplicaManager2::SetAutoUpdateScope() parameter \a construction is true /// Defaults to BQR_ALWAYS /// \param[in] connection Which connection we are referring to. 0 means unknown, in which case the system is checking for BQR_ALWAYS or BQR_NEVER as an optimization. /// \return BQR_NO and the object will be destroyed. BQR_YES and the object will be created. BQR_ALWAYS is YES for all connections, and is optimized to only be checked once. virtual BooleanQueryResult QueryConstruction(Connection_RM2 *connection); /// CALLBACK: /// For a given connection, should this object be visible (updatable?) /// Checked every Update cycle if ReplicaManager2::SetAutoUpdateScope() parameter \a serializationVisiblity is true /// Defaults to BQR_ALWAYS /// \param[in] connection Which connection we are referring to. 0 means unknown, in which case the system is checking for BQR_ALWAYS or BQR_NEVER as an optimization. /// \return BQR_NO or BQR_YES and as this value changes per connection, you will get a call to DeserializeVisibility(). virtual BooleanQueryResult QueryVisibility(Connection_RM2 *connection); /// CALLBACK: /// Does this system have control over construction of this object? /// While not strictly required, it is best to have this consistently return true for only one system. Otherwise systems may fight and override each other. /// Defaults to NetworkIDManager::IsNetworkIDAuthority(); /// \return True if an authority over this operation, for this object instance virtual bool QueryIsConstructionAuthority(void) const; /// CALLBACK: /// Does this system have control over deletion of this object? /// While not strictly required, it is best to have this consistently return true for only one system. Otherwise systems may fight and override each other. /// Defaults to NetworkIDManager::IsNetworkIDAuthority(); /// \return True if an authority over this operation, for this object instance virtual bool QueryIsDestructionAuthority(void) const; /// CALLBACK: /// Does this system have control over visibility of this object? /// While not strictly required, it is best to have this consistently return true for only one system. Otherwise systems may fight and override each other. /// Defaults to NetworkIDManager::IsNetworkIDAuthority(); /// \return True if an authority over this operation, for this object instance virtual bool QueryIsVisibilityAuthority(void) const; /// CALLBACK: /// Does this system have control over serialization of object members of this object? /// It is reasonable to have this be true for more than one system, but you would want to serialize different variables so those systems do not conflict. /// Defaults to NetworkIDManager::IsNetworkIDAuthority(); /// \return True if an authority over this operation, for this object instance virtual bool QueryIsSerializationAuthority(void) const; /// CALLBACK: /// If QueryIsConstructionAuthority() is false for a remote system, should that system be able to create this kind of object? /// \param[in] sender Which system sent this message to us? Also happens to be the system that is requesting to create an object /// \param[in] replicaData Construction data used to create this object /// \param[in] type Which type of serialization operation was performed /// \param[in] timestamp Written timestamp with the packet. 0 if not used. /// \return True to allow remote construction of this object. If true, we will reply with SEND_CONSTRUCTION_REPLY_ACCEPTED_TO_CLIENT and the network ID will be set on the requester. virtual bool AllowRemoteConstruction(SystemAddress sender, RakNet::BitStream *replicaData, SerializationType type, RakNetTime timestamp); /// Adds a timer that will elapse every \a countdown milliseconds, calling Serialize with AUTOSERIALIZE_DEFAULT or whatever value was passed to \a serializationType /// Every time this timer elapses, the value returned from Serialize() will be compared to the last value returned by Serialize(). /// If different, SendSerialize() will be called automatically. /// It is possible to create your own AUTOSERIALIZE enumerations and thus control which parts of the object is serialized /// Use CancelAutoSerializeTimer() or ClearAutoSerializeTimers() to stop the timer. /// If this timer already exists, it will simply override the existing countdown /// This timer will automatically repeat every \a countdown milliseconds /// \param[in] interval Time in milliseconds between autoserialize ticks. Use 0 to process immediately, and every tick /// \param[in] serializationType User-defined identifier for what type of serialization operation to perform. Returned in Deserialize() as the \a serializationType parameter. /// \param[in] countdown Amount of time before doing the next autoserialize. Defaults to interval virtual void AddAutoSerializeTimer(RakNetTime interval, SerializationType serializationType=AUTOSERIALIZE_DEFAULT, RakNetTime countdown=(RakNetTime)-1 ); /// Elapse time for all timers added with AddAutoSerializeTimer() /// Only necessary to call this if you call Replica2::SetDoReplicaAutoSerializeUpdate(false) (which defaults to true) /// \param[in] timeElapsed How many milliseconds have elapsed since the last call /// \param[in] resynchOnly True to only update what was considered the last send, without actually doing a send. virtual void ElapseAutoSerializeTimers(RakNetTime timeElapsed, bool resynchOnly); /// Returns how many milliseconds are remaining until the next autoserialize update /// \param[in] serializationType User-defined identifier for what type of serialization operation to perform. Returned in Deserialize() as the \a serializationType parameter. /// \return How many milliseconds are remaining until the next autoserialize update. Returns -1 if no such autoserialization timer is in place. RakNetTime GetTimeToNextAutoSerialize(SerializationType serializationType=AUTOSERIALIZE_DEFAULT); /// Do the actual send call when needed to support autoSerialize /// If you want to do different types of send calls (UNRELIABLE for example) override this function. /// \param[in] serializationContext Describes the recipient, sender. serializationContext::timestamp is an [out] parameter which if you write to, will be send along with the message /// \param[in] serializedObject Data to pass to ReplicaManager2::SendSerialize() virtual void BroadcastAutoSerialize(SerializationContext *serializationContext, RakNet::BitStream *serializedObject); /// Stop calling an autoSerialize timer previously setup with AddAutoSerializeTimer() /// \param[in] serializationType Corresponding value passed to serializationType virtual void CancelAutoSerializeTimer(SerializationType serializationType=AUTOSERIALIZE_DEFAULT); /// Remove and deallocate all previously added autoSerialize timers virtual void ClearAutoSerializeTimers(void); /// A timer has elapsed. Compare the last value sent to the current value, and if different, send the new value /// \internal virtual void OnAutoSerializeTimerElapsed(SerializationType serializationType, RakNet::BitStream *output, RakNet::BitStream *lastOutput, RakNetTime lastAutoSerializeCountdown, bool resynchOnly); /// Immediately elapse all autoserialize timers /// Used internally when a Deserialize() event occurs, so that the deserialize does not trigger an autoserialize itself /// \internal /// \param[in] resynchOnly If true, do not send a Serialize() message if the data has changed virtual void ForceElapseAllAutoserializeTimers(bool resynchOnly); /// A call to Connection_RM2 Construct() has completed and the object is now internally referenced /// \param[in] replicaData Whatever was written \a bitStream in Replica2::SerializeConstruction() /// \param[in] type Whatever was written \a serializationType in Replica2::SerializeConstruction() /// \param[in] replicaManager ReplicaManager2 instance that created this class. /// \param[in] timestamp timestamp sent with Replica2::SerializeConstruction(), 0 for none. /// \param[in] networkId NetworkID that will be assigned automatically to the new object after this function returns /// \param[in] networkIDCollision True if the network ID that should be assigned to this object is already in use. Usuallly this is because the object already exists, and you should just read your data and return 0. /// \return Return 0 to signal that construction failed or was refused for this object. Otherwise return the object that was created. A reference will be held to this object, and SetNetworkID() and SetReplicaManager() will be called automatically. virtual void OnConstructionComplete(RakNet::BitStream *replicaData, SystemAddress sender, SerializationType type, ReplicaManager2 *replicaManager, RakNetTime timestamp, NetworkID networkId, bool networkIDCollision); protected: virtual void ReceiveSerialize(SystemAddress sender, RakNet::BitStream *serializedObject, SerializationType serializationType, RakNetTime timestamp, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList ); virtual void ReceiveDestruction(SystemAddress sender, RakNet::BitStream *serializedObject, SerializationType serializationType, RakNetTime timestamp, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList ); virtual void DeleteOnReceiveDestruction(SystemAddress sender, RakNet::BitStream *serializedObject, SerializationType serializationType, RakNetTime timestamp, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList ); virtual void ReceiveVisibility(SystemAddress sender, RakNet::BitStream *serializedObject, SerializationType serializationType, RakNetTime timestamp, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList); virtual Replica2 * ReceiveConstructionReply(SystemAddress sender, BitStream *replicaData, bool constructionAllowed); friend class ReplicaManager2; friend class Connection_RM2; static unsigned char clientSharedID; static Replica2* clientPtrArray[256]; bool hasClientID; unsigned char clientID; ReplicaManager2 *rm2; struct AutoSerializeEvent { SerializationType serializationType; RakNetTime initialCountdown; RakNetTime remainingCountdown; bool writeToResult1; RakNet::BitStream lastAutoSerializeResult1; RakNet::BitStream lastAutoSerializeResult2; }; DataStructures::Map<SerializationType, AutoSerializeEvent*> autoSerializeTimers; }; /// \brief Implement this factory class to return instances of your Connection_RM2 derived object. This is used as a class factory and exposes functionality related to the connection and the system /// \ingroup REPLICA_MANAGER_2_GROUP class RAK_DLL_EXPORT Connection_RM2Factory { public: Connection_RM2Factory() {} virtual ~Connection_RM2Factory() {} virtual Connection_RM2* AllocConnection(void) const=0; virtual void DeallocConnection(Connection_RM2* s) const=0; }; /// \brief This class represents a connection between two instances of ReplicaManager2 /// Represents a connection. Allocated by user supplied factory interface Connection_RM2Factory /// Implicitly created as needed /// Generally you will want to implement at a minimum the Construct() function, used as a factory function to create your game objects /// \ingroup REPLICA_MANAGER_2_GROUP class RAK_DLL_EXPORT Connection_RM2 { public: /// Constructor Connection_RM2(); /// Destructor virtual ~Connection_RM2(); /// Factory function, used to create instances of your game objects /// Encoding is entirely up to you. \a replicaData will hold whatever was written \a bitStream in Replica2::SerializeConstruction() /// One efficient way to do it is to use StringTable.h. This allows you to send predetermined strings over the network at a cost of 9 bits, up to 65536 strings /// \note The object is not yet referenced by ReplicaManager2 in this callback. Use Replica2::OnConstructionComplete() to perform functionality such as AutoSerialize() /// \param[in] replicaData Whatever was written \a bitStream in Replica2::SerializeConstruction() /// \param[in] type Whatever was written \a serializationType in Replica2::SerializeConstruction() /// \param[in] replicaManager ReplicaManager2 instance that created this class. /// \param[in] timestamp timestamp sent with Replica2::SerializeConstruction(), 0 for none. /// \param[in] networkId NetworkID that will be assigned automatically to the new object after this function returns /// \param[in] networkIDCollision True if the network ID that should be assigned to this object is already in use. Usuallly this is because the object already exists, and you should just read your data and return 0. /// \return Return 0 to signal that construction failed or was refused for this object. Otherwise return the object that was created. A reference will be held to this object, and SetNetworkID() and SetReplicaManager() will be called automatically. virtual Replica2* Construct(RakNet::BitStream *replicaData, SystemAddress sender, SerializationType type, ReplicaManager2 *replicaManager, RakNetTime timestamp, NetworkID networkId, bool networkIDCollision)=0; /// CALLBACK: /// Called before a download is sent to a new connection, called after ID_REPLICA_MANAGER_DOWNLOAD_STARTED is sent. /// Gives you control over the list of objects to be downloaded. For greater control, you can override ReplicaManager2::DownloadToNewConnection /// Defaults to send everything in the default order /// \param[in] fullReplicaUnorderedList The list of all known objects in the order they were originally known about by the system (the first time used by any function) /// \param[out] orderedDownloadList An empty list. Copy fullReplicaUnorderedList to this list to send everything. Leave elements out to not send them. Add them to the list in a different order to send them in that order. virtual void SortInitialDownload( const DataStructures::List<Replica2*> &orderedDownloadList, DataStructures::List<Replica2*> &initialDownloadList ); /// CALLBACK: /// Called before a download is sent to a new connection /// \param[out] objectData What data you want to send to DeSerializeDownloadStarted() /// \param[in] replicaManager Which replica manager to use to perform the send /// \param[in/out] serializationContext Target recipient, optional timestamp, type of command virtual void SerializeDownloadStarted(RakNet::BitStream *objectData, ReplicaManager2 *replicaManager, SerializationContext *serializationContext); /// CALLBACK: /// Called after a download is sent to a new connection /// \param[out] objectData What data you want to send to DeSerializeDownloadComplete() /// \param[in] replicaManager Which replica manager to use to perform the send /// \param[in/out] serializationContext Target recipient, optional timestamp, type of command virtual void SerializeDownloadComplete(RakNet::BitStream *objectData, ReplicaManager2 *replicaManager, SerializationContext *serializationContext); /// CALLBACK: /// A new connection was added. All objects that are constructed and visible for this system will arrive immediately after this message. /// Write data to \a objectData by deriving from SerializeDownloadStarted() /// \note Only called if SetAutoUpdateScope is called with serializationVisiblity or construction true. (This is the default) /// \param[in] objectData objectData Data written through SerializeDownloadStarted() /// \param[in] replicaManager Which replica manager to use to perform the send /// \param[in] timestamp timestamp sent, 0 for none /// \param[in] serializationType Type of command virtual void DeserializeDownloadStarted(RakNet::BitStream *objectData, SystemAddress sender, ReplicaManager2 *replicaManager, RakNetTime timestamp, SerializationType serializationType); /// CALLBACK: /// A new connection was added. All objects that are constructed and visible for this system have now arrived. /// Write data to \a objectData by deriving from SerializeDownloadComplete /// \note Only called if SetAutoUpdateScope is called with serializationVisiblity or construction true. (This is the default) /// \param[in] objectData objectData Data written through SerializeDownloadComplete() /// \param[in] replicaManager Which replica manager to use to perform the send /// \param[in] timestamp timestamp sent, 0 for none /// \param[in] serializationType Type of command virtual void DeserializeDownloadComplete(RakNet::BitStream *objectData, SystemAddress sender, ReplicaManager2 *replicaManager, RakNetTime timestamp, SerializationType serializationType); /// Given a list of objects, compare it against lastConstructionList. /// BroadcastConstruct() is called for objects that only exist in the new list. /// BroadcastDestruct() is called for objects that only exist in the old list. /// This is used by SetConstructionByReplicaQuery() for all Replica2 that do not return BQR_ALWAYS from Replica2::QueryConstruction() /// If you want to pass your own, more efficient list to check against, call ReplicaManager2::SetAutoUpdateScope with construction=false and call this function yourself when desired /// \param[in] List of all objects that do not return BQR_ALWAYS from Replica2::QueryConstruction() that should currently be created on this system /// \param[in] replicaManager Which replica manager to use to perform the send virtual void SetConstructionByList(DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> &currentVisibility, ReplicaManager2 *replicaManager); /// Given a list of objects, compare it against lastSerializationList. /// Replica2::BroadcastVisibility(true) is called for objects that only exist in the new list. /// Replica2::BroadcastVisibility(false) is called for objects that only exist in the old list. /// This is used by SetVisibilityByReplicaQuery() for all Replica2 that do not return BQR_ALWAYS from Replica2::QueryVisibility() /// If you want to pass your own, more efficient list to check against, call ReplicaManager2::SetAutoUpdateScope with construction=false and call this function yourself when desired /// \param[in] List of all objects that do not return BQR_ALWAYS from Replica2::QueryConstruction() that should currently be created on this system /// \param[in] replicaManager Which replica manager to use to perform the send virtual void SetVisibilityByList(DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> &currentVisibility, ReplicaManager2 *replicaManager); /// Go through all registered Replica2 objects that do not return BQR_ALWAYS from Replica2::QueryConstruction() /// For each of these objects that return BQR_YES, pass them to currentVisibility in SetConstructionByList() /// Automatically called every tick if ReplicaManager2::SetAutoUpdateScope with construction=true is called (which is the default) /// \param[in] replicaManager Which replica manager to use to perform the send virtual void SetConstructionByReplicaQuery(ReplicaManager2 *replicaManager); /// Go through all registered Replica2 objects that do not return BQR_ALWAYS from Replica2::QueryVisibility() /// For each of these objects that return BQR_YES, pass them to currentVisibility in SetVisibilityByList() /// Automatically called every tick if ReplicaManager2::SetAutoUpdateScope with construction=true is called (which is the default) /// \param[in] replicaManager Which replica manager to use to perform the send virtual void SetVisibilityByReplicaQuery(ReplicaManager2 *replicaManager); /// Set the system address to use with this class instance. This is set internally when the object is created void SetSystemAddress(SystemAddress sa); /// Get the system address associated with this class instance. SystemAddress GetSystemAddress(void) const; protected: void Deref(Replica2* replica); void CalculateListExclusivity( const DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> &listOne, const DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> &listTwo, DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> &exclusiveToListOne, DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> &exclusiveToListTwo ) const; virtual Replica2 * ReceiveConstruct(RakNet::BitStream *replicaData, NetworkID networkId, SystemAddress sender, unsigned char localClientId, SerializationType type, ReplicaManager2 *replicaManager, RakNetTime timestamp, DataStructures::OrderedList<SystemAddress,SystemAddress> &exclusionList); friend class ReplicaManager2; // Address of this participant SystemAddress systemAddress; DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> lastConstructionList; DataStructures::OrderedList<Replica2*, Replica2*, ReplicaManager2::Replica2ObjectComp> lastSerializationList; }; } #endif
[ "PhillipSpiess@d8b90d80-bb63-11dd-bed2-db724ec49875" ]
[ [ [ 1, 852 ] ] ]
92caab575b9c805bc27e85700975a1ac01b11d75
450bab29aac27034d23cfaa27309f5c000e660af
/MARITServer/pc2rc.cpp
22865b4d549da9a8a7dcbf7acda565721b6e1143
[]
no_license
yinancui/MARITServer
518986831aecc03db8f5a46f35b234a85c076e3d
98884d14d38aa5fc5d60e343024c0cab4ff92433
refs/heads/master
2020-05-30T19:00:05.012007
2011-07-22T19:41:16
2011-07-22T19:41:16
2,090,431
0
0
null
null
null
null
UTF-8
C++
false
false
4,622
cpp
#include "stdafx.h" #include "pc2rc.h" #include <windows.h> #include <iostream> char port[10]; // port name "com1",... int rate; // baudrate serial_parity parityMode; HANDLE serial_handle; //HANDLE sThread; //control c; int normalized_to_pc2rc2(double cntlcmd, int troff, double slp) { int y = 15000 + troff + ((int) (cntlcmd * slp)); if ((y % 2 == 0) && (y != 15000)) y += 1; return y; } void sendArray(char *buffer, int len) { unsigned long result; if (serial_handle!=INVALID_HANDLE_VALUE) { //WriteFile(serial_handle, buffer, len, &result, NULL); if (!WriteFile(serial_handle, buffer, len, &result, NULL)) // WriteFile returns nonzero when succeeds std::cout << "Failed to write to serial port.\n"; else { std::cout << "Writing to serial port was successful.\n"; //std::cout << buffer << std::endl; } } } int initializeSerialPort(char *port_arg, int rate_arg, serial_parity parity_arg) { int error; DCB dcb = {0}; //clear all its fields COMMTIMEOUTS cto = { 0, 0, 0, 1, 1 }; /* --------------------------------------------- */ if (serial_handle!=INVALID_HANDLE_VALUE) CloseHandle(serial_handle); serial_handle = INVALID_HANDLE_VALUE; error = 0; if (port_arg!=0) { strncpy_s(port, port_arg, 10); // pass port_arg to port, and from port to serial_handle later rate = rate_arg; parityMode= parity_arg; memset(&dcb,0,sizeof(dcb)); /* -------------------------------------------------------------------- */ // set DCB to configure the serial port dcb.DCBlength = sizeof(dcb); /* ---------- Serial Port Config ------- */ dcb.BaudRate = rate; switch(parityMode) { case spNONE: dcb.Parity = NOPARITY; dcb.fParity = 0; break; case spEVEN: dcb.Parity = EVENPARITY; dcb.fParity = 1; break; case spODD: dcb.Parity = ODDPARITY; dcb.fParity = 1; break; } dcb.StopBits = ONESTOPBIT; dcb.ByteSize = 8; dcb.fOutxCtsFlow = 0; dcb.fOutxDsrFlow = 0; dcb.fDtrControl = DTR_CONTROL_DISABLE; dcb.fDsrSensitivity = 0; dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fOutX = 0; dcb.fInX = 0; /* ----------------- misc parameters ----- */ dcb.fErrorChar = 0; dcb.fBinary = 1; dcb.fNull = 0; dcb.fAbortOnError = 0; dcb.wReserved = 0; dcb.XonLim = 2; dcb.XoffLim = 4; dcb.XonChar = 0x13; dcb.XoffChar = 0x19; dcb.EvtChar = 0; /* -------------------------------------------------------------------- */ serial_handle = CreateFileA(port, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,NULL,NULL); //changed from CreateFile() // opening serial port if (serial_handle != INVALID_HANDLE_VALUE) { if(!SetCommMask(serial_handle, 0)) error = 1; // set timeouts if(!SetCommTimeouts(serial_handle,&cto)) error = 2; // set DCB if(!SetCommState(serial_handle,&dcb)) error = 4; } else error = 8; } else error = 16; /* --------------------------------------------- */ if (error!=0) { CloseHandle(serial_handle); serial_handle = INVALID_HANDLE_VALUE; } /*else { //All went well, start the command sender thread unsigned dwThreadId = 0; sThread = (HANDLE) _beginthreadex(NULL, 0,&cmdSendThread,NULL, 0,&dwThreadId); //by weizhong } */ return(error); } void closeSerialPort() { //TerminateThread(sThread,0); if (serial_handle!=INVALID_HANDLE_VALUE) CloseHandle(serial_handle); serial_handle = INVALID_HANDLE_VALUE; }
[ [ [ 1, 159 ] ] ]
a4f103f91d4806662b8610a64f2dde9437c831e2
2199870f3077e1005a36cd1cb2382368aeb977de
/faceapistreamer/Socket/stdafx.cpp
48f150ca8fbe4f57ed0a9a05d6b70a8380346878
[]
no_license
caomw/CVTrack
89f39cd579f6a419258f74baebb10470f0c02058
a384d63a1831beb724e8b11463f9b00f3015b1f8
refs/heads/master
2020-12-31T02:22:20.345394
2011-06-04T15:45:09
2011-06-04T15:45:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
385
cpp
// stdafx.cpp : source file that includes just the standard includes // Socket.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file #include "SocketConnector.h" #include "TennisWatcher.h" #include "CLEyeMulticam.h"
[ "[email protected]", "Ben@.(none)" ]
[ [ [ 1, 12 ] ], [ [ 13, 14 ] ] ]
730674a420886be307d8ec24c36fddb872409c32
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Autumn/Core/Math/Color.cpp
6b83316c5db8b27ee784ff290e860641955750b9
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
#include "stdafx.h" #include "Color.h" Color::Color() : m_cColor(0.0f, 0.0f, 0.0f, 1.0f) { } Color::Color(float _fRed, float _fGreen, float _fBlue) : m_cColor( _fRed, _fGreen, _fBlue, 1.0f) { } Color::Color(float _fRed, float _fGreen, float _fBlue, float _fAlpha) : m_cColor( _fRed, _fGreen, _fBlue, _fAlpha) { } Color::Color(const Color & c) : m_cColor( c.m_cColor ) { } Color::~Color() { } void Color::Set(float _fRed, float _fGreen, float _fBlue, float _fAlpha) { m_cColor.r = _fRed; m_cColor.g = _fGreen; m_cColor.b = _fBlue; m_cColor.a = _fAlpha; } Color operator + (const Color & _c1, const Color & _c2) { Color cRes; cRes.m_cColor = _c1.m_cColor + _c2.m_cColor; return cRes; } Color operator - (const Color & _c1, const Color & _c2) { Color cRes; cRes.m_cColor = _c1.m_cColor - _c2.m_cColor; return cRes; } Color operator * (const Color & _c1, const Color & _c2) { return Color(_c1.m_cColor.r * _c2.m_cColor.r, _c1.m_cColor.g * _c2.m_cColor.g, _c1.m_cColor.b * _c2.m_cColor.b, _c1.m_cColor.a * _c2.m_cColor.a); } Color operator * (const Color & _c, const float & _f) { Color cRes; cRes.m_cColor = _c.m_cColor * _f; return cRes; }
[ "edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 61 ] ] ]
475228c5b2215ec462e572a21cafeb955dba6a86
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-downloader/wxCURL/samples/curl_app/wxDeleteDialog.cpp
4ca1b0dd6020d49507438a4019589c630c05aaef
[]
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
UTF-8
C++
false
false
3,740
cpp
/******************************************* * base.cpp * Created by Casey O'Donnell on Tue Jun 29 2004. * Copyright (c) 2004 Casey O'Donnell. All rights reserved. * Licence: wxWidgets Licence ******************************************/ #include "wxcurl/wxcurl_config.h" #include <wx/xrc/xmlres.h> #include <wxcurl/http.h> #include "wxDeleteDialog.h" ////////////////////////////////////////////////////////////////////// // Resources ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Constants ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Event Tables and Other Macros for wxWindows ////////////////////////////////////////////////////////////////////// // the event tables connect the wxWindows events with the functions (event // handlers) which process them. It can be also done at run-time, but for the // simple menu events like this the static method is much simpler. IMPLEMENT_CLASS(wxDeleteDialog, wxDialog) BEGIN_EVENT_TABLE(wxDeleteDialog, wxDialog) EVT_BUTTON(XRCID("delete_button"), wxDeleteDialog::OnDelete) END_EVENT_TABLE() ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// wxDeleteDialog::wxDeleteDialog(wxWindow* pParent) { wxXmlResource::Get()->LoadDialog(this, pParent, "delete_dialog"); SetSize(400, -1); m_pDeleCtrl = XRCCTRL(*this, "dele_text_ctrl", wxTextCtrl); m_pUserCtrl = XRCCTRL(*this, "user_text_ctrl", wxTextCtrl); m_pPassCtrl = XRCCTRL(*this, "pass_text_ctrl", wxTextCtrl); m_pResponseCtrl = XRCCTRL(*this, "response_text_ctrl", wxTextCtrl); if(m_pDeleCtrl && m_pUserCtrl && m_pPassCtrl) { m_szDefaultDele = m_pDeleCtrl->GetValue(); m_szDefaultUser = m_pUserCtrl->GetValue(); m_szDefaultPass = m_pPassCtrl->GetValue(); } } wxDeleteDialog::~wxDeleteDialog() { } ////////////////////////////////////////////////////////////////////// // Event Handlers ////////////////////////////////////////////////////////////////////// void wxDeleteDialog::OnDelete(wxCommandEvent& WXUNUSED(event)) { if(m_pDeleCtrl && m_pUserCtrl && m_pPassCtrl) { wxString szDele = m_pDeleCtrl->GetValue(); wxString szUser = m_pUserCtrl->GetValue(); wxString szPass = m_pPassCtrl->GetValue(); wxString szResponse; if((szDele == m_szDefaultDele)) { wxMessageBox("Please change the DELETE location.", "Error...", wxICON_INFORMATION|wxOK, this); } else if((szUser == m_szDefaultUser) && (szPass == m_szDefaultPass)) { wxMessageBox("Please change the username or password.", "Error...", wxICON_INFORMATION|wxOK, this); } else { // Do it! wxCurlHTTP http(szDele, szUser, szPass); if(http.Delete()) { szResponse = "SUCCESS!\n\n"; szResponse += wxString::Format("\nResponse Code: %d\n\n", http.GetResponseCode()); szResponse += http.GetResponseHeader(); szResponse += "\n\n"; szResponse += http.GetResponseBody(); if(m_pResponseCtrl) m_pResponseCtrl->SetValue(szResponse); } else { szResponse = "FAILURE!\n\n"; szResponse += wxString::Format("\nResponse Code: %d\n\n", http.GetResponseCode()); szResponse += http.GetResponseHeader(); szResponse += "\n\n"; szResponse += http.GetResponseBody(); szResponse += "\n\n"; szResponse += http.GetErrorString(); if(m_pResponseCtrl) m_pResponseCtrl->SetValue(szResponse); } } } }
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 117 ] ] ]
a224dcfca5ee04ba01ec42f245866807b56ed636
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/TEST_MyGUI_Source/MyGUIEngine/src/MyGUI_RenderBox.cpp
8c042fe764957c8fd23e58c2cee3597a1db9d2dc
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
WINDOWS-1251
C++
false
false
8,369
cpp
/*! @file @author Evmenov Georgiy @date 01/2008 @module */ #include "MyGUI_Gui.h" #include "MyGUI_RenderBox.h" #include "MyGUI_InputManager.h" #include <OgreTextureManager.h> namespace MyGUI { const size_t TEXTURE_SIZE = 512; RenderBox::RenderBox(const IntCoord& _coord, char _align, const WidgetSkinInfoPtr _info, CroppedRectanglePtr _parent, WidgetCreator * _creator, const Ogre::String & _name) : Widget(_coord, _align, _info, _parent, _creator, _name), mUserViewport(false), mEntity(null), mBackgroungColour(Ogre::ColourValue::Blue), mMouseRotation(false), mLeftPressed(false), mRotationSpeed(RENDER_BOX_AUTO_ROTATION_SPEED), mAutoRotation(false) { // первоначальная инициализация MYGUI_DEBUG_ASSERT(null != mMainSkin, "need one subskin"); // сохраняем оригинальный курсор mPointerKeeper = mPointer; mPointer.clear(); createRenderTexture(); } RenderBox::~RenderBox() { clear(); if (mRotationSpeed) Gui::getInstance().removeFrameListener(this); Ogre::Root * root = Ogre::Root::getSingletonPtr(); if (root && mScene) root->destroySceneManager(mScene); } // добавляет в сцену объект, старый удаляеться void RenderBox::injectObject(const Ogre::String& _meshName) { if(mUserViewport) { mUserViewport = false; createRenderTexture(); } clear(); mEntity = mScene->createEntity(utility::toString(this, "_RenderBoxMesh_", _meshName), _meshName); mNode->attachObject(mEntity); mPointer = mMouseRotation ? mPointerKeeper : ""; updateViewport(); } // очищает сцену void RenderBox::clear() { setRotationAngle(Ogre::Degree(0)); if (mEntity) { mNode->detachObject(mEntity); mScene->destroyEntity(mEntity); mEntity = 0; } } void RenderBox::setAutoRotationSpeed(int _speed) { mRotationSpeed = _speed; } void RenderBox::setBackgroungColour(const Ogre::ColourValue & _colour) { if (false == mUserViewport){ mBackgroungColour = _colour; Ogre::Viewport *v = mTexture->getViewport(0); v->setBackgroundColour(mBackgroungColour); } } void RenderBox::setRotationAngle(const Ogre::Degree & _rotationAngle) { if (false == mUserViewport){ mNode->resetOrientation(); mNode->yaw(Ogre::Radian(_rotationAngle)); } } void RenderBox::setMouseRotation(bool _enable) { mMouseRotation = _enable; mPointer = (mMouseRotation && mEntity) ? mPointerKeeper : ""; } void RenderBox::setRenderTarget(Ogre::Camera * _camera) { // полная очистка clear(); mPointer = ""; Ogre::Root * root = Ogre::Root::getSingletonPtr(); if (root && mScene) root->destroySceneManager(mScene); mScene = 0; // создаем новый материал mUserViewport = true; mRttCam = _camera; std::string texture(utility::toString(this, "_TextureRenderBox")); Ogre::Root::getSingleton().getRenderSystem()->destroyRenderTexture(texture); Ogre::TextureManager & manager = Ogre::TextureManager::getSingleton(); manager.remove(texture); mTexture = manager.createManual(texture, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, TEXTURE_SIZE, TEXTURE_SIZE, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET) ->getBuffer()->getRenderTarget(); Ogre::Viewport *v = mTexture->addViewport( mRttCam ); v->setClearEveryFrame(true); _setTextureName(texture); } void RenderBox::setPosition(const IntCoord& _coord) { updateViewport(); Widget::setPosition(_coord); } void RenderBox::setSize(const IntSize& _size) { updateViewport(); Widget::setSize(_size); } void RenderBox::_frameEntered(float _time) { if ((false == mUserViewport) && (mAutoRotation) && (false == mLeftPressed)) mNode->yaw(Ogre::Radian(Ogre::Degree(_time * mRotationSpeed))); } void RenderBox::_onMouseDrag(int _left, int _top) { if ((false == mUserViewport) && mMouseRotation && mAutoRotation) { mNode->yaw(Ogre::Radian(Ogre::Degree(_left - mLastPointerX))); mLastPointerX = _left; } // !!! ОБЯЗАТЕЛЬНО вызывать в конце метода Widget::_onMouseDrag(_left, _top); } void RenderBox::_onMouseButtonPressed(bool _left) { if (mMouseRotation && mAutoRotation) { const IntPoint & point = InputManager::getInstance().getLastLeftPressed(); mLastPointerX = point.left; mLeftPressed = true; } // !!! ОБЯЗАТЕЛЬНО вызывать в конце метода Widget::_onMouseButtonPressed(_left); } void RenderBox::_onMouseButtonReleased(bool _left) { if (_left) mLeftPressed = false; // !!! ОБЯЗАТЕЛЬНО вызывать в конце метода Widget::_onMouseButtonReleased(_left); } void RenderBox::createRenderTexture() { mPointer = mMouseRotation ? mPointerKeeper : ""; // создаем новый сцен менеджер mScene = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC, utility::toString(this, "_SceneManagerRenderBox")); // создаем нод к которуму будем всякую дрянь атачить mNode = mScene->getRootSceneNode()->createChildSceneNode(); mScene->setAmbientLight(Ogre::ColourValue(0.8, 0.8, 0.8)); // главный источник света Ogre::Vector3 dir(-1, -1, 0.5); dir.normalise(); Ogre::Light * light = mScene->createLight(utility::toString(this, "_LightRenderBox")); light->setType(Ogre::Light::LT_DIRECTIONAL); light->setDirection(dir); std::string texture(utility::toString(this, "_TextureRenderBox")); Ogre::TextureManager & manager = Ogre::TextureManager::getSingleton(); manager.remove(texture); mTexture = manager.createManual(texture, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, TEXTURE_SIZE, TEXTURE_SIZE, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET) ->getBuffer()->getRenderTarget(); std::string camera(utility::toString(this, "_CameraRenderBox")); mRttCam = mScene->createCamera(camera); mCamNode = mScene->getRootSceneNode()->createChildSceneNode(camera); mCamNode->attachObject(mRttCam); mRttCam->setNearClipDistance(1); if (getHeight() == 0) mRttCam->setAspectRatio(1); else mRttCam->setAspectRatio(getWidth()/getHeight()); Ogre::Viewport *v = mTexture->addViewport( mRttCam ); v->setOverlaysEnabled(false); v->setClearEveryFrame( true ); v->setBackgroundColour(mBackgroungColour); v->setShadowsEnabled(true); v->setSkiesEnabled(false); _setTextureName(texture); } void RenderBox::updateViewport() { // при нуле вылетает if ((getWidth() <= 1) || (getHeight() <= 1) ) return; if ((false == mUserViewport) && (null != mEntity) && (null != mRttCam)) { // не ясно, нужно ли растягивать камеру, установленную юзером mRttCam->setAspectRatio((float)getWidth() / (float)getHeight()); // вычисляем расстояние, чтобы был виден весь объект const Ogre::AxisAlignedBox & box = mEntity->getBoundingBox(); box.getCenter(); Ogre::Vector3 vec = box.getSize(); float width = sqrt(vec.x*vec.x + vec.z*vec.z); // самое длинное - диагональ (если крутить модель) float len2 = width / mRttCam->getAspectRatio(); float height = vec.y; float len1 = height; if (len1 < len2) len1 = len2; len1 /= 0.86; // [sqrt(3)/2] for 60 degrees field of view // центр объекта по вертикали + отъехать так, чтобы влезла ближняя грань BoundingBox'а + чуть вверх и еще назад для красоты mCamNode->setPosition(box.getCenter() + Ogre::Vector3(0, 0, vec.z/2 + len1) + Ogre::Vector3(0, height*0.1, len1*0.2)); mCamNode->lookAt(Ogre::Vector3(0, box.getCenter().y, 0), Ogre::Node::TS_WORLD); } } void RenderBox::setAutoRotation(bool _auto) { mAutoRotation = _auto; if (mAutoRotation) Gui::getInstance().addFrameListener(this); else Gui::getInstance().removeFrameListener(this); } } // namespace MyGUI
[ [ [ 1, 250 ], [ 252, 252 ], [ 254, 264 ] ], [ [ 251, 251 ], [ 253, 253 ] ] ]
8b27477d11902ec7b81ebf5c96c074a071c04225
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/kgraphics/math/Quat.cpp
d618d74545dabcaf54d82e10f2f217f1b012039e
[]
no_license
lvtx/gamekernel
c80cdb4655f6d4930a7d035a5448b469ac9ae924
a84d9c268590a294a298a4c825d2dfe35e6eca21
refs/heads/master
2016-09-06T18:11:42.702216
2011-09-27T07:22:08
2011-09-27T07:22:08
38,255,025
3
1
null
null
null
null
UTF-8
C++
false
false
26,305
cpp
#include <stdafx.h> #include <kgraphics/math/Quat.h> #include <kgraphics/math/math.h> #include <kgraphics/math/Vector3.h> #include <kgraphics/math/Matrix33.h> namespace gfx { //------------------------------------------------------------------------------- //-- Static Members ------------------------------------------------------------- //------------------------------------------------------------------------------- Quat Quat::zero( 0.0f, 0.0f, 0.0f, 0.0f ); Quat Quat::identity( 1.0f, 0.0f, 0.0f, 0.0f ); //------------------------------------------------------------------------------- // @ Quat::Quat() //------------------------------------------------------------------------------- // Axis-angle constructor //------------------------------------------------------------------------------- Quat::Quat( const Vector3& axis, float angle ) { Set( axis, angle ); } // End of Quat::Quat() //------------------------------------------------------------------------------- // @ Quat::Quat() //------------------------------------------------------------------------------- // To-from vector constructor //------------------------------------------------------------------------------- Quat::Quat( const Vector3& from, const Vector3& to ) { Set( from, to ); } // End of Quat::Quat() //------------------------------------------------------------------------------- // @ Quat::Quat() //------------------------------------------------------------------------------- // Vector constructor //------------------------------------------------------------------------------- Quat::Quat( const Vector3& vector ) { Set( 0.0f, vector.x, vector.y, vector.z ); } // End of Quat::Quat() //------------------------------------------------------------------------------- // @ Quat::Quat() //------------------------------------------------------------------------------- // Rotation matrix constructor //------------------------------------------------------------------------------- Quat::Quat( const Matrix33& rotation ) { float trace = rotation.Trace(); if ( trace > 0.0f ) { float s = Sqrt( trace + 1.0f ); w = s*0.5f; float recip = 0.5f/s; x = (rotation(2,1) - rotation(1,2))*recip; y = (rotation(0,2) - rotation(2,0))*recip; z = (rotation(1,0) - rotation(0,1))*recip; } else { unsigned int i = 0; if ( rotation(1,1) > rotation(0,0) ) i = 1; if ( rotation(2,2) > rotation(i,i) ) i = 2; unsigned int j = (i+1)%3; unsigned int k = (j+1)%3; float s = Sqrt( rotation(i,i) - rotation(j,j) - rotation(k,k) + 1.0f ); (*this)[i] = 0.5f*s; float recip = 0.5f/s; w = (rotation(k,j) - rotation(j,k))*recip; (*this)[j] = (rotation(j,i) + rotation(i,j))*recip; (*this)[k] = (rotation(k,i) + rotation(i,k))*recip; } } // End of Quat::Quat() //------------------------------------------------------------------------------- // @ Quat::Quat() //------------------------------------------------------------------------------- // Copy constructor //------------------------------------------------------------------------------- Quat::Quat(const Quat& other) : w( other.w ), x( other.x ), y( other.y ), z( other.z ) { } // End of Quat::Quat() //------------------------------------------------------------------------------- // @ Quat::operator=() //------------------------------------------------------------------------------- // Assignment operator //------------------------------------------------------------------------------- Quat& Quat::operator=(const Quat& other) { // if same object if ( this == &other ) return *this; w = other.w; x = other.x; y = other.y; z = other.z; return *this; } // End of Quat::operator=() //------------------------------------------------------------------------------- // @ operator<<() //------------------------------------------------------------------------------- // Text output for debugging //------------------------------------------------------------------------------- Writer& operator<<(Writer& out, const Quat& source) { out << '[' << source.w << ',' << source.x << ',' << source.y << ',' << source.z << ']'; return out; } // End of operator<<() //------------------------------------------------------------------------------- // @ Quat::Magnitude() //------------------------------------------------------------------------------- // Quaternion magnitude (square root of norm) //------------------------------------------------------------------------------- float Quat::Magnitude() const { return Sqrt( w*w + x*x + y*y + z*z ); } // End of Quat::Magnitude() //------------------------------------------------------------------------------- // @ Quat::Norm() //------------------------------------------------------------------------------- // Quaternion norm //------------------------------------------------------------------------------- float Quat::Norm() const { return ( w*w + x*x + y*y + z*z ); } // End of Quat::Norm() //------------------------------------------------------------------------------- // @ Quat::operator==() //------------------------------------------------------------------------------- // Comparison operator //------------------------------------------------------------------------------- bool Quat::operator==( const Quat& other ) const { if ( gfx::IsZero( other.w - w ) && gfx::IsZero( other.x - x ) && gfx::IsZero( other.y - y ) && gfx::IsZero( other.z - z ) ) return true; return false; } // End of Quat::operator==() //------------------------------------------------------------------------------- // @ Quat::operator!=() //------------------------------------------------------------------------------- // Comparison operator //------------------------------------------------------------------------------- bool Quat::operator!=( const Quat& other ) const { if ( gfx::IsZero( other.w - w ) || gfx::IsZero( other.x - x ) || gfx::IsZero( other.y - y ) || gfx::IsZero( other.z - z ) ) return false; return true; } // End of Quat::operator!=() //------------------------------------------------------------------------------- // @ Quat::IsZero() //------------------------------------------------------------------------------- // Check for zero quat //------------------------------------------------------------------------------- bool Quat::IsZero() const { return gfx::IsZero(w*w + x*x + y*y + z*z); } // End of Quat::IsZero() //------------------------------------------------------------------------------- // @ Quat::IsUnit() //------------------------------------------------------------------------------- // Check for unit quat //------------------------------------------------------------------------------- bool Quat::IsUnit() const { return gfx::IsZero(1.0f - w*w - x*x - y*y - z*z); } // End of Quat::IsUnit() //------------------------------------------------------------------------------- // @ Quat::IsIdentity() //------------------------------------------------------------------------------- // Check for identity quat //------------------------------------------------------------------------------- bool Quat::IsIdentity() const { return gfx::IsZero(1.0f - w) && gfx::IsZero( x ) && gfx::IsZero( y ) && gfx::IsZero( z ); } // End of Quat::IsIdentity() //------------------------------------------------------------------------------- // @ Quat::Set() //------------------------------------------------------------------------------- // Set quaternion based on axis-angle //------------------------------------------------------------------------------- void Quat::Set( const Vector3& axis, float angle ) { // if axis of rotation is zero vector, just set to identity quat float length = axis.LengthSquared(); if ( gfx::IsZero( length ) ) { Identity(); return; } // take half-angle angle *= 0.5f; float sintheta, costheta; SinCos(angle, sintheta, costheta); float scaleFactor = sintheta/Sqrt( length ); w = costheta; x = scaleFactor * axis.x; y = scaleFactor * axis.y; z = scaleFactor * axis.z; } // End of Quat::Set() //------------------------------------------------------------------------------- // @ Quat::Set() //------------------------------------------------------------------------------- // Set quaternion based on start and end vectors // // This is a slightly faster method than that presented in the book, and it // doesn't require unit vectors as input. Found on GameDev.net, in an article by // minorlogic. Original source unknown. //------------------------------------------------------------------------------- void Quat::Set( const Vector3& from, const Vector3& to ) { // get axis of rotation Vector3 axis = from.Cross( to ); // get scaled cos of angle between vectors and set initial quaternion Set( from.Dot( to ), axis.x, axis.y, axis.z ); // quaternion at this point is ||from||*||to||*( cos(theta), r*sin(theta) ) // normalize to remove ||from||*||to|| factor Normalize(); // quaternion at this point is ( cos(theta), r*sin(theta) ) // what we want is ( cos(theta/2), r*sin(theta/2) ) // set up for half angle calculation w += 1.0f; // now when we normalize, we'll be dividing by sqrt(2*(1+cos(theta))), which is // what we want for r*sin(theta) to give us r*sin(theta/2) (see pages 487-488) // // w will become // 1+cos(theta) // ---------------------- // sqrt(2*(1+cos(theta))) // which simplifies to // cos(theta/2) // before we normalize, check if vectors are opposing if ( w <= kEpsilon ) { // rotate pi radians around orthogonal vector // take cross product with x axis if ( from.z*from.z > from.x*from.x ) Set( 0.0f, 0.0f, from.z, -from.y ); // or take cross product with z axis else Set( 0.0f, from.y, -from.x, 0.0f ); } // normalize again to get rotation quaternion Normalize(); } // End of Quat::Set() //------------------------------------------------------------------------------- // @ Quat::Set() //------------------------------------------------------------------------------- // Set quaternion based on fixed angles //------------------------------------------------------------------------------- void Quat::Set( float zRotation, float yRotation, float xRotation ) { zRotation *= 0.5f; yRotation *= 0.5f; xRotation *= 0.5f; // get sines and cosines of half angles float Cx, Sx; SinCos(xRotation, Sx, Cx); float Cy, Sy; SinCos(yRotation, Sy, Cy); float Cz, Sz; SinCos(zRotation, Sz, Cz); // multiply it out w = Cx*Cy*Cz - Sx*Sy*Sz; x = Sx*Cy*Cz + Cx*Sy*Sz; y = Cx*Sy*Cz - Sx*Cy*Sz; z = Cx*Cy*Sz + Sx*Sy*Cx; } // End of Quat::Set() //------------------------------------------------------------------------------- // @ Quat::GetAxisAngle() //------------------------------------------------------------------------------- // Get axis-angle based on quaternion //------------------------------------------------------------------------------- void Quat::GetAxisAngle( Vector3& axis, float& angle ) { angle = 2.0f*acosf( w ); float length = Sqrt( 1.0f - w*w ); if ( gfx::IsZero(length) ) axis.Zero(); else { length = 1.0f/length; axis.Set( x*length, y*length, z*length ); } } // End of Quat::GetAxisAngle() //------------------------------------------------------------------------------- // @ Quat::Clean() //------------------------------------------------------------------------------- // Set elements close to zero equal to zero //------------------------------------------------------------------------------- void Quat::Clean() { if ( gfx::IsZero( w ) ) w = 0.0f; if ( gfx::IsZero( x ) ) x = 0.0f; if ( gfx::IsZero( y ) ) y = 0.0f; if ( gfx::IsZero( z ) ) z = 0.0f; } // End of Quat::Clean() //------------------------------------------------------------------------------- // @ Quat::Normalize() //------------------------------------------------------------------------------- // Set to unit quaternion //------------------------------------------------------------------------------- void Quat::Normalize() { float lengthsq = w*w + x*x + y*y + z*z; if ( gfx::IsZero( lengthsq ) ) { Zero(); } else { float factor = InvSqrt( lengthsq ); w *= factor; x *= factor; y *= factor; z *= factor; } } // End of Quat::Normalize() //------------------------------------------------------------------------------- // @ ::Conjugate() //------------------------------------------------------------------------------- // Compute complex conjugate //------------------------------------------------------------------------------- Quat Conjugate( const Quat& quat ) { return Quat( quat.w, -quat.x, -quat.y, -quat.z ); } // End of Conjugate() //------------------------------------------------------------------------------- // @ Quat::Conjugate() //------------------------------------------------------------------------------- // Set self to complex conjugate //------------------------------------------------------------------------------- const Quat& Quat::Conjugate() { x = -x; y = -y; z = -z; return *this; } // End of Conjugate() //------------------------------------------------------------------------------- // @ ::Inverse() //------------------------------------------------------------------------------- // Compute quaternion inverse //------------------------------------------------------------------------------- Quat Inverse( const Quat& quat ) { float norm = quat.w*quat.w + quat.x*quat.x + quat.y*quat.y + quat.z*quat.z; // if we're the zero quaternion, just return identity if ( !gfx::IsZero( norm ) ) { // //ASSERT( false ); return Quat(); } float normRecip = 1.0f / norm; return Quat( normRecip*quat.w, -normRecip*quat.x, -normRecip*quat.y, -normRecip*quat.z ); } // End of Inverse() //------------------------------------------------------------------------------- // @ Quat::Inverse() //------------------------------------------------------------------------------- // Set self to inverse //------------------------------------------------------------------------------- const Quat& Quat::Inverse() { float norm = w*w + x*x + y*y + z*z; // if we're the zero quaternion, just return if ( gfx::IsZero( norm ) ) return *this; float normRecip = 1.0f / norm; w = normRecip*w; x = -normRecip*x; y = -normRecip*y; z = -normRecip*z; return *this; } // End of Inverse() //------------------------------------------------------------------------------- // @ Quat::operator+() //------------------------------------------------------------------------------- // Add quat to self and return //------------------------------------------------------------------------------- Quat Quat::operator+( const Quat& other ) const { return Quat( w + other.w, x + other.x, y + other.y, z + other.z ); } // End of Quat::operator+() //------------------------------------------------------------------------------- // @ Quat::operator+=() //------------------------------------------------------------------------------- // Add quat to self, store in self //------------------------------------------------------------------------------- Quat& Quat::operator+=( const Quat& other ) { w += other.w; x += other.x; y += other.y; z += other.z; return *this; } // End of Quat::operator+=() //------------------------------------------------------------------------------- // @ Quat::operator-() //------------------------------------------------------------------------------- // Subtract quat from self and return //------------------------------------------------------------------------------- Quat Quat::operator-( const Quat& other ) const { return Quat( w - other.w, x - other.x, y - other.y, z - other.z ); } // End of Quat::operator-() //------------------------------------------------------------------------------- // @ Quat::operator-=() //------------------------------------------------------------------------------- // Subtract quat from self, store in self //------------------------------------------------------------------------------- Quat& Quat::operator-=( const Quat& other ) { w -= other.w; x -= other.x; y -= other.y; z -= other.z; return *this; } // End of Quat::operator-=() //------------------------------------------------------------------------------- // @ Quat::operator-=() (unary) //------------------------------------------------------------------------------- // Negate self and return //------------------------------------------------------------------------------- Quat Quat::operator-() const { return Quat(-w, -x, -y, -z); } // End of Quat::operator-() //------------------------------------------------------------------------------- // @ operator*() //------------------------------------------------------------------------------- // Scalar multiplication //------------------------------------------------------------------------------- Quat operator*( float scalar, const Quat& quat ) { return Quat( scalar*quat.w, scalar*quat.x, scalar*quat.y, scalar*quat.z ); } // End of operator*() //------------------------------------------------------------------------------- // @ Quat::operator*=() //------------------------------------------------------------------------------- // Scalar multiplication by self //------------------------------------------------------------------------------- Quat& Quat::operator*=( float scalar ) { w *= scalar; x *= scalar; y *= scalar; z *= scalar; return *this; } // End of Quat::operator*=() //------------------------------------------------------------------------------- // @ Quat::operator*() //------------------------------------------------------------------------------- // Quaternion multiplication //------------------------------------------------------------------------------- Quat Quat::operator*( const Quat& other ) const { return Quat( w*other.w - x*other.x - y*other.y - z*other.z, w*other.x + x*other.w + y*other.z - z*other.y, w*other.y + y*other.w + z*other.x - x*other.z, w*other.z + z*other.w + x*other.y - y*other.x ); } // End of Quat::operator*() //------------------------------------------------------------------------------- // @ Quat::operator*=() //------------------------------------------------------------------------------- // Quaternion multiplication by self //------------------------------------------------------------------------------- Quat& Quat::operator*=( const Quat& other ) { Set( w*other.w - x*other.x - y*other.y - z*other.z, w*other.x + x*other.w + y*other.z - z*other.y, w*other.y + y*other.w + z*other.x - x*other.z, w*other.z + z*other.w + x*other.y - y*other.x ); return *this; } // End of Quat::operator*=() //------------------------------------------------------------------------------- // @ Quat::Dot() //------------------------------------------------------------------------------- // Dot product by self //------------------------------------------------------------------------------- float Quat::Dot( const Quat& quat ) const { return ( w*quat.w + x*quat.x + y*quat.y + z*quat.z); } // End of Quat::Dot() //------------------------------------------------------------------------------- // @ Dot() //------------------------------------------------------------------------------- // Dot product friend operator //------------------------------------------------------------------------------- float Dot( const Quat& quat1, const Quat& quat2 ) { return (quat1.w*quat2.w + quat1.x*quat2.x + quat1.y*quat2.y + quat1.z*quat2.z); } // End of Dot() //------------------------------------------------------------------------------- // @ Quat::Rotate() //------------------------------------------------------------------------------- // Rotate vector by quaternion // Assumes quaternion is normalized! //------------------------------------------------------------------------------- Vector3 Quat::Rotate( const Vector3& vector ) const { // //ASSERT( IsUnit() ); float vMult = 2.0f*(x*vector.x + y*vector.y + z*vector.z); float crossMult = 2.0f*w; float pMult = crossMult*w - 1.0f; return Vector3( pMult*vector.x + vMult*x + crossMult*(y*vector.z - z*vector.y), pMult*vector.y + vMult*y + crossMult*(z*vector.x - x*vector.z), pMult*vector.z + vMult*z + crossMult*(x*vector.y - y*vector.x) ); } // End of Quat::Rotate() //------------------------------------------------------------------------------- // @ Lerp() //------------------------------------------------------------------------------- // Linearly interpolate two quaternions // This will always take the shorter path between them //------------------------------------------------------------------------------- void Lerp( Quat& result, const Quat& start, const Quat& end, float t ) { // get cos of "angle" between quaternions float cosTheta = start.Dot( end ); // initialize result result = t*end; // if "angle" between quaternions is less than 90 degrees if ( cosTheta >= kEpsilon ) { // use standard interpolation result += (1.0f-t)*start; } else { // otherwise, take the shorter path result += (t-1.0f)*start; } } // End of Lerp() //------------------------------------------------------------------------------- // @ Slerp() //------------------------------------------------------------------------------- // Spherical linearly interpolate two quaternions // This will always take the shorter path between them //------------------------------------------------------------------------------- void Slerp( Quat& result, const Quat& start, const Quat& end, float t ) { // get cosine of "angle" between quaternions float cosTheta = start.Dot( end ); float startInterp, endInterp; // if "angle" between quaternions is less than 90 degrees if ( cosTheta >= kEpsilon ) { // if angle is greater than zero if ( (1.0f - cosTheta) > kEpsilon ) { // use standard slerp float theta = acosf( cosTheta ); float recipSinTheta = 1.0f/Sin( theta ); startInterp = Sin( (1.0f - t)*theta )*recipSinTheta; endInterp = Sin( t*theta )*recipSinTheta; } // angle is close to zero else { // use linear interpolation startInterp = 1.0f - t; endInterp = t; } } // otherwise, take the shorter route else { // if angle is less than 180 degrees if ( (1.0f + cosTheta) > kEpsilon ) { // use slerp w/negation of start quaternion float theta = acosf( -cosTheta ); float recipSinTheta = 1.0f/Sin( theta ); startInterp = Sin( (t-1.0f)*theta )*recipSinTheta; endInterp = Sin( t*theta )*recipSinTheta; } // angle is close to 180 degrees else { // use lerp w/negation of start quaternion startInterp = t - 1.0f; endInterp = t; } } result = startInterp*start + endInterp*end; } // End of Slerp() //------------------------------------------------------------------------------- // @ ApproxSlerp() //------------------------------------------------------------------------------- // Approximate spherical linear interpolation of two quaternions // Based on "Hacking Quaternions", Jonathan Blow, Game Developer, March 2002. // See Game Developer, February 2004 for an alternate method. //------------------------------------------------------------------------------- void ApproxSlerp( Quat& result, const Quat& start, const Quat& end, float t ) { float cosTheta = start.Dot( end ); // correct time by using cosine of angle between quaternions float factor = 1.0f - 0.7878088f*cosTheta; float k = 0.5069269f; factor *= factor; k *= factor; float b = 2*k; float c = -3*k; float d = 1 + k; t = t*(b*t + c) + d; // initialize result result = t*end; // if "angle" between quaternions is less than 90 degrees if ( cosTheta >= kEpsilon ) { // use standard interpolation result += (1.0f-t)*start; } else { // otherwise, take the shorter path result += (t-1.0f)*start; } } // End of ApproxSlerp() } // namespace gfx
[ "keedongpark@keedongpark" ]
[ [ [ 1, 824 ] ] ]
3e8c6fc30372e1e3c7a795c90136550379ed1568
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Dynamics/Action/hkpActionListener.h
f83c433ccefb1f334be5f0fcdf7e97d153fbae05
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,659
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DYNAMICS2_ACTION_LISTENER_H #define HK_DYNAMICS2_ACTION_LISTENER_H class hkpAction; /// hkpActionListener. class hkpActionListener { public: virtual ~hkpActionListener() {} /// Called when an action is added to the world. virtual void actionAddedCallback( hkpAction* action ) {} /// Called when an action is removed from the world. virtual void actionRemovedCallback( hkpAction* action ) {} }; #endif // HK_DYNAMICS2_ACTION_LISTENER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 45 ] ] ]
bbc223f217d0a7aa40d30975ae1392b24290a64e
0bce46a5dd859d82824f4b74c4adecd7b4bc2387
/sourcecode/input.cpp
3ea4050e30e05bce52d581148f31499847835d30
[]
no_license
xflash/moon-invaders
a08e00ddb590fa3bd395e65bb793a67166a27eb1
8124f4787a8b1b201e85c17010620488f51827a4
refs/heads/master
2021-01-25T08:38:05.896106
2009-02-19T09:41:38
2009-02-19T09:41:38
32,315,985
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
#include "input.h" #include "systemstub.h" byte MouseIsIn(float x,float y,float x2,float y2) { short msx,msy; msx=systemStub->_pi.mouseX; msy=systemStub->_pi.mouseY; return (msx>=x && msy>=y && msx<=x2 && msy<=y2); } float MouseX(void) { return (float)systemStub->_pi.mouseX; } float MouseY(void) { return (float)systemStub->_pi.mouseY; }
[ "rcoqueugniot@19f3d9c2-fe69-11dd-a3ef-1f8437fb274a" ]
[ [ [ 1, 21 ] ] ]
777277d41023b56ab033f64715532656d7c1406e
3d1a754998553b9064eec08e191047406bb57365
/dan-ai/dllmain.cpp
5bfeaf8262a9fd6fcc161348d0202c744eaf9b81
[]
no_license
TequilaLime/starcraft-bots
16abb824dc5eb76f607ef527b3f9a9d4b4456291
a56171c50fff364309de951f10dacd884e656af2
refs/heads/master
2021-01-17T09:19:42.584929
2011-04-26T20:33:21
2011-04-26T20:33:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
560
cpp
#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <stdio.h> #include <tchar.h> #include <BWAPI.h> #include "DanAI.h" namespace BWAPI { Game* Broodwar; } BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: BWAPI::BWAPI_init(); break; case DLL_PROCESS_DETACH: break; } return TRUE; } extern "C" __declspec(dllexport) BWAPI::AIModule* newAIModule(BWAPI::Game* game) { BWAPI::Broodwar = game; return new DanAI(); }
[ [ [ 1, 30 ] ] ]
008fca916387521587079b7aa173d4537ec66746
927e18c69355c4bf87b59dffefe59c2974e86354
/super-go-proj/SgStack.h
be6592bc51f4ee32a8713362a77c1b05a837dc35
[]
no_license
lqhl/iao-gim-ca
6fc40adc91a615fa13b72e5b4016a8b154196b8f
f177268804d1ba6edfd407fa44a113a44203ec30
refs/heads/master
2020-05-18T17:07:17.972573
2011-06-17T03:54:51
2011-06-17T03:54:51
32,191,309
1
0
null
null
null
null
UTF-8
C++
false
false
3,567
h
//---------------------------------------------------------------------------- /** @file SgStack.h Stack class. */ //---------------------------------------------------------------------------- #ifndef SG_STACK_H #define SG_STACK_H #include <algorithm> //---------------------------------------------------------------------------- /** Stack with up to size objects of class T. Stack does not assume ownership. Memory management of objects on stack is the user's responsibility. */ template <class T, int SIZE> class SgStack { public: SgStack() : m_sp(0) { } ~SgStack() {} /** Empty the stack */ void Clear(); /** Make this stack a copy of other*/ void CopyFrom(const SgStack<T,SIZE>& other); bool IsEmpty() const; bool NonEmpty() const; /** remove and return top element. Must be NonEmpty. */ T Pop(); void Push(T data); /** Push all elements from other stack onto this stack */ void PushAll(const SgStack<T,SIZE>& other); /** Number of elements on stack */ int Size() const; /** Exchange contents of this and other stack */ void SwapWith(SgStack<T,SIZE>& other); const T& Top() const; const T& operator[](int index) const; private: int m_sp; T m_stack[SIZE]; /** not implemented */ SgStack(const SgStack&); /** not implemented */ SgStack& operator=(const SgStack&); }; //---------------------------------------------------------------------------- template<typename T, int SIZE> void SgStack<T,SIZE>::Clear() { m_sp = 0; } template<typename T, int SIZE> void SgStack<T,SIZE>::CopyFrom(const SgStack<T,SIZE>& other) { for (int i = 0; i < other.Size(); ++i) m_stack[i] = other.m_stack[i]; m_sp = other.m_sp; } template<typename T, int SIZE> bool SgStack<T,SIZE>::IsEmpty() const { return m_sp == 0; } template<typename T, int SIZE> bool SgStack<T,SIZE>::NonEmpty() const { return m_sp != 0; } template<typename T, int SIZE> T SgStack<T,SIZE>::Pop() { poco_assert(0 < m_sp); return m_stack[--m_sp]; } template<typename T, int SIZE> void SgStack<T,SIZE>::Push(T data) { poco_assert(m_sp < SIZE); m_stack[m_sp++] = data; } template<typename T, int SIZE> void SgStack<T,SIZE>::PushAll(const SgStack<T,SIZE>& other) { for (int i = 0; i < other.Size(); ++i) Push(other.m_stack[i]); } template<typename T, int SIZE> int SgStack<T,SIZE>::Size() const { return m_sp; } template<typename T, int SIZE> void SgStack<T,SIZE>::SwapWith(SgStack<T,SIZE>& other) { int nuSwap = std::min(Size(), other.Size()); for (int i = 0; i < nuSwap; ++i) std::swap(m_stack[i], other.m_stack[i]); if (Size() < other.Size()) for (int i = Size(); i < other.Size(); ++i) m_stack[i] = other.m_stack[i]; else if (other.Size() < Size()) for (int i = other.Size(); i < Size(); ++i) other.m_stack[i] = m_stack[i]; std::swap(m_sp, other.m_sp); } template<typename T, int SIZE> const T& SgStack<T,SIZE>::Top() const { poco_assert(0 < m_sp); return m_stack[m_sp - 1]; } template<typename T, int SIZE> const T& SgStack<T,SIZE>::operator[](int index) const { poco_assert(index >= 0); poco_assert(index < m_sp); return m_stack[index]; } //---------------------------------------------------------------------------- #endif // SG_STACK_H
[ [ [ 1, 152 ] ] ]
e27878f22d9f36505d8471c050773c5a4305d8ba
282057a05d0cbf9a0fe87457229f966a2ecd3550
/EIBStdLib/src/CTime.cpp
b87baa99e6c210dd7e763a522026c421da81d703
[]
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
13,437
cpp
#include "CTime.h" void CTime::Initialize() { #ifdef WIN32 _tzset(); // set time zone #else tzset(); // set the time zone #endif } /** CTime Constructors **/ CTime::CTime() { _time_val = static_cast<int>(time(0)); } CTime::CTime(int time) { _time_val = time; } //CTime::CTime(int time) //{ // _time_val = time; // GAssert(_time_val != (int)(-1)); //} CTime::CTime(const CTime& time) { _time_val = time.GetTime(); } CTime::CTime(struct tm *pTime) { _time_val = ((pTime!=NULL) ? static_cast<int>(mktime(pTime)): static_cast<int>(time(0))); } CTime::CTime(const int day, const int month, const int year,const int hour, const int minutes,const int sec) { struct tm intm; // NOTE: struct tm months are 0 to 11 intm.tm_hour = (int)(hour); intm.tm_min = (int)(minutes); intm.tm_sec = (int)(sec); intm.tm_mday = (int)(day); intm.tm_mon = (int)(month) - 1; intm.tm_year = (int)(year) - 1900; intm.tm_isdst = -1; // day light saving time effect _time_val = static_cast<int>(mktime(&intm)); } // Converts a unix style time string // of the format: Tue May 03 21:51:03 1994 CTime::CTime(const char *time, bool local_time) { int hour, min, sec, day, month, year; char month_s[10], trash; char day_s[10], hour_s[10], min_s[10]; char year_s[10]; if (sscanf(time, "%9s %9s %4s %2s:%2s %c",day_s, month_s, year_s,hour_s, min_s, &trash) != 5) { throw CEIBException(SystemError,"Cannot initialize time class"); } day = atoi(day_s); hour = atoi(hour_s); min = atoi(min_s); sec = 0; year = atoi(year_s); // NOTE: struct tm months are 0 to 11 if (!strcmp(month_s,"Jan")) month = 0 ; else if (!strcmp(month_s,"Feb")) month = 1 ; else if (!strcmp(month_s,"Mar")) month = 2 ; else if (!strcmp(month_s,"Apr")) month = 3 ; else if (!strcmp(month_s,"May")) month = 4 ; else if (!strcmp(month_s,"Jun")) month = 5 ; else if (!strcmp(month_s,"Jul")) month = 6 ; else if (!strcmp(month_s,"Aug")) month = 7 ; else if (!strcmp(month_s,"Sep")) month = 8 ; else if (!strcmp(month_s,"Oct")) month = 9 ; else if (!strcmp(month_s,"Nov")) month = 10; else if (!strcmp(month_s,"Dec")) month = 11; else { throw CEIBException(SystemError,"Cannot initialize time class"); month = 12; //eliminate compiler warning on "may be used uninitialized". } struct tm intm; intm.tm_hour = (int)(hour); intm.tm_min = (int)(min); intm.tm_sec = (int)(sec); intm.tm_mday = (int)(day); intm.tm_mon = (int)(month); intm.tm_year = ((int)(year) - 1900); if(local_time) { // When converting a string we assume it was procuced by gmtime(). If we want // local time we ask the Operating System to take into account the daylight // savings (-1) as int as the time differences. If we want gmt time we do not // want daylight savings effect (0). In this case we need to cancel the effect // of the timezone diffrences later on (See the last if in this method) intm.tm_isdst = -1; }else{ intm.tm_isdst = 0; } _time_val = static_cast<int>(mktime(&intm)); if (!local_time) { // By default local_time is set to false, when converting a string we // assume it was produced by gmtime() // which means that time in the string is according to "UTC time zone" // To convert the time on the local machine we set tm_isdst to -1 and // use _timezone to adjust local time. #ifdef WIN32 _time_val -= _timezone; #else _time_val -= timezone; #endif } } CTime::~CTime() {}; /** @return int that corresponds to this CTime object. **/ int CTime::GetTime() const { return _time_val; } /** Calculate seconds to the given time. @return how many seconds is ('current time' - time_val) **/ int CTime::secTo() const { int sec; sec = GetTime() - static_cast<int>(time(0)); sec = ((sec < 0) ? 0 : sec); return sec; } /** Converts a CTime object into a formatted string (unix style) based on the local time zone. **/ CString CTime::Format(bool get_local) const { CString result ; AddFormatToString ( result , get_local ) ; return result ; } void CTime::AddFormatToString(CString& result,bool get_local) const { char strDest[25]; size_t maxsize = 25; int tt = GetTime(); struct tm *tm_struct; // Using thread safe functions if (!get_local) { // Use gmtime for UTC format #ifdef WIN32 tm_struct = EibGMTime(&tt); #else tm_struct = new struct tm(); if (!tm_struct) { return ; } EibGMTime_r(&tt, tm_struct); #endif } else { // Use localtime for local time format #ifdef WIN32 tm_struct = EibTime(&tt); #else tm_struct = new struct tm(); if (!tm_struct) { return ; } EIBTtime_r(&tt, tm_struct); #endif } // We keep the format of ctime, for example "Mon Aug 21 20:07:29 2000" (void) strftime(strDest, maxsize, "%a %b %d %H:%M:%S %Y", tm_struct); #ifndef WIN32 delete tm_struct; #endif // Supporting UNIX time format. if (strDest[8] == ' ') { strDest[8] = '0'; } result += strDest ; } //Sets the time value to be 'now' void CTime::SetNow() { _time_val = static_cast<int>(time(0)); } void CTime::SetTimeZero() { SetTime(GetTimeZero()); } int CTime::GetTimeZero() const { CTime tmp(STRING_TIME_ZERO.GetBuffer()); return tmp.GetTime(); } bool CTime::IsTimeZero() const { return ( GetTimeZero() == GetTime() ); } CString CTime::GetTimeStrSegment(CString format, int size, bool get_local) { CString res; AddTimeStrSegmentToString(res, format, size, get_local); return res; } void CTime::AddTimeStrSegmentToString(CString& result, CString format, int size , bool get_local ) { char* strDest = new char[size]; if (!strDest) { result += EMPTY_STRING; return ; } size_t maxsize = (unsigned int)(size); int tt = GetTime(); struct tm *tm_struct; // Using thread safe functions if (!get_local) { // Use gmtime for UTC format #ifdef WIN32 tm_struct = EibGMTime(&tt); #else tm_struct = new struct tm(); if (!tm_struct) { result += EMPTY_STRING; delete []strDest; return ; } EibGMTime_r (&tt, tm_struct); #endif } else { // Use localtime for local time format #ifdef WIN32 tm_struct = EibTime(&tt); #else tm_struct = new struct tm(); if (!tm_struct) { result += EMPTY_STRING; delete []strDest; return ; } EIBTtime_r(&tt, tm_struct); #endif } (void) strftime(strDest, maxsize, format.GetBuffer(), tm_struct); #ifndef WIN32 delete tm_struct; #endif result += strDest; delete []strDest; } /** relation operators **/ CTime& CTime::operator=(const CTime& t) { _time_val = t.GetTime(); return *this; } bool CTime::operator==(const CTime& time2) const { return (GetTime() == time2.GetTime()); } bool CTime::operator!=(const CTime& time2) const { return (GetTime() != time2.GetTime()); } bool CTime::operator<(const CTime& time2) const { return (GetTime() < time2.GetTime()); } bool CTime::operator>(const CTime& time2) const { return (GetTime() > time2.GetTime()); } bool CTime::operator>=(const CTime& time2) const { return (GetTime() >= time2.GetTime()); } bool CTime::operator<=(const CTime& time2) const { return (GetTime() <= time2.GetTime()); } CTime& CTime::operator-=(const CTime& t2) { this->_time_val -= t2.GetTime(); return *this; } CTime& CTime::operator-=(const int t2) { this->_time_val -= t2; return *this; } CTime& CTime::operator=(const int t2) { this->_time_val = t2; return *this; } EIB_STD_EXPORT CTime operator-(const CTime& t1, const CTime& t2) { CTime res(t1.GetTime() - t2.GetTime()); return res; } EIB_STD_EXPORT CTime operator-(const CTime& t1, const int t2) { CTime res(t1.GetTime() - t2); return res; } CTime& CTime::operator+=(const CTime& t2) { this->_time_val += t2.GetTime(); return *this; } CTime& CTime::operator+=(const int t2) { this->_time_val += t2; return *this; } EIB_STD_EXPORT CTime operator+(const CTime& t1, const CTime& t2) { CTime res(t1.GetTime() + t2.GetTime()); return res; } EIB_STD_EXPORT CTime operator+(const CTime& t1, const int t2) { CTime res(t1.GetTime() + t2); return res; } bool CTime::SetLocalTime(const CTime &time_to_set) { #ifdef WIN32 int tmp_time = time_to_set.GetTime(); struct tm *tmp_tm = CTime::EibTime(&tmp_time); if (!tmp_tm) return false; SYSTEMTIME systemTime; systemTime.wDay = tmp_tm->tm_mday; systemTime.wMonth = tmp_tm->tm_mon + 1; systemTime.wYear = tmp_tm->tm_year + 1900; systemTime.wHour = tmp_tm->tm_hour; systemTime.wMinute = tmp_tm->tm_min; systemTime.wSecond = tmp_tm->tm_sec; systemTime.wMilliseconds = 0; if (!::SetLocalTime(&systemTime)) return false; return true; #else struct timeval tv = { (int)(time_to_set.GetTime()), 0 }; if (settimeofday(&tv, NULL) < 0) { perror("settimeofday"); return false; } return true; #endif } bool CTime::SetLocalDate(const CTime &into_set) { #ifdef WIN32 SYSTEMTIME systemTime; int tmp_time = into_set.GetTime(); struct tm *tmp_tm = EibTime(&tmp_time); if (!tmp_tm) return false; systemTime.wDay = tmp_tm->tm_mday; systemTime.wMonth = tmp_tm->tm_mon + 1; systemTime.wYear = tmp_tm->tm_year + 1900; int now_t = static_cast<int>(time(0)); tmp_tm = EibTime(&now_t); if (!tmp_tm) return false; systemTime.wHour = tmp_tm->tm_hour; systemTime.wMinute = tmp_tm->tm_min; systemTime.wSecond = tmp_tm->tm_sec; systemTime.wMilliseconds = 0; if (!::SetLocalTime(&systemTime)) return false; return true; #else int tmp_time = into_set.GetTime(); int cur_time = time(NULL); struct tm tmp_tm; struct tm cur_tm; EIBTtime_r(&tmp_time, &tmp_tm); EIBTtime_r(&cur_time, &cur_tm); tmp_tm.tm_sec = cur_tm.tm_sec; tmp_tm.tm_min = cur_tm.tm_min; tmp_tm.tm_hour = cur_tm.tm_hour; struct timeval tv = { mktime(&tmp_tm), 0 }; if (settimeofday(&tv, NULL) < 0) { perror("settimeofday"); return false; } return true; #endif } /** Get the current time zone @param int &timezone Time zone value to get in minutes. Verify: localtime = UTC + timezone @return bool true if successfull, false if errors (see CGErrorMgr::GetLastWinMsg()) **/ bool CTime::GetTimeZone(int &answer) { #ifdef WIN32 TIME_ZONE_INFORMATION tzi; if (GetTimeZoneInformation(&tzi) == TIME_ZONE_ID_INVALID) return false; answer = -tzi.Bias; return true; #else tzset(); answer = -(timezone / 60); return true; #endif } /** Set the current time zone @param const int timezone Time zone value to set in minutes. Verify: localtime = UTC + timezone @return bool true if successfull, false if errors (see CGErrorMgr::GetLastWinMsg()) **/ bool CTime::SetTimeZone(const int timezone) { #ifdef WIN32 TIME_ZONE_INFORMATION tzi; if (GetTimeZoneInformation(&tzi) == TIME_ZONE_ID_INVALID) return false; tzi.Bias = -(long)(timezone); if (!SetTimeZoneInformation(&tzi)) return false; return true; #else if (system("tzselect > /var/tmp/tz_out.txt") != 0) { return false; } FILE *f; CString zonename; if ((f = fopen("/var/tmp/tz_out.txt", "r"))) { char buffer[128]; //unsigned long len, cnt = 0; if ( fscanf(f, "%s", buffer) != 1) { fclose (f); return false; } zonename = buffer; fclose (f); } else { return false; } return SetTimeZoneName(zonename); #endif } #ifndef WIN32 bool CTime::SetTimeZoneName(const CString& timezone) { /* static const CString sysconfig_fname("/etc/sysconfig/clock"); static const CString localtime_fname("/etc/localtime"); static const CString zoneinfo_dname("/usr/share/zoneinfo"); const CString zone_fname = zoneinfo_dname + "/" + timezone; struct stat stat_st; if (!CopyFile(zone_fname, localtime_fname)) { return false; } if (stat(sysconfig_fname.GetBuffer(), &stat_st) == 0) { FILE *f; if ((f = fopen(sysconfig_fname.GetBuffer(), "w"))) { fprintf(f, "ZONE=%s\nUTC=false\nARC=false\n", timezone.GetBuffer()); fclose(f); } else { return false; } } */ return true; } #endif struct tm* CTime::EibTime(const int* timer) { time_t l_timer; //temporary variable to be used as argument to the original time method; struct tm* ret_val; if(timer) { l_timer = (int)(*timer); ret_val = localtime(&l_timer); } else { ret_val = gmtime(NULL); } return ret_val; } struct tm* CTime::EibGMTime(const int* timer) { time_t l_timer; //temporary variable to be used as argument to the original time method; struct tm* ret_val; if(timer) { l_timer = (int)(*timer); ret_val = gmtime(&l_timer); } else { ret_val = gmtime(NULL); } return ret_val; } #ifndef WIN32 struct tm* CTime::EIBTtime_r(const int* timer, struct tm* res) { time_t l_timer; struct tm* ret_val; if (timer) { l_timer = (int)(*timer); ret_val = gmtime_r(&l_timer, res); } else { ret_val = gmtime_r(NULL, res); } return ret_val; } struct tm* CTime::EibGMTime_r(const int* timer, struct tm* res) { time_t l_timer; struct tm* ret_val; if (timer) { l_timer = (int)(*timer); ret_val = localtime_r(&l_timer, res); } else { ret_val = localtime_r(NULL, res); } return ret_val; } #endif
[ [ [ 1, 626 ] ] ]
d176a44e9889847eda1d3e4ba278ed88f1322c4e
7b916b09fa11731210d01baa9cfa6212e103e5f5
/Component/SiftGPU-V340/include/SiftGPU.h
9b467b69a4b6c26559a2d2a579af9f45b3642b27
[]
no_license
Barbakas/windage
a09d46f249c8f565435474001d999efabe515d64
de7f1234256bce8209a9c42fa8c6c69649c75509
refs/heads/master
2016-09-14T00:11:02.048456
2011-04-21T00:06:30
2011-04-21T00:06:30
58,064,128
0
1
null
null
null
null
UTF-8
C++
false
false
13,014
h
//////////////////////////////////////////////////////////////////////////// // File: SiftGPU.h // Author: Changchang Wu // Description : interface for the SIFTGPU class. // SiftGPU: The SiftGPU Tool. // SiftGPUEX: SiftGPU + viewer // SiftParam: Sift Parameters // SiftMatchGPU: GPU SIFT Matcher; // // // Copyright (c) 2007 University of North Carolina at Chapel Hill // All Rights Reserved // // Permission to use, copy, modify and distribute this software and its // documentation for educational, research and non-profit purposes, without // fee, and without a written agreement is hereby granted, provided that the // above copyright notice and the following paragraph appear in all copies. // // The University of North Carolina at Chapel Hill make no representations // about the suitability of this software for any purpose. It is provided // 'as is' without express or implied warranty. // // Please send BUG REPORTS to [email protected] // //////////////////////////////////////////////////////////////////////////// #ifndef GPU_SIFT_H #define GPU_SIFT_H #if defined(_WIN32) #ifdef SIFTGPU_DLL #ifdef DLL_EXPORT #define SIFTGPU_EXPORT __declspec(dllexport) #else #define SIFTGPU_EXPORT __declspec(dllimport) #endif #else #define SIFTGPU_EXPORT #endif #define SIFTGPU_EXPORT_EXTERN SIFTGPU_EXPORT #if _MSC_VER > 1000 #pragma once #endif #else #define SIFTGPU_EXPORT #define SIFTGPU_EXPORT_EXTERN extern "C" #endif #if !defined(_MAX_PATH) #if defined (MAX_PATH) #define _MAX_PATH MAX_PATH #else #define _MAX_PATH 512 #endif #endif /////////////////////////////////////////////////////////////////// //clss SiftParam //description: SIFT parameters //////////////////////////////////////////////////////////////////// class GlobalUtil; class SiftParam { public: float* _sigma; float _sigma_skip0; // float _sigma_skip1; // //sigma of the first level float _sigma0; float _sigman; int _sigma_num; //how many dog_level in an octave int _dog_level_num; int _level_num; //starting level in an octave int _level_min; int _level_max; int _level_ds; //dog threshold float _dog_threshold; //edge elimination float _edge_threshold; void ParseSiftParam(); public: float GetLevelSigma(int lev); float GetInitialSmoothSigma(int octave_min); SIFTGPU_EXPORT SiftParam(); }; class GLTexInput; class ShaderMan; class SiftPyramid; class ImageList; //////////////////////////////////////////////////////////////// //class SIftGPU //description: Interface of SiftGPU lib //////////////////////////////////////////////////////////////// class SiftGPU:public SiftParam { public: enum { SIFTGPU_NOT_SUPPORTED = 0, SIFTGPU_PARTIAL_SUPPORTED = 1, // detction works, but not orientation/descriptor SIFTGPU_FULL_SUPPORTED = 2 }; typedef struct SiftKeypoint { float x, y, s, o; //x, y, scale, orientation. }SiftKeypoint; protected: //when more than one images are specified //_current indicates the active one int _current; //_initialized indicates if the shaders and OpenGL/SIFT parameters are initialized //they are initialized only once for one SiftGPU inistance //that is, SIFT parameters will not be changed int _initialized; //_image_loaded indicates if the current images are loaded int _image_loaded; //the name of current input image char _imgpath[_MAX_PATH]; //_outpath containes the name of the output file char _outpath[_MAX_PATH]; //the list of image filenames ImageList * _list; //the texture that holds loaded input image GLTexInput * _texImage; //the SiftPyramid SiftPyramid * _pyramid; SiftPyramid ** _pyramids; int _nPyramid; //print out the command line options static void PrintUsage(); //Initialize OpenGL and SIFT paremeters, and create the shaders accordingly void InitSiftGPU(); //load the image list from a file void LoadImageList(char *imlist); public: //timing results for 10 steps float _timing[10]; public: //set the image list for processing SIFTGPU_EXPORT virtual void SetImageList(int nimage, const char** filelist); //get the number of SIFT features in current image SIFTGPU_EXPORT virtual int GetFeatureNum(); //save the SIFT result as a ANSCII/BINARY file SIFTGPU_EXPORT virtual void SaveSIFT(const char * szFileName); //Copy the SIFT result to two vectors SIFTGPU_EXPORT virtual void GetFeatureVector(SiftKeypoint * keys, float * descriptors); //Set keypoint list before running sift to get descriptors SIFTGPU_EXPORT virtual void SetKeypointList(int num, const SiftKeypoint * keys, int keys_have_orientation = 1); //Enable downloading results to CPU. //create a new OpenGL context for processing //call VerifyContextGL instead if you want to crate openGL context yourself, or your are //mixing mixing siftgpu with other openGL code SIFTGPU_EXPORT virtual int CreateContextGL(); //verify the current opengl context.. //(for example, you call wglmakecurrent yourself and verify the current context) SIFTGPU_EXPORT virtual int VerifyContextGL(); //check if all siftgpu functions are supported SIFTGPU_EXPORT virtual int IsFullSupported(); //set verbose mode SIFTGPU_EXPORT virtual void SetVerbose(int verbose = 4); //set SiftGPU to brief display mode, which is faster inline void SetVerboseBrief(){SetVerbose(2);}; //parse SiftGPU parameters SIFTGPU_EXPORT virtual void ParseParam(int argc, char **argv); //retrieve the size of current input image SIFTGPU_EXPORT virtual void GetImageDimension(int &w, int&h); //run SIFT on a new image given filename SIFTGPU_EXPORT virtual int RunSIFT(char * imgpath); //run SIFT on an image in the image list given the file index SIFTGPU_EXPORT virtual int RunSIFT(int index); //run SIFT on a new image given the pixel data and format/type; //gl_format (e.g. GL_LUMINANCE, GL_RGB) is the format of the pixel data //gl_type (e.g. GL_UNSIGNED_BYTE, GL_FLOAT) is the data type of the pixel data; //Check glTexImage2D(...format, type,...) for the accepted values //Using image data of GL_LUMINANCE + GL_UNSIGNED_BYTE can minimize transfer time SIFTGPU_EXPORT virtual int RunSIFT(int width, int height, const void * data, unsigned int gl_format, unsigned int gl_type); //run SIFT on current image (specified by arguments), or processing the current image again SIFTGPU_EXPORT virtual int RunSIFT(); //run SIFT with keypoints on current image again. SIFTGPU_EXPORT virtual int RunSIFT(int num, const SiftKeypoint * keys, int keys_have_orientation = 1); //constructor, (np is the number of pyramids) SIFTGPU_EXPORT SiftGPU(int np = 1); //destructor SIFTGPU_EXPORT virtual ~SiftGPU(); //set the active pyramid SIFTGPU_EXPORT virtual void SetActivePyramid(int index); //retrieve the number of images in the image list SIFTGPU_EXPORT virtual int GetImageCount(); //set parameter GlobalUtil::_ForceTightPyramid SIFTGPU_EXPORT virtual void SetTightPyramid(int tight = 1); //allocate pyramid for a given size of image SIFTGPU_EXPORT virtual int AllocatePyramid(int width, int height); //none of the texture in processing can be larger //automatic down-sample is used if necessary. SIFTGPU_EXPORT virtual void SetMaxDimension(int sz); /// public: //overload the new operator because delete operator is virtual //and it is operating on the heap inside the dll (due to the //compiler setting of /MT and /MTd). Without the overloaded operator //deleting a SiftGPU object will cause a heap corruption in the //static link case (but not for the runtime dll loading). SIFTGPU_EXPORT void* operator new (size_t size); }; //////////////////////////////////////////////////////////////// //class SIftGPUEX //description: add viewing extension to Interface of SiftGPU //////////////////////////////////////////////////////////////// class SiftGPUEX:public SiftGPU { //view mode int _view; //sub view mode int _sub_view; //whether display a debug view int _view_debug; //colors for SIFT feature display enum{COLOR_NUM = 36}; float _colors[COLOR_NUM*3]; //display functions void DisplayInput(); //display gray level image of input image void DisplayDebug(); //display debug view void DisplayFeatureBox(int i); //display SIFT features void DisplayLevel(void (*UseDisplayShader)(), int i); //display one level image void DisplayOctave(void (*UseDisplayShader)(), int i); //display all images in one octave //display different content of Pyramid by specifying different data and display shader //the first nskip1 levels and the last nskip2 levels are skiped in display void DisplayPyramid( void (*UseDisplayShader)(), int dataName, int nskip1 = 0, int nskip2 = 0); //use HSVtoRGB to generate random colors static void HSVtoRGB(float hsv[3],float rgb[3]); public: SIFTGPU_EXPORT SiftGPUEX(); //change view mode SIFTGPU_EXPORT void SetView(int view, int sub_view, char * title); //display current view SIFTGPU_EXPORT void DisplaySIFT(); //toggle debug mode on/off SIFTGPU_EXPORT void ToggleDisplayDebug(); //randomize the display colors SIFTGPU_EXPORT void RandomizeColor(); }; ///matcher export //This is a gpu-based sift match implementation. class SiftMatchGPU { public: enum SIFTMATCH_LANGUAGE { SIFTMATCH_SAME_AS_SIFTGPU = 0, //when siftgpu already initialized. SIFTMATCH_CG = 1, SIFTMATCH_GLSL = 2, SIFTMATCH_CUDA = 3 }; private: int __max_sift; int __language; SiftMatchGPU * __matcher; virtual void InitSiftMatch(){} public: //OpenGL Context creation/verification, initialization is done automatically inside SIFTGPU_EXPORT virtual int CreateContextGL(); SIFTGPU_EXPORT virtual int VerifyContextGL(); //Consructor, the argument specifies the maximum number of features to match SIFTGPU_EXPORT SiftMatchGPU(int max_sift = 4096); //chagne gpu_language : 0(same as siftgpu), 1 (cg), 2 (glsl), 3 (cuda) //they can the four in SIFTMATCH_LANGUAGE. SIFTGPU_EXPORT virtual void SetLanguage(int gpu_language); //change the maximum of features to match whenever you want SIFTGPU_EXPORT virtual void SetMaxSift(int max_sift); //desctructor SIFTGPU_EXPORT virtual ~SiftMatchGPU(); //Specifiy descriptors to match, index = [0/1] for two features sets respectively //Option1, use float descriptors, and they be already normalized to 1.0 SIFTGPU_EXPORT virtual void SetDescriptors(int index, int num, const float* descriptors, int id = -1); //Option 2 unsigned char descriptors. They must be already normalized to 512 SIFTGPU_EXPORT virtual void SetDescriptors(int index, int num, const unsigned char * descriptors, int id = -1); //match two sets of features, the function RETURNS the number of matches. //Given two normalized descriptor d1,d2, the distance here is acos(d1 *d2); SIFTGPU_EXPORT virtual int GetSiftMatch( int max_match, // the length of the match_buffer. int match_buffer[][2], //buffer to receive the matched feature indices float distmax = 0.7, //maximum distance of sift descriptor float ratiomax = 0.8, //maximum distance ratio int mutual_best_match = 1); //mutual best match or one way //two functions for guded matching, two constraints can be used //one homography and one fundamental matrix, the use is as follows //1. for each image, first call SetDescriptor then call SetFeatureLocation //2. Call GetGuidedSiftMatch //input feature location is a vector of [float x, float y, float skip[gap]] SIFTGPU_EXPORT virtual void SetFeautreLocation(int index, const float* locations, int gap = 0); inline void SetFeatureLocation(int index, const SiftGPU::SiftKeypoint * keys) { SetFeautreLocation(index, (const float*) keys, 2); } //use a guiding Homography H and a guiding Fundamental Matrix F to compute feature matches //the function returns the number of matches. SIFTGPU_EXPORT virtual int GetGuidedSiftMatch( int max_match, int match_buffer[][2], //buffer to recieve float H[3][3], //homography matrix, (Set NULL to skip) float F[3][3], //fundamental matrix, (Set NULL to skip) float distmax = 0.7, //maximum distance of sift descriptor float ratiomax = 0.8, //maximum distance ratio float hdistmax = 32, //threshold for |H * x1 - x2|_1 float fdistmax = 16, //threshold for sampson error of x2'FX1 int mutual_best_match = 1); //mutual best or one way public: //overload the new operator, the same reason as SiftGPU above SIFTGPU_EXPORT void* operator new (size_t size); }; //Two exported global functions used to create SiftGPU and SiftMatchGPU SIFTGPU_EXPORT_EXTERN SiftGPU * CreateNewSiftGPU(int np =1); SIFTGPU_EXPORT_EXTERN SiftMatchGPU * CreateNewSiftMatchGPU(int max_sift = 4096); #endif
[ "bwhyuk@8292896d-4b4e-0410-821e-153bc45fc8c1" ]
[ [ [ 1, 338 ] ] ]