blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
aa065a4e4207c81b769c96c8264859412b07fb45
1e01b697191a910a872e95ddfce27a91cebc57dd
/GrfParseAsBNF.cpp
78d2dc8ca08798f10a81c48e6f3ea7ac4a5082ca
[]
no_license
canercandan/codeworker
7c9871076af481e98be42bf487a9ec1256040d08
a68851958b1beef3d40114fd1ceb655f587c49ad
refs/heads/master
2020-05-31T22:53:56.492569
2011-01-29T19:12:59
2011-01-29T19:12:59
1,306,254
7
5
null
null
null
null
IBM852
C++
false
false
4,155
cpp
/* "CodeWorker": a scripting language for parsing and generating text. Copyright (C) 1996-1997, 1999-2002 CÚdric Lemaire This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA To contact the author: [email protected] */ #ifdef WIN32 #pragma warning (disable : 4786) #endif #include "UtlException.h" #include "ScpStream.h" #include "CppCompilerEnvironment.h" #include "ExprScriptExpression.h" #include "ExprScriptVariable.h" #include "CGRuntime.h" // for CGRuntime::getCurrentDirectory() #include "DtaBNFScript.h" #include "DtaScriptVariable.h" #include "BNFClause.h" #include "DtaProject.h" #include "GrfParseAsBNF.h" namespace CodeWorker { GrfParseAsBNF::GrfParseAsBNF() : _pClass(NULL), _pCachedScript(NULL), _pBNFFileName(NULL), _pFileName(NULL) { _sCurrentDirectoryAtCompileTime = CGRuntime::getCurrentDirectory(); } GrfParseAsBNF::~GrfParseAsBNF() { delete _pBNFFileName; delete _pClass; delete _pFileName; if (_pCachedScript != NULL) delete _pCachedScript; } void GrfParseAsBNF::setBNFFileName(ExprScriptScriptFile* pBNFFileName) { if (pBNFFileName->isFileName()) _pBNFFileName = pBNFFileName->getFileName(); _pCachedScript = dynamic_cast<DtaBNFScript*>(pBNFFileName->getBody()); pBNFFileName->release(); } SEQUENCE_INTERRUPTION_LIST GrfParseAsBNF::executeInternal(DtaScriptVariable& visibility) { DtaScriptVariable* pClass = visibility.getExistingVariable(*_pClass); if (pClass == NULL) throw UtlException("runtime error: variable '" + _pClass->toString() + "' doesn't exist while calling procedure 'parseAsBNF()'"); std::string sOutputFile = _pFileName->getValue(visibility); if (_pBNFFileName != NULL) { std::string sBNFFileName = _pBNFFileName->getValue(visibility); if ((_pCachedScript == NULL) || (_sCachedBNFFile != sBNFFileName) || ScpStream::existVirtualFile(sBNFFileName)) { if (_pCachedScript != NULL) delete _pCachedScript; _pCachedScript = new DtaBNFScript(getParent()); _sCachedBNFFile = sBNFFileName; _pCachedScript->parseFile(sBNFFileName.c_str(), _sCurrentDirectoryAtCompileTime); } } SEQUENCE_INTERRUPTION_LIST result = _pCachedScript->generate(sOutputFile.c_str(), *pClass); switch(result) { case CONTINUE_INTERRUPTION: case BREAK_INTERRUPTION: case RETURN_INTERRUPTION: result = NO_INTERRUPTION; break; } return result; } void GrfParseAsBNF::compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const { ExprScriptConstant* pConstantFileName = dynamic_cast<ExprScriptConstant*>(_pBNFFileName); std::string sScriptFilename; if (pConstantFileName == NULL) { sScriptFilename = theCompilerEnvironment.newInlineScriptFilename(); } else { sScriptFilename = pConstantFileName->getConstant(); } std::string sRadical = DtaScript::convertFilenameAsIdentifier(CppCompilerEnvironment::getRadical(CppCompilerEnvironment::filename2Module(sScriptFilename))); CW_BODY_INDENT << "CGRuntime::parseAsBNF(&Execute" << sRadical << "::instance(), "; _pClass->compileCpp(theCompilerEnvironment); CW_BODY_STREAM << ", "; _pFileName->compileCppString(theCompilerEnvironment); CW_BODY_STREAM << ");"; CW_BODY_ENDL; if (_pCachedScript == NULL) { _pCachedScript = new DtaBNFScript(getParent()); _sCachedBNFFile = sScriptFilename; _pCachedScript->parseFile(_sCachedBNFFile.c_str()); } _pCachedScript->compileCpp(theCompilerEnvironment, sScriptFilename); } }
[ "cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4" ]
[ [ [ 1, 105 ] ] ]
85fa6650a766d55a974573e950e7086791ecf772
941e1c9c87576247aac5c28db16e2d73a2bec0af
/GMSDlg.h
3551fae908cca8745855be67646f0b11c62d22ea
[]
no_license
luochong/vc-gms-1
49a5ccc2edd3da74da2a7d9271352db8213324cb
607b087e37cc0946b4562b681bb65875863bc084
refs/heads/master
2016-09-06T09:32:16.340313
2009-06-14T07:35:19
2009-06-14T07:35:19
32,432,320
0
0
null
null
null
null
UTF-8
C++
false
false
1,798
h
// GMSDlg.h : header file // #if !defined(AFX_GMSDLG_H__9E5EF495_59B2_4824_B54E_3374DBBC3484__INCLUDED_) #define AFX_GMSDLG_H__9E5EF495_59B2_4824_B54E_3374DBBC3484__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 ///////////////////////////////////////////////////////////////////////////// // CGMSDlg dialog class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; class CGMSDlg : public CDialog { // Construction public: CGMSDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CGMSDlg) enum { IDD = IDD_GMS_DIALOG }; CString m_strName; CString m_strPasswd; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CGMSDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CGMSDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnButtonCancel(); afx_msg void OnButtonOk(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_GMSDLG_H__9E5EF495_59B2_4824_B54E_3374DBBC3484__INCLUDED_)
[ "luochong1987@29d93fdc-527c-11de-bf49-a932634fd5a9" ]
[ [ [ 1, 73 ] ] ]
079026438ec21ec7a886eccfc643eb9de1cc6fd5
3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c
/unpassed/1063.cpp
fc002a0e55499a0c5a736fb9f8b7e88d1a64fe0d
[]
no_license
usherfu/zoj
4af6de9798bcb0ffa9dbb7f773b903f630e06617
8bb41d209b54292d6f596c5be55babd781610a52
refs/heads/master
2021-05-28T11:21:55.965737
2009-12-15T07:58:33
2009-12-15T07:58:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,698
cpp
#include<iostream> using namespace std; // Wrong answer enum { SIZ = 60, MRK = 10000, }; int move[6][3] = { {-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1} }; int N, M, K, l, F; int m[SIZ][SIZ][SIZ]; int i,j,k,t; bool valid(int a, int b, int c){ return (a>=0&&a<K)&&(b>=0&&b<M)&&(c>=0&&c<N); } int path(int a, int b, int c){ int na,nb,nc; m[a][b][c] = MRK; for(int i=0; i<6; i++){ na = a + move[i][0]; nb = b + move[i][1]; nc = c + move[i][2]; if(!valid(na,nb,nc) || (m[na][nb][nc]==-1&&path(na, nb, nc) ==1)){ return 1; } } return 0; } void flood(int a, int b, int c, int v){ int na, nb, nc; m[a][b][c] = v; for(int i=0; i<6; i++){ na = a + move[i][0]; nb = b + move[i][1]; nc = c + move[i][2]; if(!valid(na,nb,nc)){ continue; } if(m[na][nb][nc]==MRK){ m[na][nb][nc] = v; flood(na, nb, nc, v); } } } void fun(){ int face = 0; for(i=0; i<K; i++){ for(j=0; j<M; j++){ for(k=0; k<N; k++){ if(m[i][j][k] == -1){ if(path(i,j,k) == 1){ flood(i,j,k, 1); } else { flood(i,j,k, 0); } } } } } for(i=0; i<K; i++){ for(j=0; j<M; j++){ for(k=0; k<N; k++){ if(m[i][j][k] != 0) continue; face += 6; if(i!=0&&m[i-1][j][k]==0){//down face--; } if(i!=K-1&&m[i+1][j][k] ==0){// up face--; } if(j!=0&&m[i][j-1][k]==0){ //front face--; } if(j!=M-1&&m[i][j+1][k]==0){ //back face--; } if(k!=0&&m[i][j][k-1]==0){ // left face--; } if(k!=N-1&&m[i][j][k+1]==0){ // right face--; } } } } printf("The number of faces needing shielding is %d.\n", face); } int readIn(){ scanf("%d%d%d%d",&N,&M,&K,&l); if(N + M + K + l ==0) return 0; memset(m, -1, sizeof(m)); F = N * M; for(;l>0;l--){ scanf("%d", &t); i = t/F; t %= F; j = t/N; t %= N; m[i][j][t] = 0; } return 1; } int main(){ while(readIn() > 0){ fun(); } return 0; }
[ [ [ 1, 110 ] ] ]
7c19591476d29af3a23aaadeccbf420232afedc4
1c80a726376d6134744d82eec3129456b0ab0cbf
/Project/C++/POJ/3681/3681.cpp
d3b91d9e06d4e5fa69bef19003b82d7bbe8eb8ed
[]
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
UTF-8
C++
false
false
360
cpp
#include "stdio.h" #include "iostream" #include "string.h" #include "math.h" #include "string" #include "vector" #include "set" #include "map" #include "queue" #include "list" using namespace std; int main() { int a[6]; for(int i=0;i<6;i++) cin>>a[i]; int sum=0; for(int i=1;i<6;i++) if(a[i]<a[0]) sum+=a[i]; cout<<sum<<endl; }
[ "[email protected]@592586dc-1302-11df-8689-7786f20063ad" ]
[ [ [ 1, 23 ] ] ]
df86b6788d1ff8033e5e9345f807fb01a292a741
63fc6506b8e438484a013b3c341a1f07f121686b
/apps/addonsExamples/opencvExample/src/testApp.h
9455aaed2f0df8e7cd469e9613a01d525814dbe7
[]
no_license
progen/ofx-dev
c5a54d3d588d8fd7318e35e9b57bf04c62cda5a8
45125fcab657715abffc7e84819f8097d594e28c
refs/heads/master
2021-01-20T07:15:39.755316
2009-03-03T22:33:37
2009-03-03T22:33:37
140,479
1
0
null
null
null
null
UTF-8
C++
false
false
935
h
#ifndef _TEST_APP #define _TEST_APP #include "ofMain.h" #define OF_ADDON_USING_OFXOPENCV #include "ofAddons.h" //#define _USE_LIVE_VIDEO // uncomment this to use a live camera // otherwise, we'll use a movie file class testApp : public ofBaseApp { public: void setup(); void update(); void draw(); void keyPressed (int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(); #ifdef _USE_LIVE_VIDEO ofVideoGrabber vidGrabber; #else ofVideoPlayer vidPlayer; #endif ofxCvColorImage colorImg; ofxCvGrayscaleImage grayImage; ofxCvGrayscaleImage grayBg; ofxCvGrayscaleImage grayDiff; ofxCvContourFinder contourFinder; int threshold; bool bLearnBakground; }; #endif
[ [ [ 1, 48 ] ] ]
e7f1449b5edb575380b30451e77d1a0be733901a
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/core_billiard/BaseImp.h
acf5ae0ec055997802988bfe87723e2c4589861b
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
421
h
#pragma once namespace my_render_imp { class BaseImp : IMPLEMENTS_INTERFACE( Base ) { public: // from Base virtual wstring getID() OVERRIDE; virtual wstring getName() OVERRIDE; virtual wstring getURI() OVERRIDE; public: // set void setID( wstring id ); void setName( wstring name ); void setURI( wstring uri ); private: // from Base wstring id_, name_, uri_; }; }
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 22 ] ] ]
e09fafed8e26af06ae53bdc544e7dd48e67adcc9
d8f64a24453c6f077426ea58aaa7313aafafc75c
/GUI/DKInput.h
5f097a3fccc58e08399e10b3e42bd760502e52ee
[]
no_license
dotted/wfto
5b98591645f3ddd72cad33736da5def09484a339
6eebb66384e6eb519401bdd649ae986d94bcaf27
refs/heads/master
2021-01-20T06:25:20.468978
2010-11-04T21:01:51
2010-11-04T21:01:51
32,183,921
1
0
null
null
null
null
UTF-8
C++
false
false
1,287
h
#ifndef DKINPUT_H #define DKINPUT_H #include "DKcommons.h" class CDKInput { public: CDKInput(); ~CDKInput(); GLint get_screen_x(); GLint get_screen_y(); GLvoid update(UINT message, WPARAM wParam, LPARAM lParam); bool is_left_down(); bool is_right_down(); bool is_up_down(); bool is_down_down(); bool is_esc_down(); bool is_space_down(); bool is_enter_down(); bool is_shift_down(); bool is_tab_down(); bool is_control_down(); bool is_plus_down(); bool is_minus_down(); bool is_F1_down(); bool is_F2_down(); bool is_F3_down(); bool is_F4_down(); bool is_F5_down(); bool is_F6_down(); bool is_F7_down(); bool is_F8_down(); bool is_F9_down(); bool is_F10_down(); bool is_F11_down(); bool is_F12_down(); bool is_key_down(char key); GLvoid set_z_depth(GLfloat z_depth); /* 11,044x...10z x.... nz x=11,044*nz/10 ==> world_screen_width=fabs(1,1044*z_depth); ==> world_screen_height=fabs(0,8283*z_depth); */ GLfloat get_world_x(); GLfloat get_world_y(); GLvoid set_mouse_pos(GLint xpos, GLint ypos); bool is_lmouse_down(); bool is_rmouse_down(); private: bool keys[256]; bool lmouse_down,rmouse_down; GLfloat z_depth,wsw,wsh,w_2,h_2, cos_45; }; #endif // DKINPUT_H
[ [ [ 1, 69 ] ] ]
759b65aa8a64ff2add5a5c2db1e2d69c42dddb64
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10Multithread.h
9b3748ce2289c5e1c60b08e790dc43d5e3bd072a
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
1,636
h
//Copyright (c) Microsoft Corporation. All rights reserved. #pragma once #include "DirectUnknown.h" namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D10 { using namespace System; using namespace Microsoft::WindowsAPICodePack::DirectX; /// <summary> /// A multithread interface accesses multithread settings and can only be used if the thread-safe layer is turned on. /// <para>(Also see DirectX SDK: ID3D10Multithread)</para> /// </summary> public ref class Multithread : public DirectUnknown { public: /// <summary> /// Enter a device's critical section. /// <para>(Also see DirectX SDK: ID3D10Multithread::Enter)</para> /// </summary> void Enter(); /// <summary> /// Leave a device's critical section. /// <para>(Also see DirectX SDK: ID3D10Multithread::Leave)</para> /// </summary> void Leave(); /// <summary> /// Find out if multithreading is turned on or not. /// <para>(Also see DirectX SDK: ID3D10Multithread::GetMultithreadProtected)</para> /// <para>(Also see DirectX SDK: ID3D10Multithread::SetMultithreadProtected)</para> /// </summary> property Boolean IsMultithreadProtected { Boolean get(); void set(Boolean value); } internal: Multithread() { } Multithread(ID3D10Multithread* pNativeID3D10Multithread) : DirectUnknown(pNativeID3D10Multithread) { } }; } } } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 52 ] ] ]
13bb7f1c1fa3bbd1f1dd4db258a482d87f5ab8fe
9907be749dc7553f97c9e51c5f35e69f55bd02c0
/april5/framework code & project/sprite.cpp
a3fdcf1617b86dc8655a51ebd4636d40a0dcd064
[]
no_license
jdeering/csci476winthrop
bc8907b9cc0406826de76aca05e6758810377813
2bc485781f819c8fd82393ac86de33404e7ad6d3
refs/heads/master
2021-01-10T19:53:14.853438
2009-04-24T14:26:36
2009-04-24T14:26:36
32,223,762
0
0
null
null
null
null
UTF-8
C++
false
false
7,603
cpp
#include "sprite.h" /****************************************************** Default Constructor ******************************************************/ Sprite::Sprite() { box.SetPosition(0, 0); box.SetSize(0, 0); numFrames = 1; currFrame = 0; visible = true; moving = false; animating = false; alive = true; rest = 0; } /****************************************************** Constructor @param spriteName The name of the sprite. @param x The initial x coordinate of the sprite @param y The initial y coordinate of the sprite @param w The initial width of the sprite in pixels @param h The initial height of the sprite in pixels ******************************************************/ Sprite::Sprite(std::string imageRef, int x = 0, int y = 0, int w = 0, int h = 0) { fileRefName = imageRef; numFrames = 1; currFrame = 0; box.SetPosition(x, y); box.SetSize(w, h); visible = true; moving = false; animating = false; alive = true; rest = 0; } /****************************************************** Deconstructor ******************************************************/ Sprite::~Sprite() { } /****************************************************** Toggles animation of the sprite and sets the frame rate @param delay The number of ticks to wait before moving to the next frame. Higher numbers yield slower animations. 0 or less will turn animation off. ******************************************************/ void Sprite::SetAnimation(int delay = 0) { if(delay > 0) { frameDelay = delay; animating = true; } } /****************************************************** Sets the rate at which to animate the sprite @param delay The number of ticks to wait before moving to the next frame. Higher numbers yield slower animations. 0 will turn animation off. ******************************************************/ void Sprite::SetFrameDelay(int delay) { frameDelay = delay; } /****************************************************** Toggles whether or not the sprite is alive. @param val <code>true</code> to have the sprite drawn, <code>false</code> to have it not drawn ******************************************************/ void Sprite::SetAlive(bool val) { alive = val; } /****************************************************** @return <code>true</code> if the sprite is being animated, <code>false</code> otherwise ******************************************************/ bool Sprite::isAnimating(){ return animating; } /****************************************************** @return <code>true</code> if the sprite is being drawn, <code>false</code> otherwise ******************************************************/ bool Sprite::isAlive(){ return alive; } /****************************************************** Sets the current animation frame to draw. @param frame The index of the frame to draw @return <code>true</code> if the frame index is valid, <code>false</code> otherwise. ******************************************************/ void Sprite::SetFrame(int frame) { currFrame = frame; } /****************************************************** Sets the position of the sprite on the screen. @param x The x coordinate of the position @param y The y coordinate of the position ******************************************************/ void Sprite::SetPosition(int x , int y) { box.SetPosition(x, y); } /****************************************************** Sets the width and height of the sprite. @param w The width of the sprite @param h The height of the sprite ******************************************************/ void Sprite::SetSize(int w, int h) { box.SetSize(w, h); } /****************************************************** Sets a sprite in motion until it reaches its destination. @param x The x coordinate being moved to @param y The y coordinate being moved to @param speed The number of pixels to move per tick (0 to stop movement) ******************************************************/ void Sprite::MoveTo(int x, int y, int s) { new_x = x; new_y = y; speed = s; moving = true; if(speed < 0) speed = 0 - speed; if(speed == 0) moving = false; } /****************************************************** Updates the sprite's location and animation. @param img The sprite image being drawn @param dest The screen bitmap on which to draw the sprite ******************************************************/ void Sprite::Update() { if(alive) { NextFrame(); MovePosition(); } } /****************************************************** Moves to the next frame of animation. If looping is enabled, the animation is restarted once the last frame has been rendered, otherwise animating is stopped. ******************************************************/ void Sprite::NextFrame() { if(animating) { currFrame++; if(currFrame >= numFrames) { if(loops) currFrame = 0; // Start frames over else { currFrame--; // Reset to last valid frame animating = false; } } } } /****************************************************** Draws the sprite in its current location. @param image The sprite image being drawn @param dest The screen bitmap on which to draw the sprite ******************************************************/ void Sprite::Draw(BITMAP *frame, BITMAP *buffer) { if(visible) masked_blit(frame, buffer, 0, 0, box.GetPositionX(), box.GetPositionY(), box.GetWidth(), box.GetHeight()); } /****************************************************** Uses values specified in MoveTo() to change the position of the sprite. ******************************************************/ void Sprite::MovePosition() { if(moving && rest == 0) { rest = speed; if(new_x > box.GetPositionX()) { box.SetPosition(box.GetPositionX()+speed, box.GetPositionY()); if(new_x <= box.GetPositionX()) box.SetPosition(new_x, box.GetPositionY()); // Prevents wobbling } if(new_x < box.GetPositionX()) { box.SetPosition(box.GetPositionX()-speed, box.GetPositionY()); if(new_x >= box.GetPositionX()) box.SetPosition(new_x, box.GetPositionY()); // Prevents wobbling } if(new_y > box.GetPositionY()) { box.SetPosition(box.GetPositionX(), box.GetPositionY()+speed); if(new_y <= box.GetPositionY()) box.SetPosition(box.GetPositionX(), new_y); // Prevents wobbling } if(new_y < box.GetPositionY()) { box.SetPosition(box.GetPositionX(), box.GetPositionY()-speed); if(new_y >= box.GetPositionY()) box.SetPosition(box.GetPositionX(), new_y); // Prevents wobbling } if(new_y == box.GetPositionY() && new_x == box.GetPositionX()) { moving = false; speed = 0; } } if(moving && rest > 0) { rest--; } } int Sprite::GetFrameNum() { return currFrame; } void Sprite::SetFrameCount(int fCount) { numFrames = fCount; } int Sprite::GetWidth() { return box.GetWidth(); } int Sprite::GetHeight() { return box.GetHeight(); } void Sprite::SetVisible(bool in) { visible = in; } bool Sprite::isVisible() { return visible; } bool Sprite::isColliding(BoundingBox &other_box) { return box.isColliding(other_box); } bool Sprite::isColliding(Sprite &other_sprite) { return box.isColliding(other_sprite.box); } void Sprite::ChangeBitmap(std::string ref) { fileRefName = ref; }
[ "lcairco@2656ef14-ecf4-11dd-8fb1-9960f2a117f8" ]
[ [ [ 1, 294 ] ] ]
102a4211c988af2f2f4ceed0ceefc357402a8e8a
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Include/CRand.h
fa89c4892e05eae13d7440d3bc9060ae99964ea7
[]
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
3,271
h
/* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not 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. Any feedback is very welcome. http://www.math.keio.ac.jp/matumoto/emt.html email: [email protected] */ #ifndef _CRAND_H #define _CRAND_H 1 #include <stdio.h> #include <stdlib.h> #define N_SEED 624 #define M_SEED 397 /* CRand */ class CRand { public: CRand(unsigned long s = (unsigned long)-1L); virtual ~CRand() {} unsigned long Rand(void) { unsigned long n = labs(genrand_int32()); if(n==m_nPrevious) { while(n==m_nPrevious) n = labs(genrand_int32()); } else m_nPrevious = n; return(n); } unsigned long RandMax(unsigned long nMax) {return(Rand() % nMax);} unsigned long RandRange(unsigned long nMin,unsigned long nMax) {return(Rand() % (nMax - nMin + 1) + nMin);} void Seed(unsigned long s) {init_genrand(s);} void SeedArray(unsigned long init_key[],int key_length) {init_by_array(init_key,key_length);} private: void init_genrand(unsigned long s); void init_by_array(unsigned long init_key[],int key_length); unsigned long genrand_int32(void); long genrand_int31(void); double genrand_real1(void); double genrand_real2(void); double genrand_real3(void); double genrand_res53(void); unsigned long m_nPrevious; unsigned long mt[N_SEED]; /* the array for the state vector */ int mti; /* mti==N_SEED+1 means mt[N_SEED] is not initialized */ }; #endif // _CRAND_H
[ [ [ 1, 95 ] ] ]
caf5c7c0f5f1821a86d8ab1d71849f541e8bb638
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/hitlnew/isimulator.h
a18c16ba33bb027f2a9f5ac35c6ae557cf0b07f5
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,682
h
#ifndef ISIMULATOR_H #define ISIMULATOR_H #include <QObject> #include <QUdpSocket> #include <QTimer> #include <math.h> #include "uavtalk/telemetrymanager.h" #include "uavobjects/uavobjectmanager.h" #include "uavobjects/actuatordesired.h" #include "uavobjects/altitudeactual.h" #include "uavobjects/attitudeactual.h" #include "uavobjects/velocityactual.h" #include "uavobjects/positionactual.h" #include "uavobjects/gcstelemetrystats.h" class Simulator: public QObject { Q_OBJECT public: //static ISimulator* Instance(); //protected: Simulator(); ~ISimulator(); bool isAutopilotConnected(); bool isFGConnected(); signals: void myStart(); void autopilotConnected(); void autopilotDisconnected(); void fgConnected(); void fgDisconnected(); private slots: void onStart(); void transmitUpdate(); void receiveUpdate(); void onAutopilotConnect(); void onAutopilotDisconnect(); void onFGConnectionTimeout(); void telStatsUpdated(UAVObject* obj); private: //static ISimulator* _instance; QUdpSocket* inSocket; QUdpSocket* outSocket; ActuatorDesired* actDesired; AltitudeActual* altActual; VelocityActual* velActual; AttitudeActual* attActual; PositionActual* posActual; GCSTelemetryStats* telStats; QHostAddress fgHost; int inPort; int outPort; int updatePeriod; QTimer* txTimer; QTimer* fgTimer; bool autopilotConnectionStatus; bool fgConnectionStatus; int fgTimeout; void processUpdate(QString& data); void setupOutputObject(UAVObject* obj, int updatePeriod); void setupInputObject(UAVObject* obj, int updatePeriod); void setupObjects(); }; #endif // ISIMULATOR_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 74 ] ] ]
fee38351b874f46b6c2cc5f8cec98e3ac902bfc4
6777a1d08a287959ad5db2cbbb29f529e3ab5e3c
/JinShell/JinShell/source/rcplib.cpp
3417d8cffd3153d6fa074a9c13df080559e6e2ae
[]
no_license
btuduri/codecomposer
07d6b68c0b836ae92429b6123b7a78094acb4e0c
b3225b456da3d77f5cc13c3d1b1c0d5291dc0277
refs/heads/master
2016-09-09T18:52:07.106499
2008-07-03T16:49:43
2008-07-03T16:49:43
32,828,244
0
0
null
null
null
null
UTF-8
C++
false
false
2,233
cpp
#include <stdio.h> #include <nds.h> #include "plugin.h" #include "plugin_def.h" #include "rcplib.h" static u8 *bdata; static u32 bSampleRate; static u32 bSampleBufCount; static u32 bMaxChannelCount; static u32 bGenVolume; void rcplibSetParam(u8 *data,u32 SampleRate,u32 SampleBufCount,u32 MaxChannelCount,u32 GenVolume) { bdata=data; bSampleRate=SampleRate; bMaxChannelCount=MaxChannelCount; bGenVolume=GenVolume; } bool rcplibStart(void) { RCP_Init(); RCP_LoadRCP(bdata,bSampleRate); PCH_Init(bSampleRate,bSampleBufCount,bMaxChannelCount,bGenVolume); MTRKCC_Init(); return(true); } void rcplibFree(void) { MTRKCC_Free(); PCH_Free(); RCP_Free(); } int rcplibGetNearClock(void) { TRCP *pRCP=&RCP; u32 TrackCount=RCP_Chank.TrackCount; int NearClock=0x7fffffff; for(u32 TrackNum=0;TrackNum<TrackCount;TrackNum++){ TRCP_Track *pRCP_Track=&pRCP->RCP_Track[TrackNum]; if(pRCP_Track->EndFlag==false){ if(pRCP_Track->WaitClock<NearClock) NearClock=pRCP_Track->WaitClock; } } int GTNearClock=PCH_GT_GetNearClock(); if(GTNearClock!=0){ if(GTNearClock<NearClock) NearClock=GTNearClock; } if(NearClock==0x7fffffff) NearClock=0; return(NearClock); } bool rcplibNextClock(bool ShowEventMessage,bool EnableNote,int DecClock) { TRCP *pRCP=&RCP; u32 TrackCount=RCP_Chank.TrackCount; while(1){ if(RCP_isAllTrackEOF()==true) return(false); if(EnableNote==true) PCH_GT_DecClock(DecClock); for(u32 TrackNum=0;TrackNum<TrackCount;TrackNum++){ TRCP_Track *pRCP_Track=&pRCP->RCP_Track[TrackNum]; if(pRCP_Track->EndFlag==false){ pRCP_Track->WaitClock-=DecClock; while(pRCP_Track->WaitClock==0){ RCP_ProcRCP(ShowEventMessage,EnableNote,pRCP_Track); if(pRCP_Track->EndFlag==true){ // _consolePrintf("end of Track(%d)\n",TrackNum); break; } } } } if(pRCP->FastNoteOn==true) break; DecClock=rcplibGetNearClock(); } return(true); } void rcplibAllSoundOff(void) { PCH_AllSoundOff(); }
[ "feeljuin@73b7253b-944e-0410-bf16-698164e7ef75" ]
[ [ [ 1, 105 ] ] ]
d6aa7ec7043a2510df569eb0b0bfa4759b044b6f
3dbc9695143310833b523b1c6c98f42da3c21d32
/src/perfectPixelsRescale.h
fe09e97eaaecd200207401c12a6e01bfd2c8b1f9
[]
no_license
victordiaz/cityfireflies
00328d5e52b13d7f0783864303fb495c1e2cad68
2b775f856f5804516902c1851195b49c140202b8
refs/heads/master
2021-01-04T02:36:56.472042
2011-11-15T17:06:18
2011-11-15T17:06:18
1,383,568
1
1
null
null
null
null
UTF-8
C++
false
false
949
h
/* * perfectPixelRescale.h * * Created by Mar Canet Sola on 6/12/10. * Copyright 2010 lummo. All rights reserved. * * http://www.openframeworks.cc/forum/viewtopic.php?f=9&t=3505&view=unread * */ #ifndef ___PERFECT_PIXELS_RESCALE__H__ #define ___PERFECT_PIXELS_RESCALE__H__ #include "ofMain.h" class perfectPixelsRescale { public: perfectPixelsRescale(); ~perfectPixelsRescale(); void resample(unsigned char* pixels); void setSize(int _pixelSizeX, int _pixelSizeY, int _width, int _height); void draw(int x, int y, bool alignCenter=true); unsigned char* getPixels(); ofImage getImage(); int getPixelSizeX(); int getPixelSizeY(); int getWidth(); int getHeight(); private: ofImage img; int totalPixel; int pixelSizeX; int pixelSizeY; int width; int height; unsigned char* newPixels; int p1; int p2; int p3; }; #endif
[ [ [ 1, 44 ] ] ]
a00e93caf99699542a9d9b45b89c749192770459
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/MyWheelDirector/src/F6Table.cpp
07cc18fd6b052a81e4b448a1832334d0e16073e8
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,296
cpp
#include "MyWheelDirectorStableHeaders.h" #include "F6Table.h" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/iostreams/stream.hpp> using namespace Orz; std::string Item2String(F6TableInterface::ITEM item) { switch(item) { case F6TableInterface::PoTaiFenShu: return "Data.PoTaiFenShu"; //////////////////////// case F6TableInterface::DongWuZuiDaYaZhu: return "Data.DongWuZuiDaYaZhu"; ////////////////// case F6TableInterface::DongWuZuiXiaoYaZhu: return "Data.DongWuZuiXiaoYaZhu"; ///////// case F6TableInterface::DaoShuShiJian: return "Data.DaoShuShiJian"; ///////// case F6TableInterface::TuiBiGongNeng: return "Data.TuiBiGongNeng"; ///////// case F6TableInterface::KaiFenDanWei: return "Data.KaiFenDanWei"; ///////// case F6TableInterface::KaiFenShangXian: return "Data.KaiFenShangXian"; ///////// case F6TableInterface::ZhuangXianZuiDaYaZhu: return "Data.ZhuangXianZuiDaYaZhu"; case F6TableInterface::HeZuiDaYaZhu: return "Data.HeZuiDaYaZhu"; } return ""; } int GetData(F6TableInterface::ITEM item, int index) { switch(item) { case F6TableInterface::PoTaiFenShu: switch(index) { case 1: return 10000; case 2: return 20000; case 3: return 30000; case 4: return 50000; case 5: return 100000; case 6: return 200000; case 7: return 500000; } break; //////////////////////// case F6TableInterface::DongWuZuiDaYaZhu: switch(index) { case 1: return 50; case 2: return 99; case 3: return 250; case 4: return 999; } break; ////////////////// case F6TableInterface::DongWuZuiXiaoYaZhu: switch(index) { case 1: return 1; case 2: return 5; case 3: return 10; case 4: return 20; } break; ///////// case F6TableInterface::DaoShuShiJian: switch(index) { case 1: return 10; case 2: return 15; case 3: return 20; case 4: return 25; case 5: return 30; case 6: return 35; } break; ///////// case F6TableInterface::TuiBiGongNeng: switch(index) { case 0: return F6TableInterface::BackNone; case 1: return F6TableInterface::BackAll; case 2: return F6TableInterface::Back5; case 3: return F6TableInterface::BackPush; } break; ///////// case F6TableInterface::KaiFenDanWei: switch(index) { case 0: return 0; case 1: return 100; case 2: return 200; case 3: return 400; case 4: return 500; case 5: return 1000; case 6: return 2000; case 7: return 4000; case 8: return 5000; case 9: return 10000; } break; ///////// case F6TableInterface::KaiFenShangXian: switch(index) { case 1: return 5000; case 2: return 10000; case 3: return 20000; case 4: return 50000; case 5: return 100000; } break; ///////// case F6TableInterface::ZhuangXianZuiDaYaZhu: switch(index) { case 1: return 100; case 2: return 500; case 3: return 1000; case 4: return 2000; case 5: return 3000; case 6: return 5000; case 7: return 6000; case 8: return 8000; case 9: return 9999; } break; case F6TableInterface::HeZuiDaYaZhu: switch(index) { case 1: return 10; case 2: return 50; case 3: return 100; case 4: return 300; case 5: return 500; case 6: return 1000; case 7: return 2000; } break; } return -1; } void F6Table::save(void) { // Create an empty property tree object using boost::property_tree::ptree; ptree pt; BOOST_FOREACH(F6Map::value_type it, _f6Data) { pt.put( Item2String(it.first), it.second); } std::string filename("F6Table.dll"); using boost::property_tree::ptree; using namespace boost::iostreams::zlib; using namespace boost::iostreams; using namespace std; ofstream file(filename.c_str(), ios_base::out| ios_base::binary); filtering_ostream out; out.push(zlib_compressor()); out.push(file); write_json(out, pt); } void F6Table::load(void) { std::string filename("F6Table.dll"); // Create an empty property tree object using namespace std; using boost::property_tree::ptree; using namespace boost::iostreams::zlib; using namespace boost::iostreams; ifstream file(filename.c_str(), ios_base::in| ios_base::binary); filtering_istream in; in.push(zlib_decompressor()); in.push(file); ptree pt; // Load the XML file into the property tree. If reading fails // (cannot open file, parse error), an exception is thrown. try { read_json(in, pt); _f6Data[F6TableInterface::PoTaiFenShu] = pt.get<int>(Item2String(F6TableInterface::PoTaiFenShu), 1); _f6Data[F6TableInterface::DongWuZuiDaYaZhu] = pt.get<int>(Item2String(F6TableInterface::DongWuZuiDaYaZhu), 1); _f6Data[F6TableInterface::DongWuZuiXiaoYaZhu] = pt.get<int>(Item2String(F6TableInterface::DongWuZuiXiaoYaZhu), 1); _f6Data[F6TableInterface::DaoShuShiJian] = pt.get<int>(Item2String(F6TableInterface::DaoShuShiJian), 1); _f6Data[F6TableInterface::TuiBiGongNeng] = pt.get<int>(Item2String(F6TableInterface::TuiBiGongNeng), 1); _f6Data[F6TableInterface::KaiFenDanWei] = pt.get<int>(Item2String(F6TableInterface::KaiFenDanWei), 1); _f6Data[F6TableInterface::KaiFenShangXian] = pt.get<int>(Item2String(F6TableInterface::KaiFenShangXian), 1); _f6Data[F6TableInterface::ZhuangXianZuiDaYaZhu] = pt.get<int>(Item2String(F6TableInterface::ZhuangXianZuiDaYaZhu), 1); _f6Data[F6TableInterface::HeZuiDaYaZhu] = pt.get<int>(Item2String(F6TableInterface::HeZuiDaYaZhu), 1); } catch(...) { _f6Data[F6TableInterface::PoTaiFenShu] = 1; _f6Data[F6TableInterface::DongWuZuiDaYaZhu] = 1; _f6Data[F6TableInterface::DongWuZuiXiaoYaZhu] = 1; _f6Data[F6TableInterface::DaoShuShiJian] = 1; _f6Data[F6TableInterface::TuiBiGongNeng] = 1; _f6Data[F6TableInterface::KaiFenDanWei] = 1; _f6Data[F6TableInterface::KaiFenShangXian] = 1; _f6Data[F6TableInterface::ZhuangXianZuiDaYaZhu] = 1; _f6Data[F6TableInterface::HeZuiDaYaZhu] = 1; save(); } } int F6Table::getData(F6TableInterface::ITEM item) const { return GetData(item, getDataIndex(item)); } bool F6Table::setDataIndex(F6TableInterface::ITEM item, int data) { if(GetData(item, data) == -1) return false; _f6Data[item] = data; return true; } int F6Table::getDataIndex(F6TableInterface::ITEM item) const { F6Map::const_iterator it = _f6Data.find(item); if(it == _f6Data.end()) return -1; return it->second; } F6Table & F6Table::getInstance(void) { return *(getInstancePtr()); } F6Table::F6Table(void) { load(); } F6Table * F6Table::getInstancePtr(void) { static F6Table instance; return &instance; }
[ [ [ 1, 377 ] ] ]
396a1c6289d99f555227408685da1f2b30427efe
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/bigint.h
45848cc3856693c0b1cff3aa8a3c851287fba091
[ "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
885
h
// Copyright (C) 2003 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_BIGINt_ #define DLIB_BIGINt_ #include "bigint/bigint_kernel_1.h" #include "bigint/bigint_kernel_2.h" #include "bigint/bigint_kernel_c.h" namespace dlib { class bigint { bigint() {} public: //----------- kernels --------------- // kernel_1a typedef bigint_kernel_1 kernel_1a; typedef bigint_kernel_c<kernel_1a> kernel_1a_c; // kernel_2a typedef bigint_kernel_2 kernel_2a; typedef bigint_kernel_c<kernel_2a> kernel_2a_c; }; } #endif // DLIB_BIGINt_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 43 ] ] ]
469bbcdf24f840a840694e26d6809605d8332c5a
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/has_key.hpp
35c9d8e35fcf2fa9f054b78b43ce7668503ccb7b
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,210
hpp
#ifndef BOOST_MPL_HAS_KEY_HPP_INCLUDED #define BOOST_MPL_HAS_KEY_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // Copyright David Abrahams 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/has_key.hpp,v $ // $Date: 2006/04/17 23:48:05 $ // $Revision: 1.1 $ #include <boost/mpl/has_key_fwd.hpp> #include <boost/mpl/sequence_tag.hpp> #include <boost/mpl/aux_/has_key_impl.hpp> #include <boost/mpl/aux_/na_spec.hpp> #include <boost/mpl/aux_/lambda_support.hpp> namespace boost { namespace mpl { template< typename BOOST_MPL_AUX_NA_PARAM(AssociativeSequence) , typename BOOST_MPL_AUX_NA_PARAM(Key) > struct has_key : has_key_impl< typename sequence_tag<AssociativeSequence>::type > ::template apply<AssociativeSequence,Key> { BOOST_MPL_AUX_LAMBDA_SUPPORT(2,has_key,(AssociativeSequence,Key)) }; BOOST_MPL_AUX_NA_SPEC(2, has_key) }} #endif // BOOST_MPL_HAS_KEY_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 41 ] ] ]
cb71295f190bd9dc353434f9016f9bf6ce6b07fe
19a8b66a1ea85a0a7bbec304b42970b190acceae
/inputarea.h
ad10d35377b731d35e03ea0ef587c84e2068816c
[]
no_license
tilli/ardrone-n9
6321470417067ff88fff32f66f792a54d42481ed
dbffe42b4e68859f7cf683e3359701675bfdb361
refs/heads/master
2020-05-16T23:55:55.368916
2011-10-25T11:28:06
2011-10-25T11:28:06
2,642,882
1
0
null
null
null
null
UTF-8
C++
false
false
2,394
h
#ifndef INPUTAREA_H #define INPUTAREA_H // Debug //#define PAINT_TOUCH_AREAS //#define SHOW_FPS #include <QWidget> #include <QTextBrowser> struct HUD_item { HUD_item(){} HUD_item(QPixmap i, QPointF l, QRect r, qreal o) { image = i; location = l; touchArea = r; opacity = o; } QPixmap image; QPointF location; QRectF touchArea; qreal opacity; }; class InputArea : public QWidget { Q_OBJECT public: explicit InputArea(QWidget *parent = 0); void setLoadText(QString s); void setFirmwareVersion(QString version); signals: void emergencyPressed(); void resetPressed(); void startPressed(); void stopPressed(); void cameraPressed(); void accelPressed(); void accelReleased(); void dataChange(qreal, qreal); public slots: void recieveVideoImage(QImage image); void updateBatteryLevel(uint level); void updateEmergencyState(bool on); private slots: void handleDataTimer(); void handleFPSTimer(); void handleNavdataTimer(); protected: void paintEvent(QPaintEvent *event); void resizeEvent(QResizeEvent *event); bool event(QEvent *event); private: void generateHUD(); void handleKeyPress(int key); enum HUD_ITEMS { HUD_EMERGENCY, HUD_START, HUD_SETTINGS, HUD_CAMERA, HUD_EXIT, HUD_BATTERY, HUD_ACCEL_BG, HUD_LAST_ITEM }; bool mUIReady; bool mVideoImageReady; bool mUIVisible; QPixmap mVideoPixmap; QPixmap mSplashPixmap; int mAccelId; QPointF mAccelOffset; QPointF mAccelCenter; qreal mMaxAccelDistance; QPointF mOriginalAccelPos; QPointF mOriginalAccelBGPos; QPointF mOriginalAccelCenter; qreal mOriginalAccelOpacity; HUD_item mAccelItem; HUD_item mHudItems[HUD_LAST_ITEM]; qreal mDefaultOpacities[HUD_LAST_ITEM]; bool mEmergencyActivated; bool mIsStarted; bool mIsLoading; int mLoadDots; QString mLoadDotString; bool mNavdataTimedOut; bool mShowSettings; QTextBrowser *mTextAbout; QString mFirmwareVersion; QTimer *mDataTimer; QTimer *mFpsTimer; #ifdef SHOW_FPS int mFpsCounter; QString mFpsString; #endif }; #endif // INPUTAREA_H
[ [ [ 1, 110 ] ] ]
8227d91ceb4dcb5fe3233481e26379d81dd519a0
8fcfa439a6c1ea4753ace06b87d7d49f55bdd1e6
/tgeInterpreter.h
a58f8418742ee6254c379d3d5e2a2964db3d5d65
[]
no_license
blacksqr/tge-cpp
bb3e0216830ace08d9381d14bd1916994009ba19
e51f36dcc46790ccadab2f2dcaa0849970b57eb3
refs/heads/master
2021-01-10T14:14:34.381325
2010-03-22T12:37:36
2010-03-22T12:37:36
48,471,490
0
0
null
null
null
null
UTF-8
C++
false
false
1,441
h
#pragma once #include "tgeCommon.h" #include "tgeObj.h" #include "tgeResult.h" namespace tge { /** Wrapper for TCL interpreter. */ class Interpreter { public: typedef std::map<String, Cmd*> CmdMap; public: Interpreter (void); virtual ~Interpreter(void); /** For effieciency, evaluate things all in GLOBAL namespace. */ Result eval(Obj* objPtr) throw (tge::except); Result eval(const String& str) throw (tge::except); bool registerCmd(const String& name, Cmd* cmdObject); bool unregisterCmd(const String& name); /** Sets vars in GLOBAL space. Need to ref to them later with :: qualifiers.*/ void setVar(const String& name, const Obj& obj); /** Retrieves a var matching name in GLOBAL space. */ Obj& getVar(const String& name) throw(tge::except); void removeVar(const String& name); /** Queries if some commands exists. */ bool commandExists(const String& cmdName); static Cmd* getUnknownCmd(void); /** _Panic throws! */ void _panic(const String& msg, const String& wh = "") throw (except); Tcl_Interp* _interp(void); /// link to TCL static int _objCmdProc( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]); protected: protected: static UnknownCmd* msUnknownCmd; Tcl_Interp* mInterp; CmdStatus mStatus; String mError; CmdMap mInternalCmdList; private: }; }
[ "jeffreybian@99f00b9d-c5df-25c8-5ecf-577a790fa8fa" ]
[ [ [ 1, 61 ] ] ]
e222d9065c8a841893b99773918c71a6fd4fdaa1
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/TestDX9/RenderTest.cpp
4e40c3a635cffd48eb52bfad5f428e867b0e755b
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
2,709
cpp
#include "stdafx.h" #include "test_dx9.h" using namespace System; using namespace System::Text; using namespace System::Collections::Generic; using namespace Microsoft::VisualStudio::TestTools::UnitTesting; class RenderListener_clear : public RenderEventListenerNull { public: void setClearColor( NxU32 clearColor ) { clearColor_ = clearColor; } NxU32 getClearColor() const { return clearColor_; } public: virtual void display( Render * render ) OVERRIDE { render->clear_Color( clearColor_ ); } private: NxU32 clearColor_; }; namespace TestDX9 { [TestClass] public ref class RenderTest { private: RenderWin32DX9 * render; RenderBufferFactory * factory; public: [TestInitialize()] void MyTestInitialize() { render = new RenderWin32DX9Imp(); render->setBackbufferLockable( true ); Assert::IsTrue( render->createDevice( true, 30, 30 ) ); factory = new RenderBufferFactoryDX9Imp( render->getD3D9Device() ); }; [TestCleanup()] void MyTestCleanup() { delete factory; render->destroyDevice(); delete render; }; public: [TestMethod] void FixtureOnly() { } [TestMethod] void Render_Clear() { RenderListener_clear * const evt = new RenderListener_clear(); render->addRenderEventListener( evt ); evt->setClearColor( PixelColor( 255, 0, 0, 0 ) ); render->renderOneFrame(); { BackbufferHelper backbuffer( factory ); NxU32 * const ptr = backbuffer.getBitPointer(); Assert::IsTrue( NULL != ptr ); Assert::AreEqual( evt->getClearColor() & 0xffffff, ptr[10] & 0xffffff ); } evt->setClearColor( PixelColor( 255, 256, 0, 0 ) ); render->renderOneFrame(); { BackbufferHelper backbuffer( factory ); NxU32 * const ptr = backbuffer.getBitPointer(); Assert::IsTrue( NULL != ptr ); Assert::AreEqual( evt->getClearColor() & 0xffffff, ptr[10] & 0xffffff ); } evt->setClearColor( PixelColor( 255, 0, 128, 127 ) ); render->renderOneFrame(); { BackbufferHelper backbuffer( factory ); NxU32 * const ptr = backbuffer.getBitPointer(); Assert::IsTrue( NULL != ptr ); Assert::AreEqual( evt->getClearColor() & 0xffffff, ptr[10] & 0xffffff ); } }; }; }
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 89 ] ] ]
9d3da7f1af67e7e5dd8620cd2e7119a6f6681414
2112057af069a78e75adfd244a3f5b224fbab321
/branches/refactor/src_root/include/common/OgreTypes/OgrePlatform.h
fff0b6cc433494d223dd36e40a6e9287fdbcf641
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,123
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2005 The OGRE Team Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __Platform_H_ #define __Platform_H_ #include "OgreConfig.h" namespace Ogre { /* Initial platform/compiler-related stuff to set. */ #define OGRE_PLATFORM_WIN32 1 #define OGRE_PLATFORM_LINUX 2 #define OGRE_PLATFORM_APPLE 3 #define OGRE_COMPILER_MSVC 1 #define OGRE_COMPILER_GNUC 2 #define OGRE_COMPILER_BORL 3 #define OGRE_ENDIAN_LITTLE 1 #define OGRE_ENDIAN_BIG 2 #define OGRE_ARCHITECTURE_32 1 #define OGRE_ARCHITECTURE_64 2 /* Finds the compiler type and version. */ #if defined( _MSC_VER ) # define OGRE_COMPILER OGRE_COMPILER_MSVC # define OGRE_COMP_VER _MSC_VER #elif defined( __GNUC__ ) # define OGRE_COMPILER OGRE_COMPILER_GNUC # define OGRE_COMP_VER (((__GNUC__)*100) + \ (__GNUC_MINOR__*10) + \ __GNUC_PATCHLEVEL__) #elif defined( __BORLANDC__ ) # define OGRE_COMPILER OGRE_COMPILER_BORL # define OGRE_COMP_VER __BCPLUSPLUS__ #else # pragma error "No known compiler. Abort! Abort!" #endif /* See if we can use __forceinline or if we need to use __inline instead */ #if OGRE_COMPILER == OGRE_COMPILER_MSVC # if OGRE_COMP_VER >= 1200 # define FORCEINLINE __forceinline # endif #else # define FORCEINLINE __inline #endif /* Finds the current platform */ #if defined( __WIN32__ ) || defined( _WIN32 ) # define OGRE_PLATFORM OGRE_PLATFORM_WIN32 #elif defined( __APPLE_CC__) # define OGRE_PLATFORM OGRE_PLATFORM_APPLE #else # define OGRE_PLATFORM OGRE_PLATFORM_LINUX #endif /* Find the arch type */ #if defined(__x86_64__) # define OGRE_ARCH_TYPE OGRE_ARCHITECTURE_64 #else # define OGRE_ARCH_TYPE OGRE_ARCHITECTURE_32 #endif // For generating compiler warnings - should work on any compiler // As a side note, if you start your message with 'Warning: ', the MSVC // IDE actually does catch a warning :) #define OGRE_QUOTE_INPLACE(x) # x #define OGRE_QUOTE(x) OGRE_QUOTE_INPLACE(x) #define OGRE_WARN( x ) message( __FILE__ "(" QUOTE( __LINE__ ) ") : " x "\n" ) //---------------------------------------------------------------------------- // Windows Settings #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 // If we're not including this from a client build, specify that the stuff // should get exported. Otherwise, import it. # if defined( __MINGW32__ ) // Linux compilers don't have symbol import/export directives. # define _OgreExport # define _OgrePrivate # else # if defined( OGRE_NONCLIENT_BUILD ) # define _OgreExport __declspec( dllexport ) # else # define _OgreExport __declspec( dllimport ) # endif # define _OgrePrivate # endif // Win32 compilers use _DEBUG for specifying debug builds. # ifdef _DEBUG # define OGRE_DEBUG_MODE 1 # else # define OGRE_DEBUG_MODE 0 # endif #if defined( __MINGW32__ ) #define EXT_HASH #else #define snprintf _snprintf #define vsnprintf _vsnprintf #endif #if OGRE_DEBUG_MODE #define OGRE_PLATFORM_LIB "OgrePlatform_d.dll" #else #define OGRE_PLATFORM_LIB "OgrePlatform.dll" #endif #endif //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Linux/Apple Settings #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE // Enable GCC 4.0 symbol visibility # if OGRE_COMP_VER >= 400 # define _OgreExport __attribute__ ((visibility("default"))) # define _OgrePrivate __attribute__ ((visibility("hidden"))) # else # define _OgreExport # define _OgrePrivate # endif // A quick define to overcome different names for the same function # define stricmp strcasecmp // Unlike the Win32 compilers, Linux compilers seem to use DEBUG for when // specifying a debug build. # ifdef DEBUG # define OGRE_DEBUG_MODE 1 # else # define OGRE_DEBUG_MODE 0 # endif #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE #define OGRE_PLATFORM_LIB "OgrePlatform.bundle" #else //OGRE_PLATFORM_LINUX #define OGRE_PLATFORM_LIB "libOgrePlatform.so" #endif #endif //For apple, we always have a custom config.h file #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE # include "config.h" //SDL_main must be included in the file that contains //the application's main() function. #ifndef OGRE_NONCLIENT_BUILD # include <SDL/SDL_main.h> #endif #endif //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Endian Settings // check for BIG_ENDIAN config flag, set OGRE_ENDIAN correctly #ifdef CONFIG_BIG_ENDIAN # define OGRE_ENDIAN OGRE_ENDIAN_BIG #else # define OGRE_ENDIAN OGRE_ENDIAN_LITTLE #endif // Integer formats of fixed bit width typedef unsigned int uint32; typedef unsigned short uint16; typedef unsigned char uint8; } #endif
[ [ [ 1, 205 ] ] ]
ba865a3886356d15aa4b12c0bedd0230afbcd45b
24bc1634133f5899f7db33e5d9692ba70940b122
/src/ammo/game/server.cpp
5af993e417cd7d14fffba449ef8f449535cd7871
[]
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
4,064
cpp
#include "ammo/game/server.hpp" #include "ammo/game/gameobjects/gameobjectlist.hpp" #include "ammo/game/gamestateauth.hpp" #include "ammo/graphics.hpp" #include "ammo/audio.hpp" #include "ammo/physics.hpp" #include "ammo/util/profiler.hpp" #include "RakNetTypes.h" #include "MessageIdentifiers.h" #include <iostream> namespace ammo { Server::Server(unsigned short portNum, unsigned int maxConns) { _peer = new NetPeer(this, true, portNum, maxConns ); _gameState = new AuthGameState(this); _graphics = new PassiveGraphicSys(); _sound = new PassiveSoundSys(); _physic = new ActivePhysicSys(); _input = new InputSys(); // Add our Physics Blueprints // TODO: Read these from some sort of file Polygon myPoly; myPoly.body.allowSleep = false; myPoly.shape.density = .1f; myPoly.shape.friction = 0.f; myPoly.shape.SetAsBox(1.28f, .48f);//, b2Vec2(4.8f, 12.8f), 0.0f); _physic->AddSchema("player", myPoly); } Server::~Server() { delete _peer; delete _gameState; delete _graphics; delete _sound; delete _physic; delete _input; } void Server::Draw(float deltaTime) { // We could draw our graphics system here, if we wanted // Or log some things, or draw monkeys // Yeah, we should totally draw monkeys } // deltaTime - the change in time (in seconds) since the last // frame. void Server::Update(float deltaTime) { // Our main update loop for the server Packet* packet; // TEMPORARY // TODO GameObject* newPlayer = NULL; // Grab all packets, handing them to the gamestate for (packet = _peer->Receive(); packet != NULL; _peer->DeallocatePacket(packet), packet = _peer->Receive()) { PROFILE_TIMER(server_packetPump) std::cout << "SERVER: Packet Received from: "<< packet->systemAddress.ToString() << std::endl; switch (packet->data[0]) { case ID_CONNECTION_ATTEMPT_FAILED: printf("ID_CONNECTION_ATTEMPT_FAILED\n"); break; case ID_NO_FREE_INCOMING_CONNECTIONS: printf("ID_NO_FREE_INCOMING_CONNECTIONS\n"); break; case ID_CONNECTION_REQUEST_ACCEPTED: printf("ID_CONNECTION_REQUEST_ACCEPTED\n"); break; case ID_NEW_INCOMING_CONNECTION: printf("ID_NEW_INCOMING_CONNECTION from %s\n", packet->systemAddress.ToString()); // When a new player connects, we need to add that player object to the game _input->AddInputMap(packet->systemAddress, std::vector<ammo::InputAction*>()); newPlayer = new PlayerObject(packet->systemAddress); newPlayer->AddAutoSerializeTimer(15); _gameState->RegisterGameObject(newPlayer); // Register our player object with the server _players[packet->systemAddress] = (PlayerObject*)newPlayer; newPlayer = new SampleObject(); newPlayer->AddAutoSerializeTimer(20); _gameState->RegisterGameObject(newPlayer); break; case ID_DISCONNECTION_NOTIFICATION: printf("ID_DISCONNECTION_NOTIFICATION\n"); newPlayer = _players[packet->systemAddress]; _gameState->UnregisterGameObject(newPlayer); _players.erase(packet->systemAddress); break; case ID_CONNECTION_LOST: printf("ID_CONNECTION_LOST\n"); break; default: printf("UNKNOWN PACKET TYPE: %i", packet->data[0]); break; } } // Update all our child objects if (_gameState) { PROFILE_TIMER(server_gamestate) _gameState->Update(deltaTime); } if (_graphics) { PROFILE_TIMER(server_graphics) _graphics->Update(deltaTime); } if (_sound) { PROFILE_TIMER(server_sound) _sound->update(deltaTime); } if (_physic) { PROFILE_TIMER(server_physic) _physic->Update(deltaTime); } } }
[ "PhillipSpiess@d8b90d80-bb63-11dd-bed2-db724ec49875", "j.nick.terry@d8b90d80-bb63-11dd-bed2-db724ec49875" ]
[ [ [ 1, 27 ], [ 31, 31 ], [ 33, 120 ], [ 122, 133 ] ], [ [ 28, 30 ], [ 32, 32 ], [ 121, 121 ], [ 134, 134 ] ] ]
95212af068c3232fa0fbd7fca638aa3297c46584
9756190964e5121271a44aba29a5649b6f95f506
/SimpleParam/Param/src/Param/QuadDistortion.cc
07af688bcb0327022ef933020a4c531d7f314603
[]
no_license
feengg/Parameterization
40f71bedd1adc7d2ccbbc45cc0c3bf0e1d0b1103
f8d2f26ff83d6f53ac8a6abb4c38d9b59db1d507
refs/heads/master
2020-03-23T05:18:25.675256
2011-01-21T15:19:08
2011-01-21T15:19:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,769
cc
#include "QuadDistortion.h" #include "QuadParameter.h" #include "Barycentric.h" #include "../ModelMesh/MeshModel.h" #include <boost/shared_ptr.hpp> #include <hj_3rd/hjlib/math/blas_lapack.h> #include <hj_3rd/zjucad/matrix/lapack.h> #include <hj_3rd/zjucad/matrix/io.h> namespace PARAM { QuadDistortion::QuadDistortion(const QuadParameter& quad_parameter) : m_quad_parameter(quad_parameter){} QuadDistortion::~QuadDistortion(){} void QuadDistortion::ComputeDistortion() { boost::shared_ptr<MeshModel> p_mesh = m_quad_parameter.GetMeshModel(); assert(p_mesh != NULL); const PolyIndexArray& face_list_array = p_mesh->m_Kernel.GetFaceInfo().GetIndex(); size_t face_num = p_mesh->m_Kernel.GetModelInfo().GetFaceNum(); m_face_harmonic_distortion.clear(); m_face_harmonic_distortion.resize(face_num); m_face_isometric_distortion.clear(); m_face_isometric_distortion.resize(face_num); for(size_t fid = 0; fid < face_num; ++fid) { zjucad::matrix::matrix<double> jacobi_mat = ComputeParamJacobiMatrix(fid); m_face_harmonic_distortion[fid] = ComputeHarmonicDistortion(jacobi_mat); m_face_isometric_distortion[fid] = ComputeIsometricDistortion(jacobi_mat); } } zjucad::matrix::matrix<double> QuadDistortion::ComputeParamJacobiMatrix(int fid) const { boost::shared_ptr<MeshModel> p_mesh = m_quad_parameter.GetMeshModel(); const CoordArray& vert_coord_array = p_mesh->m_Kernel.GetVertexInfo().GetCoord(); const PolyIndexArray& face_list_array = p_mesh->m_Kernel.GetFaceInfo().GetIndex(); const IndexArray& faces = face_list_array[fid]; // Algorithm : Sig2007 parameterization course, p40, equation(4.8) std::vector<Coord> tri_vert_coord_3d(3); for(size_t k=0; k<3; ++k) tri_vert_coord_3d[k] = vert_coord_array[faces[k]]; std::vector<Coord2D> local_coord = ComputeTriangleLocal2DCoord(tri_vert_coord_3d); double area_2 = 2*(p_mesh->m_Kernel.GetFaceInfo().GetFaceArea())[fid]; /// get these three vertices's parameter coordinate int chart_id = m_quad_parameter.FindBestChartIDForTriShape(fid); std::vector<ParamCoord> vert_param_corod(3); for(size_t k=0; k<3; ++k) { int vid = faces[k]; int cur_chart_id = m_quad_parameter.GetVertexChartID(vid); ParamCoord cur_param_coord = m_quad_parameter.GetVertexParamCoord(vid); vert_param_corod[k] = cur_param_coord; if(cur_chart_id != chart_id) { m_quad_parameter.TransParamCoordBetweenCharts(cur_chart_id, chart_id, cur_param_coord, vert_param_corod[k]); } } zjucad::matrix::matrix<double> tm_0(2, 2); tm_0(0, 0) = 0; tm_0(0, 1) = -1; tm_0(1, 0) = 1; tm_0(1, 1) = 0; zjucad::matrix::matrix<double> tm_1(2, 3); tm_1(0, 0) = local_coord[2][0] - local_coord[1][0]; tm_1(1, 0) = local_coord[2][1] - local_coord[1][1]; tm_1(0, 1) = local_coord[0][0] - local_coord[2][0]; tm_1(1, 1) = local_coord[0][1] - local_coord[2][1]; tm_1(0, 2) = local_coord[1][0] - local_coord[0][0]; tm_1(1, 2) = local_coord[1][1] - local_coord[0][1]; zjucad::matrix::matrix<double> tm_2(3, 2); for(int k=0; k<3; ++k) { tm_2(k, 0) = vert_param_corod[k].s_coord; tm_2(k, 1) = vert_param_corod[k].t_coord;} zjucad::matrix::matrix<double> tmp = tm_0 * tm_1; tmp = tmp* (1.0 /area_2); return tmp * tm_2; } double QuadDistortion::ComputeHarmonicDistortion(const zjucad::matrix::matrix<double>& jacobi_mat) const { zjucad::matrix::matrix<double> J_tJ = trans(jacobi_mat) * jacobi_mat; return 0.5*(J_tJ(0, 0) + J_tJ(1, 1)); } double QuadDistortion::ComputeIsometricDistortion(const zjucad::matrix::matrix<double>& jacobi_mat) const { return norm( trans(jacobi_mat) * jacobi_mat - zjucad::matrix::eye<double>(2)); } }
[ [ [ 1, 97 ] ] ]
3ed62d6e159456666601e32259cb0a508296e2c5
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_native_Microsoft_SPOT_ResourceUtility.h
ba8b65344f4a2f5787797d30bb192fc8a921543c
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,158
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_NATIVE_MICROSOFT_SPOT_RESOURCEUTILITY_H_ #define _SPOT_NATIVE_MICROSOFT_SPOT_RESOURCEUTILITY_H_ namespace Microsoft { namespace SPOT { struct ResourceUtility { // Helper Functions to access fields of managed object // Declaration of stubs. These functions are implemented by Interop code developers static UNSUPPORTED_TYPE GetObject( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr ); static void set_CurrentUICultureInternal( UNSUPPORTED_TYPE param0, HRESULT &hr ); }; } } #endif //_SPOT_NATIVE_MICROSOFT_SPOT_RESOURCEUTILITY_H_
[ [ [ 1, 30 ] ] ]
a7a5a2bcd511f49ac2a3c688d7da30d958672890
388368e96fcf5a9d216f1f77603993cad45ceed3
/CirQueue.h
c01958c5f23b9ab01fe382beb965c840e4fc7a73
[]
no_license
huangyingw/cirQueue
760c3e4f8dc95c5c75a5fb090543c4d8301eb8af
025fa66860bc98853692bb3c3eefb0d69e817fb2
refs/heads/master
2020-04-12T10:33:52.557641
2010-11-14T10:41:55
2010-11-14T10:41:55
583,427
0
0
null
null
null
null
GB18030
C++
false
false
1,935
h
#define QueueSize 10 //应根据具体情况定义该值 template <class Type> class CirQueue { public: int front; //头指针,队非空时指向队头元素 int rear; //尾指针,队非空时指向队尾元素的下一位置 int count; //计数器,记录队中元素总数 Type data[QueueSize]; int QueueEmpty(); Type DeQueue(); int QueueFront(); void InitQueue(); void Error(char* message); int QueueFull(); void EnQueue(Type x);//加入队列 }; template<class Type> int CirQueue<Type>::QueueEmpty() { return count==0; //队列无元素为空 } template<class Type> void CirQueue<Type>::Error(char* message) { cout<<message<<endl; } template<class Type> Type CirQueue<Type>::DeQueue() { Type temp; if(QueueEmpty()) Error("Queue underflow"); //队空下溢 temp=data[front]; count--; //队列元素个数减1 front=(front+1)%QueueSize; //循环意义下的头指针加1 return temp; } //取得队列front数据 template<class Type> int CirQueue<Type>::QueueFront() { if(QueueEmpty()) Error("Queue is empty."); return data[front]; } template<class Type> void CirQueue<Type>::InitQueue() { front=rear=0; count=0; //计数器置0 } template<class Type> int CirQueue<Type>::QueueFull() { return count==QueueSize; //队中元素个数等于QueueSize时队满 } template<class Type> void CirQueue<Type>::EnQueue(Type x)//加入队列 { if(QueueFull()) { cout<<"when try to input data:"<<x; Error("Queue overflow so shrow out"); //队满上溢 cout<<DeQueue()<<endl; } count++; //队列元素个数加1 data[rear]=x; //新元素插入队尾 rear=(rear+1)%QueueSize; //循环意义下将尾指针加1 }
[ [ [ 1, 71 ] ] ]
48dc2abd834ee79424dcdfeacedfd49a33a33a57
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Graphics/RenderComponent/RenderComponentMessageBox.h
7cd87ddc88af35ebae2967fd23ac10eb940f55c6
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
2,298
h
#ifndef RenderComponentMessageBoxH_H #define RenderComponentMessageBoxH_H #include "RenderComponent.h" namespace OUAN { const std::string TEXTAREA_SUFFIX="/Message"; const double DEFAULT_MESSAGEBOX_DURATION=2.0; const std::string MESSAGEBOX_OVERLAY="OUAN/HUDMessages"; const std::string MESSAGEBOX_DEFAULT_MATERIAL="OUAN/Hud/TextBubble"; class RenderComponentMessageBox: public RenderComponent { private: Ogre::OverlayElement* mBasePanel; std::string mBasePanelName; std::string mDefaultMaterial; Ogre::OverlayElement* mCharPanel; std::string mCharPanelName; std::string mCharPanelMaterialName; std::string mMessage; double mDuration; bool mVisible; double mElapsedTime; Ogre::Overlay* mOverlay; public: RenderComponentMessageBox(); ~RenderComponentMessageBox(); // Getters/setters const std::string& getBasePanelName() const; void setBasePanelName(const std::string& basePanelName); Ogre::OverlayElement* getBasePanel() const; void setBasePanel(const std::string& basePanelName); const std::string& getCharPanelName() const; void setCharPanelName(const std::string& charPanelName); Ogre::OverlayElement* getCharPanel() const; void setCharPanel(const std::string& charPanelName, const std::string& charPanelMaterialName); const std::string& getCharPanelMaterialName() const; void setCharPanelMaterialName(const std::string& charPanelMaterialName); const std::string& getMessage() const; void setMessage(const std::string& message); void setMessageBoxText(); void setBasePanelMaterial(const std::string& material); double getDuration() const; void setDuration(double duration); //Visibility methods void show(); void hide(); void setVisible(bool visible); bool isVisible() const; //Update method void update(double elapsedTime); }; class TRenderComponentMessageBoxParameters: public TRenderComponentParameters { public: TRenderComponentMessageBoxParameters(); ~TRenderComponentMessageBoxParameters(); std::string basePanelName; std::string charPanelName; std::string charPanelMaterialName; std::string mMessage; double duration; bool mVisible; }; } #endif
[ "ithiliel@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 98 ] ] ]
5165ba0d56e9032526f61df8ef7c9528be940e68
e304ca5b7af737b67012cba6512f7e55ecefad5a
/Lib/C++/iSFX.hpp
c3ba1b3418d4d8962d08c6d87759831a88abd165
[]
no_license
iSFX-Team/iSFX
41f74c763ed70777ef66677b15c962359a9c750e
18782ca2ee26c91f777684b379906cc2bc17846c
refs/heads/master
2021-01-01T17:58:10.422062
2011-12-17T15:59:44
2011-12-17T15:59:44
2,493,382
2
0
null
null
null
null
UTF-8
C++
false
false
235
hpp
#ifndef _ISFX_HPP_ #define _ISFX_HPP_ #include "Error.hpp" #include "Sound.hpp" #include "System.hpp" namespace iSFX { struct Error; struct System; struct Sound; } #endif /* end of include guard: _ISFX_HPP_ */
[ [ [ 1, 15 ] ] ]
308e17c167513d916df0e7050141d3104c0028ec
23939b88feae85abfd72601120a54b637661c164
/RemoveLastDialog.cpp
eb147204f76caa7d51896809873a620c886108c0
[]
no_license
klanestro/textCalc
e9feae14be270cd22de347e2e4b764fadfb0709c
2634f92702aaf7d9a61187b2a34b998d92780672
refs/heads/master
2021-01-19T13:50:28.692058
2010-01-21T09:29:53
2010-01-21T09:29:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,900
cpp
// RemoveLastDialog.cpp : implementation file // #include "stdafx.h" #include "sample.h" #include "RemoveLastDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // RemoveLastDialog dialog RemoveLastDialog::RemoveLastDialog(CWnd* pParent /*=NULL*/) : CDialog(RemoveLastDialog::IDD, pParent) { //{{AFX_DATA_INIT(RemoveLastDialog) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_checkspace=TRUE; m_checkuser=FALSE; m_checkseparator=TRUE; m_userstr=",;="; } void RemoveLastDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(RemoveLastDialog) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(RemoveLastDialog, CDialog) //{{AFX_MSG_MAP(RemoveLastDialog) ON_BN_CLICKED(IDC_CHECK1, OnCheck1) ON_BN_CLICKED(IDC_CHECK3, OnCheck3) ON_BN_CLICKED(IDC_CHECK2, OnCheck2) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // RemoveLastDialog message handlers void RemoveLastDialog::OnCheck1() { // TODO: Add your control notification handler code here m_checkspace=((CButton *) GetDlgItem(IDC_CHECK1))->GetCheck(); } void RemoveLastDialog::OnCheck3() { // TODO: Add your control notification handler code here m_checkseparator=((CButton *) GetDlgItem(IDC_CHECK3))->GetCheck(); } void RemoveLastDialog::OnCheck2() { // TODO: Add your control notification handler code here m_checkuser=((CButton *) GetDlgItem(IDC_CHECK2))->GetCheck(); RefreshDialog(); } void RemoveLastDialog::OnOK() { // TODO: Add extra validation here ((CEdit *) GetDlgItem(IDC_EDIT1))->GetWindowText(m_userstr); CDialog::OnOK(); } BOOL RemoveLastDialog::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here RefreshDialog(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void RemoveLastDialog::RefreshDialog() { if (m_checkspace) { ((CButton *) GetDlgItem(IDC_CHECK1))->SetCheck(1); } else { ((CButton *) GetDlgItem(IDC_CHECK1))->SetCheck(0); } if (m_checkuser) { ((CButton *) GetDlgItem(IDC_CHECK2))->SetCheck(1); ((CEdit *) GetDlgItem(IDC_EDIT1))->EnableWindow(TRUE); } else { ((CButton *) GetDlgItem(IDC_CHECK2))->SetCheck(0); ((CEdit *) GetDlgItem(IDC_EDIT1))->EnableWindow(FALSE); } if (m_checkseparator) { ((CButton *) GetDlgItem(IDC_CHECK3))->SetCheck(1); } else { ((CButton *) GetDlgItem(IDC_CHECK3))->SetCheck(0); } ((CEdit *) GetDlgItem(IDC_EDIT1))->SetWindowText(m_userstr); }
[ [ [ 1, 120 ] ] ]
ca9ffcc100e40cc8f2cbc9b1ddd1de497fc19b72
b2ff7f6bdf1d09f1adc4d95e8bfdb64746a3d6a4
/src/sfile.cpp
c9e9aba081856e038984e26a6e817ab734438641
[]
no_license
thebruno/dabster
39a315025b9344b8cca344d2904c084516915353
f85d7ec99a95542461862b8890b2542ec7a6b28d
refs/heads/master
2020-05-20T08:48:42.053900
2007-08-29T14:29:46
2007-08-29T14:29:46
32,205,762
0
0
null
null
null
null
UTF-8
C++
false
false
1,170
cpp
/********************************************************************* Sigma Dabster 5 Copyright (C) The Dabster Team 2007. All rights reserved. http://www.dabster.prv.pl/ http://code.google.com/p/dabster/ 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; version 2 dated June, 1991. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Simple File sfile.cpp *********************************************************************/ #include "sfile.h" sfile::sfile(void) { } sfile::~sfile(void) { } void sfile::edit() { } /********************************************************************/
[ "konrad.balys@019b6672-ce2e-0410-a4f6-31e0795bab1a", "latusekpiotr@019b6672-ce2e-0410-a4f6-31e0795bab1a" ]
[ [ [ 1, 30 ], [ 32, 34 ], [ 36, 43 ] ], [ [ 31, 31 ], [ 35, 35 ] ] ]
1a91944ccee2364d41678a22a1c6d8d7084d5308
b4bff7f61d078e3dddeb760e21174a781ed7f985
/Source/Contrib/UserInterface/src/Component/ComponentContainer/ColorChooser/OSGDefaultColorSelectionModel.inl
592527fcedc1d28164dc04c462313986abd4c44f
[]
no_license
Langkamp/OpenSGToolbox
8283edb6074dffba477c2c4d632e954c3c73f4e3
5a4230441e68f001cdf3e08e9f97f9c0f3c71015
refs/heads/master
2021-01-16T18:15:50.951223
2010-05-19T20:24:52
2010-05-19T20:24:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,054
inl
/*---------------------------------------------------------------------------*\ * OpenSG ToolBox UserInterface * * * * * * * * * * Authors: David Kabala, Alden Peterson, Lee Zaniewski, Jonathan Flory * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "OSGConfig.h" OSG_BEGIN_NAMESPACE OSG_END_NAMESPACE
[ [ [ 1, 47 ] ] ]
6b96fa8b40fe938679617b1ee0f8cd1e28e17e53
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment1/test_array.cpp
f37ec9e19e59f6cf0f695ed85caebc6e02a79e80
[]
no_license
Mr-Anderson/james_mst_hw
70dbde80838e299f9fa9c5fcc16f4a41eec8263a
83db5f100c56e5bb72fe34d994c83a669218c962
refs/heads/master
2020-05-04T13:15:25.694979
2011-11-30T20:10:15
2011-11-30T20:10:15
2,639,602
2
0
null
null
null
null
UTF-8
C++
false
false
2,767
cpp
////////////////////////////////////////////////////////////////////// /// @file test_array.cpp /// @author James Anderson Section A /// @brief Implementation file for test_array class for assignment 1 ////////////////////////////////////////////////////////////////////// #include "test_array.h" CPPUNIT_TEST_SUITE_REGISTRATION (Test_array); void Test_array::test_push_back () { Array<int> test; // Constructor check CPPUNIT_ASSERT (test.size () == 0); CPPUNIT_ASSERT (test.max_size () == 20); // Push on one item test.push_back (3); // check that item CPPUNIT_ASSERT (test[0] == 3); CPPUNIT_ASSERT (test.size () == 1); CPPUNIT_ASSERT (test.max_size () == 20); // checking to see if data out of bounds is handeled try { test[2] = 50; CPPUNIT_ASSERT (false); } catch (Exception& e) { CPPUNIT_ASSERT (OUT_OF_BOUNDS == e.error_code ()); } try { test[-70] = 50; CPPUNIT_ASSERT (false); } catch (Exception& e) { CPPUNIT_ASSERT (OUT_OF_BOUNDS == e.error_code ()); } // checking to see if container full is handeled try { for (int i = 1 ; i <= 21 ; i++ ) { test.push_back (i); CPPUNIT_ASSERT (test[i] == i); CPPUNIT_ASSERT (test.size () == i + 1); CPPUNIT_ASSERT (test.max_size () == 20); } CPPUNIT_ASSERT (false); } catch (Exception& e) { CPPUNIT_ASSERT (CONTAINER_FULL == e.error_code ()); } } void Test_array::test_pop_back () { Array<int> test; // Constructor check CPPUNIT_ASSERT (test.size () == 0); CPPUNIT_ASSERT (test.max_size () == 20); // push on 20 items for (int i = 0 ; i <= 19 ; i++ ) { test.push_back (i); CPPUNIT_ASSERT (test[i] == i); CPPUNIT_ASSERT (test.size () == i +1); CPPUNIT_ASSERT (test.max_size () == 20); } //pop back 20 items for (int i = 20 ; i >= 1 ; i-- ) { test.pop_back (); CPPUNIT_ASSERT (test.size () == i - 1 ); CPPUNIT_ASSERT (test.max_size () == 20); } // checking to see if container empty is handeled try { test.pop_back (); CPPUNIT_ASSERT (false); } catch (Exception& e) { CPPUNIT_ASSERT (CONTAINER_EMPTY == e.error_code ()); } } void Test_array::test_clear () { Array<int> test; // Constructor check CPPUNIT_ASSERT (test.size () == 0); CPPUNIT_ASSERT (test.max_size () == 20); // pusth on 20 items for (int i = 0 ; i <= 19 ; i++ ) { test.push_back (i); CPPUNIT_ASSERT (test[i] == i); CPPUNIT_ASSERT (test.size () == i + 1); CPPUNIT_ASSERT (test.max_size () == 20); } // clear the array test.clear (); //check that the array was cleared CPPUNIT_ASSERT (test.size () == 0); CPPUNIT_ASSERT (test.max_size () == 20); }
[ [ [ 1, 128 ] ] ]
9487ae85f8616fc291a3facbbf1e1dacf11add82
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Animation/Animation/Motion/hkaAnimatedReferenceFrame.h
fe49e018f626c3c6498270057e6b7d1fe449cde9
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,591
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 HKANIMATION_MOTION_ANIMATED_REFERENCE_FRAME_H #define HKANIMATION_MOTION_ANIMATED_REFERENCE_FRAME_H /// hkaAnimatedReferenceFrame meta information extern const class hkClass hkaAnimatedReferenceFrameClass; /// This class represents the motion extracted from an animation. Check the Motion Extraction section in the Havok Animation User Guide for details. class hkaAnimatedReferenceFrame : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_MOTION ); HK_DECLARE_REFLECTION(); /// Default constructor inline hkaAnimatedReferenceFrame() { } /// Returns the motion stored (previously extracted from the animation) at time t. /// This motion represents the absolute offset from the start of the animation. virtual void getReferenceFrame(hkReal time, hkQsTransform& motionOut) const = 0; /// Returns the change in reference frame between two times. virtual void getDeltaReferenceFrame( hkReal time, hkReal nextTime, int loops, hkQsTransform& deltaMotionOut ) const = 0; /// Returns the length of time this reference frame is animated for. virtual hkReal getDuration() const = 0; public: // Constructor for initialisation of vtable fixup HK_FORCE_INLINE hkaAnimatedReferenceFrame( hkFinishLoadedObjectFlag flag ) : hkReferencedObject(flag) {} }; #endif // HKANIMATION_MOTION_ANIMATED_REFERENCE_FRAME_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, 58 ] ] ]
22922c4750fbd2c34aa5c3b6fe3f679abf94561b
03f06dde16b4b08989eefa144ebc2c7cc21e95ad
/tags/0.3/WinProf/NetRunTimeStat.h
c5b7b29c1170cb1c5f9d35155ef9af6f09061f82
[]
no_license
BackupTheBerlios/winprof-svn
c3d557c72d7bc0306cb6bd7fd5ac189e5c277251
21ab1356cf6d16723f688734c995c7743bbde852
refs/heads/master
2021-01-25T05:35:44.550759
2005-06-23T11:51:27
2005-06-23T11:51:27
40,824,500
0
0
null
null
null
null
UTF-8
C++
false
false
1,787
h
#pragma once #include "RunTimeStat.h" class CNetRunTimeStat : public CWinProfStatistics { public: virtual CString ToString(stat_val_t val) const {return DWORD64ToStr(val.dw64_val * 1000 / CWinProfDoc::m_Frequency);} virtual int StatCompare(const INVOC_INFO &c1, const INVOC_INFO &c2) const {return CWinProfStatistics::StatCompare<DWORD64>(GetStatValue(c1).dw64_val, GetStatValue(c2).dw64_val);} virtual CString GetStatCaption(void) const {return "Net Run Time (ms)";} virtual string GetStatName() const {return "NetRunTimeStat";} virtual bool IsPerInvocation(void) const {return true;} virtual bool IsCacheable() const {return true;} virtual bool Satisfies(const INVOC_INFO& iv, stat_val_t bound, cmp_oper oper) const {return CmpOper::cmp_oper_vect_dw64[oper](GetStatValue(iv).dw64_val, bound.dw64_val);} virtual bool GetNumerical(CString str, stat_val_t& val) const { if (!ValidForStat(str, IsDigit)) return false; val.dw64_val = _atoi64(str) * CWinProfDoc::m_Frequency / 1000; return true; } protected: virtual stat_val_t CalculateStatVal(const calls_vector_t& v, const INVOC_INFO& call) const { DWORD64 time = stats[CStatManager::GetStName2Index()["RunTimeStat"]]->GetStatValue(call).dw64_val; CTreeCtrl& tree = CStatManager::GetTreeCtrl(); func2vect_t& func2vect = CStatManager::GetDataBaseRef(); HTREEITEM item = v[call.invocation-1].treeitem; for (HTREEITEM child = tree.GetChildItem(item); child != NULL; child = tree.GetNextItem(child, TVGN_NEXT)) { INVOC_INFO* ii = reinterpret_cast<INVOC_INFO*>(tree.GetItemData(child)); time -= stats[CStatManager::GetStName2Index()["RunTimeStat"]]->GetStatValue(*ii).dw64_val; } stat_val_t val; val.dw64_val = time; return val; } };
[ "landau@f5a2dbeb-61f3-0310-bb71-ba092b21bc01" ]
[ [ [ 1, 45 ] ] ]
262bc2a94d16375b15d0acb8086e92d073b99a94
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/logger/logger_config_file.h
6cd5e8a38aa4814a871803a30df3283b06ef4dec
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
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
4,192
h
// Copyright (C) 2007 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_LOGGER_CONFIg_FILE_ #define DLIB_LOGGER_CONFIg_FILE_ #include "logger_kernel_abstract.h" #include "logger_kernel_1.h" #include <string> #include "../config_reader.h" // ---------------------------------------------------------------------------------------- namespace dlib { void configure_loggers_from_file ( const std::string& file_name ); /*! ensures - configures the loggers with the contents of the file_name file throws - dlib::error this exception is thrown if there is a problem reading the config file !*/ // ---------------------------------------------------------------------------------------- /*! # ----------------------------------------------- # ------------- EXAMPLE CONFIG FILE ------------- # ----------------------------------------------- # The overall format of the config file is the same as the one defined by # the config_reader component of this library. # This line is a comment line # The config file always has block named logger_config. This is where all the # config data for the loggers resides. logger_config { # This sets all loggers to the level LINFO since it is just inside the # logger_config block logging_level = info # Alternatively we could specify a user defined logging level by # supplying a priority number. The following line would specify # that only logging levels at or above 100 are printed. (note that # you would have to comment out the logging_level statement above # to avoid a conflict). # logging_level = 100 parent_logger { # This sets all loggers named "parent_logger" or children of # loggers with that name to not log at all (i.e. to logging level # LNONE). logging_level = none } parent_logger2 { # set loggers named "parent_logger2" and its children loggers # to write their output to a file named out.txt output = file out.txt child_logger { # Set loggers named "parent_logger2.child_logger" and children of loggers # with this name to logging level LALL logging_level = all # Note that this logger will also log to out.txt because that is what # its parent does and we haven't overridden it here with something else. # if we wanted this logger to write to cout instead we could uncomment # the following line: # output = cout } } } # So in summary, all logger config stuff goes inside a block named logger_config. Then # inside that block all blocks must be the names of loggers. There are only two keys, # logging_level and output. # # The valid values of logging_level are: # "LALL", "LNONE", "LTRACE", "LDEBUG", "LINFO", "LWARN", "LERROR", "LFATAL", # "ALL", "NONE", "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL", # "all", "none", "trace", "debug", "info", "warn", "error", "fatal", or # any integral value # # The valid values of output are: # "cout", "cerr", "clog", or a string of the form "file some_file_name" # which causes the output to be logged to the specified file. # !*/ } // ---------------------------------------------------------------------------------------- #ifdef NO_MAKEFILE #include "logger_config_file.cpp" #endif #endif // DLIB_LOGGER_CONFIg_FILE_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 112 ] ] ]
91db839f3876c2cecc809196bbcf4cf220480f70
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/webbroker.hpp
9cf1bc98aec0adf6ce0fb52ce5c0d0fb8e16a1d9
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
1,954
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'WebBroker.pas' rev: 6.00 #ifndef WebBrokerHPP #define WebBrokerHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <WebReq.hpp> // Pascal unit #include <Contnrs.hpp> // Pascal unit #include <HTTPApp.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Webbroker { //-- type declarations ------------------------------------------------------- typedef void __fastcall (__closure *TServerExceptionEvent)(Sysutils::Exception* E, Httpapp::TWebResponse* wr); class DELPHICLASS TWebApplication; class PASCALIMPLEMENTATION TWebApplication : public Webreq::TWebRequestHandler { typedef Webreq::TWebRequestHandler inherited; private: AnsiString FTitle; public: __fastcall virtual TWebApplication(Classes::TComponent* AOwner); __fastcall virtual ~TWebApplication(void); virtual void __fastcall CreateForm(TMetaClass* InstanceClass, void *Reference); virtual void __fastcall Initialize(void); virtual void __fastcall Run(void); __property AnsiString Title = {read=FTitle, write=FTitle}; }; typedef void __fastcall (*THandleShutdownException)(Sysutils::Exception* E); //-- var, const, procedure --------------------------------------------------- extern PACKAGE TWebApplication* Application; extern PACKAGE THandleShutdownException HandleShutdownException; } /* namespace Webbroker */ using namespace Webbroker; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // WebBroker
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 59 ] ] ]
f878d1654f33aca82dacc619a3dd70f504de5e7c
3187b0dd0d7a7b83b33c62357efa0092b3943110
/src/dlib/test/graph.cpp
7b5cffd297bf54e3c2e2cc0840ef50533a87c149
[ "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
12,112
cpp
// Copyright (C) 2007 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/graph.h> #include <dlib/graph_utils.h> #include <dlib/set.h> #include "tester.h" // This is called an unnamed-namespace and it has the effect of making everything inside this file "private" // so that everything you declare will have static linkage. Thus we won't have any multiply // defined symbol errors coming out of the linker when we try to compile the test suite. namespace { using namespace test; using namespace dlib; using namespace std; // Declare the logger we will use in this test. The name of the tester // should start with "test." logger dlog("test.graph"); template < typename graph > void graph_test ( ) /*! requires - graph is an implementation of graph/graph_kernel_abstract.h is instantiated with int ensures - runs tests on graph for compliance with the specs !*/ { print_spinner(); COMPILE_TIME_ASSERT(is_graph<graph>::value); graph a, b; set<unsigned long>::compare_1b_c s; DLIB_CASSERT(graph_contains_length_one_cycle(a) == false,""); DLIB_CASSERT(graph_contains_undirected_cycle(a) == false,""); DLIB_CASSERT(a.number_of_nodes() == 0,""); a.set_number_of_nodes(5); DLIB_CASSERT(graph_is_connected(a) == false,""); DLIB_CASSERT(graph_contains_undirected_cycle(a) == false,""); DLIB_CASSERT(a.number_of_nodes() == 5,""); DLIB_CASSERT(graph_contains_length_one_cycle(a) == false,""); for (int i = 0; i < 5; ++i) { a.node(i).data = i; DLIB_CASSERT(a.node(i).index() == (unsigned int)i,""); } a.remove_node(1); DLIB_CASSERT(a.number_of_nodes() == 4,""); // make sure that only the number with data == 1 was removed int count = 0; for (int i = 0; i < 4; ++i) { count += a.node(i).data; DLIB_CASSERT(a.node(i).number_of_neighbors() == 0,""); DLIB_CASSERT(a.node(i).index() == (unsigned int)i,""); } DLIB_CASSERT(count == 9,""); a.add_edge(1,1); DLIB_CASSERT(graph_contains_length_one_cycle(a) == true,""); DLIB_CASSERT(graph_contains_undirected_cycle(a) == true,""); DLIB_CASSERT(a.has_edge(1,1),""); DLIB_CASSERT(a.node(1).number_of_neighbors() == 1,""); a.add_edge(1,3); DLIB_CASSERT(a.node(1).number_of_neighbors() == 2,""); DLIB_CASSERT(a.node(2).number_of_neighbors() == 0,""); DLIB_CASSERT(a.node(3).number_of_neighbors() == 1,""); DLIB_CASSERT(a.has_edge(1,1),""); DLIB_CASSERT(a.has_edge(1,3),""); DLIB_CASSERT(a.has_edge(3,1),""); DLIB_CASSERT(graph_contains_undirected_cycle(a) == true,""); a.remove_edge(1,1); DLIB_CASSERT(graph_contains_length_one_cycle(a) == false,""); DLIB_CASSERT(graph_contains_undirected_cycle(a) == false,""); DLIB_CASSERT(a.node(1).number_of_neighbors() == 1,""); DLIB_CASSERT(a.node(2).number_of_neighbors() == 0,""); DLIB_CASSERT(a.node(3).number_of_neighbors() == 1,""); DLIB_CASSERT(a.has_edge(1,1) == false,""); DLIB_CASSERT(a.has_edge(1,3),""); DLIB_CASSERT(a.has_edge(3,1),""); DLIB_CASSERT(graph_contains_undirected_cycle(a) == false,""); swap(a,b); DLIB_CASSERT(graph_contains_undirected_cycle(b) == false,""); DLIB_CASSERT(b.node(1).number_of_neighbors() == 1,""); DLIB_CASSERT(b.node(2).number_of_neighbors() == 0,""); DLIB_CASSERT(b.node(3).number_of_neighbors() == 1,""); DLIB_CASSERT(b.has_edge(1,1) == false,""); DLIB_CASSERT(b.has_edge(1,3),""); DLIB_CASSERT(b.has_edge(3,1),""); DLIB_CASSERT(graph_contains_undirected_cycle(b) == false,""); DLIB_CASSERT(a.number_of_nodes() == 0,""); DLIB_CASSERT(b.number_of_nodes() == 4,""); copy_graph_structure(b,b); DLIB_CASSERT(b.number_of_nodes() == 4,""); b.add_edge(1,2); DLIB_CASSERT(graph_contains_undirected_cycle(b) == false,""); DLIB_CASSERT(graph_contains_undirected_cycle(b) == false,""); b.add_edge(3,2); DLIB_CASSERT(graph_contains_undirected_cycle(b) == true,""); b.add_edge(1,1); DLIB_CASSERT(graph_is_connected(b) == false,""); b.add_edge(0,2); DLIB_CASSERT(graph_is_connected(b) == true,""); DLIB_CASSERT(graph_contains_undirected_cycle(b) == true,""); DLIB_CASSERT(a.number_of_nodes() == 0,""); for (unsigned long i = 0; i < b.number_of_nodes(); ++i) { for (unsigned long j = 0; j < b.node(i).number_of_neighbors(); ++j) { b.node(i).edge(j) = 'c'; } } b.node(1).edge(0) = 'a'; const unsigned long e1 = b.node(1).neighbor(0).index(); b.node(0).edge(0) = 'n'; const unsigned long e2 = b.node(0).neighbor(0).index(); ostringstream sout; serialize(b, sout); istringstream sin(sout.str()); DLIB_CASSERT(graph_contains_undirected_cycle(a) == false,""); a.set_number_of_nodes(10); deserialize(a, sin); DLIB_CASSERT(graph_contains_undirected_cycle(a) == true,""); for (unsigned long i = 0; i < a.number_of_nodes(); ++i) { for (unsigned long j = 0; j < a.node(i).number_of_neighbors(); ++j) { if (i == 0 && a.node(i).neighbor(j).index() == e2 || i == e2 && a.node(i).neighbor(j).index() == 0 ) { DLIB_CASSERT(a.node(i).edge(j) == 'n',""); } else if (i == 1 && a.node(i).neighbor(j).index() == e1 || i == e1 && a.node(i).neighbor(j).index() == 1) { DLIB_CASSERT(a.node(i).edge(j) == 'a',""); } else { DLIB_CASSERT(i != 0 || a.node(i).neighbor(j).index() != e2,""); DLIB_CASSERT(a.node(i).edge(j) == 'c',a.node(i).edge(j)); } } } DLIB_CASSERT(a.number_of_nodes() == 4,""); DLIB_CASSERT(a.has_edge(1,2) == true,""); DLIB_CASSERT(a.has_edge(3,2) == true,""); DLIB_CASSERT(a.has_edge(1,1) == true,""); DLIB_CASSERT(a.has_edge(0,2) == true,""); DLIB_CASSERT(a.has_edge(1,3) == true,""); DLIB_CASSERT(a.has_edge(0,1) == false,""); DLIB_CASSERT(a.has_edge(0,3) == false,""); DLIB_CASSERT(a.has_edge(0,0) == false,""); DLIB_CASSERT(a.has_edge(1,0) == false,""); DLIB_CASSERT(a.has_edge(3,0) == false,""); for (unsigned long i = 0; i < a.number_of_nodes(); ++i) { a.node(i).data = static_cast<int>(i); } a.remove_node(2); DLIB_CASSERT(a.number_of_nodes() == 3,""); DLIB_CASSERT(graph_contains_undirected_cycle(a) == true,""); count = 0; for (unsigned long i = 0; i < a.number_of_nodes(); ++i) { if (a.node(i).data == 0) { DLIB_CASSERT(a.node(i).number_of_neighbors() == 0,""); } else if (a.node(i).data == 1) { DLIB_CASSERT(a.node(i).number_of_neighbors() == 2,""); } else if (a.node(i).data == 3) { DLIB_CASSERT(a.node(i).number_of_neighbors() == 1,""); } else { DLIB_CASSERT(false,"this is impossible"); } for (unsigned long j = 0; j < a.number_of_nodes(); ++j) { if (a.node(i).data == 1 && a.node(j).data == 1 || a.node(i).data == 1 && a.node(j).data == 3 || a.node(i).data == 3 && a.node(j).data == 1) { DLIB_CASSERT(a.has_edge(i,j) == true,""); ++count; } else { DLIB_CASSERT(a.has_edge(i,j) == false,""); } } } DLIB_CASSERT(count == 3,count); DLIB_CASSERT(graph_contains_undirected_cycle(a) == true,""); a.remove_edge(1,1); DLIB_CASSERT(graph_contains_undirected_cycle(a) == false,""); DLIB_CASSERT(b.number_of_nodes() == 4,""); b.clear(); DLIB_CASSERT(b.number_of_nodes() == 0,""); a.clear(); /* 1 7 | / \ 2 6 0 \ / | 3 / / \ / 4 5 */ a.set_number_of_nodes(8); a.add_edge(1,2); a.add_edge(2,3); a.add_edge(3,4); a.add_edge(3,5); a.add_edge(3,6); a.add_edge(6,7); a.add_edge(7,0); a.add_edge(0,5); DLIB_CASSERT(graph_is_connected(a),""); set<set<unsigned long>::compare_1b_c>::kernel_1b_c sos; dlib::graph<set<unsigned long>::compare_1b_c, set<unsigned long>::compare_1b_c>::kernel_1a_c join_tree; unsigned long temp; triangulate_graph_and_find_cliques(a,sos); DLIB_CASSERT(a.number_of_nodes() == 8,""); create_join_tree(a, join_tree); DLIB_CASSERT(join_tree.number_of_nodes() == 6,""); DLIB_CASSERT(graph_is_connected(join_tree) == true,""); DLIB_CASSERT(graph_contains_undirected_cycle(join_tree) == false,""); DLIB_CASSERT(is_join_tree(a, join_tree),""); // check old edges DLIB_CASSERT(a.has_edge(1,2),""); DLIB_CASSERT(a.has_edge(2,3),""); DLIB_CASSERT(a.has_edge(3,4),""); DLIB_CASSERT(a.has_edge(3,5),""); DLIB_CASSERT(a.has_edge(3,6),""); DLIB_CASSERT(a.has_edge(6,7),""); DLIB_CASSERT(a.has_edge(7,0),""); DLIB_CASSERT(a.has_edge(0,5),""); DLIB_CASSERT(graph_is_connected(a),""); DLIB_CASSERT(sos.size() == 6,""); temp = 1; s.add(temp); temp = 2; s.add(temp); DLIB_CASSERT(sos.is_member(s),""); s.clear(); temp = 2; s.add(temp); temp = 3; s.add(temp); DLIB_CASSERT(sos.is_member(s),""); s.clear(); temp = 4; s.add(temp); temp = 3; s.add(temp); DLIB_CASSERT(sos.is_member(s),""); sos.reset(); while (sos.move_next()) { DLIB_CASSERT(is_clique(a, sos.element()),""); DLIB_CASSERT(is_maximal_clique(a, sos.element()),""); } } class graph_tester : public tester { /*! WHAT THIS OBJECT REPRESENTS This object represents a test for the graph object. When it is constructed it adds itself into the testing framework. The command line switch is specified as test_directed_graph by passing that string to the tester constructor. !*/ public: graph_tester ( ) : tester ("test_graph", "Runs tests on the graph component.") {} void perform_test ( ) { dlog << LINFO << "testing kernel_1a_c"; graph_test<graph<int>::kernel_1a_c>(); dlog << LINFO << "testing kernel_1a"; graph_test<graph<int>::kernel_1a>(); } } a; }
[ [ [ 1, 359 ] ] ]
4739d64a9fa31a871167c50e56364362d2936c15
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/FlwLib/SparseSlv/SparseSlv.H
4a9e30f3120c4fb7ed3ec489205dea64f502fdad
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,104
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #ifndef __MTX_SOLV_H #define __MTX_SOLV_H #ifndef __MTX_GLBL_H #include ".\direct\mtx_glbl.h" #endif #ifndef __MTX_ORDR_H #include ".\direct\mtx_ordr.h" #endif #ifndef __MTX_MTRX_H #include ".\direct\mtx_mtrx.h" #endif #ifndef __SCDTEMPL_H #include "scdtempl.h" #endif typedef struct CBldSeqItem { dword m_Row, m_Col; double m_Value, m_OrigValue; } CBldSeqItem; class CBuildSeqList : public CSCDList<CBldSeqItem, CBldSeqItem&> {}; class CSparseSolver; // forward //-------------------------------------------------------------------------------- class CSparseSolverA { public: CSparseSolverA(CSparseSolver * pSlv) : m_Slv(*pSlv) {}; virtual ~CSparseSolverA() {}; virtual void Clear(dword n) = 0; virtual void SetValue (dword rowpos, dword colpos, double value) = 0; virtual double GetValue (dword rowpos, dword colpos) = 0; virtual int Initialise(flag Direct) = 0; virtual int Analyse () = 0; virtual int Solve () = 0; virtual void Report_Stats (Mtx_Info *table) = 0; virtual int Errors() = 0; protected: CSparseSolver & m_Slv; }; //-------------------------------------------------------------------------------- class CSparseSolverD : public CSparseSolverA, public SpM_Mtrx { DEFINE_SPARES(CSparseSolverD) public: CSparseSolverD(CSparseSolver * pSlv, dword n); ~CSparseSolverD(); void Clear(dword n); void SetValue (dword rowpos, dword colpos, double value); double GetValue (dword rowpos, dword colpos); int Initialise(flag Direct); int Analyse (); int Solve (); void Report_Stats (Mtx_Info *table); int Errors(); private : void GetNextPivot(struct CBldSeqItem *pivot, dword diag); }; //-------------------------------------------------------------------------------- class CSSColSeq : public CArray<CBldSeqItem*,CBldSeqItem*> {}; //class CSPSSColSeq : public CSmartPtrAllocate<CSSColSeq> {}; class CSSRowSeq : public CArray<CSSColSeq*,CSSColSeq*> {}; class CSparseSolverI : public CSparseSolverA { DEFINE_SPARES(CSparseSolverI) public: CSparseSolverI(CSparseSolver * pSlv, dword n); ~CSparseSolverI(); void Clear(dword n); void SetValue (dword rowpos, dword colpos, double value); double GetValue (dword rowpos, dword colpos); int Initialise(flag Direct); int Analyse (); int Solve (); void Report_Stats (Mtx_Info *table); int Errors(); private : void SwapRows(int i, int j, LPCTSTR Desc = ""); flag SwapRows(CSSRowSeq & Rows, CArray<bool, bool> & Pinned, int rhi, int rlo, int rtop, int rend); CArray<double, double> m_Val; CArray<int, int> m_RowPtr; CArray<int, int> m_ColInd; int m_iError; }; //-------------------------------------------------------------------------------- class CSparseSolver { friend class CSparseSolverD; friend class CSparseSolverI; DEFINE_SPARES(CSparseSolver) public: CSparseSolver(dword n, double ChgRTol=100.0, double ChgATol=1.0e-3); ~CSparseSolver(); void Clear(dword n, double ChgRTol=100.0, double ChgATol=1.0e-3); //int Analyse (CDArray & b); flag SetValue (dword rowpos, dword colpos, double value); flag NZValue (dword rowpos, dword colpos); double GetValue (dword rowpos, dword colpos); void SetVector(dword rowpos, double value); double GetVector(dword rowpos); double & Vector(dword rowpos); double Solution(dword rowpos) { return ((m_Soln.GetSize()) ? m_Soln[rowpos-1] : 0.0);}; flag ReAnalysisReqd () { return m_bReAnalyse; }; long Changes() { return m_iChanges; }; double BigRatio() { return m_dBigRatio; }; CBldSeqItem & ProblemElement() { return m_ProbElement; }; int Initialise(flag Direct); int Analyse (); int Solve(); void Report_Stats (Mtx_Info *table); flag Direct() { return m_bDirect; }; void RowPrint (flag Symbolic, int Wide, int Prec, bool Primary=true); static void SolveFromFile(flag Direct, char * FileName); static char * ErrorString(int Err); protected: void SetupRows(); private : CSparseSolverA * m_pSlv; dword m_nSize; CDArray m_Soln; CDArray m_Vect; flag m_bDirect; flag m_bAnalysedOK; flag m_bReAnalyse; flag m_bStartBuild; long m_iChanges; int m_Errors; flag m_bRowSetupReqd; double m_dBigRatio; CBldSeqItem m_ProbElement; CBuildSeqList m_BuildSeq; CSSRowSeq m_Rows; CArray<int,int> m_RowCnt; CArray<int,int> m_RowPos; CArray<bool,bool> m_RowPin; POSITION m_Pos; double m_dChgRTol; double m_dChgATol; flag m_RPSymolic; int m_RPWide; int m_RPPrec; }; //-------------------------------------------------------------------------------- #endif
[ [ [ 1, 195 ] ] ]
ce6ade31217cd223e003103933fd29b12cf1fb21
2d4221efb0beb3d28118d065261791d431f4518a
/OIDE源代码/OLIDE/Data/AutoCompleteString.cpp
4b167f007850ee5ca75f60a84e869663289c6709
[]
no_license
ophyos/olanguage
3ea9304da44f54110297a5abe31b051a13330db3
38d89352e48c2e687fd9410ffc59636f2431f006
refs/heads/master
2021-01-10T05:54:10.604301
2010-03-23T11:38:51
2010-03-23T11:38:51
48,682,489
1
0
null
null
null
null
GB18030
C++
false
false
7,272
cpp
#include "stdafx.h" #include "AutoCompleteString.h" #include "./StdioFile/StdioFileEx.h" CAutoCompleteString::CAutoCompleteString() { } CAutoCompleteString::~CAutoCompleteString() { while(!m_listSystemAutoCompleteGroup.IsEmpty()) { CStringArray* pstrArray = (CStringArray*)m_listSystemAutoCompleteGroup.RemoveHead(); if(pstrArray) { delete pstrArray; } } m_strarrayOASMTemplateFile.RemoveAll(); m_strarrayOMLSystemAutoComplete.RemoveAll(); m_strarrayOMLTemplateFile.RemoveAll(); } //得到文件模板列表 void CAutoCompleteString::GetTemplateFileList(LPCTSTR lpDirect,CStringArray& strarrayTemplateFile,int nRelativePathLength) { CString strRelativePath; CString strDir = lpDirect; if(strDir.GetLength() > nRelativePathLength) { strRelativePath = lpDirect; strRelativePath = strRelativePath.Mid(nRelativePathLength+1); strRelativePath += _T('\\'); } TCHAR szDirect[MAX_PATH]; WIN32_FIND_DATA winfd; _stprintf(szDirect,_T("%s\\*"),lpDirect); HANDLE hFind = FindFirstFile(szDirect,&winfd); while(FindNextFile(hFind,&winfd)) { //如果是目录不进行任何操作 if(winfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)//搜子目录 { if(_tcsicmp(winfd.cFileName,_T(".."))!=0&&_tcsicmp(winfd.cFileName,_T("."))!=0) { TCHAR szNextDirect[MAX_PATH]; _stprintf(szNextDirect,_T("%s\\%s"),lpDirect,winfd.cFileName); GetTemplateFileList(szNextDirect,strarrayTemplateFile,nRelativePathLength); } } else { CString strFileName = winfd.cFileName; //如果是模板文件 if(strFileName.Right(4) == _T(".oat")) { //得到文件名 strFileName = strFileName.Left(strFileName.GetLength()-4); //添加文件名 strarrayTemplateFile.Add(strRelativePath + strFileName); } } } FindClose(hFind); } BOOL CAutoCompleteString::RefreshOASMSystemAutoCompleteGroup(LPCTSTR lpSystemTemplateFilePath) { if(lpSystemTemplateFilePath != NULL) { m_strOASMSystemFilePath = lpSystemTemplateFilePath; } if(m_strOASMSystemFilePath.IsEmpty()) return FALSE; CStdioFileEx stdFile; if(!stdFile.Open(m_strOASMSystemFilePath, CFile::modeRead|CFile::typeText)) return FALSE; CStringArray* pstrArrayCurGroup = new CStringArray(); if(pstrArrayCurGroup == 0)return FALSE; CString strLine; while(stdFile.ReadStringEx(strLine,TRUE,_T(';'))) { //如果是分段符号 if(strLine == _T("%%")) { //添加一个Group if(!pstrArrayCurGroup->IsEmpty()) { m_listSystemAutoCompleteGroup.AddTail(pstrArrayCurGroup); pstrArrayCurGroup = new CStringArray(); if(pstrArrayCurGroup == 0)return FALSE; } continue; } pstrArrayCurGroup->Add(strLine); } if(!pstrArrayCurGroup->IsEmpty()) { m_listSystemAutoCompleteGroup.AddTail(pstrArrayCurGroup); } else { delete pstrArrayCurGroup; } return TRUE; } BOOL CAutoCompleteString::ReadTemplateFile(const CString& strFileName,CString& strText) { CStdioFileEx stdFile; if(stdFile.Open(strFileName, CFile::modeRead|CFile::typeText)) { BOOL bResult = FALSE; CString strLine; while(stdFile.ReadStringEx(strLine)) { if(bResult) { strText += _T("\r\n"); } strText += strLine; bResult = TRUE; } return TRUE; } return FALSE; } int CAutoCompleteString::GetItemCount(POSITION psAutoCompleteShift) { CStringArray* pstrArray = (CStringArray*)m_listSystemAutoCompleteGroup.GetAt(psAutoCompleteShift); ASSERT(pstrArray); return pstrArray->GetCount(); } void CAutoCompleteString::GetItemData(POSITION psAutoCompleteShift,int nIndex,CString& strText,CString& strComment,char& chKey) { CStringArray* pstrArray = (CStringArray*)m_listSystemAutoCompleteGroup.GetAt(psAutoCompleteShift); ASSERT(pstrArray); CString strItem = pstrArray->GetAt(nIndex); GetItemData(strItem,strText,strComment,chKey); } void CAutoCompleteString::GetItemData(const CString& strItem,CString& strText,CString& strComment,char& chKey) { strText.Empty(); strComment.Empty(); chKey = 0; int nPos = strItem.Find(_T("∥"),1);//从第二个字符开始查找 if(nPos>0) { strText = strItem.Left(nPos); strComment = strItem.Mid(nPos); } else { strText = strItem; } strText.Trim(); //去掉快捷键字符 if(strText.GetLength() >= 2) { char chTemp = strText[1]; if((strText[0] == '&') && (chTemp > 0x20 && chTemp <= 0x7E)) { if(chTemp == '&') { strText = strText.Right(strText.GetLength()-1); } else { chKey = tolower(strText[1]);//转换成小写字母 strText = strText.Right(strText.GetLength()-2); } } } strText.Replace(_T("\\r"),_T("\r")); strText.Replace(_T("\\n"),_T("\n")); } int CAutoCompleteString::GetOASMTemplateFileText(CString& strText,int nIndex) { //选中的是第一项则表示是刷新模板列表 if(nIndex == 0) { RefreshOASMTemplateFileList(); return -1; } CString strFileName = m_strOASMTempletDir + _T('\\') + GetOASMTemplateFileArray().GetAt(nIndex)+_T(".oat"); ReadTemplateFile(strFileName,strText); return strText.GetLength(); } void CAutoCompleteString::RefreshOASMTemplateFileList(LPCTSTR lpDirect) { if(lpDirect) { m_strOASMTempletDir = lpDirect; if(m_strOASMTempletDir.Right(1) == _T('\\')) { m_strOASMTempletDir = m_strOASMTempletDir.Left(m_strOASMTempletDir.GetLength()-1); } } if(!m_strOASMTempletDir.IsEmpty()) { GetOASMTemplateFileArray().RemoveAll(); GetOASMTemplateFileArray().Add(_T("<刷新模板列表>")); GetTemplateFileList(m_strOASMTempletDir,GetOASMTemplateFileArray(),m_strOASMTempletDir.GetLength()); } } BOOL CAutoCompleteString::RefreshOMLSystemAutoComplete(LPCTSTR lpSystemTemplateFilePath) { if(lpSystemTemplateFilePath != NULL) { m_strOMLSystemFilePath = lpSystemTemplateFilePath; } if(m_strOMLSystemFilePath.IsEmpty()) return FALSE; CStdioFileEx stdFile; if(!stdFile.Open(m_strOMLSystemFilePath, CFile::modeRead|CFile::typeText)) return FALSE; CString strLine; while(stdFile.ReadStringEx(strLine,TRUE,_T(';'))) { m_strarrayOMLSystemAutoComplete.Add(strLine); } return TRUE; } int CAutoCompleteString::GetOMLTemplateFileText(CString& strText,int nIndex) { //选中的是第一项则表示是刷新模板列表 if(nIndex == 0) { RefreshOMLTemplateFileList(); return -1; } CString strFileName = m_strOMLTempletDir + _T('\\') + GetOMLTemplateFileArray().GetAt(nIndex)+_T(".oat"); ReadTemplateFile(strFileName,strText); return strText.GetLength(); } void CAutoCompleteString::RefreshOMLTemplateFileList(LPCTSTR lpDirect) { if(lpDirect) { m_strOMLTempletDir = lpDirect; if(m_strOMLTempletDir.Right(1) == _T('\\')) { m_strOMLTempletDir = m_strOMLTempletDir.Left(m_strOMLTempletDir.GetLength()-1); } } if(!m_strOMLTempletDir.IsEmpty()) { GetOMLTemplateFileArray().RemoveAll(); GetOMLTemplateFileArray().Add(_T("<刷新模板列表>")); GetTemplateFileList(m_strOMLTempletDir,GetOMLTemplateFileArray(),m_strOMLTempletDir.GetLength()); } }
[ [ [ 1, 293 ] ] ]
08989441983c0f71b20834620e54905a16555991
7c51155f60ff037d1b8d6eea1797c7d17e1d95c2
/eJVM-Final/ExecutionEng.h
64edef97876e71bb3e684459f3bdd140b9b1321f
[]
no_license
BackupTheBerlios/ejvm
7258cd180256970d57399d0c153d00257dbb127c
626602de9ed55a825efeefd70970c36bcef0588d
refs/heads/master
2020-06-11T19:47:07.882834
2006-07-10T16:39:59
2006-07-10T16:39:59
39,960,044
0
0
null
null
null
null
UTF-8
C++
false
false
2,733
h
#ifndef EXECUTIONENG_H_ #define EXECUTIONENG_H_ #include "Object.h" #include "Method.h" #include "typeDefs.h" #include "thread.h" #include "ByteCode.h" #include <stdarg.h> #include "inst.h" #include "ConstantPool.h" #include "Heap.h" #include "jni.h" class ExecutionEng { public: static ExecutionEng * geInstance(){ //this method should be implemented , for now it will return NULL return NULL; } /** * The constructor * -creates the main thread data structure * -May take as an argument the max size of Thread stack... */ ExecutionEng(); /** * @brief This method takes a method and executes it either in java or calling native implementation of the functoin * * PseudoCode: * 1- get the current stack (with single thread, we only have the stack of mainThread). 2- push dummy frame in the stack to mark the beginning of execution 3- from the given method, get max_locals and max_operandStack 4- push new frame 5- get the signature of the given method (function name and its arguments) 6- use the signature and the given va_list to put the arguments into local variables 7- get ByteCode 8- call interpret with the ByteCode and currentThread (now it is the mainThread). */ void executeMethod(Object *object,Method * method,...); /*This version of executeMethod takes Valist as an argumetn instead of the ... */ void executeMethod(Object *object,Method * method,va_list args); void executeMethod(Object *object,Method * method,jvalue* args); /** * @brief This method takes a thread which is active now and ready to execute (i.e have a new frame pushed in its stack. * PseudoCode: 1- get top frame from the given thread. 2- let PC be a pointer to the first byte in the byte code. 3- while(true) switch(*PC){ case 0: case 1: . . . case Invoke: save PC in the current frame; get the method push new frame update the state variables (PC, currentFrame, ...) to point to the new method . . . case return: pop frame; check if the next frame is the dummy frame (used to mark end of execution) if so , pop this dummy frame and return //this case is the only case in which this function returns. . . . default: error ("unsupported OPCODE"); } */ void interpret(Thread * thread); ~ExecutionEng(); private: Thread * mainThread; void putArgInLocalVariables(Frame * invokingMethod, Frame * invokedMethod,Object * ob); void calNumOfArg(char * p,unsigned int & argCount,unsigned int & opStackArgCount); unsigned int getRefrenceIndex(char * p); }; #endif /*EXECUTIONENG_H_*/
[ "ahmed_seddiq", "almahallawy" ]
[ [ [ 1, 11 ], [ 13, 42 ], [ 44, 91 ] ], [ [ 12, 12 ], [ 43, 43 ] ] ]
eac78365193ea8802ee12a658c564e7b18610da7
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Toolset/MaterialWrapper.h
74dba4f240ab2afc0f87e27d4c50569c4208ef2b
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
17,289
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: Material.h Version: 0.01 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_MATERIALWRAPPER_H_ #define __INC_MATERIALWRAPPER_H_ #include "nGENE.h" #include <sstream> namespace nGENEToolset { using namespace System; using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Drawing; using namespace System::Text; using nGENE::Material; using nGENE::ShaderConstant; using nGENE::BLEND_OPERATION; using nGENE::FILL_MODE; using nGENE::DRAW_ORDER; using nGENE::RenderPass; using nGENE::SShaderConstantType; using nGENE::RenderTechnique; using nGENE::ShaderInstance; using nGENE::SPriorityMaterial; ref class ShaderConstantWrapperCollection; ref class ShaderConstantWrapper; ref class ShaderConstantWrapperConverter: public ExpandableObjectConverter { public: virtual Object^ ConvertTo(ITypeDescriptorContext^ context, System::Globalization::CultureInfo^ culture, Object^ value, Type^ destType) override; }; // This is a special type converter which will be associated with the ShaderConstatnWrapperCollection class. // It converts an ShaderConstantWrapperCollection object to a string representation for use in a property grid. ref class ShaderConstantWrapperCollectionConverter: public ExpandableObjectConverter { public: virtual Object^ ConvertTo(ITypeDescriptorContext^ context, System::Globalization::CultureInfo^ culture, Object^ value, Type^ destType) override; }; [TypeConverterAttribute(ShaderConstantWrapperConverter::typeid)] public ref class ShaderConstantWrapper { private: ShaderConstant* m_pConstant; String^ m_Name; float m_Value; System::Collections::Generic::List <float>^ m_Values; public: ShaderConstantWrapper(ShaderConstant* _constant) { m_Name = ""; m_Values = gcnew System::Collections::Generic::List <float>(); m_pConstant = _constant; } property System::Collections::Generic::List <float>^ Values { System::Collections::Generic::List <float>^ get() { if(m_Values->Count == m_pConstant->getValuesCount()) { float* pData = new float[m_pConstant->getValuesCount()]; for(int i = 0; i < m_pConstant->getValuesCount(); ++i) { pData[i] = m_Values[i]; } m_pConstant->setValues(pData); NGENE_DELETE_ARRAY(pData); } return m_Values; } void set(System::Collections::Generic::List <float>^ value) { m_Values = value; } } property bool Dynamic { bool get() { return m_pConstant->isDynamic(); } } property String^ DataType { String^ get() { switch(m_pConstant->getType()) { case SShaderConstantType::BASE_TYPE::BT_FLOAT: return "float"; case SShaderConstantType::BASE_TYPE::BT_INT: return "integer"; case SShaderConstantType::BASE_TYPE::BT_BOOL: return "boolean"; default: return "float"; } } } // Uncomment the next line to see the attribute in action: [Category("Required")] property String^ Name { String^ get() { return m_Name; } void set(String^ value) { m_Name = value; } } virtual String^ ToString() override { StringBuilder^ sb = gcnew StringBuilder(); sb->Append(Name); return sb->ToString(); } }; public ref class ShaderConstantWrapperCollection: public CollectionBase, public ICustomTypeDescriptor { #pragma region collection impl /// <summary> /// Adds a shader constant object to the collection /// </summary> /// <param name="emp"></param> public: void Add( ShaderConstantWrapper^ emp ) { this->List->Add( emp ); } /// <summary> /// Removes a shader constant object from the collection /// </summary> /// <param name="emp"></param> public: void Remove( ShaderConstantWrapper^ emp ) { this->List->Remove( emp ); } /// <summary> /// Returns a shader constant object at index position. /// </summary> public: property ShaderConstantWrapper^ default[ int ] { ShaderConstantWrapper^ get(int index) { return (ShaderConstantWrapper^)this->List[index]; } } #pragma endregion // Implementation of interface ICustomTypeDescriptor //#pragma region ICustomTypeDescriptor impl public: virtual String^ GetClassName() { return TypeDescriptor::GetClassName(this,true); } public: virtual AttributeCollection^ GetAttributes() { return TypeDescriptor::GetAttributes(this,true); } public: virtual String^ GetComponentName() { return TypeDescriptor::GetComponentName(this, true); } public: virtual TypeConverter^ GetConverter() { return TypeDescriptor::GetConverter(this, true); } public: virtual EventDescriptor^ GetDefaultEvent() { return TypeDescriptor::GetDefaultEvent(this, true); } public: virtual PropertyDescriptor^ GetDefaultProperty() { return TypeDescriptor::GetDefaultProperty(this, true); } public: virtual Object^ GetEditor(Type^ editorBaseType) { return TypeDescriptor::GetEditor(this, editorBaseType, true); } public: virtual EventDescriptorCollection^ GetEvents(cli::array<Attribute^>^ attributes) { return TypeDescriptor::GetEvents(this, attributes, true); } public: virtual EventDescriptorCollection^ GetEvents() { return TypeDescriptor::GetEvents(this, true); } public: virtual Object^ GetPropertyOwner(PropertyDescriptor^ pd) { return this; } /// <summary> /// Called to get the properties of this type. Returns properties with certain /// attributes. this restriction is not implemented here. /// </summary> /// <param name="attributes"></param> /// <returns></returns> public: virtual PropertyDescriptorCollection^ GetProperties(cli::array<Attribute^>^ attributes) { return GetProperties(); } /// <summary> /// Called to get the properties of this type. /// </summary> /// <returns></returns> public: virtual PropertyDescriptorCollection^ GetProperties(); //#pragma endregion }; public ref class ShaderConstantWrapperCollectionPropertyDescriptor : public PropertyDescriptor { private: ShaderConstantWrapperCollection^ collection; int index; public: ShaderConstantWrapperCollectionPropertyDescriptor(ShaderConstantWrapperCollection^ coll, int idx) : PropertyDescriptor("#"+idx.ToString(), nullptr) { this->collection = coll; this->index = idx; } public: virtual property AttributeCollection^ Attributes { AttributeCollection^ get() override { return gcnew AttributeCollection(nullptr); } } public: virtual bool CanResetValue(Object^ component) override { return true; } public: virtual property Type^ ComponentType { Type^ get() override { return this->collection->GetType(); } } public: virtual property String^ DisplayName { String^ get() override { ShaderConstantWrapper^ emp = this->collection[index]; return emp->Name; } } public: virtual property String^ Description { String^ get() override { ShaderConstantWrapper^ emp = this->collection[index]; StringBuilder^ sb = gcnew StringBuilder(); sb->Append(emp->Name); return sb->ToString(); } } public: virtual Object^ GetValue(Object^ component) override { return this->collection[index]; } public: virtual property bool IsReadOnly { bool get() override { return false; } } public: virtual property String^ Name { String^ get() override { return "#"+index.ToString(); } } public: virtual property Type^ PropertyType { Type^ get() override { return this->collection[index]->GetType(); } } public: virtual void ResetValue(Object^ component) override { } public: virtual bool ShouldSerializeValue(Object^ component) override { return true; } public: virtual void SetValue(Object^ component, Object^ value) override { // this.collection[index] = value; } }; ref class frmMaterialLib; enum class RenderMode { Solid, Wireframe, Dot }; enum class BlendingOp { Add, Subtract, Revsubtract, Min, Max }; enum class BlendType { Zero = 1, One = 2, SrcColor = 3, InvSrcColor = 4, SrcAlpha = 5, InvSrcAlpha = 6, DestAlpha = 7, InvDestAlpha = 8, DestColor = 9, InvDestColor = 10, SrcAlphaSat = 11, BothSrcAlpha = 12, BothInvSrcAlpha = 13, BlendFactor = 14, InvBlendFactor = 15, }; ref class FXWrapper { protected: SPriorityMaterial* m_pMaterial; int m_nPriority; public: FXWrapper(SPriorityMaterial* _material) { m_pMaterial = _material; } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Priority of the material")] property int Priority { int get() { return m_pMaterial->priority; } void set(int value) { m_pMaterial->priority = value; } } public: virtual String^ ToString() override { return gcnew String(m_pMaterial->material->getName().c_str()); } public: SPriorityMaterial* getMaterial() { return m_pMaterial; } }; /// Wrapper for a Material class. public ref class MaterialWrapper { protected: Material* m_pMaterial; frmMaterialLib^ m_MatLib; StringBuilder^ m_Name; StringBuilder^ m_Key; bool m_PostProcess; SPriorityMaterial* m_PostMat; ShaderConstantWrapperCollection^ constants; public: MaterialWrapper(Material* _material, frmMaterialLib^ _matLib, Hashtable^ _lib); virtual ~MaterialWrapper() { NGENE_DELETE(m_PostMat); } Material* getMaterial() { return m_pMaterial; } public: [TypeConverterAttribute(ShaderConstantWrapperCollectionConverter::typeid), Browsable(true), CategoryAttribute("Constants"), DescriptionAttribute("Name of a material")] property ShaderConstantWrapperCollection^ Constants { ShaderConstantWrapperCollection^ get() { return constants; } } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Name of a material")] property String^ Name { String^ get() { return m_Name->ToString(); } void set(String^ value) { if(m_Name != nullptr) delete m_Name; m_Name = gcnew StringBuilder(value); } } [Browsable(false), CategoryAttribute("Material"), DescriptionAttribute("Key of a material")] property String^ Key { String^ get() { return m_Key->ToString(); } void set(String^ value) { if(m_Key != nullptr) delete m_Key; m_Key = gcnew StringBuilder(value); } } [Browsable(true), CategoryAttribute("Colour"), DescriptionAttribute("Emissive factor of the material")] property float Emissive { float get() { return m_pMaterial->getEmissive(); } void set(float value) { m_pMaterial->setEmissive(value); } } [Browsable(true), CategoryAttribute("Blending"), DescriptionAttribute("Specifies if material is transparent")] property bool Transparent { bool get() { return m_pMaterial->isTransparent(); } void set(bool value) { m_pMaterial->setTransparent(value); } } [Browsable(true), CategoryAttribute("Blending"), DescriptionAttribute("Specifies if material uses alpha testing")] property bool AlphaTest { bool get() { return m_pMaterial->isAlphaTest(); } void set(bool value) { m_pMaterial->setAlphaTest(value); } } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Specifies if material is two-sided")] property bool TwoSided { bool get() { return m_pMaterial->isTwoSided(); } void set(bool value) { m_pMaterial->setTwoSided(value); } } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Specifies if material writes to the z-buffer")] property bool ZWrite { bool get() { return m_pMaterial->isZWrite(); } void set(bool value) { m_pMaterial->setZWrite(value); } } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Specifies if material is enabled")] property bool Enabled { bool get() { return m_pMaterial->isEnabled(); } void set(bool value) { m_pMaterial->setEnabled(value); } } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Specifies source blending")] property BlendType SourceBlending { BlendType get() { return (BlendType)m_pMaterial->getSrcBlend(); } void set(BlendType value) { m_pMaterial->setSrcBlend((int)value); } } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Specifies destination blending")] property BlendType DestinationBlending { BlendType get() { return (BlendType)m_pMaterial->getDestBlend(); } void set(BlendType value) { m_pMaterial->setDestBlend((int)value); } } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Specifies rendering mode of the material")] property RenderMode RenderingMode { RenderMode get() { FILL_MODE value = (FILL_MODE)m_pMaterial->getFillMode(); switch(value) { case FILL_MODE::FILL_SOLID: return RenderMode::Solid; case FILL_MODE::FILL_WIREFRAME: return RenderMode::Wireframe; case FILL_MODE::FILL_DOT: return RenderMode::Dot; default: return RenderMode::Solid; } } void set(RenderMode value) { switch(value) { case RenderMode::Solid: m_pMaterial->setFillMode(FILL_MODE::FILL_SOLID); break; case RenderMode::Wireframe: m_pMaterial->setFillMode(FILL_MODE::FILL_WIREFRAME); break; case RenderMode::Dot: m_pMaterial->setFillMode(FILL_MODE::FILL_DOT); break; } } } [Browsable(true), CategoryAttribute("Material"), DescriptionAttribute("Specifies blending operation for this material")] property BlendingOp BlendingOperation { BlendingOp get() { BLEND_OPERATION value = m_pMaterial->getBlendOperation(); switch(value) { case BLEND_OPERATION::BO_ADD: return BlendingOp::Add; case BLEND_OPERATION::BO_SUBTRACT: return BlendingOp::Subtract; case BLEND_OPERATION::BO_REVSUBTRACT: return BlendingOp::Revsubtract; case BLEND_OPERATION::BO_MIN: return BlendingOp::Min; case BLEND_OPERATION::BO_MAX: return BlendingOp::Max; default: return BlendingOp::Add; } } void set(BlendingOp value) { switch(value) { case BlendingOp::Add: m_pMaterial->setBlendOperation(BLEND_OPERATION::BO_ADD); break; case BlendingOp::Subtract: m_pMaterial->setBlendOperation(BLEND_OPERATION::BO_SUBTRACT); break; case BlendingOp::Revsubtract: m_pMaterial->setBlendOperation(BLEND_OPERATION::BO_REVSUBTRACT); break; case BlendingOp::Min: m_pMaterial->setBlendOperation(BLEND_OPERATION::BO_MIN); break; case BlendingOp::Max: m_pMaterial->setBlendOperation(BLEND_OPERATION::BO_MAX); break; } } } [Browsable(true), CategoryAttribute("Light"), DescriptionAttribute("Specifies if material casts shadows")] property bool CastShadow { bool get() { return m_pMaterial->isCastingShadow(); } void set(bool value) { m_pMaterial->setCastShadow(value); } } [Browsable(true), CategoryAttribute("Light"), DescriptionAttribute("Specifies if material is affected by lights")] property bool Lightable { bool get() { return m_pMaterial->isLightable(); } void set(bool value) { m_pMaterial->setLightable(value); } } [Browsable(false), CategoryAttribute("Material")] property bool PostProcess { bool get() { return (m_pMaterial->getRenderingOrder() == DRAW_ORDER::DO_POST ? true : false); } void set(bool value) { m_PostProcess = (value ? DRAW_ORDER::DO_POST : DRAW_ORDER::DO_SCENE); } } public: SPriorityMaterial* applyPost() { m_PostMat = new SPriorityMaterial; m_PostMat->priority = 0; m_PostMat->material = m_pMaterial; ((nGENE::PostStage*)nGENE::Renderer::getSingleton().getRenderStage(L"PostProcess"))->addToRender(m_PostMat); return m_PostMat; } }; } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 770 ] ] ]
33d7663cd7400452657d2f5c9072d50d27d33dfa
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/depends/ClanLib/src/Core/IOData/directory.cpp
424db68c14cf02c761911bb95bb6e07d2633a41e
[]
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
11,035
cpp
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** (if your name is missing here, please add it) */ #include "precomp.h" #include "API/Core/IOData/directory.h" #include "API/Core/IOData/directory_scanner.h" #include "API/Core/Text/string_format.h" #include "API/Core/Text/string_help.h" #if defined(WIN32) #include <shlobj.h> #if defined(_MSC_VER) #pragma comment(lib, "shell32.lib") #endif #endif #ifndef WIN32 #include <unistd.h> #include <cstdio> #ifndef PATH_MAX #define PATH_MAX 256 // TODO: Fixme - Paths should not have a limit #endif #ifndef MAX_PATH #define MAX_PATH PATH_MAX #endif #else #include <direct.h> #ifndef chdir #define _chdir chdir #endif #ifndef MAX_PATH #define _MAX_PATH MAX_PATH #endif #include <tchar.h> #endif #ifdef __BORLANDC__ #include <dir.h> #endif #include <sys/stat.h> #include <sys/types.h> #include <cstdlib> ///////////////////////////////////////////////////////////////////////////// // Operations bool CL_Directory::create(const CL_String &dir_name) { if (dir_name.empty()) return false; // this will be a full path CL_String full_path; // calculate the full path #ifdef WIN32 DWORD buff_len = ::GetFullPathName(CL_StringHelp::utf8_to_ucs2(dir_name).c_str(), 0, 0, 0); if (buff_len == 0) // can't calculate, return bad status return false; else { std::vector<TCHAR> buffer_vector; buffer_vector.resize(buff_len + 1); TCHAR *buffer = &(buffer_vector[0]); TCHAR *buffer_ptr_to_filename = 0; // Obtaining full path buff_len = ::GetFullPathName(CL_StringHelp::utf8_to_ucs2(dir_name).c_str(), buff_len, buffer, &buffer_ptr_to_filename); if (buff_len == 0) // can't obtain full path, return bad status return false; else // ok, save it full_path = buffer; } #else // TODO: add here Linux version of GetFullPathName full_path = dir_name; #endif #ifdef WIN32 return ::CreateDirectory(CL_StringHelp::utf8_to_ucs2(full_path).c_str(), NULL) != 0; #else return ::mkdir(full_path.c_str(), 0755) == 0; #endif } bool CL_Directory::remove(const CL_String &dir_name, bool delete_files, bool delete_sub_directories) { if (dir_name.empty()) return false; // this will be a full path CL_String full_path; // calculate the full path #ifdef WIN32 DWORD buff_len = ::GetFullPathName(CL_StringHelp::utf8_to_ucs2(dir_name).c_str(), 0, 0, 0); if (buff_len == 0) // can't calculate, return bad status return false; else { std::vector<TCHAR> buffer_vector; buffer_vector.resize(buff_len + 1); TCHAR *buffer = &(buffer_vector[0]); TCHAR *buffer_ptr_to_filename = 0; // Obtaining full path buff_len = ::GetFullPathName(CL_StringHelp::utf8_to_ucs2(dir_name).c_str(), buff_len, buffer, &buffer_ptr_to_filename); if (buff_len == 0) // can't obtaing full path, return bad status return false; else // ok, save it full_path = buffer; } #else // TODO: add here Linux version of GetFullPathName full_path = dir_name; #endif // This scope needed for deleting directiory at end of function, // because scanner lock current dir :( { CL_DirectoryScanner scanner; if (!scanner.scan(full_path)) // can't even start scaning return false; // FIXME: probably bug in directory_scanner, it return "" // for first file :( if (scanner.next()) while(true) { // If found sub_directory, try remove it, // also checking for "." and "..", because they are unremovable if (scanner.is_directory() && delete_sub_directories && scanner.get_name() != "." && scanner.get_name() != "..") { // FIXME: directory_scanner lock directory, so it can't be // removed, this is workaround CL_String sub_dir_path = scanner.get_pathname(); bool scann_successfull = scanner.next(); // delete files in sub_directory if (!CL_Directory::remove(sub_dir_path.c_str(), delete_files, delete_sub_directories)) return false; if (!scann_successfull) break; else continue; } else { // Check for deleting file (or whatever is not directory), // if this is allowed if (delete_files && !scanner.is_directory()) { // delete a file #ifdef WIN32 if (::DeleteFile(CL_StringHelp::utf8_to_ucs2(scanner.get_pathname()).c_str()) == 0) return false; #else if (::remove(scanner.get_pathname().c_str()) != 0) return false; #endif if (!scanner.next()) break; } // This is for "." and ".." else { if (!scanner.next()) break; } } } } // Finaly remove the directory (or sub_directory if in recursion) #ifdef WIN32 return ::RemoveDirectory(CL_StringHelp::utf8_to_ucs2(full_path).c_str()) != 0; #else return ::rmdir(full_path.c_str()) == 0; #endif } bool CL_Directory::set_current(const CL_String &dir_name) { #ifdef WIN32 return SetCurrentDirectory(CL_StringHelp::utf8_to_ucs2(dir_name).c_str()) == TRUE; #else return chdir(dir_name.c_str()) == 0; #endif } CL_String CL_Directory::get_current() { #ifdef WIN32 TCHAR cwd_buffer[MAX_PATH]; #ifdef _CRT_INSECURE_DEPRECATE if (_tgetcwd(cwd_buffer, MAX_PATH) == NULL) throw CL_Exception("Working dir is more than legal length !"); #else if (_tgetcwd(cwd_buffer, MAX_PATH) == NULL) throw CL_Exception("Working dir is more than legal length !"); #endif #else char cwd_buffer[MAX_PATH]; if (getcwd(cwd_buffer, MAX_PATH) == NULL) throw CL_Exception("Working dir is more than legal length !"); #endif return cwd_buffer; } CL_String CL_Directory::get_appdata(const CL_StringRef &company_name, const CL_StringRef &application_name, const CL_StringRef &version, bool create_dirs_if_missing) { #if defined(WIN32) TCHAR app_data[MAX_PATH]; if (FAILED(SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_DEFAULT, app_data))) throw CL_Exception("SHGetFolderPath failed!"); CL_String configuration_path = cl_format("%1\\%2\\%3\\%4\\", app_data, company_name, application_name, version); if (create_dirs_if_missing) { CL_String::size_type prevPos = 0; while (true) { CL_String::size_type pos = configuration_path.find_first_of("\\/", prevPos); if (pos == CL_String::npos) break; CL_StringRef folder = configuration_path.substr(0, pos); CreateDirectory(CL_StringHelp::utf8_to_ucs2(folder).c_str(), 0); prevPos = pos + 1; } } return configuration_path; #elif defined(__APPLE__) throw CL_Exception("Congratulations, you got the task to implement CL_Directory::get_appdata on this platform."); #else const char *home_dir = getenv("HOME"); if (home_dir == NULL) throw CL_Exception("Cannot object $HOME environment variable"); if (!create_dirs_if_missing) { return cl_format("%1/.%2/%3/%4/", home_dir, company_name, application_name, version); } struct stat stFileInfo; CL_String name( cl_format("%1/.%2", home_dir, company_name) ); if (stat(name.c_str(), &stFileInfo)) { if (::mkdir(name.c_str(), 0755)) throw CL_Exception(cl_format("Cannot create %1 directory", name)); } name = cl_format("%1/%2", name, application_name); if (stat(name.c_str(), &stFileInfo)) { if (::mkdir(name.c_str(), 0755)) throw CL_Exception(cl_format("Cannot create %1 directory", name)); } name = cl_format("%1/%2", name, version); if (stat(name.c_str(), &stFileInfo)) { if (::mkdir(name.c_str(), 0755)) throw CL_Exception(cl_format("Cannot create %1 directory", name)); } name = cl_format("%1/", name); return name; #endif } CL_String CL_Directory::get_local_appdata(const CL_StringRef &company_name, const CL_StringRef &application_name, const CL_StringRef &version, bool create_dirs_if_missing) { #if defined(WIN32) TCHAR app_data[MAX_PATH]; if (FAILED(SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, SHGFP_TYPE_DEFAULT, app_data))) throw CL_Exception("SHGetFolderPath failed!"); CL_String configuration_path = cl_format("%1\\%2\\%3\\%4\\", app_data, company_name, application_name, version); if (create_dirs_if_missing) { CL_String::size_type prevPos = 0; while (true) { CL_String::size_type pos = configuration_path.find_first_of("\\/", prevPos); if (pos == CL_String::npos) break; CL_StringRef folder = configuration_path.substr(0, pos); CreateDirectory(CL_StringHelp::utf8_to_ucs2(folder).c_str(), 0); prevPos = pos + 1; } } return configuration_path; #elif defined(__APPLE__) throw CL_Exception("Congratulations, you got the task to implement CL_Directory::get_local_appdata on this platform."); #else return get_appdata(company_name, application_name, version, create_dirs_if_missing); #endif } CL_String CL_Directory::get_resourcedata(const CL_StringRef &application_name) { #if defined(WIN32) TCHAR exe_filename[MAX_PATH]; DWORD result = GetModuleFileName(0, exe_filename, MAX_PATH); if (result == 0 || result == MAX_PATH) throw CL_Exception("GetModuleFileName failed!"); TCHAR drive[MAX_PATH], dir[MAX_PATH], filename[MAX_PATH], extension[MAX_PATH]; #ifdef _CRT_INSECURE_DEPRECATE _tsplitpath_s(exe_filename, drive, MAX_PATH, dir, MAX_PATH, filename, MAX_PATH, extension, MAX_PATH); #else _tsplitpath(exe_filename, drive, dir, filename, extension); #endif return cl_format("%1%2Resources\\", drive, dir); #elif defined(__APPLE__) throw CL_Exception("Congratulations, you got the task to implement CL_Directory::get_resourcedata on this platform."); #else //TODO: /// In Linux, this function will return the directory "../share/application_name/" /// relative to the executable, so if it is located in "/usr/bin" it will return /// "/usr/share/application_name/" /// (Assuming that is correct!) return "Resources/"; #endif }
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 368 ] ] ]
229455c446318e971b0ae984087c1653e635a149
e2b94ebf5916e50c1e527f936a7ab9c31711581f
/IaTest/IaTest/Module.h
56ae1784b3a3a0836d6887166d52d34526a3ca0f
[]
no_license
vindem/aviv-robot
17ec989264bad2f564dcdf1026a6068345e0505e
d7a4ce458b3cee6961c77e707810d6439842f53e
refs/heads/master
2021-05-28T15:31:19.721784
2009-11-14T09:46:50
2009-11-14T09:46:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,485
h
#include "ClassConsts.h" #define COCKPIT 1 #define LEGS 2 #define ARMS 3 class Module{ private: int code,bonus,type; unsigned int classmask; string name,description; public: Module(int code,int bonus,int type,unsigned int classmask,string name,string description); ~Module(); int getCode(); int getType(); int getBonus(); string getName(); string getDescription(); bool isForClass(unsigned int classconst); }; Module::Module(int code,int bonus,int type,unsigned int classmask,string name,string description){ this->code = code; this->bonus = bonus; this->type = type; this->classmask = classmask; this->name = name; this->description = description; } Module::~Module(){} int Module::getCode(){ return this->code; } int Module::getType(){ return this->type; } int Module::getBonus(){ return this->bonus; } string Module::getName(){ return this->name; } string Module::getDescription(){ return this->description; } /* bitwise AND between input class constant and the module mask to check if module is suitable for the input class. example: module set for TECH and SOLDIER MODULE MASK: 000001001 we check if is suitable for TECH TECH: 000001000 MASK & TECH = 000001000 = 256 >= 1 OK. otherwise, if we check for SNIPER SNIPER: 100000000 MASK & SNIPER = 00000000 = 0 < 1 FAILS. */ bool Module::isForClass(unsigned int classconst){ return (classmask & classconst)>=1; }
[ "vinc.demaio@906796ec-c859-11de-8672-e51b9359e43c" ]
[ [ [ 1, 69 ] ] ]
3f3cd5939dce7aec25cff0bda428107b3b4d6fe2
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/Plant.h
e2d9005a421572f349160e5648ee2bf0fb43c7d7
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
7,382
h
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Throw Fire Mode Implementation ------------------------------------------------------------------------- History: - 26ye:10:2005 15:45 : Created by Márcio Martins *************************************************************************/ #ifndef __PLANT_H__ #define __PLANT_H__ #if _MSC_VER > 1000 # pragma once #endif #include "Single.h" class CPlant : public IFireMode { struct StartPlantAction; protected: typedef struct SPlantParams { SPlantParams() { Reset(); }; void Reset(const IItemParamsNode *params=0, bool defaultInit=true) { CItemParamReader reader(params); string ammo_type; ResetValue(ammo_type, "c4explosive"); if (defaultInit || !ammo_type.empty()) ammo_type_class = gEnv->pEntitySystem->GetClassRegistry()->FindClass(ammo_type.c_str()); ResetValue(clip_size, 3); ResetValue(damage, 100); ResetValue(helper, true); ResetValue(impulse, 10.0f); ResetValue(delay, 0.25f); ResetValue(tick, 5.0f); ResetValue(tick_time, 0.45f); ResetValue(min_time, 5.0f); ResetValue(max_time, 180.0f); ResetValue(led_minutes, true); ResetValue(led_layers, "d%d%d"); ResetValue(simple, false); ResetValue(place_on_ground, false); ResetValue(need_to_crouch, false); }; IEntityClass* ammo_type_class; int damage; int clip_size; bool simple; bool place_on_ground; bool need_to_crouch; string helper; float impulse; float delay; float tick; float tick_time; float min_time; float max_time; bool led_minutes; string led_layers; void GetMemoryStatistics(ICrySizer * s) { s->Add(helper); s->Add(led_layers); } } SPlantParams; typedef struct SPlantActions { SPlantActions() { Reset(); }; void Reset(const IItemParamsNode *params=0, bool defaultInit=true) { CItemParamReader reader(params); ResetValue(press_button, "press_button"); ResetValue(hold_button, "hold_button"); ResetValue(release_button, "release_button"); ResetValue(tick, "tick"); ResetValue(plant, "plant"); ResetValue(refill, "select"); }; string press_button; string hold_button; string release_button; string tick; string plant; string refill; void GetMemoryStatistics(ICrySizer * s) { s->Add(press_button); s->Add(hold_button); s->Add(release_button); s->Add(tick); s->Add(plant); s->Add(refill); } } SPlantActions; public: CPlant(); virtual ~CPlant(); virtual void Init(IWeapon *pWeapon, const struct IItemParamsNode *params); virtual void Update(float frameTime, uint frameId); virtual void PostUpdate(float frameTime) {}; virtual void UpdateFPView(float frameTime); virtual void Release(); virtual void GetMemoryStatistics(ICrySizer * s); virtual void ResetParams(const struct IItemParamsNode *params); virtual void PatchParams(const struct IItemParamsNode *patch); virtual void Activate(bool activate); virtual int GetAmmoCount() const { return m_pWeapon->GetAmmoCount(m_plantparams.ammo_type_class); }; virtual int GetClipSize() const { return m_plantparams.clip_size; }; virtual bool OutOfAmmo() const; virtual bool CanReload() const { return false; }; virtual void Reload(int zoomed) {}; virtual bool IsReloading() { return false; }; virtual void CancelReload() {}; virtual bool CanCancelReload() { return false; }; virtual bool AllowZoom() const { return true; }; virtual void Cancel() {}; virtual float GetRecoil() const { return 0.0f; }; virtual float GetSpread() const { return 0.0f; }; virtual float GetMinSpread() const { return 0.0f; }; virtual float GetMaxSpread() const { return 0.0f; }; virtual const char *GetCrosshair() const { return ""; }; virtual float GetHeat() const { return 0.0f; }; virtual bool CanOverheat() const {return false;}; virtual bool CanFire(bool considerAmmo=true) const; virtual void StartFire(); virtual void StopFire(); virtual bool IsFiring() const { return m_planting; }; virtual void NetShoot(const Vec3 &hit, int ph); virtual void NetShootEx(const Vec3 &pos, const Vec3 &dir, const Vec3 &vel, const Vec3 &hit, float extra, int ph); virtual void NetEndReload() {}; virtual void NetStartFire(); virtual void NetStopFire(); virtual EntityId GetProjectileId() const; virtual void SetProjectileId(EntityId id); virtual EntityId RemoveProjectileId(); virtual const char *GetType() const; virtual IEntityClass* GetAmmoType() const; virtual int GetDamage() const; virtual float GetSpinUpTime() const { return 0.0f; }; virtual float GetSpinDownTime() const { return 0.0f; }; virtual float GetNextShotTime() const { return 0.0f; }; virtual void SetNextShotTime(float time) {}; virtual float GetFireRate() const { return 0.0f; }; virtual void Enable(bool enable) { m_enabled = enable; }; virtual bool IsEnabled() const { return m_enabled; }; virtual Vec3 GetFiringPos(const Vec3 &probableHit) const { return ZERO;} virtual Vec3 GetFiringDir(const Vec3 &probableHit, const Vec3& firingPos) const { return ZERO;} virtual void SetName(const char *name) { m_name = name; }; virtual const char *GetName() { return m_name.empty()?0:m_name.c_str();}; virtual bool HasFireHelper() const { return false; } virtual Vec3 GetFireHelperPos() const { return Vec3(ZERO); } virtual Vec3 GetFireHelperDir() const { return FORWARD_DIRECTION; } virtual int GetCurrentBarrel() const { return 0; } virtual void Serialize(TSerialize ser); virtual void PostSerialize() {}; virtual void SetRecoilMultiplier(float recoilMult) { } virtual float GetRecoilMultiplier() const { return 1.0f; } virtual void Time() { m_timing=true; }; virtual void SetTime(float time) { m_time=time; }; virtual float GetTime() const { return m_time; }; virtual void PatchSpreadMod(SSpreadModParams &sSMP){}; virtual void ResetSpreadMod(){}; virtual void PatchRecoilMod(SRecoilModParams &sRMP){}; virtual void ResetRecoilMod(){}; virtual void ResetLock() {}; virtual void StartLocking(EntityId targetId, int partId) {}; virtual void Lock(EntityId targetId, int partId) {}; virtual void Unlock() {}; protected: virtual void Plant(const Vec3 &pos, const Vec3 &dir, const Vec3 &vel, bool net=false, int ph=0); virtual void SelectDetonator(); virtual void CheckAmmo(); virtual bool PlayerStanceOK() const; virtual bool GetPlantingParameters(Vec3& pos, Vec3& dir, Vec3& vel) const; CWeapon *m_pWeapon; bool m_enabled; string m_name; EntityId m_projectileId; std::vector<EntityId> m_projectiles; SPlantParams m_plantparams; SPlantActions m_plantactions; bool m_planting; bool m_pressing; bool m_holding; bool m_timing; float m_time; float m_plantTimer; float m_tickTimer; // pos/dir/vel are stored when the user presses fire for placed weapons Vec3 m_plantPos; Vec3 m_plantDir; Vec3 m_plantVel; static IEntityClass *m_pClaymoreClass, *m_pAVMineClass; }; #endif
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 53 ], [ 56, 61 ], [ 64, 144 ], [ 147, 148 ], [ 150, 151 ], [ 154, 156 ], [ 159, 159 ], [ 162, 162 ], [ 166, 173 ], [ 175, 190 ], [ 192, 205 ], [ 208, 210 ], [ 213, 214 ], [ 217, 222 ], [ 224, 236 ], [ 244, 246 ] ], [ [ 54, 55 ], [ 62, 63 ], [ 145, 146 ], [ 149, 149 ], [ 152, 153 ], [ 157, 158 ], [ 160, 161 ], [ 163, 165 ], [ 174, 174 ], [ 191, 191 ], [ 206, 207 ], [ 211, 212 ], [ 215, 216 ], [ 223, 223 ], [ 237, 243 ] ] ]
69aef9c5fba0a1f0838d3b2b0795e3b2cbd4bf28
6fbf3695707248bfb00e3f8c4a0f9adf5d8a3d4c
/java/testjava/assert.hpp
f41d27f766b73da4ac464487686e01f3eee8b690
[]
no_license
ochafik/cppjvm
c554a2f224178bc3280f03919aff9287bd912024
e1feb48eee3396d3a5ecb539de467c0a8643cba0
refs/heads/master
2020-12-25T16:02:38.582622
2011-11-17T00:11:35
2011-11-17T00:11:35
2,790,123
1
0
null
null
null
null
UTF-8
C++
false
false
2,180
hpp
#ifndef TEST_JAVA_ASSERT_INCLUDED #define TEST_JAVA_ASSERT_INCLUDED #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <sstream> #include <iostream> template <class T> std::string toString(const T &v) { std::ostringstream o; o << v; return o.str(); } inline std::string toString(java::lang::Object obj) { return obj.toString(); } template <class T> void assert_equal(const T &expected, const T &actual, const char *description) { if (expected != actual) { std::ostringstream o; o << "Assertion failed: " << description << std::endl << "Unexpected value: " << toString(actual); throw std::logic_error(o.str()); } } #define AS_STR(l) #l #define ASSERT_EQUAL(t, exp, act) assert_equal<t>((exp), (act), #exp " == " #act " " __FILE__ "(" AS_STR(__LINE__) ")") typedef void test_func(); struct test { const char *descr; test_func *func; test *next; test(const char *d, test_func *f, test *n) : descr(d), func(f), next(n) {} }; class test_registration { public: static test **head() { static test *h = 0; return &h; } test_registration(const char *descr, test_func *func) { *(head()) = new test(descr, func, *(head())); } static int run() { int failed = 0; try { std::cout << "Running tests..." << std::endl; for (test *t = *(head()); t != 0; t = t->next) { try { std::cout << "Running " << t->descr << "..." << std::endl; t->func(); } catch (const std::exception &e) { failed++; std::cout << e.what() << std::endl; } } if (failed == 0) std::cout << "Perfect :)" << std::endl; else std::cout << std::endl << failed << " failed :(" << std::endl; } catch (const std::exception &e) { std::cout << "General problem starting Java tests" << e.what() << std::endl; } test *d = *(head()); while (d != 0) { test *n = d->next; delete d; d = n; } *(head()) = 0; return failed; } }; #define REGISTER_TEST(testname) namespace { test_registration tr_(#testname, testname); } #endif
[ "danielearwicker@ubuntu.(none)", "[email protected]" ]
[ [ [ 1, 43 ], [ 52, 56 ], [ 58, 58 ], [ 61, 64 ], [ 110, 115 ] ], [ [ 44, 51 ], [ 57, 57 ], [ 59, 60 ], [ 65, 109 ] ] ]
cf9ff90cd0cbd6e3feb94db253b581d5179d2e09
016774685beb74919bb4245d4d626708228e745e
/lib/Collide/ozcollide/aabbtreepoly_builder.cpp
762d4c009a62505354108dfc6871792c6f7dc1ac
[]
no_license
sutuglon/Motor
10ec08954d45565675c9b53f642f52f404cb5d4d
16f667b181b1516dc83adc0710f8f5a63b00cc75
refs/heads/master
2020-12-24T16:59:23.348677
2011-12-20T20:44:19
2011-12-20T20:44:19
1,925,770
1
0
null
null
null
null
UTF-8
C++
false
false
10,365
cpp
/* OZCollide - Collision Detection Library Copyright (C) 2006 Igor Kravtchenko This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact the author: [email protected] */ #include <ozcollide/ozcollide.h> #ifndef OZCOLLIDE_PCH #include <ozcollide/aabbtreepoly_builder.h> #include <ozcollide/aabbtree_poly.h> #include <ozcollide/monitor.h> #endif ENTER_NAMESPACE_OZCOLLIDE AABBTreePolyBuilder::AABBTreePolyBuilder() { } AABBTreePolyBuilder::~AABBTreePolyBuilder() { } AABBTreePoly* AABBTreePolyBuilder::buildFromPolys(const Polygon *_pols, int _nbPolys, const Vec3f *_points, int _nbPoints, int _leafDepth, Monitor *_moni) { int i; tree_ = new AABBTreePoly(_leafDepth); tree_->points_ = new Vec3f[_nbPoints]; tree_->nbPoints_ = _nbPoints; for (i = 0; i < _nbPoints; i++) tree_->points_[i] = _points[i]; WorkingItem *item = new WorkingItem(); for (i = 0; i < _nbPolys; i++) item->pols.add( (Polygon*) &_pols[i]); item->left = -1; item->right = -1; items_.add(item); int off = 0; while(true) { WorkingItem &it = *items_[off]; workOnItem(it, _leafDepth); off++; int size = items_.size(); if (off == size) break; } build(_moni); delete item; return tree_; } void AABBTreePolyBuilder::build(Monitor *_moni) { int i, j; // Now we have a bastard working tree, let's build the final clean one... int *ln = new int[items_.size()]; int nbNodes = 0; int nbLeafs = 0; for (i = 0; i < items_.size(); i++) { WorkingItem &it = *items_[i]; if (it.left == -1 && it.right == -1) ln[i] = nbLeafs++; else ln[i] = nbNodes++; } tree_->root_ = new AABBTreeNode[nbNodes]; tree_->leafs_ = new AABBTreePolygonLeaf[nbLeafs]; tree_->nbNodes_ = nbNodes; tree_->nbLeafs_ = nbLeafs; if (_moni) _moni->write("Building the final clean tree"); for (i = 0; i < items_.size(); i++) { if (_moni) _moni->setProgress(i, items_.size()); WorkingItem &it = *items_[i]; if (it.left == -1 && it.right == -1) { int indexLeaf = ln[i]; AABBTreePolygonLeaf *pl = (AABBTreePolygonLeaf*) tree_->leafs_; pl += indexLeaf; pl->aabb = it.aabb; pl->left = NULL; pl->right = NULL; int nbPols = it.pols.size(); pl->nbPolys = nbPols; pl->polys = new Polygon[nbPols]; for (j = 0; j < nbPols; j++) { Polygon *pol = (Polygon*) &pl->polys[j]; it.pols[j]->copyTo(*pol); } } else { int nodeIndex = ln[i]; AABBTreeNode *pn = &tree_->root_[nodeIndex]; pn->aabb = it.aabb; if (it.left != -1) { WorkingItem *item = items_[it.left]; if (item->left == -1 && item->right == -1) { AABBTreePolygonLeaf *pl = (AABBTreePolygonLeaf*) tree_->leafs_; pn->left = pl + ln[it.left]; } else { pn->left = tree_->root_ + ln[it.left]; } } else pn->left = NULL; if (it.right != -1) { WorkingItem *item = items_[it.right]; if (item->left == -1 && item->right == -1) { AABBTreePolygonLeaf *pl = (AABBTreePolygonLeaf*) tree_->leafs_; pn->right = pl + ln[it.right]; } else { pn->right = tree_->root_ + ln[it.right]; } } else pn->right = NULL; } } if (_moni) _moni->write("Freeing temporary buffer"); delete [] ln; items_.clear(); if (_moni) _moni->write("Done."); } void AABBTreePolyBuilder::workOnItem(WorkingItem &_item, int _leafDepth) { int i, j; int size = _item.pols.size(); if (size <= _leafDepth) { _item.left = -1; _item.right = -1; return; } int axis; float middle; int nbPols = _item.pols.size(); Vec3f min, max; min = Vec3f(FLT_MAX, FLT_MAX, FLT_MAX); max = -min; for (i = 0; i < nbPols; i++) { Polygon &pol = *_item.pols[i]; int nbVerts = pol.getNbIndices(); for (j = 0; j < nbVerts; j++) { int index = pol.getIndex(j); Vec3f &pt = tree_->points_[index]; if (pt.x < min.x) min.x = pt.x; if (pt.y < min.y) min.y = pt.y; if (pt.z < min.z) min.z = pt.z; if (pt.x > max.x) max.x = pt.x; if (pt.y > max.y) max.y = pt.y; if (pt.z > max.z) max.z = pt.z; } } _item.aabb.center = (min + max) / 2; _item.aabb.extent = (max - min) / 2; const Vec3f &center = _item.aabb.center; const Vec3f &ext = _item.aabb.extent; if (ext.x > ext.y && ext.x > ext.z) axis = 0; else { if (ext.y > ext.z) axis = 1; else axis = 2; } middle = calculAvgPoint(_item, axis); Vec3f bboxMin = center - ext; Vec3f bboxMax = center + ext; WorkingItem *left = NULL; WorkingItem *right = NULL; for (i = 0; i < nbPols; i++) { Polygon *pol = _item.pols[i]; float min, max; int res = classifyPol(*pol, axis, middle, min, max); if (res == 0) { if (!left) { left = new WorkingItem(); Box &box = left->aabb; if (axis == 0) box.setFromPoints(bboxMin, Vec3f((bboxMin.x + bboxMax.x) / 2.0f, bboxMax.y, bboxMax.z)); else if (axis == 1) box.setFromPoints(bboxMin, Vec3f(bboxMax.x, (bboxMin.y + bboxMax.y) / 2.0f, bboxMax.z)); else if (axis == 2) box.setFromPoints(bboxMin, Vec3f(bboxMax.x, bboxMax.y, (bboxMin.z + bboxMax.z) / 2.0f)); } Box &box = left->aabb; if (axis == 0 && max > (box.center.x + box.extent.x) ) box.setFromPoints(bboxMin, Vec3f(max, bboxMax.y, bboxMax.z)); else if (axis == 1 && max > (box.center.y + box.extent.y) ) box.setFromPoints(bboxMin, Vec3f(bboxMax.x, max, bboxMax.z)); else if (axis == 2 && max > (box.center.z + box.extent.z) ) box.setFromPoints(bboxMin, Vec3f(bboxMax.x, bboxMax.y, max)); left->pols.add(pol); } else { // res = 1 if (!right) { right = new WorkingItem(); Box &box = right->aabb; if (axis == 0) box.setFromPoints(Vec3f((bboxMin.x + bboxMax.x) / 2.0f, bboxMin.y, bboxMin.z), bboxMax); else if (axis == 1) box.setFromPoints(Vec3f(bboxMin.x, (bboxMin.y + bboxMax.y) / 2.0f, bboxMin.z), bboxMax); else if (axis == 2) box.setFromPoints(Vec3f(bboxMin.x, bboxMin.y, (bboxMin.z + bboxMax.z) / 2.0f), bboxMax); } Box &box = right->aabb; if (axis == 0 && min < (box.center.x - box.extent.x) ) box.setFromPoints(Vec3f(min, bboxMin.y, bboxMin.z), bboxMax); else if (axis == 1 && min < (box.center.y - box.extent.y) ) box.setFromPoints(Vec3f(bboxMin.x, min, bboxMin.z), bboxMax); else if (axis == 2 && min < (box.center.z - box.extent.z) ) box.setFromPoints(Vec3f(bboxMin.x, bboxMin.y, min), bboxMax); right->pols.add(pol); } } if ((left && !right) || (!left && right)) { if (left && !right) { right = new WorkingItem(); right->aabb = left->aabb; int nbPols = left->pols.size(); int le = nbPols / 2; int start = nbPols - le; for (i = start; i < nbPols; i++) { Polygon *p = left->pols[i]; right->pols.add(p); } left->pols.grow(-le); } else if (!left && right) { left = new WorkingItem(); left->aabb = right->aabb; int nbPols = right->pols.size(); int le = nbPols / 2; int start = nbPols - le; for (i = start; i < nbPols; i++) { Polygon *p = right->pols[i]; left->pols.add(p); } right->pols.grow(-le); } } if (left) { _item.left = items_.size(); items_.add(left); } else _item.left = -1; if (right) { _item.right = items_.size(); items_.add(right); } else _item.right = -1; } int AABBTreePolyBuilder::classifyPol(const Polygon &_pol, int _axis, float _middle, float &_min, float &_max) { int i; takeMinMax(_pol, _axis, _min, _max); int nbVerts = _pol.getNbIndices(); float m = 0.0f; for (i = 0; i < nbVerts; i++) { int index = _pol.getIndex(i); Vec3f &pt = tree_->points_[index]; if (_axis == 0) m += pt.x; else if (_axis == 1) m += pt.y; else if (_axis == 2) m += pt.z; } m /= nbVerts; if (m < _middle) return 0; return 1; } void AABBTreePolyBuilder::takeMinMax(const Polygon &_pol, int _axis, float &_min, float &_max) { int i; int nbVerts = _pol.getNbIndices(); _min = FLT_MAX; _max = -FLT_MAX; for (i = 0; i < nbVerts; i++) { int index = _pol.getIndex(i); Vec3f &pt = tree_->points_[index]; if (_axis == 0 && pt.x < _min) _min = pt.x; else if (_axis == 1 && pt.y < _min) _min = pt.y; else if (_axis == 2 && pt.z < _min) _min = pt.z; if (_axis == 0 && pt.x > _max) _max = pt.x; else if (_axis == 1 && pt.y > _max) _max = pt.y; else if (_axis == 2 && pt.z > _max) _max = pt.z; } } float AABBTreePolyBuilder::calculAvgPoint(WorkingItem &_item, int _axis) { int i, j; int nb = 0; int nbPols = _item.pols.size(); float m = 0; if (_axis == 0) { for (i = 0; i < nbPols; i++) { Polygon &pol = *_item.pols[i]; int nbVerts = pol.getNbIndices(); nb += nbVerts; for (j = 0; j < nbVerts; j++) { int index = pol.getIndex(j); m += tree_->points_[index].x; } } } else if (_axis == 1) { for (i = 0; i < nbPols; i++) { Polygon &pol = *_item.pols[i]; int nbVerts = pol.getNbIndices(); nb += nbVerts; for (j = 0; j < nbVerts; j++) { int index = pol.getIndex(j); m += tree_->points_[index].y; } } } else if (_axis == 2) { for (i = 0; i < nbPols; i++) { Polygon &pol = *_item.pols[i]; int nbVerts = pol.getNbIndices(); nb += nbVerts; for (j = 0; j < nbVerts; j++) { int index = pol.getIndex(j); m += tree_->points_[index].z; } } } return m / float(nb); } LEAVE_NAMESPACE
[ [ [ 1, 411 ] ] ]
a60bb5a3c74403f3341ac90624b39c97172583d8
e9cab5c7a673aa4ad1c09c910f4781935fc23b0a
/fuente/plantillas/CListaPos.cpp
8ead3ff5feae9c6e5ffcdc2ae99f164cc9348324
[]
no_license
wiyarmir/itanq
f1baa6e395afc0791f97ee46b8dc080ac01ccdf6
38e651f2f52e73c84feb8db138983542d1294ed2
refs/heads/master
2020-05-07T16:52:34.339355
2011-01-21T21:15:56
2011-01-21T21:15:56
1,276,617
0
0
null
null
null
null
UTF-8
C++
false
false
4,679
cpp
/* * Orellana Ruiz, Guillermo; * 1ºB; Primera Convocatoria; * 2009-06-19 */ template <typename TElem> CListaPos<TElem>::CListaPos() { ini = new TNodo; fin = new TNodo; ultVis = ini; ini->sig = fin; fin->ant = ini; ini->ant = fin->sig = NULL; nEl = ind = 0; } template <typename TElem> CListaPos<TElem>::CListaPos(CListaPos<TElem> &origen) {//Copia de CopiarLista para evitar llamadas recursivas si llamo a la funcion ini = new TNodo; fin = new TNodo; ultVis = ini; ini->sig = fin; fin->ant = ini; ini->ant = fin->sig = NULL; nEl = ind = 0; int l = origen.Longitud(); for (int i = 1; i <= l; i++) { Agregar(i, origen.Consultar(i)); } } template <typename TElem> CListaPos<TElem>::~CListaPos() { TNodo *aux; ultVis = ini; while (ultVis != NULL) { aux = ultVis; ultVis = ultVis->sig; delete aux; } } template<typename TElem> void CListaPos<TElem>::Agregar(int pos, TElem el) { TNodo *nuevo; if (pos >= 1 && pos <= nEl + 1) { nuevo = new TNodo; nuevo->elem = el; if (pos == nEl + 1) { ultVis = fin; //Para evitar duplicar codigo } else { iEsimo(pos); } ultVis->ant->sig = nuevo; nuevo->ant = ultVis->ant; ultVis->ant = nuevo; nuevo->sig = ultVis; ultVis = nuevo; //Actualizo el valor final de ultVis ind = pos; //Y pos también nEl++; } } template<typename TElem> TElem CListaPos<TElem>::Consultar(int pos) { if (pos >= 1 && pos <= nEl) { iEsimo(pos); return (ultVis->elem); } } template<typename TElem> void CListaPos<TElem>::Borrar(int pos) { TNodo *aux; iEsimo(pos); aux = ultVis->sig; ultVis->ant->sig = ultVis->sig; ultVis->sig->ant = ultVis->ant; delete ultVis; ultVis = aux; nEl--; if (ultVis == fin) { ultVis = fin->ant; ind = nEl; } } template<typename TElem> void CListaPos<TElem>::Vaciar() { if (nEl > 0) { while (ini->sig != fin) { ultVis = ini; ini = ini->sig; delete ultVis; } nEl = 0; ultVis = ini; ind = 0; } } template<typename TElem> bool CListaPos<TElem>::esVacia() { return (nEl == 0); } template<typename TElem> int CListaPos<TElem>::Longitud() { return nEl; } //MÉTODOS PRIVADOS template<typename TElem> void CListaPos<TElem>::iEsimo(int n) { int paso, dir; if (n >= 1 && n <= nEl + 1) { if (n != ind) { //Si preguntáramos por el índice actual de ultVis, ya estamos dir = menorDist(n); switch (dir) { case 0: //Inicio hacia delante ultVis = ini->sig; paso = 1; ind = 1; break; case 1: //ultVis hacia atrás paso = -1; break; case 2: //ultVis hacia delante paso = 1; break; case 3: //Fin hacia atrás ultVis = fin->ant; paso = -1; ind = nEl; break; } if (paso == 1) { //Hacia delante while (ind < n) { ultVis = ultVis->sig; ind++; } } else { //Hacia detrás while (ind > n) { ultVis = ultVis->ant; ind--; } } } } } template<typename TElem> int CListaPos<TElem>::menorDist(int n) { int m; if (n > ind) {//Si esta desde el ultVis en adelante if (n - ind > nEl - n) { //Si es mas largo desde el ultVis hacia delante que desde el fin //hacia detrás m = 3; //Fin hacia atrás } else { m = 2; //ultVis hacia delante } } else {//Esta del ultVis hacia atras if (ind - n > n) {//Si distancia desde ultVis hacia atras es mayor que desde inicio hacia //delante m = 0; //Inicio hacia delante } else { m = 1; //ultVis hacia atrás } } return m; } template<typename TElem> void CListaPos<TElem>::CopiarLista(CListaPos<TElem> origen) { Vaciar(); int l = origen.Longitud(); for (int i = 1; i <= l; i++) { Agregar(i, origen.Consultar(i)); } }
[ [ [ 1, 182 ] ] ]
734beab03e768210c98b376f41ce7c46668d061a
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGameNeedle/GameNeedleComponent/include/GameNeedleComponent.h
44f550c0b762759accd5575b5ca1a40604345fcb
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
656
h
#ifndef __Orz_GameNeedleComponent__ #define __Orz_GameNeedleComponent__ namespace Ogre { class SceneNode; } class SubEntityMaterialInstance; namespace Orz { class CGameNeedleInterface; class GameNeedleComponent: public Component//ÄÚȦ¼ýÍ· { public : GameNeedleComponent(void); virtual ~GameNeedleComponent(void); private: virtual ComponentInterface * _queryInterface(const TypeInfo & info); void setLeafVisible(bool visible); boost::scoped_ptr<CGameNeedleInterface> _needleInterface; bool load(Ogre::SceneNode * node); ComponentPtr _flowerComp; boost::scoped_ptr<SubEntityMaterialInstance> _semi; }; } #endif
[ [ [ 1, 28 ] ] ]
1adbb3e8ee3dcba81c1e3ce4dcaa32b9fafb380c
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/console/Console_run_2.cpp
fbc8ffa4a220333c8502d1ee60c909d9bc64647a
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,670
cpp
#include <iostream> #include <fstream> #include <console/Console_logger.h> #include <console/Console_run_2.h> //#include "Structure_2.h" #include <gui/app/static/Application_settings.h> #include <gui/app/Settings_table_model.h> #include <constants.h> Console_run_2::Console_run_2(int argc, char* argv[]) : Console_run(argc, argv) { } void Console_run_2::do_processing() { // create empty Structure_2 object // Structure_2 s(0); // load settings char* settingspath = ""; assign_string_parameter_if_exists(argc, argv, "-settings", settingspath); if (QString(settingspath)!="") { // std::cout << "Load settings from: " << settingspath << std::endl; Settings_table_model::load_current_settings(settingspath); } print_settings("p-"); std::cout << std::endl; // open file char* filename = ""; assign_string_parameter_if_exists(argc, argv, "-input", filename); std::fstream infile; infile.open (filename); if (infile.is_open()) { infile.close(); std::cout << "Input file: " << filename << std::endl; // s.load_generic_file(std::string(filename)); } else { std::cout << "Input file could not be opened: " << filename << std::endl; return; } char* outfilename = "out.pstg"; assign_string_parameter_if_exists(argc, argv, "-output", outfilename); std::ofstream outfile; outfile.open(outfilename); // compute set cover std::cout << std::endl << PROGRESS_STATUS << "Stage computation" << std::endl; // s.get_output_aggregate(); std::cout << PROGRESS_DONE << std::endl; // s.print_all_data(outfile); std::cout << "Result written to " << outfilename << std::endl; outfile.close(); }
[ "balint.miklos@localhost" ]
[ [ [ 1, 54 ] ] ]
b1b9227918e42f5839911c37adedaf37ed1e7ddb
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/include/symbian-r6/WFTextUtil.h
a59f457b993d732d92377d5e13b11f99130fdcdd
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,787
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WFTEXTUTIL_H #define WFTEXTUTIL_H #include "arch.h" /** */ class WFTextUtil { public: /** * @param aFileName The path and file name of the file to check for existance * @param aSymbianErrorCode OutParameter Error code from the system, * if any. Otherwise, KErrNone is returned. * @return Returns false if an error occurs. * */ static char *stripPhoneNumberL( const char *src); static char* uint32AsStringL(uint32 num); /** * Convert the TDesC to an UTF-8 char string. */ static char * TDesCToUtf8L(const TDesC& inbuf); static char * TDesCToUtf8LC(const TDesC& inbuf); static HBufC* Utf8Alloc(const char *utf8str); static HBufC* Utf8AllocL(const char *utf8str, int length); static HBufC* Utf8AllocL(const char *utf8str); static HBufC* Utf8AllocLC(const char *utf8str, int length); static HBufC* Utf8AllocLC(const char *utf8str); static HBufC* Utf8ToHBufCL(const char *utf8str); static HBufC* Utf8ToHBufCLC(const char *utf8str); static TInt Utf8ToTDes(const char *utf8str, TDes &outBuf, int length); static TInt Utf8ToTDes(const char *utf8str, TDes &outBuf); #if 0 static TInt Utf8ToTDesL(const char *utf8str, TDes &outBuf); #endif static TBool MatchesResourceStringL(const TDesC &string, TInt resourceId); static char* strsep(char**stringp, const char* delim); ///strdup for Symbian, complete with new (ELeave) and CleanupStack::PushL. static char* strdupL(const char* aSrc); static char* strdupLC(const char* aSrc); ///Duplicate string into a HBufC8. If aSrc == NULL, the function ///will return NULL as well. Note that DupAllocLC will push the ///NULL pointer on the cleanupstack. static HBufC8* DupAllocLC(const char* aSrc); static HBufC8* DupAllocL(const char* aSrc); static HBufC8* DupAlloc(const char* aSrc); /** Analyses a string to see if it fits the pattern <host:port>. * @param arg the string to analyse. * @param host the place where the host name is found after the call. * @param port the return variable for the port part. * @return true if arg was parsed succesfully, false if the arg string * didn't match the pattern. */ static TBool ParseHost(const TDesC8& aArg, TDes8& aHost, TUint& aPort); static TBool ParseHost(const TDesC16& aArg, TDes16& aHost, TUint& aPort); /** * Allocates a character array with a copy of the * data from inbuf. * * BEWARE! The TDes can contain 16bit values, these are * truncated to fit in a 8 bit char! * * It is the responsibility of the caller to deallocate * the character array. */ static char* newTDesDupL(const TDesC16 &inbuf); /** * Same as above, but pushes to cleanup stack. */ static char* newTDesDupLC(const TDesC16& inbuf); static char* newTDesDupL(const TDesC8 &inbuf); static char* newTDesDupLC(const TDesC8& inbuf); static int char2TDes(TDes &dest, const char* src); static int char2HBufC(HBufC *dest, const char* src); ///Allocates a HBufC object and copies the contents from src into ///it using the TDesWiden function. Note that if src == NULL, then ///the function will return NULL as well. Note that AllocLC will ///push the NULL pointer on the ClenaupStack in this case. //@{ static HBufC* AllocLC(const char* src, int length); static HBufC* AllocL(const char* src, int length); static HBufC* AllocLC(const char* src); static HBufC* AllocL(const char* src); static HBufC* Alloc(const char* src); //@} static TBool TDesWiden(TDes16 &aDst, const TDesC8& aSrc); static HBufC8* NarrowLC(const TDesC& aSrc); ///Safely copies the contents of one descriptor into another. ///Beware! If the contents of the source descriptor is longer than ///the maximum length of the destination descriptor, the contents ///will be truncated to fit. ///@param dst the destination descriptor. If it is not large enough /// to hold the contents of the destination descriptor, /// the eventual contents of <code>src</code> will be as /// much of the source descriptor contents as will /// fit, starting at the beginning. ///@param src the source descriptor. ///@return returns EFalse if truncation occured. static TBool TDesCopy(TDes& dst, const TDesC& src); static TBool TDesCopy(TDes8& dst, const TDesC16& src); ///Safely appends the contents of one descriptor to another. ///Beware! If the total contents of the two descriptors is longer than ///the maximum length of the destination descriptor, the contents ///will be truncated to fit. ///@param dst the destination descriptor. If it is not large enough /// to append the contents of the source descriptor, /// the eventual contents of <code>dst</code> will be as /// the original contents plus whatever of the source /// descriptor contents as fit, starting at the beginning. ///@param src the source descriptor. ///@return returns EFalse if truncation occured. static TBool TDesAppend(TDes& dst, const TDesC& src); ///Safely appends the contents of a C-style char string to a ///descriptor. Beware! If the total contents of the descriptor and ///C-string is longer than the maximum length of the destination ///descriptor, the contents will be truncated to fit. ///@param dst the destination descriptor. If it is not large enough /// to append the contents of the C-string, /// the eventual contents of <code>dst</code> will be as /// the original contents plus whatever of the C-string /// contents as fit, starting at the beginning. ///@param src the source C-string. ///@return returns EFalse if truncation occured. static TBool TDesAppend(TDes& dst, const char* src); ///Performs a classic Search-And-Replace. As the source text is ///const, the resuling text is placed in a new HBufC that is ///returned. Ownership of the HBufC is naturally transferred to the ///caller. ///@param aSrc the source text that will be searched. ///@param aSearch the string to search for. ///@param aReplace the string that will be substituted for each /// occurence of aSearch. ///@return a new HBufC with the substitutions performed. static HBufC* SearchAndReplaceL(const TDesC& aSrc, const TDesC& aSearch, const TDesC& aReplace); ///Performs a character based in-place search and replace. ///@param aSrc the string to change. ///@param aSearch the character to replace. ///@param aReplace the character to substitute for each aSearch. static void SearchAndReplace(TDes& aSrc, TChar aSearch, TText aReplace); ///Performs a character based search and replace. The source text ///is constant, so the resulting text will be returned in a new ///HBufC. ///@param aSrc the string to change. ///@param aSearch the character to replace. ///@param aReplace the character to substitute for each aSearch. ///@return a new HBufC containing the processed text. static HBufC* SearchAndReplaceLC(const TDesC& aSrc, TChar aSearch, TText aReplace); static TBool Equal(const char* aLhs, const char* aRhs); static TBool Equal(const TText8* aLhs, const TText8* aRhs); static TBool Equal(const char* aLhs, const TDesC16& aRhs); static TBool Equal(const TText8* aLhs, const TDesC16& aRhs); static TBool Equal(const char* aLhs, const TDesC8& aRhs); static TBool Equal(const TText8* aLhs, const TDesC8& aRhs); static TBool Equal(const TDesC16& aLhs, const TDesC8& aRhs); template<class A, class B> static TBool Equal(const A& aLhs,const B& aRhs) { return Equal(aRhs, aLhs); } template<class T> static TBool Equal(const T& aLhs, const T& aRhs) { return 0 == aLhs.Compare(aRhs); } /** * from mc2. * Not symbian specific, where do i put this type of functions? * Removes whitespace from end of string by overwriting with * zero-termination characters. * @param s The string to trim. */ static void trimEnd(char* s); }; /** * This class template extends the symbian TLex with two functions. */ template<typename TLexType, typename TBufType> class TLexExt : public TLexType { public: /// Constructor template<typename TDesCType> TLexExt(const TDesCType& a) : TLexType(a) {} /** * Calls Inc on the tlex unless at end of string already. * Avoids possible panics. * @param lex The lexer. * @return True if success, false if not possible to inc. */ bool tryInc() { if (!TLexType::Eos()) { TLexType::Inc(); return true; } return false; } protected: //use these functions to access the Val functions in a //type-consistent manner. TInt MyVal(TLexType& aLex, TUint& aVal){ return aLex.Val(aVal, EDecimal);} TInt MyVal(TLexType& aLex, TUint8& aVal){ return aLex.Val(aVal, EDecimal);} TInt MyVal(TLexType& aLex, TUint16& aVal){ return aLex.Val(aVal, EDecimal);} TInt MyVal(TLexType& aLex, TUint32& aVal){ return aLex.Val(aVal, EDecimal);} TInt MyVal(TLexType& aLex, TInt& aVal){ return aLex.Val(aVal); } TInt MyVal(TLexType& aLex, TInt8& aVal){ return aLex.Val(aVal); } TInt MyVal(TLexType& aLex, TInt16& aVal){ return aLex.Val(aVal); } TInt MyVal(TLexType& aLex, TInt32& aVal){ return aLex.Val(aVal); } TInt MyVal(TLexType& aLex, TInt64& aVal){ return aLex.Val(aVal); } public: /** * Reads the next value from the lexer. * @param lex The lexer. * @param val The variable that will hold the new value. * @param debugMess The debugMessage to display if anything fails. * @param tryinc If true, a call to tryInc is made after trying * to read the value. * @return True if ok, false if not. */ template<typename integerType> bool readNextVal(integerType& val, const char* debugMess, bool tryinc) { bool result = false; TLexType::Mark(); TLexType::SkipCharacters(); if (TLexType::TokenLength() > 0) { TBufType b(TLexType::MarkedToken()); TLexType l(b); integerType tempVal = 0; TInt err = MyVal(l, tempVal); val = tempVal; if (err != KErrNone) { return result; } else { result = true; } } if (tryinc) { tryInc(); } return result; } }; typedef TLexExt<TLex16, TBuf16<100> > TLexExt16; typedef TLexExt<TLex8, TBuf8<100> > TLexExt8; #if defined(_UNICODE) typedef TLexExt16 TLexExts; #else typedef TLexExt8 TLexExts; #endif #endif
[ [ [ 1, 294 ] ] ]
cdb26c7a21d4abb384a9287630791c6bdb246563
98fdb0e877bf54d799f4503ae3a312c6e0784994
/parSort.cpp
4084994a4d38fbc7c883e7dd4276411c570c0096
[]
no_license
gtg750x/kd-trees
9428ad60dd18c7d3725beb10205084d759ed0e32
96fe36de1b751bde9ebcb1e5bd3488d72b83f6c0
refs/heads/master
2021-01-21T00:11:36.451809
2010-05-04T14:59:14
2010-05-04T14:59:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,547
cpp
#include "parSort.h" #include <math.h> /********************************************************** * sample sort (returns rank) /**********************************************************/ int * sampleSort(float * a, int *index, int n) { int i, j, k, p, start, end, avg, split, * core, * coreCount, * newIndex; float * splitters, * newA; int * rank = (int *)malloc(sizeof(int) * n); #pragma omp parallel shared(a, n, p, avg, splitters, core, coreCount, rank, index) private(i, j, k, start, end, split, newA, newIndex) { /* determine section of array to sort */ p = omp_get_num_threads(); avg = (int)floor((float)n / (float)p); start = (int)omp_get_thread_num() * avg; if (omp_get_thread_num() == (p-1)) { end = n; splitters = (float *)malloc(sizeof(float) * p * p); } else { end = (omp_get_thread_num() + 1) * avg; } #pragma omp barrier //printf("tid %d :: start = %d, end = %d\n", omp_get_thread_num(), start, end); /* conduct sequential sort on "owned" portion */ seqShellSort((a + start), (index + start), (end - start)); /* determine personal splitters and save to shared location */ split = (int)floor((float)(end - start) / (float)p); j = (omp_get_thread_num() + 1) * p - 1; for(i=(end-1); i>start; i-=split) { *(splitters + j) = *(a + i); j--; } #pragma omp barrier if(omp_get_thread_num() == 0) { seqShellSort(splitters, p*p); /*printf("splitters = [%f,", *(splitters + 0)); for(i=1; i<(p*p - 1); i++) { printf("%f, ", *(splitters + i)); } printf("%f]\n", *(splitters + (p*p) - 1));*/ j = 0; for(i=(p-1); i<(p*p); i+=p){ *(splitters + j) = *(splitters + i); j++; } /*printf("splitters = [%f,", *(splitters + 0)); for(i=1; i<(p-1); i++) { printf("%f, ", *(splitters + i)); } printf("%f]\n", *(splitters + p - 1));*/ core = (int *) malloc(sizeof(int)*n); coreCount = (int *) malloc(sizeof(int) * p); for(i=0; i<p; i++) { *(coreCount + i) = 0; } } #pragma omp barrier #pragma omp for for(i=0; i<n; i++) { j = 0; while(*(a + i) > *(splitters + j)) { j++; } *(core + i) = j; } /*if(omp_get_thread_num() == 0) { printf("core = [%d, ", *(core + 0)); for(i=1; i<(n-1); i++) { printf("%d, ", *(core + i)); } printf("%d]\n", *(core + n - 1)); }*/ #pragma omp barrier newA = (float *)malloc(sizeof(float) * 2 * avg); newIndex = (int *)malloc(sizeof(float) * 2 * avg); j = 0; k = omp_get_thread_num(); for(i=0; i<n; i++) { if(*(core + i) == k) { *(newA + j) = *(a + i); *(newIndex + j) = *(index + i); j++; } } *(coreCount + k) = j; /*#pragma omp barrier if(omp_get_thread_num() == 0) { printf("coreCount = [%d, ", *(coreCount + 0)); for(i=1; i<(p-1); i++) { printf("%d, ", *(coreCount + i)); } printf("%d]\n", *(coreCount + p - 1)); }*/ #pragma omp barrier seqShellSort(newA, newIndex, j); start = 0; for(i=0; i<k; i++) { start += *(coreCount + i); } #pragma omp barrier /* each process copies its data items back to the full shared array */ for(i=0; i<j; i++) { *(a + start + i) = *(newA + i); *(index + start + i) = *(newIndex + i); } free(newA); free(newIndex); /** Determine Rank given INDEX array */ #pragma omp barrier #pragma omp for for(i = 0; i<n; i++) { *(rank + *(index + i)) = i; } }// END parallel region return rank; } /********************************************************** * sequential Shell Sorts /**********************************************************/ void seqShellSort(float *a, int *index, int n){ //printf("tid = %d, n = %d\n", omp_get_thread_num(), n); int inc, i, j, k, tempI; float tempF; inc = n/2; while (inc > 0) { for(i=inc; i<n; i++) { tempF = *(a + i); tempI = *(index + i); j = i; while((j >= inc) && (*(a + j - inc) > tempF)) { *(a+j) = *(a + j - inc); *(index + j) = *(index + j - inc); j = j - inc; } *(a + j) = tempF; *(index + j) = tempI; } inc = (int)floor((inc / 2.2) + 0.5); } } void seqShellSort(float *a, int n){ //printf("tid = %d, n = %d\n", omp_get_thread_num(), n); int inc, i, j, k; float tempF; inc = n/2; while (inc > 0) { for(i=inc; i<n; i++) { tempF = *(a + i); j = i; while((j >= inc) && (*(a + j - inc) > tempF)) { *(a+j) = *(a + j - inc); j = j - inc; } *(a + j) = tempF; } inc = (int)floor((inc / 2.2) + 0.5); } }
[ [ [ 1, 185 ] ] ]
1404b0a677e1df61f2eda8fc699280a409a7d8e7
c9390a163ae5f0bc6fdc1560be59939dcbe3eb07
/EffectWnd.cpp
8a9a2503d108f0aebbd203e4992c22d78bf6bd08
[]
no_license
trimpage/multifxvst
2ceae9da1768428288158319fcf03d603ba47672
1cb40f8e0cc873f389f2818b2f40665d2ba2b18b
refs/heads/master
2020-04-06T13:23:41.059632
2010-11-04T14:32:54
2010-11-04T14:32:54
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
15,928
cpp
/*****************************************************************************/ /* EffectWnd.cpp : implementation file */ /*****************************************************************************/ #include "stdafx.h" #include "multifxVST.h" #include "multifxVSTmain.h" #include "CCVSThost.h" #include "MAinDlg.h" #include "vsthost/SmpEffect.h" #include "EffectWnd.h" #include ".\effectwnd.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern class CChainApp theApp; #define GetApp() (&theApp)/*((CChainApp *)AfxGetApp())*/ /*===========================================================================*/ /* CEffectWnd class members */ /*===========================================================================*/ IMPLEMENT_DYNCREATE(CEffectWnd, CDialog) /*****************************************************************************/ /* CEffectWnd : constructor */ /*****************************************************************************/ void CEffectWnd::PostNcDestroy() { // TODO : ajoutez ici votre code spécialisé et/ou l'appel de la classe de base CWnd::PostNcDestroy(); m_hWnd = NULL; APP->pEffEditDlg = NULL; delete this; CString buf;buf.Format("PostNcDestroy :: CEffectWnd(%d) \n", this); TRACE(buf); } CEffectWnd::CEffectWnd(CAppPointer * m_host) { TRACE("CEffectWnd () \n"); APP = m_host; //host = m_host; /*pMain = NULL; pView = NULL;*/ nEffect = -1; rcEffFrame.SetRectEmpty(); rcEffClient.SetRectEmpty(); } /*****************************************************************************/ /* ~CEffectWnd : destructor */ /*****************************************************************************/ CEffectWnd::~CEffectWnd() { CString buf;buf.Format("DESTROY :: CEffectWnd(%d) \n", this); TRACE(buf); } /*****************************************************************************/ /* CEffectWnd message map */ /*****************************************************************************/ BEGIN_MESSAGE_MAP(CEffectWnd, CWnd) //{{AFX_MSG_MAP(CEffectWnd) ON_WM_CLOSE() //ON_COMMAND(IDM_EFF_PROGRAM_NAME, OnEffProgramName) ON_WM_CREATE() ON_WM_SETFOCUS() ON_WM_SIZE() ON_WM_SIZING() //ON_COMMAND(IDM_EFF_EDIT_PARMS, OnEffEditParms) //ON_COMMAND(IDM_EFF_EDIT, OnEffEdit) //ON_UPDATE_COMMAND_UI(IDM_EFF_EDIT, OnUpdateEffEdit) //ON_COMMAND(IDM_EFF_INFO, OnEffInfo) //ON_COMMAND(IDM_EFF_RESIZE, OnEffResize) //ON_COMMAND(IDM_EFF_CHECKSIZE, OnEffChecksize) //ON_COMMAND(IDM_EFF_LOAD, OnEffLoad) //ON_COMMAND(IDM_EFF_SAVE, OnEffSave) //ON_COMMAND(IDM_EFF_SAVEAS, OnEffSaveas) //ON_COMMAND(IDM_EFF_SELPROGRAM, OnEffSelprogram) //ON_UPDATE_COMMAND_UI(IDM_EFF_SELPROGRAM, OnUpdateEffSelprogram) //ON_COMMAND(IDM_SEL_MIDICHN, OnSelMidichn) ON_WM_KEYDOWN() ON_WM_KEYUP() ON_WM_SYSKEYDOWN() ON_WM_SYSKEYUP() //}}AFX_MSG_MAP //ON_COMMAND_RANGE(IDM_EFF_PROGRAM_0, IDM_EFF_PROGRAM_0+999, OnSetProgram) ON_WM_ERASEBKGND() ON_WM_ENTERIDLE() ON_WM_DESTROY() ON_WM_CTLCOLOR() END_MESSAGE_MAP() /*****************************************************************************/ /* OnClose : called when the editor window is closed */ /*****************************************************************************/ void CEffectWnd::FuckEffect() { ASSERT(nEffect >= 0); CSmpEffect *pEffect = (CSmpEffect *)APP->host->GetAt(nEffect); ASSERT(pEffect); if (pEffect) { pEffect->SetEditWnd(NULL); if(pEffect->bEditOpen) { //CTAFTEST //pEffect->EnterCritical(); /* make sure we're not processing */ pEffect->EffEditClose(); //ca yavait //pEffect->LeaveCritical(); /* re-enable processing */ } } CString buf;buf.Format("FuckEffect :: CEffectWnd(%d) \n", this); TRACE(buf); } void CEffectWnd::OnClose() { ShowWindow(FALSE); } /*****************************************************************************/ /* OnCreate : called when the window is created */ /*****************************************************************************/ int CEffectWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; /*if (NeedView()) { pView = CreateView(); if (!pView) { TRACE0("Failed to create view window\n"); return -1; } } SetIcon(RetrieveIcon(), TRUE);*/ return 0; } /*****************************************************************************/ /* OnSetFocus : called when the window receives the input focus */ /*****************************************************************************/ void CEffectWnd::OnSetFocus(CWnd* pOldWnd) { CWnd::OnSetFocus(pOldWnd); /*if (pView) pView->SetFocus();*/ } /*****************************************************************************/ /* GetEffectEditWndSize : calculates the effect window's size */ /*****************************************************************************/ BOOL CEffectWnd::GetEffectEditWndSize(CRect &rcFrame, CRect &rcClient, ERect *pRect) { if (/*(!pView) && */(!pRect)) { CEffect *pEffect = APP->host->GetAt(nEffect); if (!pEffect) return FALSE; pEffect->EffEditGetRect(&pRect); } if (!pRect) return FALSE; rcFrame.SetRect(pRect->left, pRect->top, pRect->right, pRect->bottom); /*rcFrame.bottom += /*::GetSystemMetrics(SM_CYCAPTION) + /*2 * ::GetSystemMetrics(SM_CYBORDER) +*/ /*4*::GetSystemMetrics(SM_CYBORDER);*/ /*rcFrame.right += /*2 * ::GetSystemMetrics(SM_CXFRAME)*/ /*+ 4 * ::GetSystemMetrics(SM_CXBORDER);*/ rcClient.left = rcClient.top = 0; rcClient.right = pRect->right - pRect->left; rcClient.bottom = pRect->bottom - pRect->top; return TRUE; } /*****************************************************************************/ /* SetEffSize : sets the effect size */ /*****************************************************************************/ void CEffectWnd::SetEffSize(ERect *pRect) { GetEffectEditWndSize(rcEffFrame, rcEffClient, pRect); SetWindowPos(&wndTop, 0, 0, rcEffFrame.Width(), rcEffFrame.Height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER); } void CEffectWnd::SetEffSize(int cx, int cy) { CRect rcW; GetWindowRect(&rcW); ERect rc; rc.left = (short)rcW.left; rc.top = (short)rcW.top; rc.right = rc.left + cx; rc.bottom = rc.top + cy; SetEffSize(&rc); } /*****************************************************************************/ /* OnSize : called when the WM_SIZE message comes in */ /*****************************************************************************/ void CEffectWnd::OnSize(UINT nType, int cx, int cy) { //CWnd::OnSize(nType, cx, cy); if((cx != 0)&&(cy != 0)) APP->pMainDlg->ChildNotify(this,cx,cy/*,true*/); } /*****************************************************************************/ /* OnEffChecksize : called to check that the window is not too big now */ /*****************************************************************************/ void CEffectWnd::OnEffChecksize() { //if (!pView) /* if not using our own view */ GetEffectEditWndSize(rcEffFrame, /* get current effect edit size idea */ rcEffClient); CRect rcFrame; GetWindowRect(&rcFrame); int cx = rcFrame.Width(), cy = rcFrame.Height(); int cxmax = rcEffFrame.Width(); int cymax = rcEffFrame.Height(); bool bReset = false; if (cx > rcEffFrame.Width()) { cx = cxmax; bReset = true; } if (cy > cymax) { cy = cymax; bReset = true; } if (bReset) SetWindowPos(&wndTop, 0, 0, cx, cy, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER); } /*****************************************************************************/ /* OnSizing : called when the window is being resized */ /*****************************************************************************/ void CEffectWnd::OnSizing(UINT fwSide, LPRECT pRect) { CWnd::OnSizing(fwSide, pRect); //if (!pView) /* if not using our own view */ GetEffectEditWndSize(rcEffFrame, /* get current effect edit size idea */ rcEffClient); if (pRect->right - pRect->left > rcEffFrame.right - rcEffFrame.left) pRect->right = pRect->left + rcEffFrame.right - rcEffFrame.left; if (pRect->bottom - pRect->top > rcEffFrame.bottom - rcEffFrame.top) pRect->bottom = pRect->top + rcEffFrame.bottom - rcEffFrame.top; } /*****************************************************************************/ /* Update : make sure screen is up-to-date */ /*****************************************************************************/ void CEffectWnd::Update() { // SetupTitle(); Invalidate(FALSE); } /*****************************************************************************/ /* MakeVstKeyCode : converts from Windows to VST */ /*****************************************************************************/ void CEffectWnd::MakeVstKeyCode(UINT nChar, UINT nRepCnt, UINT nFlags, VstKeyCode &keyCode) { #if defined(VST_2_1_EXTENSIONS) static struct { UINT vkWin; unsigned char vstVirt; } VKeys[] = { { VK_BACK, VKEY_BACK }, { VK_TAB, VKEY_TAB }, { VK_CLEAR, VKEY_CLEAR }, { VK_RETURN, VKEY_RETURN }, { VK_PAUSE, VKEY_PAUSE }, { VK_ESCAPE, VKEY_ESCAPE }, { VK_SPACE, VKEY_SPACE }, // { VK_NEXT, VKEY_NEXT }, { VK_END, VKEY_END }, { VK_HOME, VKEY_HOME }, { VK_LEFT, VKEY_LEFT }, { VK_UP, VKEY_UP }, { VK_RIGHT, VKEY_RIGHT }, { VK_DOWN, VKEY_DOWN }, { VK_PRIOR, VKEY_PAGEUP }, { VK_NEXT, VKEY_PAGEDOWN }, { VK_SELECT, VKEY_SELECT }, { VK_PRINT, VKEY_PRINT }, { VK_EXECUTE, VKEY_ENTER }, { VK_SNAPSHOT, VKEY_SNAPSHOT }, { VK_INSERT, VKEY_INSERT }, { VK_DELETE, VKEY_DELETE }, { VK_HELP, VKEY_HELP }, { VK_NUMPAD0, VKEY_NUMPAD0 }, { VK_NUMPAD1, VKEY_NUMPAD1 }, { VK_NUMPAD2, VKEY_NUMPAD2 }, { VK_NUMPAD3, VKEY_NUMPAD3 }, { VK_NUMPAD4, VKEY_NUMPAD4 }, { VK_NUMPAD5, VKEY_NUMPAD5 }, { VK_NUMPAD6, VKEY_NUMPAD6 }, { VK_NUMPAD7, VKEY_NUMPAD7 }, { VK_NUMPAD8, VKEY_NUMPAD8 }, { VK_NUMPAD9, VKEY_NUMPAD9 }, { VK_MULTIPLY, VKEY_MULTIPLY }, { VK_ADD, VKEY_ADD, }, { VK_SEPARATOR, VKEY_SEPARATOR }, { VK_SUBTRACT, VKEY_SUBTRACT }, { VK_DECIMAL, VKEY_DECIMAL }, { VK_DIVIDE, VKEY_DIVIDE }, { VK_F1, VKEY_F1 }, { VK_F2, VKEY_F2 }, { VK_F3, VKEY_F3 }, { VK_F4, VKEY_F4 }, { VK_F5, VKEY_F5 }, { VK_F6, VKEY_F6 }, { VK_F7, VKEY_F7 }, { VK_F8, VKEY_F8 }, { VK_F9, VKEY_F9 }, { VK_F10, VKEY_F10 }, { VK_F11, VKEY_F11 }, { VK_F12, VKEY_F12 }, { VK_NUMLOCK, VKEY_NUMLOCK }, { VK_SCROLL, VKEY_SCROLL }, { VK_SHIFT, VKEY_SHIFT }, { VK_CONTROL, VKEY_CONTROL }, { VK_MENU, VKEY_ALT }, // { VK_EQUALS, VKEY_EQUALS }, }; if ((nChar >= 'A') && (nChar <= 'Z')) keyCode.character = nChar + ('a' - 'A'); else keyCode.character = nChar; keyCode.virt = 0; for (int i = 0; i < (sizeof(VKeys)/sizeof(VKeys[0])); i++) if (nChar == VKeys[i].vkWin) { keyCode.virt = VKeys[i].vstVirt; break; } keyCode.modifier = 0; if (GetKeyState(VK_SHIFT) & 0x8000) keyCode.modifier |= MODIFIER_SHIFT; if (GetKeyState(VK_CONTROL) & 0x8000) keyCode.modifier |= MODIFIER_CONTROL; if (GetKeyState(VK_MENU) & 0x8000) keyCode.modifier |= MODIFIER_ALTERNATE; #endif } /*****************************************************************************/ /* OnKeyDown : called when a key is pressed on the effect window */ /*****************************************************************************/ void CEffectWnd::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { #if defined(VST_2_1_EXTENSIONS) VstKeyCode keyCode; MakeVstKeyCode(nChar, nRepCnt, nFlags, keyCode); if (APP->host->EffKeyDown(nEffect, keyCode) != 1) #endif CWnd::OnKeyDown(nChar, nRepCnt, nFlags); } /*****************************************************************************/ /* OnKeyUp : called when a key is released on the effect window */ /*****************************************************************************/ void CEffectWnd::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { #if defined(VST_2_1_EXTENSIONS) VstKeyCode keyCode; MakeVstKeyCode(nChar, nRepCnt, nFlags, keyCode); if (APP->host->EffKeyUp(nEffect, keyCode) != 1) #endif CWnd::OnKeyUp(nChar, nRepCnt, nFlags); } /*****************************************************************************/ /* OnSysKeyDown : called when a system key is pressed */ /*****************************************************************************/ void CEffectWnd::OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { #if defined(VST_2_1_EXTENSIONS) VstKeyCode keyCode; MakeVstKeyCode(nChar, nRepCnt, nFlags, keyCode); if (APP->host->EffKeyDown(nEffect, keyCode) != 1) #endif CWnd::OnSysKeyDown(nChar, nRepCnt, nFlags); } /*****************************************************************************/ /* OnSysKeyUp : called when a system key is released */ /*****************************************************************************/ void CEffectWnd::OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { #if defined(VST_2_1_EXTENSIONS) VstKeyCode keyCode; MakeVstKeyCode(nChar, nRepCnt, nFlags, keyCode); if (APP->host->EffKeyUp(nEffect, keyCode) != 1) #endif CWnd::OnSysKeyUp(nChar, nRepCnt, nFlags); } BOOL CEffectWnd::OnEraseBkgnd(CDC* pDC) { // TODO : ajoutez ici le code de votre gestionnaire de messages et/ou les paramètres par défaut des appels return FALSE;//de toutes facon il connait pas les erase le plug return CWnd::OnEraseBkgnd(pDC); //return TRUE; } void CEffectWnd::EnterIdle() { if(nEffect == -1)return; CSmpEffect *pEffect = (CSmpEffect *)APP->host->GetAt(nEffect); ASSERT(pEffect); if(pEffect) pEffect->EffEditIdle(); //OutputDebugString("Idle Plug\n"); // TODO : ajoutez ici le code de votre gestionnaire de messages } BOOL CEffectWnd::DestroyWindow() { return CWnd::DestroyWindow(); } void CEffectWnd::OnDestroy() { FuckEffect(); CWnd::OnDestroy(); } static const CBrush br(RGB(175,10,14)); HBRUSH CEffectWnd::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { // TODO : Modifier ici les attributs du DC // TODO : Retourner une autre brosse si la brosse par défaut n'est pas souhaitée return br; }
[ "CTAF@3e78e570-a0aa-6544-9a6b-7e87a0c009bc" ]
[ [ [ 1, 495 ] ] ]
a1de4070d73011a64f186e3d2921bf00b7ded9e8
53dec6da17d4088313d7d14a98fb6a2aed18b5d3
/carbon/1.0/dev/source/common/include/xplat/SessionMgr.h
97791329122759bb5d40d3a434b94a30269460fb
[]
no_license
saurabh1403/carbon-app-management
5ece03894dae1461176757cd3ba73b977287435c
c0b6f4cd31ed0cbd4308b75c5d24cfd83e9dd182
refs/heads/master
2021-01-10T19:02:26.901965
2011-07-31T12:32:39
2011-07-31T12:32:39
35,387,088
0
0
null
null
null
null
UTF-8
C++
false
false
2,508
h
#pragma once #include "Constants.h" //#include "Log.h" #include <list> #include <map> template <class T> class SessionMgr { private: SessionMgr(); ~SessionMgr(); std::map<std::string, T*> _sessions; std::string activeSession; public: //returns the last added session. not of use. instead use the function getSessionWithId with empty string as argument for getting active session T *getActiveSession(void); //if session id is empty, it returns the active session T *getSessionWithId(const std::string &sessId = ""); //it removes active session in case of empty sessId void removeSessionWithId(const std::string &sessId = ""); static SessionMgr<T> &getInstance(void); void removeAllSession(); bool createSession(std::string, T*); void getAllSessions(vector<std::string> &sessIds); //_TODO: it will set the session as active one for the given id bool setSessionAsActive(std::string); }; template <class T> SessionMgr<T>::SessionMgr():activeSession("") { } template <class T> SessionMgr<T>::~SessionMgr() { _sessions.clear(); } template <class T> void SessionMgr<T>::getAllSessions(vector<std::string> &sessIds) { std::map<std::string, T*>::const_iterator itr = _sessions.begin(); for(; itr!= _sessions.end(); itr++) sessIds.push_back(itr->first); } template <class T> SessionMgr<T> & SessionMgr<T>::getInstance(void) { static SessionMgr<T> instance; return instance; } template <class T> T * SessionMgr<T>::getActiveSession(void) { if(activeSession.empty()) return NULL; else return getSessionWithId(activeSession); } template <class T> T *SessionMgr<T>::getSessionWithId(const std::string &sessionId) { std::map<std::string, T*>::const_iterator itr = (sessionId.empty()) ? _sessions.find(activeSession) : _sessions.find(sessionId); return (itr == _sessions.end())? NULL : itr->second; } template <class T> void SessionMgr<T>::removeAllSession() { _sessions.clear(); } template <class T> void SessionMgr<T>::removeSessionWithId(const std::string &sessionId = "") { std::map<std::string, T*>::const_iterator itr = (sessionId.empty()) ? _sessions.find(activeSession) : _sessions.find(sessionId); (itr == _sessions.end())? NULL : _sessions.erase(itr); } template <class T> bool SessionMgr<T>::createSession(std::string sessionId, T* sessionPtr) { _sessions[sessionId] = sessionPtr; activeSession = sessionId; return true; }
[ "saurabhgupta1403@e16f9d33-a4db-0b4f-5d1a-325b24bf4611" ]
[ [ [ 1, 117 ] ] ]
3b4778dc483dde18001ec6d6f9e89c0f85ba7362
871585f3c45603024488cabd14184610af7a081f
/trans_inc_i/library.h
fdf264191106d8826f50f75f29750158d22ced0c
[]
no_license
davideanastasia/ORIP
9ac6fb8c490d64da355d34804d949b85ea17dbff
54c180b442a02a202076b8072ceb573f5e345871
refs/heads/master
2016-09-06T14:17:22.765343
2011-11-05T16:23:23
2011-11-05T16:23:23
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,093
h
/* ORIP_v2 –> Op Ref Im Proc -> Oper Refin Imag Process -> Operational Refinement of Image Processing * * Copyright Davide Anastasia and Yiannis Andreopoulos, University College London * * http://www.ee.ucl.ac.uk/~iandreop/ORIP.html * If you have not retrieved this source code via the above link, please contact [email protected] and [email protected] * */ #ifndef __LIBRARY_H_ #define __LIBRARY_H_ #include <iostream> #include <iomanip> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <cmath> #include "common_lib.h" using namespace std; #define LIMIT ((sizeof(my_t)*8) - 1) typedef long my_t; typedef my_t** matrix; // -- packing --- extern my_t __max_value; extern long __M; // 12 ==> __max value is 2^11 = 2048 extern my_t __inv_eps; // 2^(12) extern long __num_pack; // (12 + )12 + 12 + 12 + 12 = 48 // it should be 5, but 4 is easier for me extern my_t __mask; // -------------- void show_env_status(); void setup_env(matrix coeff_matrix, int size, int bit4bitplane = 1); void setup_env(int size); void setup_block_matrix(matrix input, int size, int max_value); void setup_block_avc(matrix input); void setup_block_bin_dct(matrix input); void setup_block_frext(matrix input); void block_multiply(matrix img, matrix block, int blk_row, int blk_col, matrix result); void block_multiply_t(matrix img, matrix block, int rows, int cols, matrix result); void pack_matrix(matrix* input_b, int elem, matrix output_p, int width, int height); void read_block(matrix img, int img_w, int img_h, matrix block, int blk_w, int blk_h, int n_blk); void write_block(matrix block, int blk_w, int blk_h, matrix img, int img_w, int img_h, int n_blk, int bitplane, int bits); void unpack_matrix_and_store_i(matrix input, matrix* output, int elem, int width, int height); void unpack_matrix_and_store(matrix input, matrix* output, int elem, int width, int height, int bitplane); #endif // __LIBRARY_H_
[ [ [ 1, 59 ] ] ]
82de5a7854fffff07f6e422d14aefda44e8321d4
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
/fbide-wx/Plugins/WebBrowser/webconnect/webframe.h
d2a59678e00fb74094f5098678d03a4a311f93cc
[]
no_license
albeva/fbide-old-svn
4add934982ce1ce95960c9b3859aeaf22477f10b
bde1e72e7e182fabc89452738f7655e3307296f4
refs/heads/master
2021-01-13T10:22:25.921182
2009-11-19T16:50:48
2009-11-19T16:50:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,901
h
/////////////////////////////////////////////////////////////////////////////// // Name: webframe.h // Purpose: wxwebconnect: embedded web browser control library // Author: Benjamin I. Williams // Modified by: // Created: 2007-04-23 // RCS-ID: // Copyright: (C) Copyright 2006-2009, Kirix Corporation, All Rights Reserved. // Licence: wxWindows Library Licence, Version 3.1 /////////////////////////////////////////////////////////////////////////////// #ifndef __WXWEBCONNECT_WEBFRAME_H #define __WXWEBCONNECT_WEBFRAME_H /////////////////////////////////////////////////////////////////////////////// // wxWebFrame class /////////////////////////////////////////////////////////////////////////////// // (CLASS) wxWebFrame // Category: Control // Description: Used for displaying a web browser control in a popup. // Remarks: The wxWebFrame class is used for displaying a web browser control in a popup. // (CONSTRUCTOR) wxWebFrame::wxWebFrame // Description: Creates a new wxWebFrame object. // // Syntax: wxWebFrame::wxWebFrame(wxWindow* parent, // wxWindowID id, // const wxString& title, // const wxPoint& pos = wxDefaultPosition, // const wxSize& size = wxDefaultSize, // long style = wxDEFAULT_FRAME_STYLE); // // Remarks: Creates a new wxWebFrame object. // (METHOD) wxWebFrame::ShouldPreventAppExit // Syntax: bool wxWebFrame::ShouldPreventAppExit() // (METHOD) wxWebFrame::SetShouldPreventAppExit // Syntax: void wxWebFrame::SetShouldPreventAppExit(bool b) class wxWebControl; class wxWebFrame : public wxFrame { public: wxWebFrame(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE); ~wxWebFrame(); wxWebControl* GetWebControl(); bool ShouldPreventAppExit() const { return m_should_prevent_app_exit; } void SetShouldPreventAppExit(bool b) { m_should_prevent_app_exit = b; } private: wxWebControl* m_ctrl; bool m_should_prevent_app_exit; DECLARE_EVENT_TABLE(); }; /////////////////////////////////////////////////////////////////////////////// // wxWebDialog class /////////////////////////////////////////////////////////////////////////////// // (CLASS) wxWebDialog // Category: Control // Description: Used for displaying a web browser control in a popup. // Remarks: The wxWebDialog class is used for displaying a web browser control in a popup. // (CONSTRUCTOR) wxWebDialog::wxWebDialog // Description: Creates a new wxWebDialog object. // // Syntax: wxWebDialog::wxWebDialog(wxWindow* parent, // wxWindowID id, // const wxString& title, // const wxPoint& pos = wxDefaultPosition, // const wxSize& size = wxDefaultSize, // long style = wxDEFAULT_DIALOG_STYLE); // // Remarks: Creates a new wxWebDialog object. // (METHOD) wxWebDialog::GetWebControl // Syntax: wxWebControl* wxWebDialog::GetWebControl() class wxWebDialog : public wxDialog { public: wxWebDialog(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE); ~wxWebDialog(); wxWebControl* GetWebControl(); private: wxWebControl* m_ctrl; DECLARE_EVENT_TABLE(); }; #endif
[ "vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7" ]
[ [ [ 1, 125 ] ] ]
27760ce1bbb4de3340a751340752ff8f0fccf0fd
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-04-24/cvpcb/listlib.cpp
3af45e2f60868e8474bdb4d481a9fd7af0f90de7
[]
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
WINDOWS-1252
C++
false
false
6,421
cpp
/**************/ /* listlib.cpp */ /**************/ /* cherche toutes les ref <chemin lib>*.??? si nom fichier pr‚sent, ou examine <chemin lib>[MODULE.LIB] */ #include "fctsys.h" #include "wxstruct.h" #include "common.h" #include "cvpcb.h" #include "protos.h" FILE *name_libmodules ; /* pour lecture librairie */ /* routines locales : */ static void ReadDocLib(const wxString & ModLibName ); static int LibCompare(void * mod1, void * mod2); static STOREMOD * TriListeModules(STOREMOD * BaseListe, int nbitems); /**/ /*********************/ int listlib(void) /*********************/ /* Routine lisant la liste des librairies, et generant la liste chainee des modules disponibles Module descr format: $MODULE c64acmd Li c64acmd Cd Connecteur DIN Europe 96 Contacts AC male droit Kw CONN DIN $EndMODULE */ { char buffer[1024]; wxString FullLibName; int errorlevel = 0, end; int flag_librairie; STOREMOD * ItemLib; unsigned ii; wxString msg; if( BaseListePkg ) /* Liste Deja existante, a supprimer */ { FreeMemoryModules(); BaseListePkg = NULL; } if ( g_LibName_List.GetCount() == 0 ) return -4; /* init recherche */ SetRealLibraryPath( wxT("modules")); nblib = 0; /* Lecture des Librairies */ for( ii= 0 ; ii < g_LibName_List.GetCount(); ii++) { /* Calcul du nom complet de la librairie */ FullLibName = MakeFileName(g_RealLibDirBuffer, g_LibName_List[ii], LibExtBuffer); /* acces a une librairie */ if ((name_libmodules = wxFopen(FullLibName, wxT("rt"))) == NULL ) { msg.Printf( _("Library file <%s> not found"),FullLibName.GetData()); DisplayError(NULL, msg, 20); continue; } /* Controle du type de la librairie : */ flag_librairie = 0; fgets(buffer,32,name_libmodules) ; if( strncmp(buffer,ENTETE_LIBRAIRIE,L_ENTETE_LIB) != 0 ) { msg.Printf(_("Library file <%s> is not a module library"), FullLibName.GetData()); DisplayError(NULL, msg, 20); fclose(name_libmodules); continue; } /* Lecture du nombre de composants */ fseek(name_libmodules,0,0) ; /* lecture nom des composants : */ end = 0; while( !end && fgets(buffer,255,name_libmodules) != NULL ) { if(strnicmp(buffer,"$INDEX",6) == 0 ) { while( fgets(buffer,255,name_libmodules) != NULL ) { if(strnicmp(buffer,"$EndINDEX",6) == 0 ) { end = 1; break; } ItemLib = new STOREMOD(); ItemLib->Pnext = BaseListePkg; BaseListePkg = ItemLib; ItemLib->m_Module = CONV_FROM_UTF8(StrPurge(buffer)); ItemLib->m_LibName = FullLibName; nblib++; } if( !end ) errorlevel = -3; } } fclose(name_libmodules); ReadDocLib(FullLibName ); } /* classement alphabetique: */ if( BaseListePkg ) BaseListePkg = TriListeModules(BaseListePkg, nblib); return(errorlevel) ; } /************************************************/ static int LibCompare(void * mod1, void * mod2) /************************************************/ /* routine compare() pour qsort() en classement alphabétique des modules */ { int ii; STOREMOD *pt1 , *pt2; pt1 = * ((STOREMOD**)mod1); pt2 = * ((STOREMOD**)mod2); ii = StrNumICmp( pt1->m_Module.GetData(), pt2->m_Module.GetData() ); return(ii); } /********************************************************************/ static STOREMOD * TriListeModules(STOREMOD * BaseListe, int nbitems) /********************************************************************/ /* Tri la liste des Modules par ordre alphabetique et met a jour le nouveau chainage avant/arriere retourne un pointeur sur le 1er element de la liste */ { STOREMOD ** bufferptr, * Item; int ii, nb; if (nbitems <= 0 ) return(NULL); if ( BaseListe == NULL ) return(NULL); if (nbitems == 1 ) return(BaseListe); // Tri inutile et impossible bufferptr = (STOREMOD**)MyZMalloc( (nbitems+3) * sizeof(STOREMOD*) ); for( ii = 1, nb = 0, Item = BaseListe; Item != NULL; Item = Item->Pnext, ii++) { nb++; bufferptr[ii] = Item; } /* ici bufferptr[0] = NULL et bufferptr[nbitem+1] = NULL et ces 2 valeurs representent le chainage arriere du 1er element ( = NULL), et le chainage avant du dernier element ( = NULL ) */ qsort(bufferptr+1,nb,sizeof(STOREMOD*), (int(*)(const void*,const void*))LibCompare) ; /* Mise a jour du chainage */ for( ii = 1; ii <= nb; ii++ ) { Item = bufferptr[ii]; Item->m_Num = ii; Item->Pnext = bufferptr[ii+1]; Item->Pback = bufferptr[ii-1]; } Item = bufferptr[1]; MyFree(bufferptr); return(Item); } /***************************************************/ static void ReadDocLib(const wxString & ModLibName ) /***************************************************/ /* Routine de lecture du fichier Doc associe a la librairie ModLibName. Cree en memoire la chaine liste des docs pointee par MList ModLibName = full file Name de la librairie Modules */ { STOREMOD * NewMod; char Line[1024]; wxString ModuleName; wxString docfilename; FILE * LibDoc; docfilename = ModLibName; ChangeFileNameExt(docfilename, EXT_DOC); if( (LibDoc = wxFopen(docfilename, wxT("rt"))) == NULL ) return; GetLine(LibDoc, Line, NULL, sizeof(Line) -1); if(strnicmp( Line,ENTETE_LIBDOC, L_ENTETE_LIB) != 0) return; /* Lecture de la librairie */ while( GetLine(LibDoc,Line, NULL, sizeof(Line) -1) ) { NewMod = NULL; if( Line[0] != '$' ) continue; if( Line[1] == 'E' ) break;; if( Line[1] == 'M' ) /* Debut decription 1 module */ { while( GetLine(LibDoc,Line, NULL, sizeof(Line) -1) ) { if( Line[0] == '$' ) /* $EndMODULE */ break; switch( Line[0] ) { case 'L': /* LibName */ ModuleName = CONV_FROM_UTF8(StrPurge(Line+3)); NewMod = BaseListePkg; while ( NewMod ) { if( ModuleName == NewMod->m_Module ) break; NewMod = NewMod->Pnext; } break; case 'K': /* KeyWords */ if( NewMod && (! NewMod->m_KeyWord) ) NewMod->m_KeyWord = CONV_FROM_UTF8(StrPurge(Line+3) ); break; case 'C': /* Doc */ if( NewMod && (! NewMod->m_Doc ) ) NewMod->m_Doc = CONV_FROM_UTF8(StrPurge(Line+3) ); break; } } } /* lecture 1 descr module */ } /* Fin lecture librairie */ fclose(LibDoc); }
[ "fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 250 ] ] ]
abeb5c63784efb359b0c77b1fbb84f0340a9b8cd
8f9358761aca3ef7c1069175ec1d18f009b81a61
/CPP/xCalc/src/qextserialport/qserialprinter.h
81c2b1c67822b30100316d6070c26191e86c9223
[]
no_license
porfirioribeiro/resplacecode
681d04151558445ed51c3c11f0ec9b7c626eba25
c4c68ee40c0182bd7ce07a4c059300a0dfd62df4
refs/heads/master
2021-01-19T10:02:34.527605
2009-10-23T10:14:15
2009-10-23T10:14:15
32,256,450
0
0
null
null
null
null
UTF-8
C++
false
false
407
h
#ifndef QSERIALPRINTER_H #define QSERIALPRINTER_H #include <QtCore> #include "qextserialport.h" class QSerialPrinter { public: QextSerialPort *port; QSerialPrinter(); QSerialPrinter(const QString & name); void close(); void print(QString str); void println(QString str); void println(); void openDrawer(QString sequence); }; #endif // QSERIALPRINTER_H
[ "porfirioribeiro@fe5bbf2e-9c30-0410-a8ad-a51b5c886b2f" ]
[ [ [ 1, 20 ] ] ]
560377677bedd38f014f157391890786a2545e6e
d0478ee5d01a3c0c2d66ddcb04adc3e2f8c40d1d
/include/Box2D/Dynamics/Contacts/b2ContactSolver.cpp
219e9587173b59c5815f2ccb437c4df9b6dace96
[]
no_license
ChadyG/MUGE
dc80d2f99fed24a1e140f58bd45181504373a36b
b02df412d388938d4f4dfc3e5ecc30861d9c6d27
refs/heads/master
2021-01-19T11:03:08.804662
2011-08-30T02:52:52
2011-08-30T02:52:52
564,392
0
0
null
null
null
null
UTF-8
C++
false
false
18,835
cpp
/* * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Dynamics/Contacts/b2ContactSolver.h> #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2World.h> #include <Box2D/Common/b2StackAllocator.h> #define B2_DEBUG_SOLVER 0 b2ContactSolver::b2ContactSolver(b2Contact** contacts, int32 contactCount, b2StackAllocator* allocator, float32 impulseRatio) { m_allocator = allocator; m_constraintCount = contactCount; m_constraints = (b2ContactConstraint*)m_allocator->Allocate(m_constraintCount * sizeof(b2ContactConstraint)); for (int32 i = 0; i < m_constraintCount; ++i) { b2Contact* contact = contacts[i]; b2Fixture* fixtureA = contact->m_fixtureA; b2Fixture* fixtureB = contact->m_fixtureB; b2Shape* shapeA = fixtureA->GetShape(); b2Shape* shapeB = fixtureB->GetShape(); float32 radiusA = shapeA->m_radius; float32 radiusB = shapeB->m_radius; b2Body* bodyA = fixtureA->GetBody(); b2Body* bodyB = fixtureB->GetBody(); b2Manifold* manifold = contact->GetManifold(); float32 friction = b2MixFriction(fixtureA->GetFriction(), fixtureB->GetFriction()); float32 restitution = b2MixRestitution(fixtureA->GetRestitution(), fixtureB->GetRestitution()); b2Vec2 vA = bodyA->m_linearVelocity; b2Vec2 vB = bodyB->m_linearVelocity; float32 wA = bodyA->m_angularVelocity; float32 wB = bodyB->m_angularVelocity; b2Assert(manifold->pointCount > 0); b2WorldManifold worldManifold; worldManifold.Initialize(manifold, bodyA->m_xf, radiusA, bodyB->m_xf, radiusB); b2ContactConstraint* cc = m_constraints + i; cc->bodyA = bodyA; cc->bodyB = bodyB; cc->manifold = manifold; cc->normal = worldManifold.normal; cc->pointCount = manifold->pointCount; cc->friction = friction; cc->localNormal = manifold->localNormal; cc->localPoint = manifold->localPoint; cc->radius = radiusA + radiusB; cc->type = manifold->type; //Conveyor cc->fixtureA = fixtureA; cc->fixtureB = fixtureB; //End Conveyor for (int32 j = 0; j < cc->pointCount; ++j) { b2ManifoldPoint* cp = manifold->points + j; b2ContactConstraintPoint* ccp = cc->points + j; ccp->normalImpulse = impulseRatio * cp->normalImpulse; ccp->tangentImpulse = impulseRatio * cp->tangentImpulse; ccp->localPoint = cp->localPoint; ccp->rA = worldManifold.points[j] - bodyA->m_sweep.c; ccp->rB = worldManifold.points[j] - bodyB->m_sweep.c; float32 rnA = b2Cross(ccp->rA, cc->normal); float32 rnB = b2Cross(ccp->rB, cc->normal); rnA *= rnA; rnB *= rnB; float32 kNormal = bodyA->m_invMass + bodyB->m_invMass + bodyA->m_invI * rnA + bodyB->m_invI * rnB; b2Assert(kNormal > b2_epsilon); ccp->normalMass = 1.0f / kNormal; b2Vec2 tangent = b2Cross(cc->normal, 1.0f); float32 rtA = b2Cross(ccp->rA, tangent); float32 rtB = b2Cross(ccp->rB, tangent); rtA *= rtA; rtB *= rtB; float32 kTangent = bodyA->m_invMass + bodyB->m_invMass + bodyA->m_invI * rtA + bodyB->m_invI * rtB; b2Assert(kTangent > b2_epsilon); ccp->tangentMass = 1.0f / kTangent; // Setup a velocity bias for restitution. ccp->velocityBias = 0.0f; float32 vRel = b2Dot(cc->normal, vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA)); if (vRel < -b2_velocityThreshold) { ccp->velocityBias = -restitution * vRel; } } // If we have two points, then prepare the block solver. if (cc->pointCount == 2) { b2ContactConstraintPoint* ccp1 = cc->points + 0; b2ContactConstraintPoint* ccp2 = cc->points + 1; float32 invMassA = bodyA->m_invMass; float32 invIA = bodyA->m_invI; float32 invMassB = bodyB->m_invMass; float32 invIB = bodyB->m_invI; float32 rn1A = b2Cross(ccp1->rA, cc->normal); float32 rn1B = b2Cross(ccp1->rB, cc->normal); float32 rn2A = b2Cross(ccp2->rA, cc->normal); float32 rn2B = b2Cross(ccp2->rB, cc->normal); float32 k11 = invMassA + invMassB + invIA * rn1A * rn1A + invIB * rn1B * rn1B; float32 k22 = invMassA + invMassB + invIA * rn2A * rn2A + invIB * rn2B * rn2B; float32 k12 = invMassA + invMassB + invIA * rn1A * rn2A + invIB * rn1B * rn2B; // Ensure a reasonable condition number. const float32 k_maxConditionNumber = 100.0f; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { // K is safe to invert. cc->K.col1.Set(k11, k12); cc->K.col2.Set(k12, k22); cc->normalMass = cc->K.GetInverse(); } else { // The constraints are redundant, just use one. // TODO_ERIN use deepest? cc->pointCount = 1; } } } } b2ContactSolver::~b2ContactSolver() { m_allocator->Free(m_constraints); } void b2ContactSolver::WarmStart() { // Warm start. for (int32 i = 0; i < m_constraintCount; ++i) { b2ContactConstraint* c = m_constraints + i; b2Body* bodyA = c->bodyA; b2Body* bodyB = c->bodyB; float32 invMassA = bodyA->m_invMass; float32 invIA = bodyA->m_invI; float32 invMassB = bodyB->m_invMass; float32 invIB = bodyB->m_invI; b2Vec2 normal = c->normal; b2Vec2 tangent = b2Cross(normal, 1.0f); for (int32 j = 0; j < c->pointCount; ++j) { b2ContactConstraintPoint* ccp = c->points + j; b2Vec2 P = ccp->normalImpulse * normal + ccp->tangentImpulse * tangent; bodyA->m_angularVelocity -= invIA * b2Cross(ccp->rA, P); bodyA->m_linearVelocity -= invMassA * P; bodyB->m_angularVelocity += invIB * b2Cross(ccp->rB, P); bodyB->m_linearVelocity += invMassB * P; } } } void b2ContactSolver::SolveVelocityConstraints() { for (int32 i = 0; i < m_constraintCount; ++i) { b2ContactConstraint* c = m_constraints + i; b2Body* bodyA = c->bodyA; b2Body* bodyB = c->bodyB; float32 wA = bodyA->m_angularVelocity; float32 wB = bodyB->m_angularVelocity; b2Vec2 vA = bodyA->m_linearVelocity; b2Vec2 vB = bodyB->m_linearVelocity; float32 invMassA = bodyA->m_invMass; float32 invIA = bodyA->m_invI; float32 invMassB = bodyB->m_invMass; float32 invIB = bodyB->m_invI; b2Vec2 normal = c->normal; b2Vec2 tangent = b2Cross(normal, 1.0f); float32 convspeed1 = c->fixtureA->GetConveyorSpeed(); float32 convspeed2 = c->fixtureB->GetConveyorSpeed(); float32 friction = c->friction; b2Assert(c->pointCount == 1 || c->pointCount == 2); // Solve tangent constraints for (int32 j = 0; j < c->pointCount; ++j) { b2ContactConstraintPoint* ccp = c->points + j; // Relative velocity at contact b2Vec2 dv = vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA); // Compute tangent force float32 vt = b2Dot(dv, tangent); /// Conveyor int flip = (c->manifold->type == b2Manifold::e_faceB ? -1 : 1); vt += convspeed1 * flip; vt -= convspeed2 * flip; /// END Conveyor float32 lambda = ccp->tangentMass * (-vt); // b2Clamp the accumulated force float32 maxFriction = friction * ccp->normalImpulse; float32 newImpulse = b2Clamp(ccp->tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - ccp->tangentImpulse; // Apply contact impulse b2Vec2 P = lambda * tangent; vA -= invMassA * P; wA -= invIA * b2Cross(ccp->rA, P); vB += invMassB * P; wB += invIB * b2Cross(ccp->rB, P); ccp->tangentImpulse = newImpulse; } // Solve normal constraints if (c->pointCount == 1) { b2ContactConstraintPoint* ccp = c->points + 0; // Relative velocity at contact b2Vec2 dv = vB + b2Cross(wB, ccp->rB) - vA - b2Cross(wA, ccp->rA); // Compute normal impulse float32 vn = b2Dot(dv, normal); float32 lambda = -ccp->normalMass * (vn - ccp->velocityBias); // b2Clamp the accumulated impulse float32 newImpulse = b2Max(ccp->normalImpulse + lambda, 0.0f); lambda = newImpulse - ccp->normalImpulse; // Apply contact impulse b2Vec2 P = lambda * normal; vA -= invMassA * P; wA -= invIA * b2Cross(ccp->rA, P); vB += invMassB * P; wB += invIB * b2Cross(ccp->rB, P); ccp->normalImpulse = newImpulse; } else { // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). // Build the mini LCP for this contact patch // // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 // // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) // b = vn_0 - velocityBias // // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid // solution that satisfies the problem is chosen. // // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). // // Substitute: // // x = x' - a // // Plug into above equation: // // vn = A * x + b // = A * (x' - a) + b // = A * x' + b - A * a // = A * x' + b' // b' = b - A * a; b2ContactConstraintPoint* cp1 = c->points + 0; b2ContactConstraintPoint* cp2 = c->points + 1; b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); b2Assert(a.x >= 0.0f && a.y >= 0.0f); // Relative velocity at contact b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); // Compute normal velocity float32 vn1 = b2Dot(dv1, normal); float32 vn2 = b2Dot(dv2, normal); b2Vec2 b; b.x = vn1 - cp1->velocityBias; b.y = vn2 - cp2->velocityBias; b -= b2Mul(c->K, a); const float32 k_errorTol = 1e-3f; B2_NOT_USED(k_errorTol); for (;;) { // // Case 1: vn = 0 // // 0 = A * x' + b' // // Solve for x': // // x' = - inv(A) * b' // b2Vec2 x = - b2Mul(c->normalMass, b); if (x.x >= 0.0f && x.y >= 0.0f) { // Resubstitute for the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; vA -= invMassA * (P1 + P2); wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); vB += invMassB * (P1 + P2); wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 // Postconditions dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); // Compute normal velocity vn1 = b2Dot(dv1, normal); vn2 = b2Dot(dv2, normal); b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); #endif break; } // // Case 2: vn1 = 0 and x2 = 0 // // 0 = a11 * x1' + a12 * 0 + b1' // vn2 = a21 * x1' + a22 * 0 + b2' // x.x = - cp1->normalMass * b.x; x.y = 0.0f; vn1 = 0.0f; vn2 = c->K.col1.y * x.x + b.y; if (x.x >= 0.0f && vn2 >= 0.0f) { // Resubstitute for the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; vA -= invMassA * (P1 + P2); wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); vB += invMassB * (P1 + P2); wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 // Postconditions dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); // Compute normal velocity vn1 = b2Dot(dv1, normal); b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); #endif break; } // // Case 3: vn2 = 0 and x1 = 0 // // vn1 = a11 * 0 + a12 * x2' + b1' // 0 = a21 * 0 + a22 * x2' + b2' // x.x = 0.0f; x.y = - cp2->normalMass * b.y; vn1 = c->K.col2.x * x.y + b.x; vn2 = 0.0f; if (x.y >= 0.0f && vn1 >= 0.0f) { // Resubstitute for the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; vA -= invMassA * (P1 + P2); wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); vB += invMassB * (P1 + P2); wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 // Postconditions dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); // Compute normal velocity vn2 = b2Dot(dv2, normal); b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); #endif break; } // // Case 4: x1 = 0 and x2 = 0 // // vn1 = b1 // vn2 = b2; x.x = 0.0f; x.y = 0.0f; vn1 = b.x; vn2 = b.y; if (vn1 >= 0.0f && vn2 >= 0.0f ) { // Resubstitute for the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; vA -= invMassA * (P1 + P2); wA -= invIA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); vB += invMassB * (P1 + P2); wB += invIB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; cp2->normalImpulse = x.y; break; } // No solution, give up. This is hit sometimes, but it doesn't seem to matter. break; } } bodyA->m_linearVelocity = vA; bodyA->m_angularVelocity = wA; bodyB->m_linearVelocity = vB; bodyB->m_angularVelocity = wB; } } void b2ContactSolver::StoreImpulses() { for (int32 i = 0; i < m_constraintCount; ++i) { b2ContactConstraint* c = m_constraints + i; b2Manifold* m = c->manifold; for (int32 j = 0; j < c->pointCount; ++j) { m->points[j].normalImpulse = c->points[j].normalImpulse; m->points[j].tangentImpulse = c->points[j].tangentImpulse; } } } struct b2PositionSolverManifold { void Initialize(b2ContactConstraint* cc, int32 index) { b2Assert(cc->pointCount > 0); switch (cc->type) { case b2Manifold::e_circles: { b2Vec2 pointA = cc->bodyA->GetWorldPoint(cc->localPoint); b2Vec2 pointB = cc->bodyB->GetWorldPoint(cc->points[0].localPoint); if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) { normal = pointB - pointA; normal.Normalize(); } else { normal.Set(1.0f, 0.0f); } point = 0.5f * (pointA + pointB); separation = b2Dot(pointB - pointA, normal) - cc->radius; } break; case b2Manifold::e_faceA: { normal = cc->bodyA->GetWorldVector(cc->localNormal); b2Vec2 planePoint = cc->bodyA->GetWorldPoint(cc->localPoint); b2Vec2 clipPoint = cc->bodyB->GetWorldPoint(cc->points[index].localPoint); separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; point = clipPoint; } break; case b2Manifold::e_faceB: { normal = cc->bodyB->GetWorldVector(cc->localNormal); b2Vec2 planePoint = cc->bodyB->GetWorldPoint(cc->localPoint); b2Vec2 clipPoint = cc->bodyA->GetWorldPoint(cc->points[index].localPoint); separation = b2Dot(clipPoint - planePoint, normal) - cc->radius; point = clipPoint; // Ensure normal points from A to B normal = -normal; } break; } } b2Vec2 normal; b2Vec2 point; float32 separation; }; // Sequential solver. bool b2ContactSolver::SolvePositionConstraints(float32 baumgarte) { float32 minSeparation = 0.0f; for (int32 i = 0; i < m_constraintCount; ++i) { b2ContactConstraint* c = m_constraints + i; b2Body* bodyA = c->bodyA; b2Body* bodyB = c->bodyB; float32 invMassA = bodyA->m_mass * bodyA->m_invMass; float32 invIA = bodyA->m_mass * bodyA->m_invI; float32 invMassB = bodyB->m_mass * bodyB->m_invMass; float32 invIB = bodyB->m_mass * bodyB->m_invI; // Solve normal constraints for (int32 j = 0; j < c->pointCount; ++j) { b2PositionSolverManifold psm; psm.Initialize(c, j); b2Vec2 normal = psm.normal; b2Vec2 point = psm.point; float32 separation = psm.separation; b2Vec2 rA = point - bodyA->m_sweep.c; b2Vec2 rB = point - bodyB->m_sweep.c; // Track max constraint error. minSeparation = b2Min(minSeparation, separation); // Prevent large corrections and allow slop. float32 C = b2Clamp(baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); // Compute the effective mass. float32 rnA = b2Cross(rA, normal); float32 rnB = b2Cross(rB, normal); float32 K = invMassA + invMassB + invIA * rnA * rnA + invIB * rnB * rnB; // Compute normal impulse float32 impulse = K > 0.0f ? - C / K : 0.0f; b2Vec2 P = impulse * normal; bodyA->m_sweep.c -= invMassA * P; bodyA->m_sweep.a -= invIA * b2Cross(rA, P); bodyA->SynchronizeTransform(); bodyB->m_sweep.c += invMassB * P; bodyB->m_sweep.a += invIB * b2Cross(rB, P); bodyB->SynchronizeTransform(); } } // We can't expect minSpeparation >= -b2_linearSlop because we don't // push the separation above -b2_linearSlop. return minSeparation >= -1.5f * b2_linearSlop; }
[ [ [ 1, 75 ], [ 81, 213 ], [ 216, 229 ], [ 237, 637 ] ], [ [ 76, 80 ], [ 214, 215 ], [ 230, 236 ] ] ]
325273ff620c0131885e254c4e69a8a04e9bce93
9d52dd06680cf4618fc128c84b65408262740397
/ID2204/ID2204_AS1/SendMoreMoney.h
8807074f784d9f629d8f2136fc3b1689180c82cb
[]
no_license
Fercho1992/wangyuhere
bd43d57108d46cdf63c3496b68db016e7766ca23
088cff2286924b2c074f3665ae902522c054ac8a
refs/heads/master
2016-08-12T23:17:23.067134
2010-10-10T11:44:26
2010-10-10T11:44:26
51,190,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,070
h
#pragma once #include <gecode/int.hh> #include <gecode/search.hh> using namespace Gecode; class SendMoreMoney : public Space { protected: IntVarArray l; public: SendMoreMoney(void) : l(*this, 8, 0, 9) { IntVar s(l[0]), e(l[1]), n(l[2]), d(l[3]), m(l[4]), o(l[5]), r(l[6]), y(l[7]); rel(*this, s, IRT_NQ, 0); rel(*this, m, IRT_NQ, 0); distinct(*this, l); IntArgs c(4+4+5); IntVarArgs x(4+4+5); c[0]=1000; c[1]=100; c[2]=10; c[3]=1; x[0]=s; x[1]=e; x[2]=n; x[3]=d; c[4]=1000; c[5]=100; c[6]=10; c[7]=1; x[4]=m; x[5]=o; x[6]=r; x[7]=e; c[8]=-10000; c[9]=-1000; c[10]=-100; c[11]=-10; c[12]=-1; x[8]=m; x[9]=o; x[10]=n; x[11]=e; x[12]=y; linear(*this, c, x, IRT_EQ, 0); branch(*this, l, INT_VAR_SIZE_MIN, INT_VAL_MIN); } SendMoreMoney(bool share, SendMoreMoney& s) : Space(share, s) { l.update(*this, share, s.l); } virtual Space* copy(bool share) { return new SendMoreMoney(share,*this); } void print(void) const { std::cout << l << std::endl; } };
[ "wangyuhere@d95a48d6-0e68-11df-9450-0db692d89755" ]
[ [ [ 1, 37 ] ] ]
c8826321a3c03b0f4b56a9dda5eaed667dd8d559
804e416433c8025d08829a08b5e79fe9443b9889
/src/argss/rpg/rpg_cache.cpp
8bd4c26116e78771dd21ef70612115cc36a07b66
[ "BSD-2-Clause" ]
permissive
cstrahan/argss
e77de08db335d809a482463c761fb8d614e11ba4
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
refs/heads/master
2020-05-20T05:30:48.876372
2010-10-03T23:21:59
2010-10-03T23:21:59
1,682,890
1
0
null
null
null
null
UTF-8
C++
false
false
8,609
cpp
///////////////////////////////////////////////////////////////////////////// // ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf) // 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. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // Headers /////////////////////////////////////////////////////////// #include "argss/rpg/rpg.h" #include "argss/rpg/rpg_cache.h" #include "argss/classes/abitmap.h" #include "argss/classes/arect.h" /////////////////////////////////////////////////////////// // Global Variables /////////////////////////////////////////////////////////// VALUE ARGSS::ARPG::ACache::id; /////////////////////////////////////////////////////////// // ARGSS RPG::Cache module methods /////////////////////////////////////////////////////////// VALUE ARGSS::ARPG::ACache::rload_bitmap(int argc, VALUE* argv, VALUE self) { if (argc > 3) raise_argn(argc, 3); else if (argc < 2) raise_argn(argc, 2); VALUE hue = argv[2]; if (argc == 2) hue = INT2NUM(0); VALUE path = rb_str_concat(rb_str_dup(argv[0]), argv[1]); VALUE cache = rb_iv_get(ARGSS::ARPG::ACache::id, "@cache"); VALUE cache_path; if ((rb_funcall(cache, rb_intern("include?"), 1, path) == Qfalse) || (ARGSS::ABitmap::rdisposedQ(rb_hash_aref(cache, path)) == Qtrue)) { if (RSTRING(argv[0])->len > 0) { cache_path = rb_hash_aset(cache, path, rb_class_new_instance(1, &path, ARGSS::ABitmap::id)); } else { VALUE args[2] = {INT2NUM(32), INT2NUM(32)}; cache_path = rb_hash_aset(cache, path, rb_class_new_instance(2, args, ARGSS::ABitmap::id)); } } else { cache_path = rb_hash_aref(cache, path); } if (hue == INT2NUM(0)) { return cache_path; } else { VALUE key = rb_ary_new3(2, path, hue); VALUE cache_key; if ((rb_funcall(cache, rb_intern("include?"), 1, key) == Qfalse) || (ARGSS::ABitmap::rdisposedQ(rb_hash_aref(cache, key)) == Qtrue)) { cache_key = rb_hash_aset(cache, key, rb_obj_clone(cache_path)); ARGSS::ABitmap::rhue_change(cache_key, hue); } else { cache_key = rb_hash_aref(cache, key); } return cache_key; } } VALUE ARGSS::ARPG::ACache::ranimation(VALUE self, VALUE filename, VALUE hue) { VALUE args[3] = {rb_str_new2("Graphics/Animations/"), filename, hue}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rautotile(VALUE self, VALUE filename) { VALUE args[3] = {rb_str_new2("Graphics/Autotiles/"), filename, INT2NUM(0)}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rbattleback(VALUE self, VALUE filename) { VALUE args[3] = {rb_str_new2("Graphics/Battlebacks/"), filename, INT2NUM(0)}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rbattler(VALUE self, VALUE filename, VALUE hue) { VALUE args[3] = {rb_str_new2("Graphics/Battlers/"), filename, hue}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rcharacter(VALUE self, VALUE filename, VALUE hue) { VALUE args[3] = {rb_str_new2("Graphics/Characters/"), filename, hue}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rfog(VALUE self, VALUE filename, VALUE hue) { VALUE args[3] = {rb_str_new2("Graphics/Fogs/"), filename, hue}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rgameover(VALUE self, VALUE filename) { VALUE args[3] = {rb_str_new2("Graphics/Gameovers/"), filename, INT2NUM(0)}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::ricon(VALUE self, VALUE filename) { VALUE args[3] = {rb_str_new2("Graphics/Icons/"), filename, INT2NUM(0)}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rpanorama(VALUE self, VALUE filename, VALUE hue) { VALUE args[3] = {rb_str_new2("Graphics/Panoramas/"), filename, hue}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rpicture(VALUE self, VALUE filename) { VALUE args[3] = {rb_str_new2("Graphics/Pictures/"), filename, INT2NUM(0)}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rtileset(VALUE self, VALUE filename) { VALUE args[3] = {rb_str_new2("Graphics/Tilesets/"), filename, INT2NUM(0)}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rtitle(VALUE self, VALUE filename) { VALUE args[3] = {rb_str_new2("Graphics/Titles/"), filename, INT2NUM(0)}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rwindowskin(VALUE self, VALUE filename) { VALUE args[3] = {rb_str_new2("Graphics/Windowskins/"), filename, INT2NUM(0)}; return rload_bitmap(3, args, self); } VALUE ARGSS::ARPG::ACache::rtile(VALUE self, VALUE filename, VALUE tile_id, VALUE hue) { VALUE key = rb_ary_new3(3, filename, tile_id, hue); VALUE cache = rb_iv_get(ARGSS::ARPG::ACache::id, "@cache"); VALUE cache_key; if ((rb_funcall(cache, rb_intern("include?"), 1, key) == Qfalse) || (ARGSS::ABitmap::rdisposedQ(rb_hash_aref(cache, key)) == Qtrue)) { VALUE args[2] = {INT2NUM(32), INT2NUM(32)}; cache_key = rb_hash_aset(cache, key, rb_class_new_instance(2, args, ARGSS::ABitmap::id)); double x = (NUM2INT(tile_id) - 384) % 8 * 32; double y = (NUM2INT(tile_id) - 384) / 8 * 32; VALUE rect = ARGSS::ARect::New(x, y, 32, 32); VALUE values[4] = {INT2NUM(0), INT2NUM(0), rtileset(self, filename), rect}; ARGSS::ABitmap::rblt(4, values, cache_key); ARGSS::ABitmap::rhue_change(cache_key, hue); } else { cache_key = rb_hash_aref(cache, key); } return cache_key; } VALUE ARGSS::ARPG::ACache::rclear(VALUE self) { VALUE cache = rb_iv_get(ARGSS::ARPG::ACache::id, "@cache"); VALUE values = rb_funcall(cache, rb_intern("values"), 0); for (int i = 0; i < RARRAY(values)->len; i++) { if (ARGSS::ABitmap::rdisposedQ(rb_ary_entry(values, i)) == Qfalse) { ARGSS::ABitmap::rdispose(rb_ary_entry(values, i)); } } rb_iv_set(ARGSS::ARPG::ACache::id, "@cache", rb_hash_new()); return rb_gc_start(); } /////////////////////////////////////////////////////////// // ARGSS RPG::Cache initialize /////////////////////////////////////////////////////////// void ARGSS::ARPG::ACache::Init() { id = rb_define_module_under(ARGSS::ARPG::id, "Cache"); rb_define_singleton_method(id, "load_bitmap", (rubyfunc)rload_bitmap, -1); rb_define_singleton_method(id, "animation", (rubyfunc)ranimation, 2); rb_define_singleton_method(id, "autotile", (rubyfunc)rautotile, 1); rb_define_singleton_method(id, "battleback", (rubyfunc)rbattleback, 1); rb_define_singleton_method(id, "battler", (rubyfunc)rbattler, 2); rb_define_singleton_method(id, "character", (rubyfunc)rcharacter, 2); rb_define_singleton_method(id, "fog", (rubyfunc)rfog, 2); rb_define_singleton_method(id, "gameover", (rubyfunc)rgameover, 1); rb_define_singleton_method(id, "icon", (rubyfunc)ricon, 1); rb_define_singleton_method(id, "panorama", (rubyfunc)rpanorama, 2); rb_define_singleton_method(id, "picture", (rubyfunc)rpicture, 1); rb_define_singleton_method(id, "tileset", (rubyfunc)rtileset, 1); rb_define_singleton_method(id, "title", (rubyfunc)rtitle, 1); rb_define_singleton_method(id, "windowskin", (rubyfunc)rwindowskin, 1); rb_define_singleton_method(id, "tile", (rubyfunc)rtile, 3); rb_define_singleton_method(id, "clear", (rubyfunc)rclear, 0); rb_iv_set(id, "@cache", rb_hash_new()); }
[ "vgvgf@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda" ]
[ [ [ 1, 182 ] ] ]
14501f0468a933343b38f065deebc5ffe4625b98
30d6818e6f7d4ad459d751226b8e91ab07990ce4
/OSGControl/trunk/OSGControl/CGridListCtrlEx/CGridColumnTraitDateTime.cpp
6e675ab69043be144394268b95c558ecd3a7cf9f
[]
no_license
TenYearsADream/osgkeyframer
cd7052e56d28e459ad6b28fea77a76f4df5d5fe7
f6b8a47827f9869a1d3b99c311ca29c455fead0f
refs/heads/master
2020-05-15T14:59:38.475978
2011-04-20T15:18:38
2011-04-20T15:18:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,370
cpp
#include "stdafx.h" #pragma warning(disable:4100) // unreferenced formal parameter #include "CGridColumnTraitDateTime.h" #include "CGridColumnTraitVisitor.h" #include "CGridListCtrlEx.h" //------------------------------------------------------------------------ //! CGridColumnTraitDateTime - Constructor //------------------------------------------------------------------------ CGridColumnTraitDateTime::CGridColumnTraitDateTime() :m_ParseDateTimeFlags(0) ,m_ParseDateTimeLCID(LOCALE_USER_DEFAULT) ,m_DateTimeCtrlStyle(0) {} //------------------------------------------------------------------------ //! Accept Visitor Pattern //------------------------------------------------------------------------ void CGridColumnTraitDateTime::Accept(CGridColumnTraitVisitor& visitor) { visitor.Visit(*this); } //------------------------------------------------------------------------ //! Set the DateTime format used to display the date //! //! @param strFormat Format string that defines the desired display //------------------------------------------------------------------------ void CGridColumnTraitDateTime::SetFormat(const CString& strFormat) { m_Format = strFormat; } //------------------------------------------------------------------------ //! Get the DateTime format used to display the date //------------------------------------------------------------------------ CString CGridColumnTraitDateTime::GetFormat() const { return m_Format; } //------------------------------------------------------------------------ //! Set the flags for converting the datetime in text format to actual date. //! //! @param dwFlags Flags for locale settings and parsing //! @param lcid Locale ID to use for the conversion //------------------------------------------------------------------------ void CGridColumnTraitDateTime::SetParseDateTime(DWORD dwFlags, LCID lcid) { m_ParseDateTimeFlags = dwFlags; m_ParseDateTimeLCID = lcid; } //------------------------------------------------------------------------ //! Set style used when creating CDataTimeCtrl for cell value editing //! //! @param dwStyle Style flags //------------------------------------------------------------------------ void CGridColumnTraitDateTime::SetStyle(DWORD dwStyle) { m_DateTimeCtrlStyle = dwStyle; } //------------------------------------------------------------------------ //! Get style used when creating CDataTimeCtrl for cell value editing //------------------------------------------------------------------------ DWORD CGridColumnTraitDateTime::GetStyle() const { return m_DateTimeCtrlStyle; } //------------------------------------------------------------------------ //! Create a CDateTimeCtrl as cell value editor //! //! @param owner The list control starting a cell edit //! @param nRow The index of the row //! @param nCol The index of the column //! @param rect The rectangle where the inplace cell value editor should be placed //! @return Pointer to the cell editor to use //------------------------------------------------------------------------ CDateTimeCtrl* CGridColumnTraitDateTime::CreateDateTimeCtrl(CGridListCtrlEx& owner, int nRow, int nCol, const CRect& rect) { // Get the text-style of the cell to edit DWORD dwStyle = m_DateTimeCtrlStyle; HDITEM hd = {0}; hd.mask = HDI_FORMAT; VERIFY( owner.GetHeaderCtrl()->GetItem(nCol, &hd) ); if (hd.fmt & HDF_RIGHT) dwStyle = DTS_RIGHTALIGN; // Create control to edit the cell CDateTimeCtrl* pDateTimeCtrl = new CGridEditorDateTimeCtrl(nRow, nCol); VERIFY( pDateTimeCtrl->Create(WS_CHILD | dwStyle, rect, &owner, 0) ); // Configure font pDateTimeCtrl->SetFont(owner.GetCellFont()); // Configure datetime format if (!m_Format.IsEmpty()) pDateTimeCtrl->SetFormat(m_Format); return pDateTimeCtrl; } //------------------------------------------------------------------------ //! Overrides OnEditBegin() to provide a CDateTimeCtrl cell value editor //! //! @param owner The list control starting edit //! @param nRow The index of the row for the cell to edit //! @param nCol The index of the column for the cell to edit //! @return Pointer to the cell editor to use (NULL if cell edit is not possible) //------------------------------------------------------------------------ CWnd* CGridColumnTraitDateTime::OnEditBegin(CGridListCtrlEx& owner, int nRow, int nCol) { // Convert cell-text to date/time format CString cellText = owner.GetItemText(nRow, nCol); COleDateTime dt; if(dt.ParseDateTime(cellText, m_ParseDateTimeFlags, m_ParseDateTimeLCID)==FALSE) dt.SetDateTime(1970, 1, 1, 0, 0, 0); // Get position of the cell to edit CRect rcItem = GetCellEditRect(owner, nRow, nCol); // Create control to edit the cell CDateTimeCtrl* pDateTimeCtrl = CreateDateTimeCtrl(owner, nRow, nCol, rcItem); VERIFY(pDateTimeCtrl!=NULL); pDateTimeCtrl->SetTime(dt); // Check with the original string CString timeText; pDateTimeCtrl->GetWindowText(timeText); if (cellText!=timeText) { dt.SetDateTime(1970, 1, 1, 0, 0, 0); pDateTimeCtrl->SetTime(dt); } return pDateTimeCtrl; } //------------------------------------------------------------------------ //! Compares two cell values according to specified sort order //! //! @param pszLeftValue Left cell value //! @param pszRightValue Right cell value //! @param bAscending Perform sorting in ascending or descending order //! @return Is left value less than right value (-1) or equal (0) or larger (1) //------------------------------------------------------------------------ int CGridColumnTraitDateTime::OnSortRows(LPCTSTR pszLeftValue, LPCTSTR pszRightValue, bool bAscending) { COleDateTime leftDate; if(leftDate.ParseDateTime(pszLeftValue, m_ParseDateTimeFlags, m_ParseDateTimeLCID)==FALSE) leftDate.SetDateTime(1970, 1, 1, 0, 0, 0); COleDateTime rightDate; if(rightDate.ParseDateTime(pszRightValue, m_ParseDateTimeFlags, m_ParseDateTimeLCID)==FALSE) rightDate.SetDateTime(1970, 1, 1, 0, 0, 0); if (bAscending) return (int)(leftDate - rightDate); else return (int)(rightDate - leftDate); } //------------------------------------------------------------------------ // CGridEditorDateTimeCtrl (For internal use) //------------------------------------------------------------------------ BEGIN_MESSAGE_MAP(CGridEditorDateTimeCtrl, CDateTimeCtrl) //{{AFX_MSG_MAP(CGridEditorDateTimeCtrl) ON_WM_KILLFOCUS() ON_WM_NCDESTROY() ON_NOTIFY_REFLECT(DTN_DATETIMECHANGE, OnDateTimeChange) ON_WM_CHAR() //}}AFX_MSG_MAP END_MESSAGE_MAP() //------------------------------------------------------------------------ //! CGridEditorDateTimeCtrl - Constructor //! //! @param nRow The index of the row //! @param nCol The index of the column //------------------------------------------------------------------------ CGridEditorDateTimeCtrl::CGridEditorDateTimeCtrl(int nRow, int nCol) :m_Row(nRow) ,m_Col(nCol) ,m_Completed(false) ,m_Modified(false) {} //------------------------------------------------------------------------ //! The cell value editor was closed and the entered should be saved. //! //! @param bSuccess Should the entered cell value be saved //------------------------------------------------------------------------ void CGridEditorDateTimeCtrl::EndEdit(bool bSuccess) { // Avoid two messages if key-press is followed by kill-focus if (m_Completed) return; m_Completed = true; // Format time back to string CString str; GetWindowText(str); // Send Notification to parent of ListView ctrl LV_DISPINFO dispinfo = {0}; dispinfo.hdr.hwndFrom = GetParent()->m_hWnd; dispinfo.hdr.idFrom = GetDlgCtrlID(); dispinfo.hdr.code = LVN_ENDLABELEDIT; dispinfo.item.iItem = m_Row; dispinfo.item.iSubItem = m_Col; if (bSuccess && m_Modified) { dispinfo.item.mask = LVIF_TEXT; dispinfo.item.pszText = str.GetBuffer(0); dispinfo.item.cchTextMax = str.GetLength(); } ShowWindow(SW_HIDE); GetParent()->GetParent()->SendMessage( WM_NOTIFY, GetParent()->GetDlgCtrlID(), (LPARAM)&dispinfo ); PostMessage(WM_CLOSE); } //------------------------------------------------------------------------ //! WM_KILLFOCUS message handler called when CDateTimeCtrl is loosing focus //! to other control. Used register that cell value editor should close. //! //! @param pNewWnd Pointer to the window that receives the input focus (may be NULL or may be temporary). //------------------------------------------------------------------------ void CGridEditorDateTimeCtrl::OnKillFocus(CWnd *pNewWnd) { CDateTimeCtrl::OnKillFocus(pNewWnd); if (GetMonthCalCtrl()==NULL) EndEdit(true); } //------------------------------------------------------------------------ //! WM_NCDESTROY message handler called when CDateTimeCtrl window is about to //! be destroyed. Used to delete the inplace CDateTimeCtrl editor object as well. //! This is necessary when the CDateTimeCtrl is created dynamically. //------------------------------------------------------------------------ void CGridEditorDateTimeCtrl::OnNcDestroy() { CDateTimeCtrl::OnNcDestroy(); delete this; } //------------------------------------------------------------------------ //! WM_CHAR message handler to monitor date modifications //! //! @param nChar Specifies the virtual key code of the given key. //! @param nRepCnt Repeat count (the number of times the keystroke is repeated as a result of the user holding down the key). //! @param nFlags Specifies the scan code, key-transition code, previous key state, and context code //------------------------------------------------------------------------ void CGridEditorDateTimeCtrl::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { m_Modified = true; CDateTimeCtrl::OnChar(nChar, nRepCnt, nFlags); } //------------------------------------------------------------------------ //! DTN_DATETIMECHANGE message handler to monitor date modifications //! //! @param pNMHDR Pointer to NMDATETIMECHANGE structure //! @param pResult Must be set to zero //------------------------------------------------------------------------ void CGridEditorDateTimeCtrl::OnDateTimeChange(NMHDR *pNMHDR, LRESULT *pResult) { m_Modified = true; *pResult = 0; } //------------------------------------------------------------------------ //! Hook to proces windows messages before they are dispatched. //! Catch keyboard events that can should cause the cell value editor to close //! //! @param pMsg Points to a MSG structure that contains the message to process //! @return Nonzero if the message was translated and should not be dispatched; 0 if the message was not translated and should be dispatched. //------------------------------------------------------------------------ BOOL CGridEditorDateTimeCtrl::PreTranslateMessage(MSG* pMsg) { switch(pMsg->message) { case WM_KEYDOWN: { switch(pMsg->wParam) { case VK_RETURN: EndEdit(true); return TRUE; case VK_TAB: EndEdit(true); return FALSE; case VK_ESCAPE: EndEdit(false);return TRUE; } break; }; case WM_MOUSEWHEEL: EndEdit(true); return FALSE; // Don't steal event } return CDateTimeCtrl::PreTranslateMessage(pMsg); }
[ "[email protected]@c71c211c-a3f6-341e-745a-b305fdfe3b14" ]
[ [ [ 1, 303 ] ] ]
baa28d54d941f3bc283280bf231457399cb34354
58496be10ead81e2531e995f7d66017ffdfc6897
/Sources/Registry/RegistryModule.cpp
a9bc023c02ca749daebcfc60cf8b7d6231bc422c
[]
no_license
Diego160289/cross-fw
ba36fc6c3e3402b2fff940342315596e0365d9dd
532286667b0fd05c9b7f990945f42279bac74543
refs/heads/master
2021-01-10T19:23:43.622578
2011-01-09T14:54:12
2011-01-09T14:54:12
38,457,864
0
0
null
null
null
null
UTF-8
C++
false
false
508
cpp
//============================================================================ // Date : 22.12.2010 // Author : Tkachenko Dmitry // Copyright : (c) Tkachenko Dmitry ([email protected]) //============================================================================ #include "Module.h" #include "Registry.h" #include "Mutex.h" DECLARE_MODULE_ENTRY_POINT( "Registry", 5631ec27-e1a0-430b-a723-4bf7575f06b5, System::Mutex, TYPE_LIST_1(IRegistryImpl))
[ "TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277" ]
[ [ [ 1, 18 ] ] ]
f2fd92a35b3d8ad7599bba61bca4ba33e5c6aa6a
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/odephysics/nodetrimesh_sphere.cc
ae88adf3f4f7ba617097576a1f608953fff7fe83
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,134
cc
#define N_IMPLEMENTS nOdeTriMesh //-------------------------------------------------------------------- // nodetrimesh_sphere.cc // // (c) 2003 Vadim Macagon // // nOdeTriMesh is licensed under the terms of the Nebula License. //-------------------------------------------------------------------- #include "odephysics/nodetrimesh.h" #include "odephysics/odeutil.h" #include "mathlib/vector.h" #include "mathlib/triangle.h" #include "mathlib/sphere.h" #include "odephysics/ncollisionmath.h" #include "odephysics/nodetrimeshshape.h" //------------------------------------------------------------------------------ /** @brief Compute contact points between a sphere and a triangle mesh. */ int nOdeTriMesh::CollideSphereMesh( dxGeom* triList, dxGeom* sphereGeom, int flags, dContactGeom* contacts, int stride ) { nOdeTriMeshShape* shape = (nOdeTriMeshShape*)dGeomGetData( triList ); nOdeTriMesh* mesh = shape->GetTriMesh(); int retval = 0; // obtain a list of triangles the sphere overlaps // setup sphere collider SphereCollider& collider = nOdeTriMesh::odeServer->opcSphereCollider; //VolumeCollider* colliderPtr = (VolumeCollider*)&collider; SphereCache& cache = nOdeTriMesh::odeServer->opcSphereCache; collider.SetCallback( mesh->collCallback, (udword)mesh ); collider.SetFirstContact( false ); // convert matrix44 to Opcode Matrix4x4 Matrix4x4 opcMeshMatrix; nOdeUtil::GetOpcodeMatrix( triList, &opcMeshMatrix ); // convert opcode matrix to neb matrix matrix44 meshMatrix( &(opcMeshMatrix.m[0][0]) ); // build an Opcode Sphere const dReal* pos = dGeomGetPosition( sphereGeom ); dReal rad = dGeomSphereGetRadius ( sphereGeom ); Point ptCenter( pos[0], pos[1], pos[2] ); const Sphere opcSphere( ptCenter, rad ); // perform collision collider.Collide( cache, opcSphere, &(mesh->opcModel), NULL/* sphere already in world space */, &opcMeshMatrix ); // if some triangles were found if ( collider.GetContactStatus() ) { triangle tri; int triCount = collider.GetNbTouchedPrimitives(); int outTriCount = 0; const udword* collFaces = collider.GetTouchedPrimitives(); // create sphere in world space sphere theSphere( pos[0], pos[1], pos[2], rad ); vector3 v0, v1, v2; vector3 tv0, tv1, tv2; int i; for ( i = 0; i < triCount; i++ ) { // get touched triangle in model space mesh->GetTriCoords( collFaces[i], v0, v1, v2 ); // transform triangle into world space tv0 = meshMatrix * v0; tv1 = meshMatrix * v1; tv2 = meshMatrix * v2; tri.set( tv0, tv1, tv2 ); float u, v, w; if ( !nCollisionMath::IntersectTriSphere( theSphere, tri, 0, &u, &v ) ) { continue; // Sphere doesn't overlap with triangle } w = 1.0f - u - v; // note: plane normal will be reverse of the corresponding triangle's normal // plane will also be normalized plane triPlane( tv0, tv1, tv2 ); vector3 planeNormal = triPlane.normal(); float contactDepth = (planeNormal % theSphere.p) + triPlane.d + theSphere.r; dContactGeom* contact = nOdeUtil::FetchContact( flags, contacts, outTriCount, stride ); // compute & store contact position contact->pos[0] = tv0.x * w + tv1.x * u + tv2.x * v; contact->pos[1] = tv0.y * w + tv1.y * u + tv2.y * v; contact->pos[2] = tv0.z * w + tv1.z * u + tv2.z * v; // using this version undesirable rolling can be avoided // but it introduces other problems //vector3 contactPos = theSphere.p + planeNormal * (theSphere.r - contactDepth); //contact->pos[0] = contactPos.x; //contact->pos[1] = contactPos.y; //contact->pos[2] = contactPos.z; contact->pos[3] = 0.0f; // store contact normal contact->normal[0] = planeNormal.x; contact->normal[1] = planeNormal.y; contact->normal[2] = planeNormal.z; contact->normal[3] = 0.0f; contact->depth = contactDepth; ++outTriCount; } // loop: for each triangle #ifdef MERGECONTACTS if ( outTriCount != 0 ) { /* mutilate everything into one contact point, err, I mean merge :) */ dContactGeom* contact = nOdeUtil::FetchContact( flags, contacts, 0, stride ); for ( i = 1; i < outTriCount; i++ ) { dContactGeom* tempContact = nOdeUtil::FetchContact( flags, contacts, i, stride ); contact->pos[0] += tempContact->pos[0]; contact->pos[1] += tempContact->pos[1]; contact->pos[2] += tempContact->pos[2]; contact->normal[0] += tempContact->normal[0] * contact->depth; contact->normal[1] += tempContact->normal[1] * contact->depth; contact->normal[2] += tempContact->normal[2] * contact->depth; } // average out the contact position contact->pos[0] /= outTriCount; contact->pos[1] /= outTriCount; contact->pos[2] /= outTriCount; // remember to divide in square space. vector3 outNormal( contact->normal[0], contact->normal[1], contact->normal[2] ); contact->depth = n_sqrt( (outNormal % outNormal) / outTriCount ); dNormalize3( contact->normal ); contact->g1 = triList; contact->g2 = sphereGeom; retval = 1; } // if outTriCount != 0 #else for ( i = 0; i < outTriCount; i++ ) { dContactGeom* contact = nOdeUtil::FetchContact( flags, contacts, i, stride ); contact->g1 = triList; contact->g2 = sphereGeom; } retval = outTriCount; #endif // MERGECONTACTS } #ifdef MERGECONTACTS #undef MERGECONTACTS #endif return retval; } //------------------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 171 ] ] ]
4d6e8f45f60c491bcaeb63b8e698c274baed85fc
3bfe835203f793ee00bdf261c26992b1efea69ed
/spring08/cs350/A1/lib/geomlib.h
000aaa5645325a8989a26bc6f72c355940b3f16e
[]
no_license
yxrkt/DigiPen
0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3
e1bb773d15f63c88ab60798f74b2e424bcc80981
refs/heads/master
2020-06-04T20:16:05.727685
2009-11-18T00:26:56
2009-11-18T00:26:56
814,145
1
3
null
null
null
null
WINDOWS-1252
C++
false
false
22,438
h
/////////////////////////////////////////////////////////////////////// // $Id: geomlib.h 1172 2008-01-18 09:05:53Z gherron $ // // Geometric objects (Points, Vectors, Planes, ...) and operations. // // Gary Herron // // Copyright © 2007 DigiPen Institute of Technology //////////////////////////////////////////////////////////////////////// #if !defined(GEOMLIB_HPP_) #define GEOMLIB_HPP_ #if !defined(__cplusplus) #error this header cannot be used outside of a C++ program #endif #include <algorithm> // transform #include <cmath> // sqrt #include <functional> // bind2nd, plus, minus, etc. #include <iostream> #include <numeric> // inner_product #include <sstream> // stringstream #include <utility> // pair // VC7 warning: "C++ exception specification ignored..." #if defined(_MSC_VER) && (1310>= _MSC_VER) #pragma warning(push) #pragma warning(disable: 4290) #endif #define PI (3.14159) struct ZeroDivide {}; // Used to signal divide-by-zero errors // Forward declarations: class Point2D; class Point3D; class Vector2D; class Vector3D; class Vector4D; class Line3D; class Box3D; class Sphere3D; class Plane3D; class Triangle3D; enum ComponentIndex {X, Y, Z, W}; //////////////////////////////////////////////////////////////////////// // Class Color represents a color with a 4-vector of floats for red, // green, blue, and alpha. It supports indexing operations, a Set // method, and several component wise operations. // // There is also a sub-class called HSVColor which provides a // constructor for a Color to be specified via hue, saturation and // value parameters. //////////////////////////////////////////////////////////////////////// class Color { public: Color(const float r=0.0, const float g=0.0, const float b=0.0, const float a=1.0); void Set(float r=0.0, float g=0.0, float b=0.0, float a=1.0); // Random-access operators. float& operator[](unsigned int i) {return rgba[i];}; const float& operator[](unsigned int i) const {return rgba[i];} // Sequential-access methods. typedef float *iterator; typedef const float *const_iterator; iterator begin() { return rgba + 0; } const_iterator begin() const { return rgba + 0; } iterator end() { return rgba + DIM; } const_iterator end() const { return rgba + DIM; } enum {DIM=4}; float rgba[DIM]; }; Color operator+(const Color& C, const Color& D); Color operator*(Color& C, float t); Color operator*(float t, const Color& C); Color operator*(float t, Color& C); Color operator*(Color& C, Color& D); class HSVColor : public Color { public: HSVColor(float h=0.0, float s=0.0, float v=0.0, float a=1.0); }; //////////////////////////////////////////////////////////////////////// // Point2D //////////////////////////////////////////////////////////////////////// class Point2D { public: // Constructor explicit Point2D(float X=0, float Y=0) { crds[0]=X; crds[1]=Y; } // In-place operators. Point2D& operator+=(const Vector2D& rhs); Point2D& operator-=(const Vector2D& rhs); // Random-access operators. float& operator[](unsigned int i) {return crds[i];}; const float& operator[](unsigned int i) const {return crds[i];} // Sequential-access methods. typedef float *iterator; typedef const float *const_iterator; iterator begin() { return crds + 0; } const_iterator begin() const { return crds + 0; } iterator end() { return crds + DIM; } const_iterator end() const { return crds + DIM; } private: enum {DIM=2}; float crds[DIM]; }; // Operators bool operator==(const Point2D& lhs, const Point2D& rhs); bool operator!=(const Point2D& lhs, const Point2D& rhs); // Stream operator template<class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& lhs, const Point2D& rhs) { std::basic_ostringstream<charT, traits> s; s.flags(lhs.flags()); s.imbue(lhs.getloc()); s.precision(lhs.precision()); typename Point2D::const_iterator i = rhs.begin(); s <<'(' <<*i; for(++i; i != rhs.end(); ++i) s <<',' <<*i; s <<')'; return lhs <<s.str(); } //////////////////////////////////////////////////////////////////////// // Vector2D //////////////////////////////////////////////////////////////////////// class Vector2D { public: // Constructor explicit Vector2D(float X=0, float Y=0) { crds[0]=X; crds[1]=Y; }; // In-place operators. Vector2D& operator+=(const Vector2D& rhs); Vector2D& operator-=(const Vector2D& rhs); Vector2D& operator*=(const float& rhs); Vector2D& operator/=(const float& rhs); void normalize() throw(ZeroDivide); // Random-access operators. float& operator[](unsigned int i) { return crds[i]; } const float& operator[](unsigned int i) const { return crds[i]; } // Sequential-access methods. typedef float *iterator; typedef const float *const_iterator; iterator begin() { return crds + 0; }; const_iterator begin() const { return crds + 0; } iterator end() { return crds + DIM; } const_iterator end() const { return crds + DIM; } // Utility methods. float length() const; Vector2D normalized() const throw(ZeroDivide); private: enum {DIM=2}; float crds[DIM]; }; // Operators bool operator==(const Vector2D& lhs, const Vector2D& rhs); bool operator!=(const Vector2D& lhs, const Vector2D& rhs); Vector2D operator+(const Vector2D& lhs, const Vector2D& rhs); Vector2D operator-(const Vector2D& lhs, const Vector2D& rhs); Vector2D operator*(const Vector2D& lhs, const float& rhs); Vector2D operator*(const float& lhs, const Vector2D& rhs); Vector2D operator/(const Vector2D& lhs, const float& rhs); float Dot(const Vector2D& vec1, const Vector2D& vec2); // Point2D/Vector2D operators Point2D operator+(const Point2D& lhs, const Vector2D& rhs); Point2D operator+(const Vector2D& lhs, const Point2D& rhs); Point2D operator-(const Point2D& lhs, const Vector2D& rhs); Vector2D operator-(const Point2D& lhs, const Point2D& rhs); // Stream operator template<class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& lhs, const Vector2D& rhs) { std::basic_ostringstream<charT, traits> s; s.flags(lhs.flags()); s.imbue(lhs.getloc()); s.precision(lhs.precision()); typename Vector2D::const_iterator i = rhs.begin(); s <<'(' <<*i; for(++i; i != rhs.end(); ++i) s <<',' <<*i; s <<')'; return lhs <<s.str(); } //////////////////////////////////////////////////////////////////////// // Line2D //////////////////////////////////////////////////////////////////////// class Line2D { public: // Constructors Line2D() : point(), vector() {return;} Line2D(const Point2D& p, const Vector2D& v): point(p), vector(v) {return;} Point2D point; Vector2D vector; }; // Functions bool Intersects(const Line2D& line1, const Line2D& line2, Point2D *rpoint=0); //////////////////////////////////////////////////////////////////////// // Segment2D //////////////////////////////////////////////////////////////////////// class Segment2D { public: // Constructor Segment2D() : point1(), point2() {return;} Segment2D(const Point2D& p1, const Point2D& p2) : point1(p1), point2(p2) {return;} Point2D point1; Point2D point2; }; // Functions bool Intersects(const Segment2D& seg1, const Segment2D& seg2, Point2D *rpoint=0); //////////////////////////////////////////////////////////////////////// // Point3D //////////////////////////////////////////////////////////////////////// class Point3D { public: // Constructor explicit Point3D(float X=0, float Y=0, float Z=0) { crds[0]=X; crds[1]=Y; crds[2]=Z; }; // In-place operators. Point3D& operator+=(const Vector3D& rhs); Point3D& operator-=(const Vector3D& rhs); // Random-access operators. float& operator[](unsigned int i) {return crds[i];} const float& operator[](unsigned int i) const {return crds[i];} // Sequential-access methods. typedef float *iterator; typedef const float *const_iterator; iterator begin() { return crds + 0; } const_iterator begin() const { return crds + 0; } iterator end() { return crds + DIM; } const_iterator end() const { return crds + DIM; } private: enum {DIM=3}; float crds[DIM]; }; // Operators bool operator==(const Point3D& lhs, const Point3D& rhs); bool operator!=(const Point3D& lhs, const Point3D& rhs); // Utility functions: float Distance(const Point3D& point, const Line3D& line); float Distance(const Point3D& point, const Plane3D& plane); bool Coplanar(const Point3D& A,const Point3D& B, const Point3D& C, const Point3D& D); // Stream operator template<class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& lhs, const Point3D& rhs) { std::basic_ostringstream<charT, traits> s; s.flags(lhs.flags()); s.imbue(lhs.getloc()); s.precision(lhs.precision()); typename Point3D::const_iterator i = rhs.begin(); s <<'(' <<*i; for(++i; i != rhs.end(); ++i) { s <<',' <<*i; } s <<')'; return lhs <<s.str(); } //////////////////////////////////////////////////////////////////////// // Vector3D //////////////////////////////////////////////////////////////////////// class Vector3D { public: // Constructor explicit Vector3D(float X=0, float Y=0, float Z=0) { crds[0]=X; crds[1]=Y; crds[2]=Z; }; // In-place operators. Vector3D& operator+=(const Vector3D& rhs); Vector3D& operator-=(const Vector3D& rhs); Vector3D& operator*=(const float& rhs); Vector3D& operator/=(const float& rhs); void normalize() throw(ZeroDivide); // Random-access operators. float& operator[](unsigned int i) { return crds[i]; } const float& operator[](unsigned int i) const { return crds[i]; } // Utility methods. float length() const; Vector3D normalized() const throw(ZeroDivide); // Sequential-access methods. typedef float *iterator; typedef const float *const_iterator; iterator begin() { return crds + 0; } const_iterator begin() const { return crds + 0; } iterator end() { return crds + DIM; } const_iterator end() const { return crds + DIM; } private: enum {DIM=3}; float crds[DIM]; }; // Operators bool operator==(const Vector3D& lhs, const Vector3D& rhs); bool operator!=(const Vector3D& lhs, const Vector3D& rhs); Vector3D operator+(const Vector3D& lhs, const Vector3D& rhs); Vector3D operator-(const Vector3D& lhs, const Vector3D& rhs); Vector3D operator*(const Vector3D& lhs, const float& rhs); Vector3D operator*(const float& lhs, const Vector3D& rhs); Vector3D operator/(const Vector3D& lhs, const float& rhs); // Functions float Dot(const Vector3D& vec1, const Vector3D& vec2); Vector3D Cross(const Vector3D& vec1, const Vector3D& vec2); // Point3D/Vector3D operators Point3D operator+(const Point3D& lhs, const Vector3D& rhs); Point3D operator+(const Vector3D& lhs, const Point3D& rhs); Point3D operator-(const Point3D& lhs, const Vector3D& rhs); Vector3D operator-(const Point3D& lhs, const Point3D& rhs); // Stream operator template<class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& lhs, const Vector3D& rhs) { std::basic_ostringstream<charT, traits> s; s.flags(lhs.flags()); s.imbue(lhs.getloc()); s.precision(lhs.precision()); typename Vector3D::const_iterator i = rhs.begin(); s <<'(' <<*i; for(++i; i != rhs.end(); ++i) { s <<',' <<*i; } s <<')'; return lhs <<s.str(); } //////////////////////////////////////////////////////////////////////// // Line3D //////////////////////////////////////////////////////////////////////// class Line3D { public: // Constructors Line3D() : point(), vector() {return;} Line3D(const Point3D& p, const Vector3D& v) : point(p),vector(v) {return;} public: Point3D point; Vector3D vector; }; // Functions float AngleBetween(const Line3D& line1, const Line3D& line2); bool Coplanar(const Line3D& line1, const Line3D& line2); bool Parallel(const Line3D& line1, const Line3D& line2); bool Perpendicular(const Line3D& line1, const Line3D& line2); float AngleBetween(const Line3D& line, const Plane3D& plane); bool Parallel(const Line3D& line, const Plane3D& plane); bool Perpendicular(const Line3D& line, const Plane3D& plane); bool Intersects(const Line3D& line, const Plane3D& plane, Point3D *rpoint=0); //////////////////////////////////////////////////////////////////////// // Segment3D //////////////////////////////////////////////////////////////////////// class Segment3D { public: // Constructors Segment3D() : point1(), point2() {return;} Segment3D(const Point3D& p1, const Point3D& p2) : point1(p1), point2(p2) {return;} // Utility methods bool contains(const Point3D& point) const; Point3D point1; Point3D point2; }; // Functions bool Intersects(const Segment3D& seg, const Triangle3D& tri, Point3D *rpoint=0); //////////////////////////////////////////////////////////////////////// // Ray3D //////////////////////////////////////////////////////////////////////// class Ray3D { public: // Constructor Ray3D() : origin(), direction() {return;} Ray3D(const Point3D& o, const Vector3D& d) : origin(o), direction(d) {return;} // Containment method bool contains(const Point3D& point, float *t=NULL) const; // Returns paramter of intersection if containment is true and t != NULL Point3D origin; Vector3D direction; }; // Utility functions: int Intersects(const Ray3D& ray, const Sphere3D& sphere, std::pair<Point3D, Point3D> *rpoints=0); bool Intersects(const Ray3D& ray, const Triangle3D& tri, Point3D *rpoint=0); int Intersects(const Ray3D& ray, const Box3D& box, std::pair<Point3D, Point3D> *rpoints=0); //////////////////////////////////////////////////////////////////////// // Box3D //////////////////////////////////////////////////////////////////////// class Box3D { public: // Constructor Box3D() {return;} Box3D(const Point3D& o, const Point3D& e) : origin(o), extent(e) {return;} // Utility method bool contains(const Point3D& point) const; Point3D origin; Point3D extent; }; //////////////////////////////////////////////////////////////////////// // Sphere3D //////////////////////////////////////////////////////////////////////// class Sphere3D { public: // Constructors Sphere3D() : center(), radius(0) {return;} Sphere3D(const Point3D& c, float r) : center(c), radius(r) {return;} Point3D center; float radius; }; //////////////////////////////////////////////////////////////////////// // Plane3D //////////////////////////////////////////////////////////////////////// class Plane3D { public: // Constructor explicit Plane3D(float A=0, float B=0, float C=0, float D=0) { crds[0]=A; crds[1]=B; crds[2]=C; crds[3]=D; } // Random-access operators. float& operator[](unsigned int i) { return crds[i]; } const float& operator[](unsigned int i) const { return crds[i]; } // Utility methods. Vector3D normal() const { return Vector3D(crds[X], crds[Y], crds[Z]); } float Evaluate(Point3D p) const { return crds[0]*p[0] + crds[1]*p[1] + crds[2]*p[2] + crds[3]; } // Sequential-access methods. typedef float *iterator; typedef const float *const_iterator; iterator begin() { return crds + 0; } const_iterator begin() const { return crds + 0; } iterator end() { return crds + DIM; } const_iterator end() const { return crds + DIM; } private: enum {DIM=4} ; float crds[DIM]; }; // Utility functions: float AngleBetween(const Plane3D& plane1, const Plane3D& plane2); bool Parallel(const Plane3D& plane1, const Plane3D& plane2); bool Perpendicular(const Plane3D& plane1, const Plane3D& plane2); bool Intersects(const Segment3D& seg, const Plane3D& plane, Point3D *rpoint=0); //////////////////////////////////////////////////////////////////////// // Triangle3D //////////////////////////////////////////////////////////////////////// class Triangle3D { public: // Constructor Triangle3D() {return;} Triangle3D(const Point3D& p1, const Point3D& p2, const Point3D& p3) { points[0]=p1; points[1]=p2; points[2]=p3; } Point3D& operator[](unsigned int i) { return points[i]; } const Point3D& operator[](unsigned int i) const { return points[i]; } bool contains(const Point3D& point) const; // Sequential-access methods. typedef Point3D *iterator; typedef const Point3D *const_iterator; iterator begin() { return points + 0; } const_iterator begin() const { return points + 0; } iterator end() { return points + DIM; } const_iterator end() const { return points + DIM; } private: enum{ DIM=3 }; Point3D points[DIM]; }; // Utility function: int Intersects(const Triangle3D& tri1, const Triangle3D& tri2, std::pair<Point3D, Point3D> *rpoints=0); //////////////////////////////////////////////////////////////////////// // Vector4D //////////////////////////////////////////////////////////////////////// class Vector4D { public: // Constructor explicit Vector4D(float X=0, float Y=0, float Z=0, float W=1) { crds[0]=X; crds[1]=Y; crds[2]=Z; crds[3]=W; } Vector4D(Vector3D V) { crds[0]=V[0]; crds[1]=V[1]; crds[2]=V[2]; crds[3]=1.0; } Vector4D(Point3D P) { crds[0]=P[0]; crds[1]=P[1]; crds[2]=P[2]; crds[3]=1.0; } // In-place operators. Vector4D& operator+=(const Vector4D& rhs); Vector4D& operator-=(const Vector4D& rhs); Vector4D& operator*=(const float& rhs); Vector4D& operator/=(const float& rhs); void normalize() throw(ZeroDivide); Point3D Hdiv() throw(ZeroDivide); // Random-access operators. float& operator[](unsigned int i) { return crds[i]; } const float& operator[](unsigned int i) const { return crds[i]; } // Utility methods. float length() const; Vector4D normalized() const throw(ZeroDivide); // Sequential-access methods. typedef float *iterator; typedef const float *const_iterator; iterator begin() { return crds + 0; } const_iterator begin() const { return crds + 0; } iterator end() { return crds + DIM; } const_iterator end() const { return crds + DIM; } private: enum {DIM=4}; float crds[DIM]; }; // (Global) operators. bool operator==(const Vector4D& lhs, const Vector4D& rhs); bool operator!=(const Vector4D& lhs, const Vector4D& rhs); Vector4D operator+(const Vector4D& lhs, const Vector4D& rhs); Vector4D operator-(const Vector4D& lhs, const Vector4D& rhs); Vector4D operator*(const Vector4D& lhs, const float& rhs); Vector4D operator*(const float& lhs, const Vector4D& rhs); Vector4D operator/(const Vector4D& lhs, const float& rhs); // Utility function: float Dot(const Vector4D& hvec1, const Vector4D& hvec2); float ToRadians(const float& Degrees); // Stream operator template<class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& lhs, const Vector4D& rhs) { std::basic_ostringstream<charT, traits> s; s.flags(lhs.flags()); s.imbue(lhs.getloc()); s.precision(lhs.precision()); typename Vector4D::const_iterator i = rhs.begin(); s <<'(' <<*i; for(++i; i != rhs.end(); ++i) { s <<',' <<*i; } s <<')'; return lhs <<s.str(); } //////////////////////////////////////////////////////////////////////// // Matrix4x4 //////////////////////////////////////////////////////////////////////// class Matrix4x4 { public: // Constructor explicit Matrix4x4(const Vector4D& row0=Vector4D(1, 0, 0, 0), const Vector4D& row1=Vector4D(0, 1, 0, 0), const Vector4D& row2=Vector4D(0, 0, 1, 0), const Vector4D& row3=Vector4D(0, 0, 0, 1)) { rows[0] = row0; rows[1] = row1; rows[2] = row2; rows[3] = row3; } // In-place operators. Matrix4x4& operator*=(const Matrix4x4& rhs); void reset(); // Random-access operators. Vector4D& operator[](unsigned int i) { return rows[i]; } const Vector4D& operator[](unsigned int i) const { return rows[i]; } // Sequential-access methods. typedef Vector4D *iterator; typedef const Vector4D *const_iterator; iterator begin() { return rows + 0; } const_iterator begin() const { return rows + 0; } iterator end() { return rows + DIM; } const_iterator end() const { return rows + DIM; } private: enum {DIM=4}; Vector4D rows[DIM]; }; // (Global) operators.typedef Vector4D MatrixRow; Matrix4x4 operator*(const Matrix4x4& lhs, const Matrix4x4& rhs); Vector4D operator*(const Matrix4x4& lhs, const Vector3D& rhs); Vector4D operator*(const Matrix4x4& lhs, const Point3D& rhs); Vector4D operator*(const Matrix4x4& lhs, const Vector4D& rhs); // Utility functions Matrix4x4 LookAt(const Point3D& center, const Point3D& direction, const Vector3D& up); Matrix4x4 Perspective(const float w, const float h, const float d, const float f); // Stream operator template<class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& lhs, const Matrix4x4& rhs) { std::basic_ostringstream<charT, traits> s; s.flags(lhs.flags()); s.imbue(lhs.getloc()); s.precision(lhs.precision()); for(typename Matrix4x4::const_iterator i=rhs.begin(); i != rhs.end(); ++i) s << *i << '\n'; return lhs << s.str(); } // Restore the warnings to their previous state. #if defined(_MSC_VER) && (1300 >= _MSC_VER) #pragma warning(pop) #endif #endif // #if !defined(GEOMLIB_HPP_)
[ [ [ 1, 737 ] ] ]
9b8e403d1f566aba95e409ba9135be4be67b9d50
e9944cc3f8c362cd0314a2d7a01291ed21de19ee
/ xcommon/HWXDbg.cpp
1b270e5c6330a9d417394407649ab7d7946116b5
[]
no_license
wermanhme1990/xcommon
49d7185a28316d46992ad9311ae9cdfe220cb586
c9b1567da1f11e7a606c6ed638a9fde1f6ece577
refs/heads/master
2016-09-06T12:43:43.593776
2008-12-05T04:24:11
2008-12-05T04:24:11
39,864,906
2
0
null
null
null
null
GB18030
C++
false
false
3,118
cpp
#include "..\\HWXDbg\\HWXDbg.h" #include <assert.h> #include <stdio.h> #include <malloc.h> #include <memory.h> #include <stdarg.h> #include <crtdbg.h> #include <time.h> TCHAR CHWXLog::m_athMutexName[NAME_MAX] = _T("HWX_DBG_MUTEX"); HANDLE CHWXLog::m_MutexLog = NULL; TCHAR CHWXLog::m_athLogFile[PATH_MAX] = _T("D:\\MyLog.txt"); void CHWXLog::HWLog(const TCHAR *pthFormat, ...) { const long nLimit = 1024; TCHAR achBuffer[1024] = {0}; long nBufferLen = 0; TCHAR *pthBgn = achBuffer; CHWXLog &tLog = GetInstance(); DWORD dwWaitRet = tLog.WaitForMutex(); if(dwWaitRet) { va_list tArgs; va_start( tArgs, pthFormat); nBufferLen = _vsctprintf(pthFormat, tArgs) + 20; if (nBufferLen > nLimit) { VERIFY(pthBgn = (TCHAR *)_alloca(nBufferLen * sizeof(TCHAR))); } _tstrtime(pthBgn); long nTimeLen = _tcslen(pthBgn); pthBgn[nTimeLen ++] = TEXT('\t'); //pthBgn[nTimeLen ++] = 0; _vstprintf(pthBgn + nTimeLen, pthFormat, tArgs); tLog.HWCout(pthBgn); va_end(tArgs); if (!tLog.ReleaseMutex()) { tLog.HWCout(TEXT("ReleaseMutex Error\n")); } } else { tLog.HWCout(TEXT("Wait Error: WAIT_FAILED\n")); } } void CHWXLog::PrintProcessName() { TCHAR athName[MAX_PATH]; DWORD dwPID = GetCurrentProcessId(); DWORD dwTID = GetCurrentThreadId(); GetModuleFileName(NULL, athName, MAX_PATH); HWLog(_T("Process:%s PID=%d TID=%d\n"), athName, (long)dwPID, (long)dwTID); } void CHWXLog::PrintCurError() { DWORD dwErr = GetLastError(); LPVOID lpMsgBuf; DWORD dwPID, dwTID; dwPID = GetCurrentProcessId(); dwTID = GetCurrentThreadId(); if (!FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL )) { return; } HWLog(_T("PID=%d TID=%d CurError:ID= %d %s\n"), (long)dwPID, (long)dwTID, (long)dwErr, lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); return ; } CHWXLog::CHWXLog() { //创建Log互斥变量 if (!(m_MutexLog = OpenMutex(MUTEX_ALL_ACCESS, TRUE, m_athMutexName))) { VERIFY(m_MutexLog = CreateMutex(NULL, FALSE, m_athMutexName)); } _ASSERT(m_MutexLog); //_tremove(m_athLogFile); } CHWXLog::~CHWXLog() { if (m_MutexLog) { CloseHandle(m_MutexLog); m_MutexLog = NULL; } } CHWXLog& CHWXLog:: GetInstance() { static CHWXLog tLog; return tLog; } void CHWXLog::HWCout(const TCHAR *ptString) { //创建文件 FILE *m_pFile= NULL; m_pFile = _tfopen(m_athLogFile, TEXT("a")); if (m_pFile) { fwrite(ptString, sizeof(TCHAR), _tcslen(ptString), m_pFile); fclose(m_pFile); m_pFile = NULL; } } BOOL CHWXLog::WaitForMutex() { return WaitForSingleObject(m_MutexLog, INFINITE) == WAIT_OBJECT_0; } BOOL CHWXLog::ReleaseMutex() { return ::ReleaseMutex(m_MutexLog); }
[ [ [ 1, 123 ] ] ]
12ad2ef95b2e41a215c91559fe94576dcaa2c7f6
723202e673511cf9f243177d964dfeba51cb06a3
/10/oot_Mozg/SRC/Mozg.cpp
17cb530d0f0c6ba63593486b8ce16af089ffc7f5
[]
no_license
aeremenok/a-team-777
c2ffe04b408a266f62c523fb8d68c87689f2a2e9
0945efbe00c3695c9cc3dbcdb9177ff6f1e9f50b
refs/heads/master
2020-12-24T16:50:12.178873
2009-06-16T14:55:41
2009-06-16T14:55:41
32,388,114
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,410
cpp
// ************************************************************************** //! \file Mozg.cpp //! \brief main source file for Mozg.exe //! \author Bessonov A.V. //! \date 17.May.2008 - 19.May.2008 // ************************************************************************** #include "stdafx.h" #include <new.h> CAppModule _Module; // ========================================================================== int Mozg_new_handler( size_t ) { CONFIRM(!"Оператор new вернул NULL!!!"); throw std::bad_alloc(); return 0; } // ========================================================================== int Run(LPTSTR /*lpstrCmdLine*/ = NULL, int nCmdShow = SW_SHOWDEFAULT) { // БРОСАТЬ ИСКЛЮЧЕНИЕ, ЕСЛИ new ВЕРНУЛ NULL _set_new_handler( Mozg_new_handler ); _set_new_mode(1); // ТО ЖЕ, ДЛЯ malloc CMessageLoop theLoop; _Module.AddMessageLoop(&theLoop); //CMainDlg* dlgMain; Game::CMainDlg* dlgMain = new Game::CMainDlg; //if(dlgMain.Create(NULL) == NULL) if(dlgMain->Create(NULL) == NULL) { ATLTRACE(_T("Main dialog creation failed!\n")); return 0; } //dlgMain.ShowWindow(nCmdShow); dlgMain->ShowWindow(nCmdShow); //! Создаем объкт контролирующий ход игры Game::Controller* g_control = Game::Controller::Instance(dlgMain); //Game::Controller* g_control = new Game::Controller(dlgMain); int nRet = theLoop.Run(); _Module.RemoveMessageLoop(); delete dlgMain; delete g_control; return nRet; } int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow) { HRESULT hRes = ::CoInitialize(NULL); // If you are running on NT 4.0 or higher you can use the following call instead to // make the EXE free threaded. This means that calls come in on a random RPC thread. // HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED); ATLASSERT(SUCCEEDED(hRes)); // this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used ::DefWindowProc(NULL, 0, 0, 0L); AtlInitCommonControls(ICC_BAR_CLASSES); // add flags to support other controls hRes = _Module.Init(NULL, hInstance); ATLASSERT(SUCCEEDED(hRes)); int nRet = Run(lpstrCmdLine, nCmdShow); _Module.Term(); ::CoUninitialize(); return nRet; }
[ "AVBessonov@9273621a-9230-0410-b1c6-9ffd80c20a0c", "scorpion1105@9273621a-9230-0410-b1c6-9ffd80c20a0c" ]
[ [ [ 1, 7 ], [ 45, 46 ] ], [ [ 8, 44 ], [ 47, 79 ] ] ]
5564a9a4fcfc9630818663e887ee10a526f74d1c
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Components/Optimizers/FiniteDifferenceGradientDescent/elxFiniteDifferenceGradientDescent.hxx
aef65d2121a2e56b6f2526fdc37caa3a04a51e88
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
7,035
hxx
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxFiniteDifferenceGradientDescent_hxx #define __elxFiniteDifferenceGradientDescent_hxx #include "elxFiniteDifferenceGradientDescent.h" #include <iomanip> #include <string> #include "math.h" namespace elastix { using namespace itk; /** * ********************* Constructor **************************** */ template <class TElastix> FiniteDifferenceGradientDescent<TElastix> ::FiniteDifferenceGradientDescent() { this->m_ShowMetricValues = false; } // end Constructor /** * ***************** BeforeRegistration *********************** */ template <class TElastix> void FiniteDifferenceGradientDescent<TElastix>:: BeforeRegistration(void) { std::string showMetricValues("false"); this->GetConfiguration()->ReadParameter( showMetricValues, "ShowMetricValues", 0); if (showMetricValues == "false") { this->m_ShowMetricValues = false; this->SetComputeCurrentValue(this->m_ShowMetricValues); } else { this->m_ShowMetricValues = true; this->SetComputeCurrentValue(this->m_ShowMetricValues); } /** Add some target cells to xout["iteration"].*/ xout["iteration"].AddTargetCell("2:Metric"); xout["iteration"].AddTargetCell("3:Gain a_k"); xout["iteration"].AddTargetCell("4:||Gradient||"); /** Format them as floats */ xl::xout["iteration"]["2:Metric"] << std::showpoint << std::fixed; xl::xout["iteration"]["3:Gain a_k"] << std::showpoint << std::fixed; xl::xout["iteration"]["4:||Gradient||"] << std::showpoint << std::fixed; } // end BeforeRegistration /** * ***************** BeforeEachResolution *********************** */ template <class TElastix> void FiniteDifferenceGradientDescent<TElastix> ::BeforeEachResolution(void) { /** Get the current resolution level.*/ unsigned int level = static_cast<unsigned int>( this->m_Registration->GetAsITKBaseType()->GetCurrentLevel() ); /** Set the maximumNumberOfIterations.*/ unsigned int maximumNumberOfIterations = 500; this->m_Configuration->ReadParameter( maximumNumberOfIterations, "MaximumNumberOfIterations", this->GetComponentLabel(), level, 0 ); this->SetNumberOfIterations( maximumNumberOfIterations ); /** \todo GuessParameters function */ double a = 400.0; double c = 1.0; double A = 50.0; double alpha = 0.602; double gamma = 0.101; this->GetConfiguration()->ReadParameter(a, "SP_a", this->GetComponentLabel(), level, 0 ); this->GetConfiguration()->ReadParameter(c, "SP_c", this->GetComponentLabel(), level, 0 ); this->GetConfiguration()->ReadParameter(A, "SP_A", this->GetComponentLabel(), level, 0 ); this->GetConfiguration()->ReadParameter(alpha, "SP_alpha", this->GetComponentLabel(), level, 0 ); this->GetConfiguration()->ReadParameter(gamma, "SP_gamma", this->GetComponentLabel(), level, 0 ); this->SetParam_a( a ); this->SetParam_c( c ); this->SetParam_A( A ); this->SetParam_alpha( alpha ); this->SetParam_gamma( gamma ); } // end BeforeEachResolution /** * ***************** AfterEachIteration ************************* */ template <class TElastix> void FiniteDifferenceGradientDescent<TElastix> ::AfterEachIteration(void) { /** Print some information */ if (this->m_ShowMetricValues) { xl::xout["iteration"]["2:Metric"] << this->GetValue(); } else { xl::xout["iteration"]["2:Metric"] << "---"; } xl::xout["iteration"]["3:Gain a_k"] << this->GetLearningRate(); xl::xout["iteration"]["4:||Gradient||"] << this->GetGradientMagnitude(); /** Select new spatial samples for the computation of the metric * \todo You may also choose to select new samples after evaluation * of the metric value */ if ( this->GetNewSamplesEveryIteration() ) { this->SelectNewSamples(); } } // end AfterEachIteration /** * ***************** AfterEachResolution ************************* */ template <class TElastix> void FiniteDifferenceGradientDescent<TElastix> ::AfterEachResolution(void) { /** * enum StopConditionType { MaximumNumberOfIterations, MetricError } */ std::string stopcondition; switch( this->GetStopCondition() ) { case MaximumNumberOfIterations : stopcondition = "Maximum number of iterations has been reached"; break; case MetricError : stopcondition = "Error in metric"; break; default: stopcondition = "Unknown"; break; } /** Print the stopping condition */ elxout << "Stopping condition: " << stopcondition << "." << std::endl; } // end AfterEachResolution /** * ******************* AfterRegistration ************************ */ template <class TElastix> void FiniteDifferenceGradientDescent<TElastix> ::AfterRegistration(void) { /** Print the best metric value */ double bestValue; if (this->m_ShowMetricValues) { bestValue = this->GetValue(); elxout << std::endl << "Final metric value = " << bestValue << std::endl; } else { elxout << std::endl << "Run Elastix again with the option \"ShowMetricValues\" set" << " to \"true\", to see information about the metric values. " << std::endl; } } // end AfterRegistration /** * ******************* StartOptimization *********************** */ template <class TElastix> void FiniteDifferenceGradientDescent<TElastix> ::StartOptimization(void) { /** Check if the entered scales are correct and != [ 1 1 1 ...] */ this->SetUseScales(false); const ScalesType & scales = this->GetScales(); if ( scales.GetSize() == this->GetInitialPosition().GetSize() ) { ScalesType unit_scales( scales.GetSize() ); unit_scales.Fill(1.0); if (scales != unit_scales) { /** only then: */ this->SetUseScales(true); } } this->Superclass1::StartOptimization(); } //end StartOptimization } // end namespace elastix #endif // end #ifndef __elxFiniteDifferenceGradientDescent_hxx
[ [ [ 1, 249 ] ] ]
353ed388a0e5ca15f85b443564c692f223f931fa
9fb229975cc6bd01eb38c3e96849d0c36985fa1e
/Tools/MergeCar/TgaWriter.h
a16a58a3041e89e306f502d154210bb0eca0a95f
[]
no_license
Danewalker/ahr
3758bf3219f407ed813c2bbed5d1d86291b9237d
2af9fd5a866c98ef1f95f4d1c3d9b192fee785a6
refs/heads/master
2016-09-13T08:03:43.040624
2010-07-21T15:44:41
2010-07-21T15:44:41
56,323,321
0
0
null
null
null
null
UTF-8
C++
false
false
1,296
h
#ifndef _TGAWRITER_H_ #define _TGAWRITER_H_ #include <string> #include <fstream> class CSurface; class CTgaWriter { public: struct SHeader { SHeader(); void Write(std::ofstream&); char IdentSize; //size of ID field that follows 18 byte header (0 usually) char ColorMapType; //type of colour map 0=none, 1=has palette char ImageType; //type of image 0=none,1=indexed,2=rgb,3=grey,+8=rle packed short ColorMapStart; //first colour map entry in palette short ColorMapLength; //number of colours in palette char ColorMapBits; //number of bits per palette entry 15,16,24,32 short XStart; //image x origin short YStart; //image y origin unsigned short Width; //image width in pixels short Height; //image height in pixels char Bits; //image bits per pixel 8,16,24,32 char Descriptor; //image descriptor bits (vh flip bits) }; CTgaWriter(); CTgaWriter::~CTgaWriter(); bool Write(const std::string&, CSurface& surface); short GetWidth() const {return(m_Header.Width);} short GetHeight() const {return(m_Header.Height);} char GetDepth() const {return(m_Header.Bits);} private: std::string m_FileName; SHeader m_Header; std::ofstream m_File; //CSurface& m_Surface; }; #endif
[ "jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae" ]
[ [ [ 1, 50 ] ] ]
8842463945c7d31ae40ba209b85677e451d8e5fc
4308e61561bc2b164dffc0b86b38b949d535f775
/AAA/RTT/main.cpp
5373cd1f009e33fa0917cbcab59e9ec89854d515
[]
no_license
GunioRobot/all
3526922dfd75047e78521f5716c1db2f3f299c38
22f5d77e12070dc6f60e9a39eb3504184360e061
refs/heads/master
2021-01-22T13:38:14.634356
2011-10-30T23:17:30
2011-10-30T23:17:30
2,995,713
0
0
null
null
null
null
UTF-8
C++
false
false
10,898
cpp
#include <cstdio> #include "blas.hpp" #include <algorithm> #include <GL/glew.h> #include <GL/freeglut.h> #include <iostream> #include "GLSLShader.h" #include <cassert> #define GL_CHECK_ERRORS assert(glGetError() == GL_NO_ERROR); // The polygon (triangle), 3 numbers that aim 3 vertices typedef struct{ uint a,b,c; }polygon_type; struct vertex_type { float x,y,z; }; // The mapcoord type, 2 texture coordinates for each vertex typedef struct{ float u,v; }mapcoord_type; #define MAX_VERTICES 2000 #define MAX_POLYGONS 2000 // The object type typedef struct { vertex_type vertex[MAX_VERTICES]; polygon_type polygon[MAX_POLYGONS]; mapcoord_type mapcoord[MAX_VERTICES]; } obj_type; obj_type cube = { { {-1, -1, -1}, {1, -1, -1}, {-1, 1, -1}, {1, 1, -1}, {-1, -1, 1}, {1, -1, 1}, {-1, 1, 1}, {1, 1, 1} }, { {0, 1, 3}, // back {0, 2, 3}, {0, 4, 5}, // bottom {0, 1, 5}, {0, 4, 6}, // left {0, 2, 6}, {1, 5, 7}, // right {1, 3, 7}, {2, 6, 7}, // top {2, 3, 7}, {4, 5, 7}, // front {4, 6, 7} }, { {0, 0}, {1, 0}, {0, 1}, {1, 1}, {0, 0}, {1, 0}, {0, 1}, {1, 1} } }; uint n_indices = sizeof(cube.polygon) / sizeof(cube.polygon[0]); GLuint vboVerticesID, vboIndicesID, vaoID; GLuint sqvboTexCoordID, sqvaoID; GLSLShader colorshader, texshader; int filling = 1; // Projection and View matrices Matrix4 V(1); void InitShaders() { colorshader.LoadFromFile(GL_VERTEX_SHADER, "shader.vert"); colorshader.LoadFromFile(GL_FRAGMENT_SHADER, "shader.frag"); colorshader.CreateAndLinkProgram(); colorshader.Use(); colorshader.AddAttribute("vVertex"); colorshader.AddUniform("MVP"); colorshader.UnUse(); GL_CHECK_ERRORS texshader.LoadFromFile(GL_VERTEX_SHADER, "tex_shader.vert"); texshader.LoadFromFile(GL_FRAGMENT_SHADER, "tex_shader.frag"); texshader.CreateAndLinkProgram(); texshader.Use(); texshader.AddAttribute("vVertex"); texshader.AddAttribute("vUV"); texshader.AddUniform("MVP"); texshader.AddUniform("textureMap"); glUniform1i(texshader("textureMap"),0); texshader.UnUse(); GL_CHECK_ERRORS } void InitVAO() { glGenVertexArrays(1, &vaoID); glGenBuffers(1, &vboVerticesID); glGenBuffers(1, &vboIndicesID); GL_CHECK_ERRORS glBindVertexArray(vaoID); glBindBuffer (GL_ARRAY_BUFFER, vboVerticesID); glBufferData (GL_ARRAY_BUFFER, sizeof(cube.vertex), &cube.vertex[0], GL_STATIC_DRAW); GL_CHECK_ERRORS glEnableVertexAttribArray(colorshader["vVertex"]); glVertexAttribPointer (colorshader["vVertex"], 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*3 ,0); GL_CHECK_ERRORS glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboIndicesID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube.polygon), &cube.polygon[0], GL_STATIC_DRAW); GL_CHECK_ERRORS glBindVertexArray(0); GL_CHECK_ERRORS } void InitSQVAO() { glGenVertexArrays(1, &sqvaoID); glGenBuffers(1, &sqvboTexCoordID); GL_CHECK_ERRORS glBindVertexArray(sqvaoID); glBindBuffer(GL_ARRAY_BUFFER, vboVerticesID); glBufferData(GL_ARRAY_BUFFER, sizeof(cube.vertex), &cube.vertex[0], GL_STATIC_DRAW); GL_CHECK_ERRORS glEnableVertexAttribArray(colorshader["vVertex"]); glVertexAttribPointer(colorshader["vVertex"], 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*3 ,0); GL_CHECK_ERRORS glBindBuffer(GL_ARRAY_BUFFER, sqvboTexCoordID); glBufferData(GL_ARRAY_BUFFER, sizeof(cube.mapcoord), &cube.mapcoord[0], GL_STATIC_DRAW); glEnableVertexAttribArray(texshader["vUV"]); glVertexAttribPointer(texshader["vUV"], 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*2 ,0); GL_CHECK_ERRORS glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboIndicesID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube.polygon), &cube.polygon[0], GL_STATIC_DRAW); GL_CHECK_ERRORS glBindVertexArray(0); GL_CHECK_ERRORS } class Timer { double m_previous, m_delta; public: Timer() : m_previous(0), m_delta(0) {} double delta() const { return m_delta; } void update() { const double current = (double)glutGet(GLUT_ELAPSED_TIME) / 1000.0; m_delta = current - m_previous; m_previous = current; } }; class Accumulator { double m_accum, m_resolution; public: Accumulator(double resolution) : m_accum(0), m_resolution(resolution) {} bool ready() const { return m_accum > m_resolution; } void add(double dt) { m_accum += dt; } void reset() { m_accum = 0; } }; struct RenderDetail { Matrix4 MV; uint vao, indices; RenderDetail(const Matrix4& mv, uint v, uint i) : MV(mv), vao(v), indices(i) {} }; class Viewport { uint m_width, m_height; public: Viewport(uint width, uint height) : m_width(width), m_height(height) {} void bind() { glViewport(0, 0, m_width, m_height); } void resize(uint width, uint height) { m_width = width; m_height = height; } uint width() const { return m_width; } uint height() const { return m_height; } }; class Renderer { std::vector<RenderDetail> queue; unsigned int fbo_id; unsigned int depth_buffer; int m_FBOWidth, m_FBOHeight; unsigned int m_TextureID; Viewport m_FBOViewport, m_ScreenViewport; public: Renderer(int sw, int sh, int fw, int fh) : m_FBOWidth(fw), m_FBOHeight(fh), m_FBOViewport(fw, fh), m_ScreenViewport(sw, sh) {} void enqueue(const RenderDetail& rd) { queue.push_back(rd); } void resize(int sw, int sh) { m_ScreenViewport.resize(sw, sh); m_FBOViewport.resize(sw, sh); } void initFBO() { //const GLenum fbo_buffers[] = { GL_COLOR_ATTACHMENT0 }; glGenRenderbuffers(1, &depth_buffer); glBindRenderbuffer(GL_RENDERBUFFER, depth_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_FBOWidth, m_FBOHeight); glGenTextures(1, &m_TextureID); glBindTexture(GL_TEXTURE_2D, m_TextureID); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_FBOWidth, m_FBOHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); glGenFramebuffers(1, &fbo_id); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_id); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_buffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_TextureID, 0); assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void render() { uint prevVAO = 0; Matrix4 P = perspective(45.0f, (float)m_FBOViewport.width() / (float)m_FBOViewport.height(), 1.f, 100.f); glBindFramebuffer(GL_FRAMEBUFFER, fbo_id); m_FBOViewport.bind(); glClearColor(0, 0, 0.2f,0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); colorshader.Use(); const uint csmvp = colorshader("MVP"); for (size_t i = 0; i < queue.size(); ++i) { const RenderDetail& rd = queue[i]; const Matrix4 MVP = rd.MV * P; glUniformMatrix4fv(csmvp, 1, GL_FALSE, &MVP[0]); if (prevVAO != rd.vao) { prevVAO = rd.vao; glBindVertexArray(rd.vao); } glDrawElements(GL_TRIANGLES, rd.indices, GL_UNSIGNED_INT, 0); } //colorshader.UnUse(); glBindFramebuffer(GL_FRAMEBUFFER, 0); m_ScreenViewport.bind(); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); texshader.Use(); glBindTexture(GL_TEXTURE_2D, m_TextureID); // float aspect = (float)m_ScreenViewport.width() / (float)m_ScreenViewport.height(); P = orthographic(-1, 1, -1, 1, -1, 1); //P = perspective(90.0f, aspect, 1.f, 100.f); //translate(P, Vector3(0,0, -0.5)); const uint tsmvp = texshader("MVP"); glUniformMatrix4fv(tsmvp, 1, GL_FALSE, &P[0]); if (prevVAO != sqvaoID) { prevVAO = sqvaoID; glBindVertexArray(sqvaoID); } glDrawElements(GL_TRIANGLES, n_indices, GL_UNSIGNED_INT, 0); queue.clear(); glutSwapBuffers(); } }; Renderer renderer(800, 600, 800, 600); // Absolute rotation values (0-359 degrees) and rotiation increments for each frame float rotation_x = 0; float rotation_y = 0; float rotation_z = 0; float drawdist = 40.f; void OnRender() { Matrix4 M(1); scale(M, Vector3(10,10,10)); //translate(M, Vector3(0, 0, 0)); Matrix4 MV = M * V; renderer.enqueue(RenderDetail(MV, vaoID, n_indices)); renderer.render(); } void OnResize(int w, int h) { renderer.resize(w, h); } void OnKey(unsigned char key, int, int) { switch (key) { case 'w': case 'W': translate(V, Vector3(0,0,1)); break; case 's': case 'S': translate(V, Vector3(0,0,-1)); break; } } Timer framet; Accumulator fps(1.0), input(1.0 / 30.0), render(1.0 / 60.0), spinner(1.0 / 120.0); uint frames; void OnIdle() { framet.update(); const double dt = framet.delta(); fps.add(dt); input.add(dt); render.add(dt); spinner.add(dt); ++frames; if (fps.ready()) { printf("%i %f\n", frames, dt); frames = 0; fps.reset(); } if (render.ready()) { glutPostRedisplay(); // call onRender() render.reset(); } if (input.ready()) { input.reset(); } if (spinner.ready()) { rotation_x = rotation_x + 0.00000f; rotation_y = rotation_y + 0.00002f; rotation_z = rotation_z + 0.00000f; if (rotation_x > 359) rotation_x = 0; if (rotation_y > 359) rotation_y = 0; if (rotation_z > 359) rotation_z = 0; spinner.reset(); } } void InitGL() { glGetError(); GL_CHECK_ERRORS InitShaders(); InitVAO(); InitSQVAO(); renderer.initFBO(); GL_CHECK_ERRORS glEnable(GL_DEPTH_TEST); GL_CHECK_ERRORS } int main(int argc, char** argv) { //GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitContextVersion(3, 3); glutInitContextFlags(GLUT_CORE_PROFILE | GLUT_DEBUG); glutInitWindowSize(800, 600); glutCreateWindow("RTT"); // GLEW glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err) std::cerr << "Error: " << glewGetErrorString(err) << std::endl; else if (GLEW_VERSION_3_2) std::cout << "Driver supports OpenGL 3.2\nDetails:" << std::endl; std::cout << "Using GLEW "<<glewGetString(GLEW_VERSION) << std::endl; std::cout << "Vendor: "<<glGetString (GL_VENDOR) << std::endl; std::cout << "Renderer: "<<glGetString (GL_RENDERER) << std::endl; std::cout << "Version: "<<glGetString (GL_VERSION) << std::endl; std::cout << "GLSL: "<<glGetString (GL_SHADING_LANGUAGE_VERSION) << std::endl; InitGL(); glutDisplayFunc(OnRender); glutReshapeFunc(OnResize); glutKeyboardFunc(OnKey); glutIdleFunc(OnIdle); glutMainLoop(); return 0; }
[ [ [ 1, 416 ] ] ]
161185b2b215fac6b841a576e00f1b417d3cae20
6c413a226324f2318f54e3a1c04a839f8362b87f
/Vision/dx50/picolo_ntsc.cpp
6d1badea33d4baef871ed34e2d5df1b2a2a64e1d
[]
no_license
stephengeorgewest/MarsRover
3cd9414fa2b9dcf97a440013513d57fb531bfaa1
cee1ad8c25d45ae7936f50b5713028daa6c33a57
refs/heads/master
2023-07-12T04:23:11.095549
2009-08-03T22:09:08
2009-08-03T22:09:08
397,507,518
0
0
null
null
null
null
UTF-8
C++
false
false
9,622
cpp
/* +-------------------------------- DISCLAIMER ---------------------------------+ | | | This application program is provided to you free of charge as an example. | | Despite the considerable efforts of Euresys personnel to create a usable | | example, you should not assume that this program is error-free or suitable | | for any purpose whatsoever. | | | | EURESYS does not give any representation, warranty or undertaking that this | | program is free of any defect or error or suitable for any purpose. EURESYS | | shall not be liable, in contract, in torts or otherwise, for any damages, | | loss, costs, expenses or other claims for compensation, including those | | asserted by third parties, arising out of or in connection with the use of | | this program. | | | +-----------------------------------------------------------------------------+ */ /*********************************************************************** MultiCam C++ Sample program. Acquires an image from the first board and save it in a ppm file. The board must come from Picolo family. The ppm file can be easily viewed with most image display programs, like gimp, kview, xv. ***********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "RoverNetwork.h" #include "/usr/local/euresys/multicam/include/MultiCamCpp.h" #define COMPRESS true #ifndef BYTE #define BYTE unsigned char #endif using namespace Euresys::MultiCam; void ProcessImage(BYTE *pImage, int sizeX, int sizeY, int *saved_images); void SaveImage(BYTE *pImage, int count); class CPicoloGrab { public: unsigned int imageBuffer; char* buffer; int count; int buffer_size; int buffer_index; int sizex, sizey, bufferPitch; int saved_images; int sizeb; RoverNetwork RN; Channel *pChannel; bool done; CPicoloGrab(); ~CPicoloGrab(); BOOL Init(); void AcquireImages(); void ProcessingCallback(Channel &channel, SignalInfo &info); void AcqFailureCallback(Channel &channel, SignalInfo &info); }; CPicoloGrab::CPicoloGrab() { /* Initialize the MultiCam driver. Do it once at the beginning of your program. */ buffer_size = 100000; buffer = new char[buffer_size]; buffer_index = 0; sizex = 0; sizey = 0; sizeb = -1; count = 0; done = false; saved_images = 0; pChannel = NULL; init_multicast(&RN, ROVER_GROUP_VIDEO, ROVER_PORT_VIDEO); } CPicoloGrab::~CPicoloGrab() { if (pChannel != NULL) delete pChannel; } BOOL CPicoloGrab::Init() { try { // Create a channel and associate it with the first connector on the first board pChannel = new Channel(Boards[0], "VID1"); pChannel->SetParam(MC_CamFile, "NTSC"); pChannel->SetParam(MC_ColorFormat, MC_ColorFormat_RGB24); if(COMPRESS){ pChannel->SetParam(MC_CompressionType, MC_CompressionType_DX50); pChannel->SetParam(MC_ColorFormat, MC_ColorFormat_DX50); // pChannel->SetParam(MC_BitrateControl, MC_BitrateControl_CBR); // pChannel->SetParam(MC_AverageBitrate, 10000*8); pChannel->SetParam(MC_BitrateControl, MC_BitrateControl_VBR); pChannel->SetParam(MC_VideoQuality, 10); pChannel->SetParam(MC_GopStructure, MC_GopStructure_IPONLY); pChannel->SetParam(MC_GopSize, 20); pChannel->SetParam(MC_Resolution, MC_Resolution_CIF); } pChannel->SetParam(MC_TrigMode, MC_TrigMode_IMMEDIATE); pChannel->SetParam(MC_NextTrigMode, MC_NextTrigMode_PERIODIC); pChannel->SetParam(MC_TargetFrameRate_Hz, 20); pChannel->SetParam(MC_AcquisitionMode, MC_AcquisitionMode_VIDEO); pChannel->SetParam(MC_SeqLength_Fr, MC_INDETERMINATE); pChannel->GetParam(MC_ImageSizeX, sizex); pChannel->GetParam(MC_ImageSizeY, sizey); // Register the callback function called when a new image is available pChannel->RegisterCallback(this, &CPicoloGrab::ProcessingCallback, MC_SIG_SURFACE_PROCESSING); pChannel->RegisterCallback(this, &CPicoloGrab::AcqFailureCallback, MC_SIG_ACQUISITION_FAILURE); /* Enable the signals we need: MC_SIG_SURFACE_PROCESSING: acquisition done and locked for processing MC_SIG_ACQUISITION_FAILURE: acquisition failed. */ // Enable the signal corresponding to the callback function pChannel->SetParam(MC_SignalEnable + MC_SIG_SURFACE_PROCESSING, MC_SignalEnable_ON); pChannel->SetParam(MC_SignalEnable + MC_SIG_ACQUISITION_FAILURE, MC_SignalEnable_ON); // Prepare the channel in order to minimize the acquisition sequence startup latency pChannel->Prepare(); } catch(Euresys::MultiCam::Exception &e) { printf("Error : %s\n", e.What()); if (pChannel != NULL) delete pChannel; return FALSE; } return TRUE; } /* Acquire images and process them. */ void CPicoloGrab::AcquireImages() { /* Start Acquisitions for this channel. Acquisition will start when the channel is active. */ fprintf(stderr,"SetParam MC_ChannelState <MC_ChannelState_ACTIVE>\n"); pChannel->SetParam(MC_ChannelState, MC_ChannelState_ACTIVE); fprintf(stderr,"WAITING for image processing callbacks\n"); /* Wait 3 seconds. That should be enough for the acquisition to finish. In industrial programs, this will probably be replaced with some wait for the end of the application. */ while(!done){ usleep(100); } } /* Callback function registered to our channel. Called at the asynchronous signals. */ void CPicoloGrab::ProcessingCallback(Channel &Ch, SignalInfo &Info) { try { // fprintf(stderr,"Processing surface.\n"); // Update the bitmap image with the acquired image data Info.Surf->GetParam(MC_FillCount, sizeb); pChannel->GetParam(MC_ImageSizeX, sizex); pChannel->GetParam(MC_ImageSizeY, sizey); Info.Surf->GetParam(MC_SurfacePitch, bufferPitch); Info.Surf->GetParam(MC_SurfaceAddr, imageBuffer); // Info.Surf->GetParam(MC_ // ProcessImage(reinterpret_cast<unsigned char*>(imageBuffer), sizex, sizey, &saved_images); /* Insert image analysis and processing code here */ if(COMPRESS){ int type = -1; Info.Surf->GetParam(MC_FrameType, type); if(type == MC_FrameType_I) printf("I frame "); if(type == MC_FrameType_B) printf("B frame "); if(type == MC_FrameType_P) printf("P frame "); } else { printf("Raw Frame "); } printf(" size = %i\n", sizeb); printf("sizex = %i, sizey = %i\n", sizex, sizey); char vidcode = ROVER_MAGIC_VIDEO; char chanID = 0; int frameID = count++; char packetNum = 1; char totalPackets = 1; int packetPayload = sizeb ; int totalPayload = sizeb; char vidType[4] = {'d', 'x', '5', '0'}; int width = sizex; int height = sizey; char fps = 20; char empty = 0; buffer[0] = vidcode; buffer[1] = chanID; buffer[2] = (frameID >> 24) & 0xFF; buffer[3] = (frameID >> 16) & 0xFF; buffer[4] = (frameID >> 8) & 0xFF; buffer[5] = (frameID) & 0xFF; buffer[6] = packetNum; buffer[7] = totalPackets; buffer[8] = (packetPayload >> 24) & 0xFF; buffer[9] = (packetPayload >> 16) & 0xFF; buffer[10] = (packetPayload >> 8) & 0xFF; buffer[11] = (packetPayload) & 0xFF; buffer[12] = (totalPayload >> 24) & 0xFF; buffer[13] = (totalPayload >> 16) & 0xFF; buffer[14] = (totalPayload >> 8) & 0xFF; buffer[15] = (totalPayload ) & 0xFF; memcpy(buffer + 16, vidType, 4); buffer[20] = (width >> 24) & 0xFF; buffer[21] = (width >> 16) & 0xFF; buffer[22] = (width >> 8) & 0xFF; buffer[23] = (width ) & 0xFF; buffer[24] = (height >> 24) & 0xFF; buffer[25] = (height >> 16) & 0xFF; buffer[26] = (height >> 8) & 0xFF; buffer[27] = (height ) & 0xFF; buffer[28] = fps; buffer[29] = 0; buffer[30] = 0; buffer[31] = 0; memcpy(buffer+32, (char*)imageBuffer, sizeb); send_message(&RN, buffer, sizeb+32); } catch (Euresys::MultiCam::Exception &e) { printf("Error during callback processing : %s\n", e.What()); } } void CPicoloGrab::AcqFailureCallback(Channel &channel, SignalInfo &info) { fprintf(stderr, "Acquisition Failure. Is a video signal connected ?\n"); } int main(int argc, char* argv[]) { CPicoloGrab *PicoloGrab; try { /* Initialize the MultiCam driver. */ Euresys::MultiCam::Initialize(); PicoloGrab = new CPicoloGrab(); if (PicoloGrab->Init() == FALSE) { delete PicoloGrab; /* Close the MultiCam driver. */ Euresys::MultiCam::Terminate(); return -1; } /* Acquire the images and process them.*/ PicoloGrab->AcquireImages(); delete PicoloGrab; /* Close the MultiCam driver. */ Euresys::MultiCam::Terminate(); } catch(Euresys::MultiCam::Exception &e) { printf("Error during image grabbing : %s\n", e.What()); } return 0; }
[ [ [ 1, 303 ] ] ]
f896f5eef9238bdbbc505d18dbbe9c081ef4bd1c
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_AIInterface/AIBear.h
11af7485325d0d5fe627cdca281ddbe186862db5
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
2,133
h
#ifndef __AI_BEAR_H #define __AI_BEAR_H #include "mempooler.h" class CAIBear : public CAIInterface { CTimer m_cTimeBuff; BOOL m_bEventFlag[5]; D3DXVECTOR3 m_vPosBegin; // 최초 생성된 좌표. int m_nEvent; // 현재 패턴 상태. int m_nAttackType; // 공격 방식. DWORD m_tmReattack; // 재공격 타이머. DWORD m_tmAddReattack; // 재공격 타이머의 랜덤변위값.(이 랜덤값으로 더 빨리 쏘는 경우도 생김) DWORD m_tmTrace; // 추적시간. DWORD m_tmTimeOver; // 예상치 못한 상황으로 더이상 공격을 안하던가 하는경우를 감별 OBJID m_idTarget; // 공격 대상 D3DXVECTOR3 m_vTarget; // 공격 위치. int m_nAppearCnt; // 등장 카운터. OBJID m_idLastAttacker; // 날 마지막으로 공격한 쉐리. BOOL m_bDefenseMode; // 방어태세 모드. BOOL MoveProcessIdle(); BOOL MoveProcessRage(); BOOL MoveProcessRunaway(); BOOL StopProcessIdle(); BOOL SelectTarget( void ); // 리어택 타이밍이 됬을때 타겟을 선정함. void Init( void ); void Destroy( void ); public: CAIBear(); CAIBear( CObj* pObj ); virtual ~CAIBear(); virtual void InitAI(); void SummonMonster( DWORD dwObjIndex, D3DXVECTOR3 vPos ); int GetEvent( void ) { return m_nEvent; } BOOL StateInit( const AIMSG & msg ); BOOL StateIdle( const AIMSG & msg ); BOOL StateWander( const AIMSG & msg ); BOOL StateRunaway( const AIMSG & msg ); BOOL StateEvade( const AIMSG & msg ); BOOL StateRage( const AIMSG & msg ); public: #ifndef __VM_0820 #ifndef __MEM_TRACE static MemPooler<CAIBear>* m_pPool; void* operator new( size_t nSize ) { return CAIBear::m_pPool->Alloc(); } void* operator new( size_t nSize, LPCSTR lpszFileName, int nLine ) { return CAIBear::m_pPool->Alloc(); } void operator delete( void* lpMem ) { CAIBear::m_pPool->Free( (CAIBear*)lpMem ); } void operator delete( void* lpMem, LPCSTR lpszFileName, int nLine ) { CAIBear::m_pPool->Free( (CAIBear*)lpMem ); } #endif // __MEM_TRACE #endif // __VM_0820 DECLARE_AISTATE() }; #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 69 ] ] ]
3d6f427ded0178ae3af42b9b4e6e42715da63675
2d72b8eb524b1dfe596ba142827d0aaf6809b5a5
/XYCQ/OgreMax/PGManager.cpp
7665aa6f3048cf109d824673f1a316415915699f
[]
no_license
sdfwds4/xuanyuanchuanqi
49194d5df8cb59224fb357e07a876729a19919fc
c4ebf9a1af46a270b74357aa2bb259ac4253bec6
refs/heads/master
2021-01-10T04:55:00.543614
2009-05-27T12:20:59
2009-05-27T12:20:59
46,041,443
0
0
null
null
null
null
UTF-8
C++
false
false
669
cpp
#include "PGManager.h" PGManager::PGManager(void): mCamera(0), mTrees(0),mTreeLoader(0), mBushes(0),mBushLoader(0), mGrass(0),mGrassLoader(0), mWorldSize(2000.0), mShow(PM_ALL) { } PGManager::~PGManager(void) { deInitialise(); } void PGManager::deInitialise() { if(mTreeLoader) { delete mTreeLoader; mTreeLoader = 0; } if(mTrees) { delete mTrees; mTrees = 0; } if(mBushLoader) { delete mBushLoader; mBushLoader = 0; } if(mBushes) { delete mBushes; mBushes = 0; } if(mGrassLoader) { delete mGrassLoader; mGrassLoader = 0; } if(mGrass) { delete mGrass; mGrass = 0; } }
[ "eplaylity@7a9255ae-169e-11de-b69a-45dc1c5e4070" ]
[ [ [ 1, 53 ] ] ]
18989dec0dbf425a79c183ca77c2fc4456bd8a0d
60bc06fb1bcb40b96533bfb9c8dd930c8d05bed5
/Freelancer Interfaces/CRCSupport.h
e3350f352232ed32f3e05a364e317bcc1cdb89f8
[]
no_license
TheStarport/FLDev
b69b6c42bc10cad1a48c6ac08fc17183e5fedf6d
21ff46442f359a26c3391fd4b27b9f74fd50869c
refs/heads/master
2023-02-22T07:50:09.661915
2010-11-22T04:18:48
2010-11-22T04:18:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,371
h
#pragma once using namespace System; using namespace System::IO; using namespace System::Text; using namespace System::Runtime::InteropServices; using namespace System::Threading; typedef unsigned long DWORD; typedef unsigned char BYTE; typedef struct TagFLHashContext { DWORD lookup[256]; } FLHashContext; DWORD FLHash (FLHashContext const *context, char const *text, size_t length); void InitFLHashContext (FLHashContext *context); static FLHashContext global_context; namespace Interfaces { // The main CRC class, manages loading files, parsing them and producing CRC database files public ref class UnCRCDatabase : ProcessingClass { public: UnCRCDatabase(String^ path, bool is_folder, String^ workdir); String^ SearchDB(Int64 CRC, bool %iscrc); String^ database_file_path; static DWORD GetFLHash(char const *text, unsigned int length) { return FLHash (&global_context, text, length); } static void InitializeGlobalContext() { InitFLHashContext(&global_context); } private: void ParseFolder(String^ path); void ParseFile(String^ path); void OpenDB(String^ path); void Optimize(); array<String^>^ names; array<Int64>^ crcs; array<Int64>^ hashes; StreamWriter^ dbsw; StreamReader^ dbsr; int parsed_files_count; }; // Very basic support for the UTF format public ref class UTF { public: UTF(String^ path); void ParseNode(array<Byte>^ buf, int nodeBlockStart, int nodeStart, int stringBlockOffset, String^ depth); }; public ref class FLCRC32 { // CRC32 table for Freelancer private: static array<unsigned int>^ flcrc32tbl = { 0x0, 0x9073096, 0x120E612C, 0x1B0951BA, 0xFF6DC419, 0xF66AF48F, 0xED63A535, 0xE46495A3, 0xFEDB8832, 0xF7DCB8A4, 0xECD5E91E, 0xE5D2D988, 0x1B64C2B, 0x8B17CBD, 0x13B82D07, 0x1ABF1D91, 0xFDB71064, 0xF4B020F2, 0xEFB97148, 0xE6BE41DE, 0x2DAD47D, 0xBDDE4EB, 0x10D4B551, 0x19D385C7, 0x36C9856, 0xA6BA8C0, 0x1162F97A, 0x1865C9EC, 0xFC015C4F, 0xF5066CD9, 0xEE0F3D63, 0xE7080DF5, 0xFB6E20C8, 0xF269105E, 0xE96041E4, 0xE0677172, 0x403E4D1, 0xD04D447, 0x160D85FD, 0x1F0AB56B, 0x5B5A8FA, 0xCB2986C, 0x17BBC9D6, 0x1EBCF940, 0xFAD86CE3, 0xF3DF5C75, 0xE8D60DCF, 0xE1D13D59, 0x6D930AC, 0xFDE003A, 0x14D75180, 0x1DD06116, 0xF9B4F4B5, 0xF0B3C423, 0xEBBA9599, 0xE2BDA50F, 0xF802B89E, 0xF1058808, 0xEA0CD9B2, 0xE30BE924, 0x76F7C87, 0xE684C11, 0x15611DAB, 0x1C662D3D, 0xF6DC4190, 0xFFDB7106, 0xE4D220BC, 0xEDD5102A, 0x9B18589, 0xB6B51F, 0x1BBFE4A5, 0x12B8D433, 0x807C9A2, 0x100F934, 0x1A09A88E, 0x130E9818, 0xF76A0DBB, 0xFE6D3D2D, 0xE5646C97, 0xEC635C01, 0xB6B51F4, 0x26C6162, 0x196530D8, 0x1062004E, 0xF40695ED, 0xFD01A57B, 0xE608F4C1, 0xEF0FC457, 0xF5B0D9C6, 0xFCB7E950, 0xE7BEB8EA, 0xEEB9887C, 0xADD1DDF, 0x3DA2D49, 0x18D37CF3, 0x11D44C65, 0xDB26158, 0x4B551CE, 0x1FBC0074, 0x16BB30E2, 0xF2DFA541, 0xFBD895D7, 0xE0D1C46D, 0xE9D6F4FB, 0xF369E96A, 0xFA6ED9FC, 0xE1678846, 0xE860B8D0, 0xC042D73, 0x5031DE5, 0x1E0A4C5F, 0x170D7CC9, 0xF005713C, 0xF90241AA, 0xE20B1010, 0xEB0C2086, 0xF68B525, 0x66F85B3, 0x1D66D409, 0x1461E49F, 0xEDEF90E, 0x7D9C998, 0x1CD09822, 0x15D7A8B4, 0xF1B33D17, 0xF8B40D81, 0xE3BD5C3B, 0xEABA6CAD, 0xEDB88320, 0xE4BFB3B6, 0xFFB6E20C, 0xF6B1D29A, 0x12D54739, 0x1BD277AF, 0xDB2615, 0x9DC1683, 0x13630B12, 0x1A643B84, 0x16D6A3E, 0x86A5AA8, 0xEC0ECF0B, 0xE509FF9D, 0xFE00AE27, 0xF7079EB1, 0x100F9344, 0x1908A3D2, 0x201F268, 0xB06C2FE, 0xEF62575D, 0xE66567CB, 0xFD6C3671, 0xF46B06E7, 0xEED41B76, 0xE7D32BE0, 0xFCDA7A5A, 0xF5DD4ACC, 0x11B9DF6F, 0x18BEEFF9, 0x3B7BE43, 0xAB08ED5, 0x16D6A3E8, 0x1FD1937E, 0x4D8C2C4, 0xDDFF252, 0xE9BB67F1, 0xE0BC5767, 0xFBB506DD, 0xF2B2364B, 0xE80D2BDA, 0xE10A1B4C, 0xFA034AF6, 0xF3047A60, 0x1760EFC3, 0x1E67DF55, 0x56E8EEF, 0xC69BE79, 0xEB61B38C, 0xE266831A, 0xF96FD2A0, 0xF068E236, 0x140C7795, 0x1D0B4703, 0x60216B9, 0xF05262F, 0x15BA3BBE, 0x1CBD0B28, 0x7B45A92, 0xEB36A04, 0xEAD7FFA7, 0xE3D0CF31, 0xF8D99E8B, 0xF1DEAE1D, 0x1B64C2B0, 0x1263F226, 0x96AA39C, 0x6D930A, 0xE40906A9, 0xED0E363F, 0xF6076785, 0xFF005713, 0xE5BF4A82, 0xECB87A14, 0xF7B12BAE, 0xFEB61B38, 0x1AD28E9B, 0x13D5BE0D, 0x8DCEFB7, 0x1DBDF21, 0xE6D3D2D4, 0xEFD4E242, 0xF4DDB3F8, 0xFDDA836E, 0x19BE16CD, 0x10B9265B, 0xBB077E1, 0x2B74777, 0x18085AE6, 0x110F6A70, 0xA063BCA, 0x3010B5C, 0xE7659EFF, 0xEE62AE69, 0xF56BFFD3, 0xFC6CCF45, 0xE00AE278, 0xE90DD2EE, 0xF2048354, 0xFB03B3C2, 0x1F672661, 0x166016F7, 0xD69474D, 0x46E77DB, 0x1ED16A4A, 0x17D65ADC, 0xCDF0B66, 0x5D83BF0, 0xE1BCAE53, 0xE8BB9EC5, 0xF3B2CF7F, 0xFAB5FFE9, 0x1DBDF21C, 0x14BAC28A, 0xFB39330, 0x6B4A3A6, 0xE2D03605, 0xEBD70693, 0xF0DE5729, 0xF9D967BF, 0xE3667A2E, 0xEA614AB8, 0xF1681B02, 0xF86F2B94, 0x1C0BBE37, 0x150C8EA1, 0xE05DF1B, 0x702EF8D, }; // Many thanks to Anton's CRCTool source for the algorithm and the CRC table! public: static unsigned int fl_crc32(String^ str) { unsigned int crc; crc = 0xFFFFFFFFL; for (unsigned int i = 0; i < static_cast<unsigned int> (str->Length); i++) crc = ((crc>>8) & 0x00FFFFFFL) ^ flcrc32tbl[(crc^ (str[i]) ) & 0xFF]; crc = crc^0xFFFFFFFFL; return crc; } }; }
[ [ [ 1, 137 ] ] ]
08753e9003deb02c1427383997f4c72b24500a8b
ed46c0131e0aeffc47589bfd34f705fd20031008
/server/connectionthread.h
3f8b956b1281d60f52738e093cda586640ded3c9
[]
no_license
locoman452/remsms
1f137790b76a550a40d4b336fafaa101c66f7458
c7a0c543181f19b4aeb499c2f64ec6ef284d70a4
refs/heads/master
2021-01-10T08:10:22.267508
2011-01-28T21:39:50
2011-01-28T21:39:50
53,303,564
0
0
null
null
null
null
UTF-8
C++
false
false
752
h
#ifndef CONNECTIONTHREAD_H #define CONNECTIONTHREAD_H #include <QThread> #include <QTcpSocket> #include <QXmlStreamReader> #include "smsmanager.h" #include "log.h" class ConnectionThread : public QThread { Q_OBJECT public: ConnectionThread(Log * logger, SMSManager * smsManager, int socketDescriptor, QObject *parent); ~ConnectionThread(); void run(); signals: void error(QTcpSocket::SocketError socketError); public slots: void readyRead(); private: Log * logger; void parseXml(); QTcpSocket *tcpSocket; int socketDescriptor; QString text; QXmlStreamReader xml; SMSManager * smsManager; quint16 blockSize; }; #endif // CONNECTIONTHREAD_H
[ [ [ 1, 41 ] ] ]
3155af128b73e679f1660bb07eb412e2e4abd2a2
6e563096253fe45a51956dde69e96c73c5ed3c18
/ZKit/ZKit_TestSuite.cpp
2ddcc963c759773ce31d70cbdd0fb144d2835ef4
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
943
cpp
#include "ZKit_TestSuite.h" #include <typeinfo.h> BEGIN_ZKIT TestSuite* TestSuite::m_instance = NULL; TestSuite* TestSuite::Instance() { if (m_instance == NULL) { m_instance = new TestSuite(); } return m_instance; }; void TestSuite::Add( TestFixture* test ) { m_tests.push_back(test); }; void TestSuite::Run() { TestFixture* t = NULL; using namespace std; for (Iterator i = m_tests.begin(); i != m_tests.end(); ++i) { t = *i; printf("\n**************Tests Begin******************"); printf("\nHello, I'm %s", (typeid(*t).name())); t->Run(); printf("\n**************Tests End********************"); } }; TestSuite::TestSuite() { }; TestSuite::~TestSuite() { for (Iterator i = m_tests.begin(); i != m_tests.end(); ++i) { TestFixture* t = (*i); delete t; t = NULL; } m_tests.clear(); }; void TestSuite::UnInstance() { delete m_instance; } END_ZKIT
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 57 ] ] ]
ed5f71c2595168120041b51a1141fe7154edaff6
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osgViewer/View
89422c57db10175ba9303eddcf0e5f76cceb7320
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
11,532
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #ifndef OSGVIEWER_VIEW #define OSGVIEWER_VIEW 1 #include <osg/View> #include <osgUtil/PolytopeIntersector> #include <osgUtil/LineSegmentIntersector> #include <osgUtil/UpdateVisitor> #include <osgUtil/SceneView> #include <osgGA/MatrixManipulator> #include <osgGA/EventVisitor> #include <osgGA/EventQueue> #include <osgViewer/Scene> #include <osgViewer/ViewerBase> namespace osgViewer { /** View holds a single view on a scene, this view may be composed of one or more slave cameras.*/ class OSGVIEWER_EXPORT View : public osg::View, public osgGA::GUIActionAdapter { public: View(); View(const osgViewer::View& view, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); META_Object(osgViewer,View); /** Provide a mechanism for getting the osg::View associated from the GUIActionAdapter. * One would use this to case view to osgViewer::View(er) if supported by the subclass.*/ virtual osg::View* asView() { return this; } /** Provide a mechanism for getting the viewer object from this osgViewer::View. * In the case of a osgViewer::Viewer the ViewerBase will effectively point to this object as Viewer subclasses from View. * In the case of a osgViewer::CompsoiteViewer the ViewerBase will point to the CompositeViewer that owns this View. */ ViewerBase* getViewerBase() { return _viewerBase.get(); } /** Take all the settings, Camera and Slaves from the passed in view, leaving it empty. */ virtual void take(osg::View& rhs); virtual void setStartTick(osg::Timer_t tick); osg::Timer_t getStartTick() const { return _startTick; } Scene* getScene() { return _scene.get(); } const Scene* getScene() const { return _scene.get(); } /** Set the scene graph that the View will use.*/ virtual void setSceneData(osg::Node* node); /** Get the View's scene graph.*/ osg::Node* getSceneData() { return _scene.valid() ? _scene->getSceneData() : 0; } /** Get the const View's scene graph.*/ const osg::Node* getSceneData() const { return _scene.valid() ? _scene->getSceneData() : 0; } /** Set the View's database pager.*/ void setDatabasePager(osgDB::DatabasePager* dp); /** Get the View's database pager.*/ osgDB::DatabasePager* getDatabasePager(); /** Get the const View's database pager.*/ const osgDB::DatabasePager* getDatabasePager() const; /** Set the View's image pager.*/ void setImagePager(osgDB::ImagePager* ip); /** Get the View's image pager.*/ osgDB::ImagePager* getImagePager(); /** Get the const View's image pager.*/ const osgDB::ImagePager* getImagePager() const; /* Set the EventQueue that View uses to integrate external non window related events.*/ void setEventQueue(osgGA::EventQueue* eventQueue) { _eventQueue = eventQueue; } /* Get the View's EventQueue.*/ osgGA::EventQueue* getEventQueue() { return _eventQueue.get(); } /* Get the const View's EventQueue.*/ const osgGA::EventQueue* getEventQueue() const { return _eventQueue.get(); } /** Set the CameraManipulator that moves the View's master Camera position in response to events. * The parameter resetPosition determines whether manipulator is set to its home position.*/ void setCameraManipulator(osgGA::MatrixManipulator* manipulator, bool resetPosition = true); /** Get the View's CameraManipulator.*/ osgGA::MatrixManipulator* getCameraManipulator() { return _cameraManipulator.get(); } /** Get the const View's CameraManipulator.*/ const osgGA::MatrixManipulator* getCameraManipulator() const { return _cameraManipulator.get(); } /** Set the view to the CameraManipulator's home position, if non is attached home() is does nothing. * Note, to set the home position use getCamaraManipulator()->setHomePosition(...). */ void home(); typedef std::list< osg::ref_ptr<osgGA::GUIEventHandler> > EventHandlers; /** Add an EventHandler that adds handling of events to the View.*/ void addEventHandler(osgGA::GUIEventHandler* eventHandler); /** Remove an EventHandler from View.*/ void removeEventHandler(osgGA::GUIEventHandler* eventHandler); /** Get the View's list of EventHandlers.*/ EventHandlers& getEventHandlers() { return _eventHandlers; } /** Get the const View's list of EventHandlers.*/ const EventHandlers& getEventHandlers() const { return _eventHandlers; } /** Set the NodePath to any active CoordinateSystemNode present in the Scene. * The CoordinateSystemNode path is used to help applications and CamaraManipualtors handle geocentric coordinates systems, * such as known which way is the local up at any position on the a whole earth. */ void setCoordinateSystemNodePath(const osg::NodePath& nodePath); /** Get the NodePath to any active CoordinateSystemNode present in the Scene.*/ osg::NodePath getCoordinateSystemNodePath() const; /** Compute the NodePath to any active CoordinateSystemNode present in the Scene.*/ void computeActiveCoordinateSystemNodePath(); /** Set the DisplaySettings object associated with this view.*/ void setDisplaySettings(osg::DisplaySettings* ds) { _displaySettings = ds; } /** Set the DisplaySettings object associated with this view.*/ osg::DisplaySettings* getDisplaySettings() { return _displaySettings.get(); } /** Set the DisplaySettings object associated with this view.*/ const osg::DisplaySettings* getDisplaySettings() const { return _displaySettings.get(); } /** Set the FusionDistanceMode and Value. Note, is used only when working in stereo.*/ void setFusionDistance(osgUtil::SceneView::FusionDistanceMode mode,float value=1.0f) { _fusionDistanceMode = mode; _fusionDistanceValue = value; } /** Get the FusionDistanceMode.*/ osgUtil::SceneView::FusionDistanceMode getFusionDistanceMode() const { return _fusionDistanceMode; } /** Get the FusionDistanceValue. Note, only used for USE_FUSION_DISTANCE_VALUE & PROPORTIONAL_TO_SCREEN_DISTANCE modes.*/ float getFusionDistanceValue() const { return _fusionDistanceValue; } /** Convenience method for creating slave Cameras and associated GraphicsWindows across all screens.*/ void setUpViewAcrossAllScreens(); /** Convenience method for a single camera on a single window.*/ void setUpViewInWindow(int x, int y, int width, int height, unsigned int screenNum=0); /** Convenience method for a single camera associated with a single full screen GraphicsWindow.*/ void setUpViewOnSingleScreen(unsigned int screenNum=0); /** Convenience method for spherical display using 6 slave cameras rendering the 6 sides of a cube map, and 7th camera doing distortion correction to present on a spherical display.*/ void setUpViewFor3DSphericalDisplay(double radius=1.0, double collar=0.45, unsigned int screenNum=0, osg::Image* intensityMap=0, const osg::Matrixd& projectorMatrix = osg::Matrixd()); /** Convenience method for spherical display by rendering main scene to as panoramic 2:1 texture and then doing distortion correction to present onto a spherical display.*/ void setUpViewForPanoramicSphericalDisplay(double radius=1.0, double collar=0.45, unsigned int screenNum=0, osg::Image* intensityMap=0, const osg::Matrixd& projectorMatrix = osg::Matrixd()); /** Convenience method for autostereoscopic Philips WoWvx display.*/ void setUpViewForWoWVxDisplay(unsigned int screenNum, unsigned char wow_content, unsigned char wow_factor, unsigned char wow_offset, float wow_disparity_Zd, float wow_disparity_vz, float wow_disparity_M, float wow_disparity_C); /** Return true if this view contains a specified camera.*/ bool containsCamera(const osg::Camera* camera) const; /** Get the camera which contains the pointer position x,y specified master cameras window/eye coords. * Also passes back the local window coords for the graphics context associated with the camera passed back. */ const osg::Camera* getCameraContainingPosition(float x, float y, float& local_x, float& local_y) const; /** Compute intersections between a ray through the specified master cameras window/eye coords and a specified node. * Note, when a master cameras has slaves and no viewport itself its coordinate frame will be in clip space i.e. -1,-1 to 1,1, * while if its has a viewport the coordintates will be relative to its viewport dimensions. * Mouse events handled by the view will automatically be attached into the master camera window/clip coords so can be passed * directly on to the computeIntersections method. */ bool computeIntersections(float x,float y, osgUtil::LineSegmentIntersector::Intersections& intersections,osg::Node::NodeMask traversalMask = 0xffffffff); /** Compute intersections between a ray through the specified master cameras window/eye coords and a specified nodePath's subgraph. */ bool computeIntersections(float x,float y, const osg::NodePath& nodePath, osgUtil::LineSegmentIntersector::Intersections& intersections,osg::Node::NodeMask traversalMask = 0xffffffff); virtual void requestRedraw(); virtual void requestContinuousUpdate(bool needed=true); virtual void requestWarpPointer(float x,float y); public: void assignSceneDataToCameras(); void init(); protected: friend class CompositeViewer; virtual ~View(); virtual osg::GraphicsOperation* createRenderer(osg::Camera* camera); osg::observer_ptr<ViewerBase> _viewerBase; osg::Timer_t _startTick; osg::ref_ptr<osgViewer::Scene> _scene; osg::ref_ptr<osgGA::EventQueue> _eventQueue; osg::ref_ptr<osgGA::MatrixManipulator> _cameraManipulator; EventHandlers _eventHandlers; osg::ObserverNodePath _coordinateSystemNodePath; osg::ref_ptr<osg::DisplaySettings> _displaySettings; osgUtil::SceneView::FusionDistanceMode _fusionDistanceMode; float _fusionDistanceValue; }; } #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 240 ] ] ]
7273363809c32396c32875b9d2856fcfcd979c6b
c63c4fed502fd4cbf82acc7901ba0d72b0338bdb
/Create/Map/GridMap.cpp
2b1cf9867f3468b48bda5321d83b25e9b9149c99
[]
no_license
seeyousystems/core
7436a38fb09ea08f5d29cf8db2490c92f48d9267
baddc89a366ad769a1a9c9a59c14f28291b81971
refs/heads/master
2020-05-17T19:11:57.814200
2011-05-06T04:00:59
2011-05-06T04:00:59
1,517,217
1
4
null
null
null
null
UTF-8
C++
false
false
1,817
cpp
/* * GridMap.cpp * * =========================================================================== * * Copyright 2008-2009 Daniel Kruesi (Dan Krusi) and David Grob * * This file is part of the emms framework. * * The emms framework 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. * * The emms framework 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 software. If not, see <http://www.gnu.org/licenses/>. * */ #include "GridMap.h" #include "../Library/Util.h" GridMap::GridMap(Create *create, long gridSize) : Map("GridMap", create) { this->gridSize = gridSize; gridColor = Util::convertStringToRGB(create->stringSetting("Map_GridMap_Color")); } GridMap::~GridMap() { } void GridMap::paint(QPainter &painter, QRect view) { long gs = create->mmToPixels(gridSize); painter.setPen(gridColor); painter.setOpacity(0.3); // Draw vertical lines for(int i = 0; i < (view.width() / (gs) + 2); i++) { int x = (gs * i) - (view.x() % gs); painter.drawLine(x, 0, x, (int)(view.height())); } // Draw horizontal lines for(int i = 0; i < (view.height() / (gs) + 2); i++) { int y = view.height() - (gs * i) + (view.y() % gs); painter.drawLine(0, y, (int)(view.width()), y); } } long GridMap::width() { return 0; } long GridMap::height() { return 0; }
[ [ [ 1, 65 ] ] ]
5d79e1255aba2aad3d88551ba2aafe4ab5d5b8db
30e4267e1a7fe172118bf26252aa2eb92b97a460
/code/pkg_Utility/Modules/ConfigDB/Cx_ConfigFactory.cpp
bf4405492327899b94d4d4aafda2a7c21ef58005
[ "Apache-2.0" ]
permissive
thinkhy/x3c_extension
f299103002715365160c274314f02171ca9d9d97
8a31deb466df5d487561db0fbacb753a0873a19c
refs/heads/master
2020-04-22T22:02:44.934037
2011-01-07T06:20:28
2011-01-07T06:20:28
1,234,211
2
0
null
null
null
null
UTF-8
C++
false
false
2,910
cpp
// Copyright 2008-2011 Zhang Yun Gui, [email protected] // https://sourceforge.net/projects/x3c/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "StdAfx.h" #include "Cx_ConfigFactory.h" #include "Cx_CfgDatabase.h" #include <Ix_FileUtility.h> #include "ClsID_Internal.h" #include "Ix_InitDatabase.h" #include "Cx_SQLParser.h" Cx_ConfigFactory::Cx_ConfigFactory() { } Cx_ConfigFactory::~Cx_ConfigFactory() { } Cx_Ptr Cx_ConfigFactory::OpenAccessDB(const std::wstring& filename, const std::wstring& user, const std::wstring& password) { Cx_Interface<Ix_FileUtility> pIFUtility(CLSID_FileUtility); if (pIFUtility && !pIFUtility->IsPathFileExists(filename.c_str())) { LOG_ERROR2(LOGHEAD L"IDS_NO_FILE", filename); return Cx_Ptr(); } if (pIFUtility && !pIFUtility->VerifyFileCanWrite(filename.c_str())) { LOG_ERROR2(LOGHEAD L"IDS_FILE_READONLY", filename); return Cx_Ptr(); } std::wostringstream conn; if (StrCmpIW(PathFindExtensionW(filename.c_str()), L".accdb") == 0) { conn << L"Provider=Microsoft.ACE.OLEDB.12.0;" ; } else { conn << L"Provider=Microsoft.Jet.OLEDB.4.0;" ; } conn << L"Data Source=" << filename << L";" ; if (!user.empty()) { conn << L"User Id=" << user << L";" ; } if (password.empty()) { conn << L"Password=" << password << L";" ; } else { conn << L"Jet OLEDB:Database Password=" << password << L";" ; } Cx_Interface<Ix_InitDatabase> pIFDB(CLSID_CfgDatabase); ASSERT(pIFDB.IsNotNull()); return pIFDB->OpenConnection(conn.str(), new SQLParser_Access()) ? Cx_Ptr(pIFDB) : Cx_Ptr(); } Cx_Ptr Cx_ConfigFactory::OpenSQLServerDB(const std::wstring& server, const std::wstring& database, const std::wstring& user, const std::wstring& password) { if (server.empty() || database.empty()) { return Cx_Ptr(); } std::wostringstream conn; conn << L"Provider=SQLOLEDB;" << L"Data Source=" << server << L";" << L"Initial Catalog=" << database << L";"; if (!user.empty()) { conn << L"User ID=" << user << L";" ; conn << L"Password=" << password << L";" ; } Cx_Interface<Ix_InitDatabase> pIFDB(CLSID_CfgDatabase); ASSERT(pIFDB.IsNotNull()); return pIFDB->OpenConnection(conn.str(), new SQLParser_SQLServer()) ? Cx_Ptr(pIFDB) : Cx_Ptr(); }
[ "rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3" ]
[ [ [ 1, 108 ] ] ]
d6e968b4e7471ff3f351970935937e5a42212335
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEApplications/SE_OGLES2_Application/SEOGLES2Application/SEWindowApplication.cpp
15492d35da369c3eebc64c32089a8d00f9383bf6
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
GB18030
C++
false
false
4,130
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "SEOGLES2ApplicationPCH.h" #include "SEWindowApplication.h" using namespace Swing; //---------------------------------------------------------------------------- SEWindowApplication::SEWindowApplication(const char* acWindowTitle, int iXPosition, int iYPosition, int iWidth, int iHeight, const SEColorRGBA& rBackgroundColor) : m_acWindowTitle(acWindowTitle), m_iXPosition(iXPosition), m_iYPosition(iYPosition), m_iWidth(iWidth), m_iHeight(iHeight), m_BackgroundColor(rBackgroundColor) { m_iWindowID = 0; m_pRenderer = 0; // 默认frame buffer参数. // 这些参数可以被派生类构造函数覆盖. // 当前硬件经常使用24bit depth buffer,8bit stencil buffer,建议不要修改. // 最常修改的是multisampling值. m_eFormat = SEFrameBuffer::FT_FORMAT_RGBA; m_eDepth = SEFrameBuffer::DT_DEPTH_24; m_eStencil = SEFrameBuffer::ST_STENCIL_8; m_eBuffering = SEFrameBuffer::BT_BUFFERED_DOUBLE; m_eMultisampling = SEFrameBuffer::MT_SAMPLING_NONE; m_pAudioRenderer= 0; } //---------------------------------------------------------------------------- SEWindowApplication::~SEWindowApplication() { } //---------------------------------------------------------------------------- int SEWindowApplication::Run(int iArgCount, char** apcArgument) { SEWindowApplication* pTheApp = (SEWindowApplication*)TheApplication; return pTheApp->Main(iArgCount, apcArgument); } //---------------------------------------------------------------------------- bool SEWindowApplication::OnInitialize() { m_pRenderer->SetClearColor(m_BackgroundColor); // 通知catalogs,渲染器已经创建. SE_ASSERT( SEVertexProgramCatalog::GetActive() ); SEVertexProgramCatalog::GetActive()->SetRenderer(m_pRenderer); SE_ASSERT( SEPixelProgramCatalog::GetActive() ); SEPixelProgramCatalog::GetActive()->SetRenderer(m_pRenderer); return true; } //---------------------------------------------------------------------------- void SEWindowApplication::OnTerminate() { // 通知catalogs,渲染器即将被释放, // 因此可以删除默认shader程序了. SE_ASSERT( SEVertexProgramCatalog::GetActive() ); SEVertexProgramCatalog::GetActive()->SetRenderer(0); SE_ASSERT( SEPixelProgramCatalog::GetActive() ); SEPixelProgramCatalog::GetActive()->SetRenderer(0); SE_DELETE m_pRenderer; m_pRenderer = 0; SE_DELETE m_pAudioRenderer; m_pAudioRenderer = 0; } //---------------------------------------------------------------------------- void SEWindowApplication::OnMove(int iX, int iY) { m_iXPosition = iX; m_iYPosition = iY; } //---------------------------------------------------------------------------- void SEWindowApplication::OnResize(int iWidth, int iHeight) { if( iWidth > 0 && iHeight > 0 ) { if( m_pRenderer ) { m_pRenderer->Resize(iWidth, iHeight); } m_iWidth = iWidth; m_iHeight = iHeight; } } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 115 ] ] ]
c5000dce993e6526574ecf0fb2d47cce7f48b219
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/test/impl/exception_safety.ipp
033f015807be497d1d004e3b111d2d7a5b3c0adc
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
18,756
ipp
// (C) Copyright Gennadiy Rozental 2005. // Use, modification, and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile: exception_safety.ipp,v $ // // Version : $Revision: 1.7.2.1 $ // // Description : Facilities to perform exception safety tests // *************************************************************************** #ifndef BOOST_TEST_EXECUTION_SAFETY_IPP_112005GER #define BOOST_TEST_EXECUTION_SAFETY_IPP_112005GER // Boost.Test #include <boost/test/detail/config.hpp> #if !BOOST_WORKAROUND(__GNUC__, < 3) && \ !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) && \ !BOOST_WORKAROUND(BOOST_MSVC, <1310) && \ !BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x530)) #include <boost/test/detail/global_typedef.hpp> #include <boost/test/detail/unit_test_parameters.hpp> #include <boost/test/utils/callback.hpp> #include <boost/test/utils/wrap_stringstream.hpp> #include <boost/test/utils/iterator/token_iterator.hpp> #include <boost/test/interaction_based.hpp> #include <boost/test/test_tools.hpp> #include <boost/test/unit_test_log.hpp> #include <boost/test/framework.hpp> #include <boost/test/test_observer.hpp> #include <boost/test/detail/suppress_warnings.hpp> // Boost #include <boost/lexical_cast.hpp> // STL #include <vector> #include <cstdlib> #include <map> #include <iomanip> #include <cctype> #include <boost/limits.hpp> //____________________________________________________________________________// namespace boost { using namespace ::boost::unit_test; namespace itest { // ************************************************************************** // // ************** execution_path_point ************** // // ************************************************************************** // enum exec_path_point_type { EPP_SCOPE, EPP_EXCEPT, EPP_DECISION, EPP_ALLOC }; struct execution_path_point { execution_path_point( exec_path_point_type t, const_string file, std::size_t line_num ) : m_type( t ) , m_file_name( file ) , m_line_num( line_num ) {} exec_path_point_type m_type; const_string m_file_name; std::size_t m_line_num; // Execution path point specific struct decision_data { bool value; unsigned forced_exception_point; }; struct scope_data { unsigned size; char const* name; }; struct except_data { char const* description; }; struct alloc_data { void* ptr; std::size_t size; }; union { struct decision_data m_decision; struct scope_data m_scope; struct except_data m_except; struct alloc_data m_alloc; }; }; // ************************************************************************** // // ************** exception safety test implementation ************** // // ************************************************************************** // struct exception_safety_tester : itest::manager, test_observer { // helpers types struct unique_exception {}; // Constructor explicit exception_safety_tester( const_string test_name ); ~exception_safety_tester(); // check last run and prepare for next bool next_execution_path(); // memory tracking // manager interface implementation virtual void exception_point( const_string file, std::size_t line_num, const_string description ); virtual bool decision_point( const_string file, std::size_t line_num ); virtual unsigned enter_scope( const_string file, std::size_t line_num, const_string scope_name ); virtual void leave_scope( unsigned enter_scope_point ); virtual void allocated( const_string file, std::size_t line_num, void* p, std::size_t s ); virtual void freed( void* p ); // test observer interface virtual void assertion_result( bool passed ); virtual int priority() { return (std::numeric_limits<int>::max)(); } // we want this observer to run the last private: void failure_point(); void report_error(); typedef std::vector<execution_path_point> exec_path; typedef std::map<void*,unsigned> registry; // Data members bool m_internal_activity; unsigned m_exception_point_counter; unsigned m_forced_exception_point; unsigned m_exec_path_point; exec_path m_execution_path; unsigned m_exec_path_counter; unsigned m_break_exec_path; bool m_invairant_failed; registry m_memory_in_use; }; //____________________________________________________________________________// struct activity_guard { bool& m_v; activity_guard( bool& v ) : m_v( v ) { m_v = true; } ~activity_guard() { m_v = false; } }; //____________________________________________________________________________// exception_safety_tester::exception_safety_tester( const_string test_name ) : m_internal_activity( true ) , m_exception_point_counter( 0 ) , m_forced_exception_point( 1 ) , m_exec_path_point( 0 ) , m_exec_path_counter( 1 ) , m_break_exec_path( (unsigned)-1 ) , m_invairant_failed( false ) { framework::register_observer( *this ); if( !runtime_config::break_exec_path().is_empty() ) { using namespace unit_test; string_token_iterator tit( runtime_config::break_exec_path(), (dropped_delimeters = ":",kept_delimeters = " ") ); const_string test_to_break = *tit; if( test_to_break == test_name ) { ++tit; m_break_exec_path = lexical_cast<unsigned>( *tit ); } } m_internal_activity = false; } //____________________________________________________________________________// exception_safety_tester::~exception_safety_tester() { m_internal_activity = true; framework::deregister_observer( *this ); } //____________________________________________________________________________// bool exception_safety_tester::next_execution_path() { activity_guard ag( m_internal_activity ); // check memory usage if( m_execution_path.size() > 0 ) { bool errors_detected = m_invairant_failed || (m_memory_in_use.size() != 0); framework::assertion_result( !errors_detected ); if( errors_detected ) report_error(); m_memory_in_use.clear(); } m_exec_path_point = 0; m_exception_point_counter = 0; m_invairant_failed = false; ++m_exec_path_counter; while( m_execution_path.size() > 0 ) { switch( m_execution_path.back().m_type ) { case EPP_SCOPE: case EPP_ALLOC: m_execution_path.pop_back(); break; case EPP_DECISION: if( !m_execution_path.back().m_decision.value ) { m_execution_path.pop_back(); break; } m_execution_path.back().m_decision.value = false; m_forced_exception_point = m_execution_path.back().m_decision.forced_exception_point; return true; case EPP_EXCEPT: m_execution_path.pop_back(); ++m_forced_exception_point; return true; } } BOOST_TEST_MESSAGE( "Total tested " << --m_exec_path_counter << " execution path" ); return false; } //____________________________________________________________________________// void exception_safety_tester::exception_point( const_string file, std::size_t line_num, const_string description ) { activity_guard ag( m_internal_activity ); if( ++m_exception_point_counter == m_forced_exception_point ) { m_execution_path.push_back( execution_path_point( EPP_EXCEPT, file, line_num ) ); m_execution_path.back().m_except.description = description.begin(); ++m_exec_path_point; failure_point(); } } //____________________________________________________________________________// bool exception_safety_tester::decision_point( const_string file, std::size_t line_num ) { activity_guard ag( m_internal_activity ); if( m_exec_path_point < m_execution_path.size() ) { BOOST_REQUIRE_MESSAGE( m_execution_path[m_exec_path_point].m_type == EPP_DECISION && m_execution_path[m_exec_path_point].m_file_name == file && m_execution_path[m_exec_path_point].m_line_num == line_num, "Function under test exibit non-deterministic behavior" ); } else { m_execution_path.push_back( execution_path_point( EPP_DECISION, file, line_num ) ); m_execution_path.back().m_decision.value = true; m_execution_path.back().m_decision.forced_exception_point = m_forced_exception_point; } return m_execution_path[m_exec_path_point++].m_decision.value; } //____________________________________________________________________________// unsigned exception_safety_tester::enter_scope( const_string file, std::size_t line_num, const_string scope_name ) { activity_guard ag( m_internal_activity ); if( m_exec_path_point < m_execution_path.size() ) { BOOST_REQUIRE_MESSAGE( m_execution_path[m_exec_path_point].m_type == EPP_SCOPE && m_execution_path[m_exec_path_point].m_file_name == file && m_execution_path[m_exec_path_point].m_line_num == line_num, "Function under test exibit non-deterministic behavior" ); } else { m_execution_path.push_back( execution_path_point( EPP_SCOPE, file, line_num ) ); } m_execution_path[m_exec_path_point].m_scope.size = 0; m_execution_path[m_exec_path_point].m_scope.name = scope_name.begin(); return m_exec_path_point++; } //____________________________________________________________________________// void exception_safety_tester::leave_scope( unsigned enter_scope_point ) { activity_guard ag( m_internal_activity ); BOOST_REQUIRE_MESSAGE( m_execution_path[enter_scope_point].m_type == EPP_SCOPE, "Function under test exibit non-deterministic behavior" ); m_execution_path[enter_scope_point].m_scope.size = m_exec_path_point - enter_scope_point; } //____________________________________________________________________________// void exception_safety_tester::allocated( const_string file, std::size_t line_num, void* p, std::size_t s ) { if( m_internal_activity ) return; activity_guard ag( m_internal_activity ); if( m_exec_path_point < m_execution_path.size() ) BOOST_REQUIRE_MESSAGE( m_execution_path[m_exec_path_point].m_type == EPP_ALLOC, "Function under test exibit non-deterministic behavior" ); else m_execution_path.push_back( execution_path_point( EPP_ALLOC, file, line_num ) ); m_execution_path[m_exec_path_point].m_alloc.ptr = p; m_execution_path[m_exec_path_point].m_alloc.size = s; m_memory_in_use.insert( std::make_pair( p, m_exec_path_point++ ) ); } //____________________________________________________________________________// void exception_safety_tester::freed( void* p ) { if( m_internal_activity ) return; activity_guard ag( m_internal_activity ); registry::iterator it = m_memory_in_use.find( p ); if( it != m_memory_in_use.end() ) { m_execution_path[it->second].m_alloc.ptr = 0; m_memory_in_use.erase( it ); } } //____________________________________________________________________________// void exception_safety_tester::assertion_result( bool passed ) { if( !m_internal_activity && !passed ) { m_invairant_failed = true; failure_point(); } } //____________________________________________________________________________// void exception_safety_tester::failure_point() { if( m_exec_path_counter == m_break_exec_path ) BOOST_ASSERT( false ); throw unique_exception(); } //____________________________________________________________________________// namespace { inline void format_location( wrap_stringstream& formatter, execution_path_point const& p, unsigned indent ) { if( indent ) formatter << std::left << std::setw( indent ) << ""; // !! ?? optional if( p.m_file_name ) // formatter << p.m_file_name << '(' << p.m_line_num << "): "; } //____________________________________________________________________________// template<typename ExecPathIt> inline void format_execution_path( wrap_stringstream& formatter, ExecPathIt it, ExecPathIt end, unsigned indent = 0 ) { while( it != end ) { switch( it->m_type ) { case EPP_SCOPE: format_location( formatter, *it, indent ); formatter << "> \"" << it->m_scope.name << "\"\n"; format_execution_path( formatter, it+1, it + it->m_scope.size, indent + 2 ); format_location( formatter, *it, indent ); formatter << "< \"" << it->m_scope.name << "\"\n"; it += it->m_scope.size; break; case EPP_DECISION: format_location( formatter, *it, indent ); formatter << "Decision made as " << std::boolalpha << it->m_decision.value << '\n'; ++it; break; case EPP_EXCEPT: format_location( formatter, *it, indent ); formatter << "Forced failure"; if( it->m_except.description ) formatter << ": " << it->m_except.description; formatter << "\n"; ++it; break; case EPP_ALLOC: if( it->m_alloc.ptr ) { format_location( formatter, *it, indent ); formatter << "Allocated memory block 0x" << std::uppercase << it->m_alloc.ptr << ", " << it->m_alloc.size << " bytes long: <"; unsigned i; for( i = 0; i < std::min<std::size_t>( it->m_alloc.size, 8 ); i++ ) { unsigned char c = ((unsigned char*)it->m_alloc.ptr)[i]; if( std::isprint( c ) ) formatter << c; else formatter << '.'; } formatter << "> "; for( i = 0; i < std::min<std::size_t>( it->m_alloc.size, 8 ); i++ ) { unsigned c = ((unsigned char*)it->m_alloc.ptr)[i]; formatter << std::hex << std::uppercase << c << ' '; } formatter << "\n"; } ++it; break; } } } //____________________________________________________________________________// } // local namespace void exception_safety_tester::report_error() { activity_guard ag( m_internal_activity ); unit_test_log << unit_test::log::begin( m_execution_path.back().m_file_name, m_execution_path.back().m_line_num ) << log_all_errors; wrap_stringstream formatter; if( m_invairant_failed ) formatter << "Failed invariant"; if( m_memory_in_use.size() != 0 ) { if( m_invairant_failed ) formatter << " and "; formatter << m_memory_in_use.size() << " memory leak"; if( m_memory_in_use.size() > 1 ) formatter << 's'; } formatter << " detected in the execution path " << m_exec_path_counter << ":\n"; format_execution_path( formatter, m_execution_path.begin(), m_execution_path.end() ); unit_test_log << const_string( formatter.str() ) << unit_test::log::end(); } //____________________________________________________________________________// // ************************************************************************** // // ************** exception safety test ************** // // ************************************************************************** // void BOOST_TEST_DECL exception_safety( callback0<> const& F, const_string test_name ) { exception_safety_tester est( test_name ); do { try { F(); } catch( exception_safety_tester::unique_exception const& ) {} } while( est.next_execution_path() ); } //____________________________________________________________________________// } // namespace itest } // namespace boost //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> #endif // non-ancient compiler // *************************************************************************** // Revision History : // // $Log: exception_safety.ipp,v $ // Revision 1.7.2.1 2006/07/27 11:48:49 gennaro_prota // boost guidelines (mainly from inspect tool: tabs, license reference text, etc.); more to do... // // Revision 1.7 2006/02/23 15:10:00 rogeeff // vc70 out // // Revision 1.6 2006/02/06 10:06:56 rogeeff // MSVC restored for now // // Revision 1.5 2006/01/28 08:52:35 rogeeff // operator new overloads made inline to: // 1. prevent issues with export them from DLL // 2. release link issue fixed // // Revision 1.4 2006/01/15 11:14:39 rogeeff // simpl_mock -> mock_object<>::prototype() // operator new need to be rethinked // // Revision 1.3 2005/12/22 15:49:32 rogeeff // sunpro port // made operator new conformant // // Revision 1.2 2005/12/16 02:33:17 rogeeff // portability fix // // Revision 1.1 2005/12/14 05:56:09 rogeeff // exception safety testing introduced // // *************************************************************************** #endif // BOOST_TEST_EXECUTION_SAFETY_IPP_112005GER
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 573 ] ] ]
2a67a6c7465ad30a3be9572e720c858f2035b4ba
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/multiplayer/dmc/cl_dll/inputw32.cpp
421c088d3d40b07c6f58519940ec8cad3623a91e
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
23,085
cpp
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= // in_win.c -- windows 95 mouse and joystick code // 02/21/97 JCB Added extended DirectInput code to support external controllers. #include "hud.h" #include "cl_util.h" #include "camera.h" #include "kbutton.h" #include "cvardef.h" #include "usercmd.h" #include "const.h" #include "camera.h" #include "in_defs.h" #include "../engine/keydefs.h" #include "view.h" #include "windows.h" #define MOUSE_BUTTON_COUNT 5 // Set this to 1 to show mouse cursor. Experimental int g_iVisibleMouse = 0; extern "C" { void DLLEXPORT IN_ActivateMouse( void ); void DLLEXPORT IN_DeactivateMouse( void ); void DLLEXPORT IN_MouseEvent (int mstate); void DLLEXPORT IN_Accumulate (void); void DLLEXPORT IN_ClearStates (void); } extern cl_enginefunc_t gEngfuncs; extern int iMouseInUse; extern kbutton_t in_strafe; extern kbutton_t in_mlook; extern kbutton_t in_speed; extern kbutton_t in_jlook; extern cvar_t *m_pitch; extern cvar_t *m_yaw; extern cvar_t *m_forward; extern cvar_t *m_side; extern cvar_t *lookstrafe; extern cvar_t *lookspring; extern cvar_t *cl_pitchdown; extern cvar_t *cl_pitchup; extern cvar_t *cl_yawspeed; extern cvar_t *cl_sidespeed; extern cvar_t *cl_forwardspeed; extern cvar_t *cl_pitchspeed; extern cvar_t *cl_movespeedkey; // mouse variables cvar_t *m_filter; cvar_t *sensitivity; int mouse_buttons; int mouse_oldbuttonstate; POINT current_pos; int mouse_x, mouse_y, old_mouse_x, old_mouse_y, mx_accum, my_accum; static int restore_spi; static int originalmouseparms[3], newmouseparms[3] = {0, 0, 1}; static int mouseactive; int mouseinitialized; static int mouseparmsvalid; static int mouseshowtoggle = 1; // joystick defines and variables // where should defines be moved? #define JOY_ABSOLUTE_AXIS 0x00000000 // control like a joystick #define JOY_RELATIVE_AXIS 0x00000010 // control like a mouse, spinner, trackball #define JOY_MAX_AXES 6 // X, Y, Z, R, U, V #define JOY_AXIS_X 0 #define JOY_AXIS_Y 1 #define JOY_AXIS_Z 2 #define JOY_AXIS_R 3 #define JOY_AXIS_U 4 #define JOY_AXIS_V 5 enum _ControlList { AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn }; DWORD dwAxisFlags[JOY_MAX_AXES] = { JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV }; DWORD dwAxisMap[ JOY_MAX_AXES ]; DWORD dwControlMap[ JOY_MAX_AXES ]; PDWORD pdwRawValue[ JOY_MAX_AXES ]; // none of these cvars are saved over a session // this means that advanced controller configuration needs to be executed // each time. this avoids any problems with getting back to a default usage // or when changing from one controller to another. this way at least something // works. cvar_t *in_joystick; cvar_t *joy_name; cvar_t *joy_advanced; cvar_t *joy_advaxisx; cvar_t *joy_advaxisy; cvar_t *joy_advaxisz; cvar_t *joy_advaxisr; cvar_t *joy_advaxisu; cvar_t *joy_advaxisv; cvar_t *joy_forwardthreshold; cvar_t *joy_sidethreshold; cvar_t *joy_pitchthreshold; cvar_t *joy_yawthreshold; cvar_t *joy_forwardsensitivity; cvar_t *joy_sidesensitivity; cvar_t *joy_pitchsensitivity; cvar_t *joy_yawsensitivity; cvar_t *joy_wwhack1; cvar_t *joy_wwhack2; int joy_avail, joy_advancedinit, joy_haspov; DWORD joy_oldbuttonstate, joy_oldpovstate; int joy_id; DWORD joy_flags; DWORD joy_numbuttons; static JOYINFOEX ji; /* =========== Force_CenterView_f =========== */ void Force_CenterView_f (void) { vec3_t viewangles; if (!iMouseInUse) { gEngfuncs.GetViewAngles( (float *)viewangles ); viewangles[PITCH] = 0; gEngfuncs.SetViewAngles( (float *)viewangles ); } } /* =========== IN_ActivateMouse =========== */ void DLLEXPORT IN_ActivateMouse (void) { if (mouseinitialized) { if (mouseparmsvalid) restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0); mouseactive = 1; } } /* =========== IN_DeactivateMouse =========== */ void DLLEXPORT IN_DeactivateMouse (void) { if (mouseinitialized) { if (restore_spi) SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0); mouseactive = 0; } } /* =========== IN_StartupMouse =========== */ void IN_StartupMouse (void) { if ( gEngfuncs.CheckParm ("-nomouse", NULL ) ) return; mouseinitialized = 1; mouseparmsvalid = SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0); if (mouseparmsvalid) { if ( gEngfuncs.CheckParm ("-noforcemspd", NULL ) ) newmouseparms[2] = originalmouseparms[2]; if ( gEngfuncs.CheckParm ("-noforcemaccel", NULL ) ) { newmouseparms[0] = originalmouseparms[0]; newmouseparms[1] = originalmouseparms[1]; } if ( gEngfuncs.CheckParm ("-noforcemparms", NULL ) ) { newmouseparms[0] = originalmouseparms[0]; newmouseparms[1] = originalmouseparms[1]; newmouseparms[2] = originalmouseparms[2]; } } mouse_buttons = MOUSE_BUTTON_COUNT; } /* =========== IN_Shutdown =========== */ void IN_Shutdown (void) { IN_DeactivateMouse (); } /* =========== IN_GetMousePos Ask for mouse position from engine =========== */ void IN_GetMousePos( int *mx, int *my ) { gEngfuncs.GetMousePosition( mx, my ); } /* =========== IN_ResetMouse FIXME: Call through to engine? =========== */ void IN_ResetMouse( void ) { SetCursorPos ( gEngfuncs.GetWindowCenterX(), gEngfuncs.GetWindowCenterY() ); } /* =========== IN_MouseEvent =========== */ void DLLEXPORT IN_MouseEvent (int mstate) { int i; if ( !mouseactive ) return; // perform button actions for (i=0 ; i<mouse_buttons ; i++) { if ( (mstate & (1<<i)) && !(mouse_oldbuttonstate & (1<<i)) ) { gEngfuncs.Key_Event (K_MOUSE1 + i, 1); } if ( !(mstate & (1<<i)) && (mouse_oldbuttonstate & (1<<i)) ) { gEngfuncs.Key_Event (K_MOUSE1 + i, 0); } } mouse_oldbuttonstate = mstate; } /* =========== IN_MouseMove =========== */ void IN_MouseMove ( float frametime, usercmd_t *cmd) { int mx, my; vec3_t viewangles; gEngfuncs.GetViewAngles( (float *)viewangles ); if ( in_mlook.state & 1) { V_StopPitchDrift (); } //jjb - this disbles normal mouse control if the user is trying to // move the camera if ( !iMouseInUse && !g_iVisibleMouse ) { GetCursorPos (&current_pos); mx = current_pos.x - gEngfuncs.GetWindowCenterX() + mx_accum; my = current_pos.y - gEngfuncs.GetWindowCenterY() + my_accum; mx_accum = 0; my_accum = 0; if (m_filter->value) { mouse_x = (mx + old_mouse_x) * 0.5; mouse_y = (my + old_mouse_y) * 0.5; } else { mouse_x = mx; mouse_y = my; } old_mouse_x = mx; old_mouse_y = my; if ( gHUD.GetSensitivity() != 0 ) { mouse_x *= gHUD.GetSensitivity(); mouse_y *= gHUD.GetSensitivity(); } else { mouse_x *= sensitivity->value; mouse_y *= sensitivity->value; } // add mouse X/Y movement to cmd if ( (in_strafe.state & 1) || (lookstrafe->value && (in_mlook.state & 1) )) cmd->sidemove += m_side->value * mouse_x; else viewangles[YAW] -= m_yaw->value * mouse_x; if ( (in_mlook.state & 1) && !(in_strafe.state & 1)) { viewangles[PITCH] += m_pitch->value * mouse_y; if (viewangles[PITCH] > cl_pitchdown->value) viewangles[PITCH] = cl_pitchdown->value; if (viewangles[PITCH] < -cl_pitchup->value) viewangles[PITCH] = -cl_pitchup->value; } else { if ((in_strafe.state & 1) && gEngfuncs.IsNoClipping() ) { cmd->upmove -= m_forward->value * mouse_y; } else { cmd->forwardmove -= m_forward->value * mouse_y; } } // if the mouse has moved, force it to the center, so there's room to move if ( mx || my ) { IN_ResetMouse(); } } gEngfuncs.SetViewAngles( (float *)viewangles ); /* //#define TRACE_TEST #if defined( TRACE_TEST ) { int mx, my; void V_Move( int mx, int my ); IN_GetMousePos( &mx, &my ); V_Move( mx, my ); } #endif */ } /* =========== IN_Accumulate =========== */ void DLLEXPORT IN_Accumulate (void) { //only accumulate mouse if we are not moving the camera with the mouse if ( !iMouseInUse && !g_iVisibleMouse ) { if (mouseactive) { GetCursorPos (&current_pos); mx_accum += current_pos.x - gEngfuncs.GetWindowCenterX(); my_accum += current_pos.y - gEngfuncs.GetWindowCenterY(); // force the mouse to the center, so there's room to move IN_ResetMouse(); } } } /* =================== IN_ClearStates =================== */ void DLLEXPORT IN_ClearStates (void) { if ( !mouseactive ) return; mx_accum = 0; my_accum = 0; mouse_oldbuttonstate = 0; } /* =============== IN_StartupJoystick =============== */ void IN_StartupJoystick (void) { int numdevs; JOYCAPS jc; MMRESULT mmr; // assume no joystick joy_avail = 0; // abort startup if user requests no joystick if ( gEngfuncs.CheckParm ("-nojoy", NULL ) ) return; // verify joystick driver is present if ((numdevs = joyGetNumDevs ()) == 0) { gEngfuncs.Con_DPrintf ("joystick not found -- driver not present\n\n"); return; } // cycle through the joystick ids for the first valid one for (joy_id=0 ; joy_id<numdevs ; joy_id++) { memset (&ji, 0, sizeof(ji)); ji.dwSize = sizeof(ji); ji.dwFlags = JOY_RETURNCENTERED; if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR) break; } // abort startup if we didn't find a valid joystick if (mmr != JOYERR_NOERROR) { gEngfuncs.Con_DPrintf ("joystick not found -- no valid joysticks (%x)\n\n", mmr); return; } // get the capabilities of the selected joystick // abort startup if command fails memset (&jc, 0, sizeof(jc)); if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR) { gEngfuncs.Con_DPrintf ("joystick not found -- invalid joystick capabilities (%x)\n\n", mmr); return; } // save the joystick's number of buttons and POV status joy_numbuttons = jc.wNumButtons; joy_haspov = jc.wCaps & JOYCAPS_HASPOV; // old button and POV states default to no buttons pressed joy_oldbuttonstate = joy_oldpovstate = 0; // mark the joystick as available and advanced initialization not completed // this is needed as cvars are not available during initialization gEngfuncs.Con_Printf ("joystick found\n\n", mmr); joy_avail = 1; joy_advancedinit = 0; } /* =========== RawValuePointer =========== */ PDWORD RawValuePointer (int axis) { switch (axis) { case JOY_AXIS_X: return &ji.dwXpos; case JOY_AXIS_Y: return &ji.dwYpos; case JOY_AXIS_Z: return &ji.dwZpos; case JOY_AXIS_R: return &ji.dwRpos; case JOY_AXIS_U: return &ji.dwUpos; case JOY_AXIS_V: return &ji.dwVpos; } // FIX: need to do some kind of error return &ji.dwXpos; } /* =========== Joy_AdvancedUpdate_f =========== */ void Joy_AdvancedUpdate_f (void) { // called once by IN_ReadJoystick and by user whenever an update is needed // cvars are now available int i; DWORD dwTemp; // initialize all the maps for (i = 0; i < JOY_MAX_AXES; i++) { dwAxisMap[i] = AxisNada; dwControlMap[i] = JOY_ABSOLUTE_AXIS; pdwRawValue[i] = RawValuePointer(i); } if( joy_advanced->value == 0.0) { // default joystick initialization // 2 axes only with joystick control dwAxisMap[JOY_AXIS_X] = AxisTurn; // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS; dwAxisMap[JOY_AXIS_Y] = AxisForward; // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS; } else { if ( strcmp ( joy_name->string, "joystick") != 0 ) { // notify user of advanced controller gEngfuncs.Con_Printf ("\n%s configured\n\n", joy_name->string); } // advanced initialization here // data supplied by user via joy_axisn cvars dwTemp = (DWORD) joy_advaxisx->value; dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisy->value; dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisz->value; dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisr->value; dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisu->value; dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisv->value; dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS; } // compute the axes to collect from DirectInput joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV; for (i = 0; i < JOY_MAX_AXES; i++) { if (dwAxisMap[i] != AxisNada) { joy_flags |= dwAxisFlags[i]; } } } /* =========== IN_Commands =========== */ void IN_Commands (void) { int i, key_index; DWORD buttonstate, povstate; if (!joy_avail) { return; } // loop through the joystick buttons // key a joystick event or auxillary event for higher number buttons for each state change buttonstate = ji.dwButtons; for (i=0 ; i < (int)joy_numbuttons ; i++) { if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) ) { key_index = (i < 4) ? K_JOY1 : K_AUX1; gEngfuncs.Key_Event (key_index + i, 1); } if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) ) { key_index = (i < 4) ? K_JOY1 : K_AUX1; gEngfuncs.Key_Event (key_index + i, 0); } } joy_oldbuttonstate = buttonstate; if (joy_haspov) { // convert POV information into 4 bits of state information // this avoids any potential problems related to moving from one // direction to another without going through the center position povstate = 0; if(ji.dwPOV != JOY_POVCENTERED) { if (ji.dwPOV == JOY_POVFORWARD) povstate |= 0x01; if (ji.dwPOV == JOY_POVRIGHT) povstate |= 0x02; if (ji.dwPOV == JOY_POVBACKWARD) povstate |= 0x04; if (ji.dwPOV == JOY_POVLEFT) povstate |= 0x08; } // determine which bits have changed and key an auxillary event for each change for (i=0 ; i < 4 ; i++) { if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) ) { gEngfuncs.Key_Event (K_AUX29 + i, 1); } if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) ) { gEngfuncs.Key_Event (K_AUX29 + i, 0); } } joy_oldpovstate = povstate; } } /* =============== IN_ReadJoystick =============== */ int IN_ReadJoystick (void) { memset (&ji, 0, sizeof(ji)); ji.dwSize = sizeof(ji); ji.dwFlags = joy_flags; if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR) { // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver // rather than having 32768 be the zero point, they have the zero point at 32668 // go figure -- anyway, now we get the full resolution out of the device if (joy_wwhack1->value != 0.0) { ji.dwUpos += 100; } return 1; } else { // read error occurred // turning off the joystick seems too harsh for 1 read error,\ // but what should be done? // Con_Printf ("IN_ReadJoystick: no response\n"); // joy_avail = 0; return 0; } } /* =========== IN_JoyMove =========== */ void IN_JoyMove ( float frametime, usercmd_t *cmd ) { float speed, aspeed; float fAxisValue, fTemp; int i; vec3_t viewangles; gEngfuncs.GetViewAngles( (float *)viewangles ); // complete initialization if first time in // this is needed as cvars are not available at initialization time if( joy_advancedinit != 1 ) { Joy_AdvancedUpdate_f(); joy_advancedinit = 1; } // verify joystick is available and that the user wants to use it if (!joy_avail || !in_joystick->value) { return; } // collect the joystick data, if possible if (IN_ReadJoystick () != 1) { return; } if (in_speed.state & 1) speed = cl_movespeedkey->value; else speed = 1; aspeed = speed * frametime; // loop through the axes for (i = 0; i < JOY_MAX_AXES; i++) { // get the floating point zero-centered, potentially-inverted data for the current axis fAxisValue = (float) *pdwRawValue[i]; // move centerpoint to zero fAxisValue -= 32768.0; if (joy_wwhack2->value != 0.0) { if (dwAxisMap[i] == AxisTurn) { // this is a special formula for the Logitech WingMan Warrior // y=ax^b; where a = 300 and b = 1.3 // also x values are in increments of 800 (so this is factored out) // then bounds check result to level out excessively high spin rates fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3); if (fTemp > 14000.0) fTemp = 14000.0; // restore direction information fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp; } } // convert range from -32768..32767 to -1..1 fAxisValue /= 32768.0; switch (dwAxisMap[i]) { case AxisForward: if ((joy_advanced->value == 0.0) && (in_jlook.state & 1)) { // user wants forward control to become look control if (fabs(fAxisValue) > joy_pitchthreshold->value) { // if mouse invert is on, invert the joystick pitch value // only absolute control support here (joy_advanced is 0) if (m_pitch->value < 0.0) { viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; } else { viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; } V_StopPitchDrift(); } else { // no pitch movement // disable pitch return-to-center unless requested by user // *** this code can be removed when the lookspring bug is fixed // *** the bug always has the lookspring feature on if(lookspring->value == 0.0) { V_StopPitchDrift(); } } } else { // user wants forward control to be forward control if (fabs(fAxisValue) > joy_forwardthreshold->value) { cmd->forwardmove += (fAxisValue * joy_forwardsensitivity->value) * speed * cl_forwardspeed->value; } } break; case AxisSide: if (fabs(fAxisValue) > joy_sidethreshold->value) { cmd->sidemove += (fAxisValue * joy_sidesensitivity->value) * speed * cl_sidespeed->value; } break; case AxisTurn: if ((in_strafe.state & 1) || (lookstrafe->value && (in_jlook.state & 1))) { // user wants turn control to become side control if (fabs(fAxisValue) > joy_sidethreshold->value) { cmd->sidemove -= (fAxisValue * joy_sidesensitivity->value) * speed * cl_sidespeed->value; } } else { // user wants turn control to be turn control if (fabs(fAxisValue) > joy_yawthreshold->value) { if(dwControlMap[i] == JOY_ABSOLUTE_AXIS) { viewangles[YAW] += (fAxisValue * joy_yawsensitivity->value) * aspeed * cl_yawspeed->value; } else { viewangles[YAW] += (fAxisValue * joy_yawsensitivity->value) * speed * 180.0; } } } break; case AxisLook: if (in_jlook.state & 1) { if (fabs(fAxisValue) > joy_pitchthreshold->value) { // pitch movement detected and pitch movement desired by user if(dwControlMap[i] == JOY_ABSOLUTE_AXIS) { viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; } else { viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * speed * 180.0; } V_StopPitchDrift(); } else { // no pitch movement // disable pitch return-to-center unless requested by user // *** this code can be removed when the lookspring bug is fixed // *** the bug always has the lookspring feature on if( lookspring->value == 0.0 ) { V_StopPitchDrift(); } } } break; default: break; } } // bounds check pitch if (viewangles[PITCH] > cl_pitchdown->value) viewangles[PITCH] = cl_pitchdown->value; if (viewangles[PITCH] < -cl_pitchup->value) viewangles[PITCH] = -cl_pitchup->value; gEngfuncs.SetViewAngles( (float *)viewangles ); } /* =========== IN_Move =========== */ void IN_Move ( float frametime, usercmd_t *cmd) { if ( !iMouseInUse && mouseactive ) { IN_MouseMove ( frametime, cmd); } IN_JoyMove ( frametime, cmd); } /* =========== IN_Init =========== */ void IN_Init (void) { m_filter = gEngfuncs.pfnRegisterVariable ( "m_filter","0", FCVAR_ARCHIVE ); sensitivity = gEngfuncs.pfnRegisterVariable ( "sensitivity","3", FCVAR_ARCHIVE ); // user mouse sensitivity setting. in_joystick = gEngfuncs.pfnRegisterVariable ( "joystick","0", FCVAR_ARCHIVE ); joy_name = gEngfuncs.pfnRegisterVariable ( "joyname", "joystick", 0 ); joy_advanced = gEngfuncs.pfnRegisterVariable ( "joyadvanced", "0", 0 ); joy_advaxisx = gEngfuncs.pfnRegisterVariable ( "joyadvaxisx", "0", 0 ); joy_advaxisy = gEngfuncs.pfnRegisterVariable ( "joyadvaxisy", "0", 0 ); joy_advaxisz = gEngfuncs.pfnRegisterVariable ( "joyadvaxisz", "0", 0 ); joy_advaxisr = gEngfuncs.pfnRegisterVariable ( "joyadvaxisr", "0", 0 ); joy_advaxisu = gEngfuncs.pfnRegisterVariable ( "joyadvaxisu", "0", 0 ); joy_advaxisv = gEngfuncs.pfnRegisterVariable ( "joyadvaxisv", "0", 0 ); joy_forwardthreshold = gEngfuncs.pfnRegisterVariable ( "joyforwardthreshold", "0.15", 0 ); joy_sidethreshold = gEngfuncs.pfnRegisterVariable ( "joysidethreshold", "0.15", 0 ); joy_pitchthreshold = gEngfuncs.pfnRegisterVariable ( "joypitchthreshold", "0.15", 0 ); joy_yawthreshold = gEngfuncs.pfnRegisterVariable ( "joyyawthreshold", "0.15", 0 ); joy_forwardsensitivity = gEngfuncs.pfnRegisterVariable ( "joyforwardsensitivity", "-1.0", 0 ); joy_sidesensitivity = gEngfuncs.pfnRegisterVariable ( "joysidesensitivity", "-1.0", 0 ); joy_pitchsensitivity = gEngfuncs.pfnRegisterVariable ( "joypitchsensitivity", "1.0", 0 ); joy_yawsensitivity = gEngfuncs.pfnRegisterVariable ( "joyyawsensitivity", "-1.0", 0 ); joy_wwhack1 = gEngfuncs.pfnRegisterVariable ( "joywwhack1", "0.0", 0 ); joy_wwhack2 = gEngfuncs.pfnRegisterVariable ( "joywwhack2", "0.0", 0 ); gEngfuncs.pfnAddCommand ("force_centerview", Force_CenterView_f); gEngfuncs.pfnAddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f); IN_StartupMouse (); IN_StartupJoystick (); }
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 947 ] ] ]
97d5fc7d6b8f5b7ddda7c9d86edb1b6191aaafb9
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/Graphics/WS/VectorSprite/Base.cpp
78741c1f78a47590b8a2bd6c222b1aefec438fce
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
5,101
cpp
// Base.cpp // // Copyright (c) 2005 Symbian Softwares Ltd. All rights reserved. // #include <w32std.h> #include "Base.h" /////////////////////////////////////////////////////////////////////////////// // CWindow implementation /////////////////////////////////////////////////////////////////////////////// CWindow::CWindow(CWsClient* aClient) : iClient(aClient) { } void CWindow::ConstructL(const TRect& aRect, const TRgb& aColor, CWindow* aParent) { _LIT(KFontName,"Swiss"); // If a parent window was specified, use it; if not, use the window group // (aParent defaults to 0). RWindowTreeNode* parent = aParent ? (RWindowTreeNode*) &(aParent->Window()) : &(iClient->iGroup); // Allocate and construct the window iWindow = RWindow(iClient->iWs); User::LeaveIfError(iWindow.Construct(*parent, (TUint32) this)); // Store the window's extent iRect = aRect; // Set up the new window's extent iWindow.SetExtent(iRect.iTl, iRect.Size()); // Set its background color iWindow.SetBackgroundColor(aColor); // Set up font for displaying text TFontSpec fontSpec(KFontName, 200); User::LeaveIfError(iClient->iScreen->GetNearestFontInTwips(iFont, fontSpec)); // Activate the window iWindow.Activate(); } CWindow::~CWindow() { iWindow.Close(); iClient->iScreen->ReleaseFont(iFont); } RWindow& CWindow::Window() { return iWindow; } CWindowGc* CWindow::SystemGc() { return iClient->iGc; } CWsScreenDevice* CWindow::Screen() { return iClient->iScreen; } CFont* CWindow::Font() { return iFont; } /////////////////////////////////////////////////////////////////////////////// // CWsRedrawer implementation /////////////////////////////////////////////////////////////////////////////// CWsRedrawer::CWsRedrawer() : CActive(CActive::EPriorityLow) { } void CWsRedrawer::ConstructL(CWsClient* aClient) { iClient = aClient; // remember WsClient that owns us CActiveScheduler::Add(this); // add ourselves to the scheduler IssueRequest(); // issue request to draw } CWsRedrawer::~CWsRedrawer() { Cancel(); } void CWsRedrawer::IssueRequest() { iClient->iWs.RedrawReady(&iStatus); SetActive(); } void CWsRedrawer::DoCancel() { iClient->iWs.RedrawReadyCancel(); } void CWsRedrawer::RunL() { // find out what needs to be done in response to the event TWsRedrawEvent redrawEvent; iClient->iWs.GetRedraw(redrawEvent); // get event CWindow* window = (CWindow*) (redrawEvent.Handle()); // get window if (window) { TRect rect = redrawEvent.Rect(); // and rectangle that needs redrawing // now do drawing iClient->iGc->Activate(window->Window()); window->Window().BeginRedraw(); window->Draw(rect); window->Window().EndRedraw(); iClient->iGc->Deactivate(); } // maintain outstanding request IssueRequest(); } ///////////////////////////////////////////////////////////////////////////////////// // CWsClient implementation ///////////////////////////////////////////////////////////////////////////////////// CWsClient::CWsClient() : CActive(CActive::EPriorityStandard) { } void CWsClient::ConstructL() { // add ourselves to active scheduler CActiveScheduler::Add(this); // get a session going User::LeaveIfError(iWs.Connect()); // construct our one and only window group iGroup = RWindowGroup(iWs); User::LeaveIfError(iGroup.Construct(2, ETrue)); // '2' is a meaningless handle // construct screen device and graphics context iScreen = new (ELeave) CWsScreenDevice(iWs); // make device for this session User::LeaveIfError(iScreen->Construct()); // and complete its construction User::LeaveIfError(iScreen->CreateContext(iGc)); // create graphics context // construct redrawer iRedrawer = new (ELeave) CWsRedrawer; iRedrawer->ConstructL(this); // construct main window ConstructMainWindowL(); // request first event and start scheduler IssueRequest(); } CWsClient::~CWsClient() { // neutralize us as an active object Deque(); // cancels and removes from scheduler // get rid of everything we allocated delete iGc; delete iScreen; delete iRedrawer; // destroy window group iGroup.Close(); // what's the difference between this and destroy? // finish with window server iWs.Close(); } void CWsClient::IssueRequest() { iWs.EventReady(&iStatus); // request an event SetActive(); // so we're now active } void CWsClient::DoCancel() { iWs.EventReadyCancel(); // cancel event request } void CWsClient::ConstructMainWindowL() { }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 181 ] ] ]
ad273f1ad5f0bb385c262d1ed06bb8d5bd94bba6
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Tools/UIEditor/ScriptFrame.h
0dd491cad3390e3f1abf808b42b3a61b717d35b9
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
868
h
// ScriptFrame.h : interface of the CScriptFrame class // #pragma once #include "ScriptWnd.h" class CScriptFrame : public CMDIChildWnd { DECLARE_DYNCREATE(CScriptFrame) public: CScriptFrame(); // Attributes public: // Operations public: // Overrides public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); // Implementation public: // view for the client area of the frame. CScriptWnd m_wndView; virtual ~CScriptFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: afx_msg void OnFileClose(); afx_msg void OnSetFocus(CWnd* pOldWnd); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() };
[ "acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 42 ] ] ]
4c2e311ca1d91d7418ea524693740cf3b94ccbc8
e99d8eb7e3cc6f75d2bd5621414b79499e9578ed
/src/gfx/Text.cpp
36acf143676217050b77aacbd53fa693cd1ee4b6
[]
no_license
skydave/mpchristmas
32c84def30dfe045029454b4f27625d3fc9f15b7
4f25403b2b5d69a217a70c03383c43247eb91f38
refs/heads/master
2016-09-05T22:02:17.417514
2010-12-11T18:42:58
2010-12-14T12:48:38
1,157,617
0
0
null
null
null
null
UTF-8
C++
false
false
498
cpp
#include "Text.h" #include "../sys/msys.h" static unsigned int g_fontLists; static unsigned int g_fontInitialised = false; Text::Text( const char *text ) { if(!g_fontInitialised) { // initialise fontlists g_fontLists = msys_buildFont(); g_fontInitialised = true; } } void Text::render() { char *t = "hicknhack"; glPushAttrib( GL_LIST_BIT ); glColor3f(1.0f, 0.0f, 0.0f); glListBase( g_fontLists ); glCallLists( 9, GL_UNSIGNED_BYTE, t ); glPopAttrib(); }
[ [ [ 1, 26 ] ] ]
ca7b115109a9c30729031ef22a6060ded33365af
5c4e36054f0752a610ad149dfd81e6f35ccb37a1
/libs/src2.75/BulletCollision/CollisionShapes/btConvexInternalShape.h
74f7547721f43d54bfbcd1d40a0e14490f6ed861
[]
no_license
Akira-Hayasaka/ofxBulletPhysics
4141dc7b6dff7e46b85317b0fe7d2e1f8896b2e4
5e45da80bce2ed8b1f12de9a220e0c1eafeb7951
refs/heads/master
2016-09-15T23:11:01.354626
2011-09-22T04:11:35
2011-09-22T04:11:35
1,152,090
6
0
null
null
null
null
UTF-8
C++
false
false
3,998
h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_CONVEX_INTERNAL_SHAPE_H #define BT_CONVEX_INTERNAL_SHAPE_H #include "btConvexShape.h" #include "LinearMath/btAabbUtil2.h" ///The btConvexInternalShape is an internal base class, shared by most convex shape implementations. class btConvexInternalShape : public btConvexShape { protected: //local scaling. collisionMargin is not scaled ! btVector3 m_localScaling; btVector3 m_implicitShapeDimensions; btScalar m_collisionMargin; btScalar m_padding; btConvexInternalShape(); public: virtual ~btConvexInternalShape() { } virtual btVector3 localGetSupportingVertex(const btVector3& vec)const; const btVector3& getImplicitShapeDimensions() const { return m_implicitShapeDimensions; } ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { getAabbSlow(t,aabbMin,aabbMax); } virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void setLocalScaling(const btVector3& scaling); virtual const btVector3& getLocalScaling() const { return m_localScaling; } const btVector3& getLocalScalingNV() const { return m_localScaling; } virtual void setMargin(btScalar margin) { m_collisionMargin = margin; } virtual btScalar getMargin() const { return m_collisionMargin; } btScalar getMarginNV() const { return m_collisionMargin; } virtual int getNumPreferredPenetrationDirections() const { return 0; } virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const { (void)penetrationVector; (void)index; btAssert(0); } }; ///btConvexInternalAabbCachingShape adds local aabb caching for convex shapes, to avoid expensive bounding box calculations class btConvexInternalAabbCachingShape : public btConvexInternalShape { btVector3 m_localAabbMin; btVector3 m_localAabbMax; bool m_isLocalAabbValid; protected: btConvexInternalAabbCachingShape(); void setCachedLocalAabb (const btVector3& aabbMin, const btVector3& aabbMax) { m_isLocalAabbValid = true; m_localAabbMin = aabbMin; m_localAabbMax = aabbMax; } inline void getCachedLocalAabb (btVector3& aabbMin, btVector3& aabbMax) const { btAssert(m_isLocalAabbValid); aabbMin = m_localAabbMin; aabbMax = m_localAabbMax; } inline void getNonvirtualAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax, btScalar margin) const { //lazy evaluation of local aabb btAssert(m_isLocalAabbValid); btTransformAabb(m_localAabbMin,m_localAabbMax,margin,trans,aabbMin,aabbMax); } public: virtual void setLocalScaling(const btVector3& scaling); virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; void recalcLocalAabb(); }; #endif //BT_CONVEX_INTERNAL_SHAPE_H
[ [ [ 1, 151 ] ] ]
b665026633b411db5ba6711e8f3906b1808ba25c
02c2e62bcb9a54738bfbd95693978b8709e88fdb
/opencv/cvoptflowlk.cpp
3b4576e4e92b22520d115dd19d6b79948d244603
[]
no_license
ThadeuFerreira/sift-coprojeto
7ab823926e135f0ac388ae267c40e7069e39553a
bba43ef6fa37561621eb5f2126e5aa7d1c3f7024
refs/heads/master
2021-01-10T15:15:21.698124
2009-05-08T17:38:51
2009-05-08T17:38:51
45,042,655
0
0
null
null
null
null
UTF-8
C++
false
false
22,251
cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ #include "_cv.h" typedef struct { float xx; float xy; float yy; float xt; float yt; } icvDerProduct; #define CONV( A, B, C) ((float)( A + (B<<1) + C )) /*F/////////////////////////////////////////////////////////////////////////////////////// // Name: icvCalcOpticalFlowLK_8u32fR ( Lucas & Kanade method ) // Purpose: calculate Optical flow for 2 images using Lucas & Kanade algorithm // Context: // Parameters: // imgA, // pointer to first frame ROI // imgB, // pointer to second frame ROI // imgStep, // width of single row of source images in bytes // imgSize, // size of the source image ROI // winSize, // size of the averaging window used for grouping // velocityX, // pointer to horizontal and // velocityY, // vertical components of optical flow ROI // velStep // width of single row of velocity frames in bytes // // Returns: CV_OK - all ok // CV_OUTOFMEM_ERR - insufficient memory for function work // CV_NULLPTR_ERR - if one of input pointers is NULL // CV_BADSIZE_ERR - wrong input sizes interrelation // // Notes: 1.Optical flow to be computed for every pixel in ROI // 2.For calculating spatial derivatives we use 3x3 Sobel operator. // 3.We use the following border mode. // The last row or column is replicated for the border // ( IPL_BORDER_REPLICATE in IPL ). // // //F*/ static CvStatus CV_STDCALL icvCalcOpticalFlowLK_8u32fR( uchar * imgA, uchar * imgB, int imgStep, CvSize imgSize, CvSize winSize, float *velocityX, float *velocityY, int velStep ) { /* Loops indexes */ int i, j, k; /* Gaussian separable kernels */ float GaussX[16]; float GaussY[16]; float *KerX; float *KerY; /* Buffers for Sobel calculations */ float *MemX[2]; float *MemY[2]; float ConvX, ConvY; float GradX, GradY, GradT; int winWidth = winSize.width; int winHeight = winSize.height; int imageWidth = imgSize.width; int imageHeight = imgSize.height; int HorRadius = (winWidth - 1) >> 1; int VerRadius = (winHeight - 1) >> 1; int PixelLine; int ConvLine; int BufferAddress; int BufferHeight = 0; int BufferWidth; int BufferSize; /* buffers derivatives product */ icvDerProduct *II; /* buffers for gaussian horisontal convolution */ icvDerProduct *WII; /* variables for storing number of first pixel of image line */ int Line1; int Line2; int Line3; /* we must have 2*2 linear system coeffs | A1B2 B1 | {u} {C1} {0} | | { } + { } = { } | A2 A1B2 | {v} {C2} {0} */ float A1B2, A2, B1, C1, C2; int pixNumber; /* auxiliary */ int NoMem = 0; /* Checking bad arguments */ if( imgA == NULL ) return CV_NULLPTR_ERR; if( imgB == NULL ) return CV_NULLPTR_ERR; if( imageHeight < winHeight ) return CV_BADSIZE_ERR; if( imageWidth < winWidth ) return CV_BADSIZE_ERR; if( winHeight >= 16 ) return CV_BADSIZE_ERR; if( winWidth >= 16 ) return CV_BADSIZE_ERR; if( !(winHeight & 1) ) return CV_BADSIZE_ERR; if( !(winWidth & 1) ) return CV_BADSIZE_ERR; BufferHeight = winHeight; BufferWidth = imageWidth; /****************************************************************************************/ /* Computing Gaussian coeffs */ /****************************************************************************************/ GaussX[0] = 1; GaussY[0] = 1; for( i = 1; i < winWidth; i++ ) { GaussX[i] = 1; for( j = i - 1; j > 0; j-- ) { GaussX[j] += GaussX[j - 1]; } } for( i = 1; i < winHeight; i++ ) { GaussY[i] = 1; for( j = i - 1; j > 0; j-- ) { GaussY[j] += GaussY[j - 1]; } } KerX = &GaussX[HorRadius]; KerY = &GaussY[VerRadius]; /****************************************************************************************/ /* Allocating memory for all buffers */ /****************************************************************************************/ for( k = 0; k < 2; k++ ) { MemX[k] = (float *) cvAlloc( (imgSize.height) * sizeof( float )); if( MemX[k] == NULL ) NoMem = 1; MemY[k] = (float *) cvAlloc( (imgSize.width) * sizeof( float )); if( MemY[k] == NULL ) NoMem = 1; } BufferSize = BufferHeight * BufferWidth; II = (icvDerProduct *) cvAlloc( BufferSize * sizeof( icvDerProduct )); WII = (icvDerProduct *) cvAlloc( BufferSize * sizeof( icvDerProduct )); if( (II == NULL) || (WII == NULL) ) NoMem = 1; if( NoMem ) { for( k = 0; k < 2; k++ ) { if( MemX[k] ) cvFree( (void **) &MemX[k] ); if( MemY[k] ) cvFree( (void **) &MemY[k] ); } if( II ) cvFree( (void **) &II ); if( WII ) cvFree( (void **) &WII ); return CV_OUTOFMEM_ERR; } /****************************************************************************************/ /* Calculate first line of memX and memY */ /****************************************************************************************/ MemY[0][0] = MemY[1][0] = CONV( imgA[0], imgA[0], imgA[1] ); MemX[0][0] = MemX[1][0] = CONV( imgA[0], imgA[0], imgA[imgStep] ); for( j = 1; j < imageWidth - 1; j++ ) { MemY[0][j] = MemY[1][j] = CONV( imgA[j - 1], imgA[j], imgA[j + 1] ); } pixNumber = imgStep; for( i = 1; i < imageHeight - 1; i++ ) { MemX[0][i] = MemX[1][i] = CONV( imgA[pixNumber - imgStep], imgA[pixNumber], imgA[pixNumber + imgStep] ); pixNumber += imgStep; } MemY[0][imageWidth - 1] = MemY[1][imageWidth - 1] = CONV( imgA[imageWidth - 2], imgA[imageWidth - 1], imgA[imageWidth - 1] ); MemX[0][imageHeight - 1] = MemX[1][imageHeight - 1] = CONV( imgA[pixNumber - imgStep], imgA[pixNumber], imgA[pixNumber] ); /****************************************************************************************/ /* begin scan image, calc derivatives and solve system */ /****************************************************************************************/ PixelLine = -VerRadius; ConvLine = 0; BufferAddress = -BufferWidth; while( PixelLine < imageHeight ) { if( ConvLine < imageHeight ) { /*Here we calculate derivatives for line of image */ int address; i = ConvLine; int L1 = i - 1; int L2 = i; int L3 = i + 1; int memYline = L3 & 1; if( L1 < 0 ) L1 = 0; if( L3 >= imageHeight ) L3 = imageHeight - 1; BufferAddress += BufferWidth; BufferAddress -= ((BufferAddress >= BufferSize) ? 0xffffffff : 0) & BufferSize; address = BufferAddress; Line1 = L1 * imgStep; Line2 = L2 * imgStep; Line3 = L3 * imgStep; /* Process first pixel */ ConvX = CONV( imgA[Line1 + 1], imgA[Line2 + 1], imgA[Line3 + 1] ); ConvY = CONV( imgA[Line3], imgA[Line3], imgA[Line3 + 1] ); GradY = ConvY - MemY[memYline][0]; GradX = ConvX - MemX[1][L2]; MemY[memYline][0] = ConvY; MemX[1][L2] = ConvX; GradT = (float) (imgB[Line2] - imgA[Line2]); II[address].xx = GradX * GradX; II[address].xy = GradX * GradY; II[address].yy = GradY * GradY; II[address].xt = GradX * GradT; II[address].yt = GradY * GradT; address++; /* Process middle of line */ for( j = 1; j < imageWidth - 1; j++ ) { ConvX = CONV( imgA[Line1 + j + 1], imgA[Line2 + j + 1], imgA[Line3 + j + 1] ); ConvY = CONV( imgA[Line3 + j - 1], imgA[Line3 + j], imgA[Line3 + j + 1] ); GradY = ConvY - MemY[memYline][j]; GradX = ConvX - MemX[(j - 1) & 1][L2]; MemY[memYline][j] = ConvY; MemX[(j - 1) & 1][L2] = ConvX; GradT = (float) (imgB[Line2 + j] - imgA[Line2 + j]); II[address].xx = GradX * GradX; II[address].xy = GradX * GradY; II[address].yy = GradY * GradY; II[address].xt = GradX * GradT; II[address].yt = GradY * GradT; address++; } /* Process last pixel of line */ ConvX = CONV( imgA[Line1 + imageWidth - 1], imgA[Line2 + imageWidth - 1], imgA[Line3 + imageWidth - 1] ); ConvY = CONV( imgA[Line3 + imageWidth - 2], imgA[Line3 + imageWidth - 1], imgA[Line3 + imageWidth - 1] ); GradY = ConvY - MemY[memYline][imageWidth - 1]; GradX = ConvX - MemX[(imageWidth - 2) & 1][L2]; MemY[memYline][imageWidth - 1] = ConvY; GradT = (float) (imgB[Line2 + imageWidth - 1] - imgA[Line2 + imageWidth - 1]); II[address].xx = GradX * GradX; II[address].xy = GradX * GradY; II[address].yy = GradY * GradY; II[address].xt = GradX * GradT; II[address].yt = GradY * GradT; address++; /* End of derivatives for line */ /****************************************************************************************/ /* ---------Calculating horizontal convolution of processed line----------------------- */ /****************************************************************************************/ address -= BufferWidth; /* process first HorRadius pixels */ for( j = 0; j < HorRadius; j++ ) { int jj; WII[address].xx = 0; WII[address].xy = 0; WII[address].yy = 0; WII[address].xt = 0; WII[address].yt = 0; for( jj = -j; jj <= HorRadius; jj++ ) { float Ker = KerX[jj]; WII[address].xx += II[address + jj].xx * Ker; WII[address].xy += II[address + jj].xy * Ker; WII[address].yy += II[address + jj].yy * Ker; WII[address].xt += II[address + jj].xt * Ker; WII[address].yt += II[address + jj].yt * Ker; } address++; } /* process inner part of line */ for( j = HorRadius; j < imageWidth - HorRadius; j++ ) { int jj; float Ker0 = KerX[0]; WII[address].xx = 0; WII[address].xy = 0; WII[address].yy = 0; WII[address].xt = 0; WII[address].yt = 0; for( jj = 1; jj <= HorRadius; jj++ ) { float Ker = KerX[jj]; WII[address].xx += (II[address - jj].xx + II[address + jj].xx) * Ker; WII[address].xy += (II[address - jj].xy + II[address + jj].xy) * Ker; WII[address].yy += (II[address - jj].yy + II[address + jj].yy) * Ker; WII[address].xt += (II[address - jj].xt + II[address + jj].xt) * Ker; WII[address].yt += (II[address - jj].yt + II[address + jj].yt) * Ker; } WII[address].xx += II[address].xx * Ker0; WII[address].xy += II[address].xy * Ker0; WII[address].yy += II[address].yy * Ker0; WII[address].xt += II[address].xt * Ker0; WII[address].yt += II[address].yt * Ker0; address++; } /* process right side */ for( j = imageWidth - HorRadius; j < imageWidth; j++ ) { int jj; WII[address].xx = 0; WII[address].xy = 0; WII[address].yy = 0; WII[address].xt = 0; WII[address].yt = 0; for( jj = -HorRadius; jj < imageWidth - j; jj++ ) { float Ker = KerX[jj]; WII[address].xx += II[address + jj].xx * Ker; WII[address].xy += II[address + jj].xy * Ker; WII[address].yy += II[address + jj].yy * Ker; WII[address].xt += II[address + jj].xt * Ker; WII[address].yt += II[address + jj].yt * Ker; } address++; } } /****************************************************************************************/ /* Calculating velocity line */ /****************************************************************************************/ if( PixelLine >= 0 ) { int USpace; int BSpace; int address; if( PixelLine < VerRadius ) USpace = PixelLine; else USpace = VerRadius; if( PixelLine >= imageHeight - VerRadius ) BSpace = imageHeight - PixelLine - 1; else BSpace = VerRadius; address = ((PixelLine - USpace) % BufferHeight) * BufferWidth; for( j = 0; j < imageWidth; j++ ) { int addr = address; A1B2 = 0; A2 = 0; B1 = 0; C1 = 0; C2 = 0; for( i = -USpace; i <= BSpace; i++ ) { A2 += WII[addr + j].xx * KerY[i]; A1B2 += WII[addr + j].xy * KerY[i]; B1 += WII[addr + j].yy * KerY[i]; C2 += WII[addr + j].xt * KerY[i]; C1 += WII[addr + j].yt * KerY[i]; addr += BufferWidth; addr -= ((addr >= BufferSize) ? 0xffffffff : 0) & BufferSize; } /****************************************************************************************\ * Solve Linear System * \****************************************************************************************/ { float delta = (A1B2 * A1B2 - A2 * B1); if( delta ) { /* system is not singular - solving by Kramer method */ float deltaX; float deltaY; float Idelta = 8 / delta; deltaX = -(C1 * A1B2 - C2 * B1); deltaY = -(A1B2 * C2 - A2 * C1); velocityX[j] = deltaX * Idelta; velocityY[j] = deltaY * Idelta; } else { /* singular system - find optical flow in gradient direction */ float Norm = (A1B2 + A2) * (A1B2 + A2) + (B1 + A1B2) * (B1 + A1B2); if( Norm ) { float IGradNorm = 8 / Norm; float temp = -(C1 + C2) * IGradNorm; velocityX[j] = (A1B2 + A2) * temp; velocityY[j] = (B1 + A1B2) * temp; } else { velocityX[j] = 0; velocityY[j] = 0; } } } /****************************************************************************************\ * End of Solving Linear System * \****************************************************************************************/ } /*for */ *((char **) &velocityX) += velStep; *((char **) &velocityY) += velStep; } /*for */ PixelLine++; ConvLine++; } /* Free memory */ for( k = 0; k < 2; k++ ) { cvFree( (void **) &MemX[k] ); cvFree( (void **) &MemY[k] ); } cvFree( (void **) &II ); cvFree( (void **) &WII ); return CV_OK; } /*icvCalcOpticalFlowLK_8u32fR*/ /*F/////////////////////////////////////////////////////////////////////////////////////// // Name: cvCalcOpticalFlowLK // Purpose: Optical flow implementation // Context: // Parameters: // srcA, srcB - source image // velx, vely - destination image // Returns: // // Notes: //F*/ CV_IMPL void cvCalcOpticalFlowLK( const void* srcarrA, const void* srcarrB, CvSize winSize, void* velarrx, void* velarry ) { CV_FUNCNAME( "cvCalcOpticalFlowLK" ); __BEGIN__; CvMat stubA, *srcA = (CvMat*)srcarrA; CvMat stubB, *srcB = (CvMat*)srcarrB; CvMat stubx, *velx = (CvMat*)velarrx; CvMat stuby, *vely = (CvMat*)velarry; CV_CALL( srcA = cvGetMat( srcA, &stubA )); CV_CALL( srcB = cvGetMat( srcB, &stubB )); CV_CALL( velx = cvGetMat( velx, &stubx )); CV_CALL( vely = cvGetMat( vely, &stuby )); if( !CV_ARE_TYPES_EQ( srcA, srcB )) CV_ERROR( CV_StsUnmatchedFormats, "Source images have different formats" ); if( !CV_ARE_TYPES_EQ( velx, vely )) CV_ERROR( CV_StsUnmatchedFormats, "Destination images have different formats" ); if( !CV_ARE_SIZES_EQ( srcA, srcB ) || !CV_ARE_SIZES_EQ( velx, vely ) || !CV_ARE_SIZES_EQ( srcA, velx )) CV_ERROR( CV_StsUnmatchedSizes, "" ); if( CV_MAT_TYPE( srcA->type ) != CV_8UC1 || CV_MAT_TYPE( velx->type ) != CV_32FC1 ) CV_ERROR( CV_StsUnsupportedFormat, "Source images must have 8uC1 type and " "destination images must have 32fC1 type" ); if( srcA->step != srcB->step || velx->step != vely->step ) CV_ERROR( CV_BadStep, "source and destination images have different step" ); IPPI_CALL( icvCalcOpticalFlowLK_8u32fR( (uchar*)srcA->data.ptr, (uchar*)srcB->data.ptr, srcA->step, cvGetMatSize( srcA ), winSize, velx->data.fl, vely->data.fl, velx->step )); __END__; } /* End of file. */
[ [ [ 1, 609 ] ] ]
7a4b8cc48d350fd562e4d0bef685b44e51cdd113
ffb363eadafafb4b656355b881395f8d59270f55
/my/include/my/matrix/matrix_slice_interop.hpp
d467ee92e0e550a0bea313238007ae4faebd8493
[ "MIT" ]
permissive
hanji/matrix
1c28830eb4fdb7eefe21b2f415a9ec354e18f168
9f3424628ab182d249c62aeaf4beb4fb2d073518
refs/heads/master
2023-08-08T07:36:26.581667
2009-12-03T06:25:24
2009-12-03T06:25:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,208
hpp
#ifndef MATRIX_SLICE_INTEROP_HPP #define MATRIX_SLICE_INTEROP_HPP /* matrix_slice_interop.hpp Copyright (C) 2009, Ji Han 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. */ namespace my { template <typename Ts, const std::size_t M, const size_t N> class matrix; template <typename Ts, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> class matrix_slice; //////// //////// //////// // non-member functions //////// //////// //////// //////// //////// // addition //////// //////// // matrix slice + matrix slice template <typename T, const std::size_t M, const std::size_t N, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y> const matrix<T, X, Y> operator+ (const matrix_slice<T,M,N,X,Y> &A, const matrix_slice<T,P,Q,X,Y> &B) { matrix<T, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = A(i,j) + B(i,j); } } return ret; } // matrix + matrix slice template <typename T, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y> const matrix<T, X, Y> operator+ (const matrix<T,X,Y> &A, const matrix_slice<T,P,Q,X,Y> &B) { matrix<T, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = A(i,j) + B(i,j); } } return ret; } // matrix slice + matrix template <typename T, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> const matrix<T, X, Y> operator+ (const matrix_slice<T,M,N,X,Y> &A, const matrix<T,X,Y> &B) { matrix<T, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = A(i,j) + B(i,j); } } return ret; } // addition with type promotion: matrix slice + matrix slice template <typename T1, typename T2, const std::size_t M, const std::size_t N, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> operator+ (const matrix_slice<T1,M,N,X,Y> &A, const matrix_slice<T2,P,Q,X,Y> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, j)) + static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(i, j)); } } return ret; } // addition with type promotion: matrix + matrix slice template <typename T1, typename T2, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> operator+ (const matrix<T1,X,Y> &A, const matrix_slice<T2,P,Q,X,Y> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, j)) + static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(i, j)); } } return ret; } // addition with type promotion: matrix slice + matrix template <typename T1, typename T2, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> operator+ (const matrix_slice<T1,M,N,X,Y> &A, const matrix<T2,X,Y> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, j)) + static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(i, j)); } } return ret; } //////// //////// // subtraction //////// //////// // subtraction: matrix slice - matrix slice template <typename T, const std::size_t M, const std::size_t N, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y> const matrix<T, X, Y> operator- (const matrix_slice<T,M,N,X,Y> &A, const matrix_slice<T,P,Q,X,Y> &B) { matrix<T, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = A(i,j) - B(i,j); } } return ret; } // matrix - matrix slice template <typename T, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y> const matrix<T, X, Y> operator- (const matrix<T,X,Y> &A, const matrix_slice<T,P,Q,X,Y> &B) { matrix<T, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = A(i,j) - B(i,j); } } return ret; } // matrix slice - matrix template <typename T, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> const matrix<T, X, Y> operator- (const matrix_slice<T,M,N,X,Y> &A, const matrix<T,X,Y> &B) { matrix<T, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = A(i,j) - B(i,j); } } return ret; } // subtraction with type promotion: matrix slice - matrix slice template <typename T1, typename T2, const std::size_t M, const std::size_t N, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> operator- (const matrix_slice<T1,M,N,X,Y> &A, const matrix_slice<T2,P,Q,X,Y> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, j)) - static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(i, j)); } } return ret; } // subtraction with type promotion: matrix - matrix slice template <typename T1, typename T2, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> operator- (const matrix<T1,X,Y> &A, const matrix_slice<T2,P,Q,X,Y> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, j)) - static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(i, j)); } } return ret; } // subtraction with type promotion: matrix slice - matrix template <typename T1, typename T2, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> operator- (const matrix_slice<T1,M,N,X,Y> &A, const matrix<T2,X,Y> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, j)) - static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(i, j)); } } return ret; } //////// //////// // multiplication //////// //////// // matrix_slice * matrix_slice template <typename T, const std::size_t M, const std::size_t N, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y, const std::size_t W> const matrix<T, X, W> operator* (const matrix_slice<T,M,N,X,Y> &A, const matrix_slice<T,P,Q,Y,W> &B) { matrix<T, X, W> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < W; ++j) { ret(i, j) = 0; for (std::size_t k = 0; k < Y; ++k) { ret(i, j) += A(i, k) * B(k, j); } } } return ret; } // matrix * matrix slice template <typename T, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y, const std::size_t W> const matrix<T, X, W> operator* (const matrix<T,X,Y> &A, const matrix_slice<T,P,Q,Y,W> &B) { matrix<T, X, W> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < W; ++j) { ret(i, j) = 0; for (std::size_t k = 0; k < Y; ++k) { ret(i, j) += A(i, k) * B(k, j); } } } return ret; } // matrix slice * matrix template <typename T, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y, const std::size_t W> const matrix<T, X, W> operator* (const matrix_slice<T,M,N,X,Y> &A, const matrix<T,Y,W> &B) { matrix<T, X, W> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < W; ++j) { ret(i, j) = 0; for (std::size_t k = 0; k < Y; ++k) { ret(i, j) += A(i, k) * B(k, j); } } } return ret; } // matrix_slice * matrix_slice with type promotion template <typename T1, typename T2, const std::size_t M, const std::size_t N, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y, const std::size_t W> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, W> operator* (const matrix_slice<T1,M,N,X,Y> &A, const matrix_slice<T2,P,Q,Y,W> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, W> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < W; ++j) { ret(i, j) = 0; for (std::size_t k = 0; k < Y; ++k) { ret(i, j) += static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, k)) * static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(k, j)); } } } return ret; } // matrix * matrix slice with type promotion template <typename T1, typename T2, const std::size_t P, const std::size_t Q, const std::size_t X, const std::size_t Y, const std::size_t W> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, W> operator* (const matrix<T1,X,Y> &A, const matrix_slice<T2,P,Q,Y,W> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, W> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < W; ++j) { ret(i, j) = 0; for (std::size_t k = 0; k < Y; ++k) { ret(i, j) += static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, k)) * static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(k, j)); } } } return ret; } // matrix slice * matrix with type promotion template <typename T1, typename T2, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y, const std::size_t W> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, W> operator* (const matrix_slice<T1,M,N,X,Y> &A, const matrix<T2,Y,W> &B) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, W> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < W; ++j) { ret(i, j) = 0; for (std::size_t k = 0; k < Y; ++k) { ret(i, j) += static_cast<typename promotion_trait<T1,T2>::promoted_type>(A(i, k)) * static_cast<typename promotion_trait<T1,T2>::promoted_type>(B(k, j)); } } } return ret; } //////// //////// // scalar mult. //////// //////// // scalar * matrix slice template <typename Ts, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> const matrix<Ts, X, Y> operator* (const Ts &op1, const matrix_slice<Ts,M,N,X,Y> &op2) { matrix<Ts, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = op1 * op2(i,j); } } return ret; } // matrix slice * scalar template <typename Ts, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> const matrix<Ts, X, Y> operator* (const matrix_slice<Ts,M,N,X,Y> &op2, const Ts &op1) { matrix<Ts, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = op1 * op2(i,j); } } return ret; } // scalar * matrix slice with type promotion template <typename T1, typename T2, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> operator* (const T1 &op1, const matrix_slice<T2,M,N,X,Y> &op2) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = static_cast<typename promotion_trait<T1,T2>::promoted_type>(op1) * static_cast<typename promotion_trait<T1,T2>::promoted_type>(op2(i,j)); } } return ret; } // matrix slice * scalar with type promotion template <typename T1, typename T2, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> const matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> operator* (const matrix_slice<T2,M,N,X,Y> &op2, const T1 &op1) { matrix<typename promotion_trait<T1,T2>::promoted_type, X, Y> ret; for (std::size_t i = 0; i < X; ++i) { for (std::size_t j = 0; j < Y; ++j) { ret(i,j) = static_cast<typename promotion_trait<T1,T2>::promoted_type>(op1) * static_cast<typename promotion_trait<T1,T2>::promoted_type>(op2(i,j)); } } return ret; } //////// //////// // IO //////// //////// template <typename Ts, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> std::ostream& operator<<(std::ostream& os, const matrix_slice<Ts,M,N,X,Y>& m) { for(std::size_t i = 0; i < X; ++i) { for(std::size_t j = 0; j < Y; ++j) { os << m(i,j) << " "; } os << "\n"; } return os; } template <typename Ts, const std::size_t M, const std::size_t N, const std::size_t X, const std::size_t Y> std::istream& operator>>(std::istream& is, matrix_slice<Ts,M,N,X,Y>& m) { for(std::size_t i = 0; i < X; ++i) { for(std::size_t j = 0; j < Y; ++j) { is >> m(i,j); } } return is; } } // namespace my #endif // MATRIX_SLICE_INTEROP_HPP
[ "hanji1984@2159fae2-c2cd-11de-acfc-b766374499fb" ]
[ [ [ 1, 499 ] ] ]
855c214adda82ba83cbdd048c170cf412a7e0d91
971b000b9e6c4bf91d28f3723923a678520f5bcf
/demo_write_mng/main.cpp
6dbd21d91c5bb2ed80919e6712bba2ace5be66d1
[]
no_license
google-code-export/fop-miniscribus
14ce53d21893ce1821386a94d42485ee0465121f
966a9ca7097268c18e690aa0ea4b24b308475af9
refs/heads/master
2020-12-24T17:08:51.551987
2011-09-02T07:55:05
2011-09-02T07:55:05
32,133,292
2
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
#include <QtCore> #include <QDebug> #include <QCoreApplication> #include <QObject> #include <QApplication> #include "gui_main.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Gui_Main w; w.show(); a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) ); return a.exec(); }
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 17 ] ] ]
260e4997f40a803c9105c2d7d965fd3f7dc4fd40
f90b1358325d5a4cfbc25fa6cccea56cbc40410c
/src/SicForma/isotopologue.cpp
e71e93855842d4ad501b0a7bb0e3fe7d184c68d9
[]
no_license
ipodyaco/prorata
bd52105499c3fad25781d91952def89a9079b864
1f17015d304f204bd5f72b92d711a02490527fe6
refs/heads/master
2021-01-10T09:48:25.454887
2010-05-11T19:19:40
2010-05-11T19:19:40
48,766,766
0
0
null
null
null
null
UTF-8
C++
false
false
17,248
cpp
#include "isotopologue.h" IsotopeDistribution::IsotopeDistribution() { } IsotopeDistribution::IsotopeDistribution( vector< double > vItsMass, vector< double > vItsProb ) { vMass = vItsMass; vProb = vItsProb; } IsotopeDistribution::~IsotopeDistribution() { // destructor } void IsotopeDistribution::print() { cout << "Mass " << '\t' << "Inten" << endl; for( unsigned int i = 0; i < vMass.size(); i++) { cout << setprecision(8) << vMass[i] << '\t' << vProb[i] << endl; } } double IsotopeDistribution::getMostAbundantMass() { double dMaxProb = 0; double dMass = 0; for( unsigned int i = 0; i < vMass.size(); ++i ) { if( dMaxProb < vProb[i] ) { dMaxProb = vProb[i]; dMass = vMass[i]; } } return dMass; } double IsotopeDistribution::getAverageMass() { double dSumProb = 0; double dSumMass = 0; for( unsigned int i = 0; i < vMass.size(); ++i ) { dSumProb = dSumProb + vProb[i]; dSumMass = dSumMass + vProb[i] * vMass[i]; } if(dSumProb <= 0) return 1.0; return ( dSumMass / dSumProb ) ; } Isotopologue::Isotopologue() : MassPrecision(0.1), ProbabilityCutoff(0.000000001), AtomName("CHONPS"), AtomNumber( 12 ) { } Isotopologue::Isotopologue( string sName, string sTable ) : MassPrecision(0.1), ProbabilityCutoff(0.000000001), AtomName("CHONPS"), AtomNumber( 12 ) { setupIsotopologue( sName, sTable ); } Isotopologue::~Isotopologue() { // destructor } bool Isotopologue::setupIsotopologue( const string & sName, const string & sTable ) { sIsotoplogueName = sName; istringstream issStream( sTable ); string sResidue; vector< int > viAtomVector; int iNumber; int i; // parse out the RESIDUE_ATOMIC_COMPOSITION table while( !( issStream.eof() ) ) { // each row is expected to start with the residue name, following by 12 numbers for the natuual and enriched CHONPS issStream >> sResidue; if( sResidue == "" ) continue; viAtomVector.clear(); viAtomVector.reserve( AtomNumber ); for( i = 0; i < AtomNumber; ++i ) { if( issStream.eof() ) { // this row doesn't have 12 fields cout << "ERROR: the RESIDUE_ATOMIC_COMPOSITION table in ProRataConfig is not correct!" << endl; return false; } issStream >> iNumber; viAtomVector.push_back( iNumber ); } // add this row into the mResidueAtomicComposition table mResidueAtomicComposition[ sResidue ] = viAtomVector; sResidue = ""; } // push 12 empty IsotopeDistributions into vAtomIsotopicDistribution vAtomIsotopicDistribution.reserve( AtomNumber ); for( i = 0; i < ( AtomNumber ); ++i ) { IsotopeDistribution TempDistribution; vAtomIsotopicDistribution.push_back( TempDistribution ); } // variables to be passed as reference to ProRataConfig::getAtomIsotopicComposition // to receive its return value vector< double > vdMassTemp; vector< double > vdNaturalCompositionTemp; vector< double > vdEnrichedCompositionTemp; // the isotopic distribution is pushed into vAtomIsotopicDistribution in the order of // natural CHONPS and then enriched CHONPS for( i = 0; i < AtomName.size(); ++i ) { if( ! ProRataConfig::getAtomIsotopicComposition( AtomName[i], vdMassTemp, vdNaturalCompositionTemp, vdEnrichedCompositionTemp ) ) { cout << "ERROR: cannot retrieve isotopic composition for atom " << AtomName[i] << " from ProRataConfig" << endl; return false; } vAtomIsotopicDistribution[i].vMass = vdMassTemp; vAtomIsotopicDistribution[i].vProb = vdNaturalCompositionTemp; vAtomIsotopicDistribution[ ( i+AtomName.size() ) ].vMass = vdMassTemp; vAtomIsotopicDistribution[ ( i+AtomName.size() ) ].vProb = vdEnrichedCompositionTemp; } // calculate Isotopic distribution for all residues map< string, vector< int > >::iterator ResidueIter; IsotopeDistribution tempIsotopeDistribution; for( ResidueIter = mResidueAtomicComposition.begin(); ResidueIter != mResidueAtomicComposition.end(); ResidueIter++ ) { if( !computeIsotopicDistribution( ResidueIter->second, tempIsotopeDistribution ) ) { cout << "ERROR: cannot calculate the isotopic distribution for residue " << ResidueIter->first << endl; return false; } vResidueIsotopicDistribution[ ResidueIter->first ] = tempIsotopeDistribution; } return true; } bool Isotopologue::computeMZwindows( string sSequence, int iChargeState, MZwindows & myMZwindows ) { formatSequence( sSequence ); IsotopeDistribution distributionPeptide; if( !computeIsotopicDistribution( sSequence, distributionPeptide ) ) { cout << "WARNNING: cannot compute isotopic distribution for peptide " << sSequence << endl; return false; } int i = 0; // get the masses that passes the isotopic envelop cutoff vector< double > vMassFiltered; double dMaxProb = *max_element( distributionPeptide.vProb.begin(), distributionPeptide.vProb.end() ); double dCutoffProb = dMaxProb * ProRataConfig::getIsotopicEnvelopCutoff(); for( i = 0; i < distributionPeptide.vProb.size(); i++ ) { if( distributionPeptide.vProb[i] > dCutoffProb ) vMassFiltered.push_back( distributionPeptide.vMass[i] ); } if( iChargeState <= 0 ) { cout << "ERROR: the charge state cannot be zero or negative number! " << endl; return false; } // calculate the mass to charge ratios vector< double > vMassToCharge; for( i = 0; i < vMassFiltered.size(); i++ ) vMassToCharge.push_back( (vMassFiltered[i]+iChargeState)/((double)iChargeState) ); // calculate the m/z ranges for each m/z value vector< double > vPeakUpperMZ; vector< double > vPeakLowerMZ; for( i = 0; i < vMassToCharge.size(); i++ ) { vPeakLowerMZ.push_back( (vMassToCharge[i] - ProRataConfig::getMinusMZerror() ) ); if( vPeakLowerMZ[i] < 0 ) vPeakLowerMZ[i] = 0; vPeakUpperMZ.push_back( (vMassToCharge[i] + ProRataConfig::getPlusMZerror() ) ); } // merge overlaping m/z ranges in vPeakUpperMZ and vPeakLowerMZ int j = 0; for( i = 0; i < vPeakUpperMZ.size(); i++ ) { // determine if this m/z range has been merged previously if( (vPeakUpperMZ[i] > 0) && (vPeakLowerMZ[i] > 0) ) { // compare with other m/z ranges for( j = (i+1); j < vPeakUpperMZ.size(); j++ ) { if( (vPeakUpperMZ[j] > 0) && (vPeakLowerMZ[j] > 0) ) { // determined if these two m/z ranges overlap if( ( -0.05 <= (vPeakUpperMZ[j] - vPeakLowerMZ[i]) ) && ( -0.05 <= (vPeakUpperMZ[i] - vPeakLowerMZ[j]) ) ) { // if so, set the joint m/z range to m/z range [i] and flag m/z range [j] as having been merged vPeakUpperMZ[i] = maximum( vPeakUpperMZ[i], vPeakUpperMZ[j] ); vPeakLowerMZ[i] = minimum( vPeakLowerMZ[i], vPeakLowerMZ[j] ); vPeakUpperMZ[j] = (-1.0); vPeakLowerMZ[j] = (-1.0); } } } } } // save the merged m/z ranges to myMZwindows to be returned myMZwindows.vfUpperMZ.clear(); myMZwindows.vfLowerMZ.clear(); for( i = 0; i < vPeakUpperMZ.size(); i++ ) { if( (vPeakUpperMZ[i] > 0) && (vPeakLowerMZ[i] > 0) ) { myMZwindows.vfUpperMZ.push_back( (float)vPeakUpperMZ[i] ); myMZwindows.vfLowerMZ.push_back( (float)vPeakLowerMZ[i] ); } } return true; } double Isotopologue::computeMostAbundantMass( string sSequence ) { IsotopeDistribution tempIsotopeDistribution; if( !computeIsotopicDistribution( sSequence, tempIsotopeDistribution ) ) return 0; else return tempIsotopeDistribution.getMostAbundantMass(); } double Isotopologue::computeAverageMass( string sSequence ) { IsotopeDistribution tempIsotopeDistribution; if( !computeIsotopicDistribution( sSequence, tempIsotopeDistribution ) ) return 0; else return tempIsotopeDistribution.getAverageMass(); } bool Isotopologue::computeIsotopicDistribution( string sSequence , IsotopeDistribution & myIsotopeDistribution ) { formatSequence( sSequence ); IsotopeDistribution sumDistribution; IsotopeDistribution currentDistribution; map< string, IsotopeDistribution >::iterator ResidueIter; ResidueIter = vResidueIsotopicDistribution.find("NTerm"); if(ResidueIter != vResidueIsotopicDistribution.end() ) { currentDistribution = ResidueIter->second; sumDistribution = currentDistribution; } else { cout << "ERROR: can't find the N-terminus" << endl; return false; } ResidueIter = vResidueIsotopicDistribution.find("CTerm"); if(ResidueIter != vResidueIsotopicDistribution.end() ) { currentDistribution = ResidueIter->second; sumDistribution = sum( currentDistribution, sumDistribution ); } else { cout << "ERROR: can't find the C-terminus" << endl; return false; } // add up all residues's isotopic distribution for( int j = 0; j < sSequence.length(); j++) { string currentResidue = sSequence.substr( j, 1 ); ResidueIter = vResidueIsotopicDistribution.find( currentResidue ); if(ResidueIter != vResidueIsotopicDistribution.end() ) { currentDistribution = ResidueIter->second; sumDistribution = sum( currentDistribution, sumDistribution ); } else { cout << "ERROR: can't find the residue" << currentResidue << endl; return false; } } myIsotopeDistribution = sumDistribution; return true; } bool Isotopologue::computeProductIonMass( string sSequence, vector< double > & vdYion, vector< double > & vdBion ) { formatSequence( sSequence ); // cout << "sSequence = " << sSequence << endl; vdYion.clear(); vdBion.clear(); IsotopeDistribution sumDistribution; IsotopeDistribution currentDistribution; map< string, IsotopeDistribution >::iterator ResidueIter; // compute B-ion series ResidueIter = vResidueIsotopicDistribution.find("NTerm"); if(ResidueIter != vResidueIsotopicDistribution.end() ) { currentDistribution = ResidueIter->second; sumDistribution = currentDistribution; } else { cout << "ERROR: can't find the N-terminus" << endl; return false; } for( int j = 0; j < sSequence.length(); j++) { string currentResidue = sSequence.substr( j, 1 ); ResidueIter = vResidueIsotopicDistribution.find( currentResidue ); if(ResidueIter != vResidueIsotopicDistribution.end() ) { currentDistribution = ResidueIter->second; sumDistribution = sum( currentDistribution, sumDistribution ); } else { cout << "ERROR: can't find the residue" << currentResidue << endl; return false; } // if the current residue is an alphabet then it is a amino acid residue ( not a PTM ) // then save it to vdBion if( isalpha( currentResidue[0] ) ) vdBion.push_back( sumDistribution.getAverageMass() ); } // compute Y-ion series ResidueIter = vResidueIsotopicDistribution.find("CTerm"); if(ResidueIter != vResidueIsotopicDistribution.end() ) { currentDistribution = ResidueIter->second; sumDistribution = currentDistribution; } else { cout << "ERROR: can't find the N-terminus" << endl; return false; } for( int j = (sSequence.length() - 1) ; j > -1 ; j--) { string currentResidue = sSequence.substr( j, 1 ); ResidueIter = vResidueIsotopicDistribution.find( currentResidue ); if(ResidueIter != vResidueIsotopicDistribution.end() ) { currentDistribution = ResidueIter->second; sumDistribution = sum( currentDistribution, sumDistribution ); } else { cout << "ERROR: can't find the residue" << currentResidue << endl; return false; } // if the current residue is an alphabet then it is a amino acid residue ( not a PTM ) // then save it to vdBion if( isalpha( currentResidue[0] ) ) vdYion.push_back( ( sumDistribution.getAverageMass() + 2.0 ) ); } return true; } bool Isotopologue::computeIsotopicDistribution( vector< int > AtomicComposition, IsotopeDistribution & myIsotopeDistribution ) { IsotopeDistribution sumDistribution; IsotopeDistribution currentAtomDistribution; currentAtomDistribution = multiply( vAtomIsotopicDistribution[0], AtomicComposition[0] ); sumDistribution = currentAtomDistribution; for( int i = 1; i < AtomNumber; i++ ) { currentAtomDistribution = multiply( vAtomIsotopicDistribution[i], AtomicComposition[i] ); sumDistribution = sum( currentAtomDistribution, sumDistribution ); } myIsotopeDistribution = sumDistribution; return true; } bool Isotopologue::computeAtomicComposition( string sSequence, vector< int > & myAtomicComposition ) { formatSequence( sSequence ); vector< int > AtomicComposition; vector< int > CurrentComposition; int i; map< string, vector< int > >::iterator ResidueIter; for( i = 0; i < AtomNumber; i++) AtomicComposition.push_back( 0 ); ResidueIter = mResidueAtomicComposition.find("NTerm"); if(ResidueIter != mResidueAtomicComposition.end() ) { CurrentComposition = ResidueIter->second; for( i = 0; i < AtomNumber; i++) AtomicComposition[i] = CurrentComposition[i]; } else { cout << "ERROR: can't find the atomic composition for the N-terminus" << endl; return false; } ResidueIter = mResidueAtomicComposition.find("CTerm"); if(ResidueIter != mResidueAtomicComposition.end() ) { CurrentComposition = ResidueIter->second; for( i = 0; i < AtomNumber; i++) AtomicComposition[i] += CurrentComposition[i]; } else { cout << "ERROR: can't find the atomic composition for the C-terminus" << endl; return false; } for( int j = 0; j < sSequence.length(); j++) { string currentResidue = sSequence.substr( j, 1 ); ResidueIter = mResidueAtomicComposition.find( currentResidue ); if(ResidueIter != mResidueAtomicComposition.end() ) { CurrentComposition = ResidueIter->second; for( i = 0; i < AtomNumber; i++) AtomicComposition[i] += CurrentComposition[i]; } else { cout << "ERROR: can't find the atomic composition for residue/PTM: " << currentResidue << endl; return false; } } myAtomicComposition = AtomicComposition; return true; } IsotopeDistribution Isotopologue::sum( IsotopeDistribution distribution0, IsotopeDistribution distribution1) { IsotopeDistribution sumDistribution; double currentMass; double currentProb; bool bIsMerged; int iSizeDistribution0 = distribution0.vMass.size(); int iSizeDistribution1 = distribution1.vMass.size(); int iSizeSumDistribution; int i; int j; int k; for( i = 0; i < iSizeDistribution0; ++i ) { for( j = 0; j < iSizeDistribution1; ++j ) { // combine one isotopologue from distribution0 with one isotopologue distribution1 currentMass = (distribution0.vMass[i] + distribution1.vMass[j]); currentProb = (distribution0.vProb[i] * distribution1.vProb[j]); if ( ( currentProb > ProbabilityCutoff ) ) { iSizeSumDistribution = sumDistribution.vMass.size(); // push back the first peak if( iSizeSumDistribution == 0 ) { sumDistribution.vMass.push_back( currentMass ); sumDistribution.vProb.push_back( currentProb ); } else { bIsMerged = false; // check if the combined isotopologue can be merged with the existing isotopologues for ( k = 0; k < iSizeSumDistribution; ++k ) { if( fabs( currentMass - sumDistribution.vMass[k] ) < MassPrecision ) { // average Mass sumDistribution.vMass[k] = ( currentMass*currentProb + sumDistribution.vMass[k]*sumDistribution.vProb[k] ) / ( currentProb + sumDistribution.vProb[k] ); // sum Prob sumDistribution.vProb[k] = currentProb + sumDistribution.vProb[k]; bIsMerged = true; break; } } if( !bIsMerged ) { sumDistribution.vMass.push_back( currentMass ); sumDistribution.vProb.push_back( currentProb ); } } } } } // normalize the probability space to 1 double sumProb = 0; iSizeSumDistribution = sumDistribution.vMass.size(); for( i = 0; i < iSizeSumDistribution; ++i ) sumProb += sumDistribution.vProb[i]; if( sumProb <= 0 ) return sumDistribution; for( i = 0; i < iSizeSumDistribution; ++i ) sumDistribution.vProb[i] = sumDistribution.vProb[i]/sumProb; return sumDistribution; } IsotopeDistribution Isotopologue::multiply( IsotopeDistribution distribution0, int count ) { if( count == 1 ) return distribution0; IsotopeDistribution productDistribution; productDistribution.vMass.push_back( 0.0 ); productDistribution.vProb.push_back( 1.0 ); for( int i = 0; i < ( abs(count) ); ++i ) { productDistribution = sum( productDistribution, distribution0 ); } return productDistribution; } void Isotopologue::formatSequence( string & sSequence ) { int iLength = sSequence.length(); // check if this sequence is of the format X.XXXX.X // its minimum length is 5 if(iLength > 4 ) { // its second residues from both the left side and the right side should be '.' if( sSequence[1] == '.' && sSequence[ ( iLength - 2 ) ] == '.') { // if so, extract the sequence between '.' sSequence = sSequence.substr( 2, (iLength - 4) ); } } }
[ "chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a" ]
[ [ [ 1, 597 ] ] ]
bc184019601a56a70525000e7d33c6aea18e4c10
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Agent/MiscAgent/Phantom/hkpPhantomAgent.h
eb1c28a3a3fa05a7db5a38b5abca30e74f6f403c
[]
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,378
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_COLLIDE2_PHANTOM_AGENT_H #define HK_COLLIDE2_PHANTOM_AGENT_H #include <Physics/Collide/Agent/hkpCollisionAgent.h> #include <Physics/Collide/Shape/hkpShapeType.h> class hkpCollisionDispatcher; class hkpPhantomCallbackShape; class hkpCollidable; /// An hkpPhantomAgent handles collisions between hkPhantomShapes and any other shapes. /// No collision response takes place, but events will still be fired. class hkpPhantomAgent : public hkpCollisionAgent { public: /// Registers this agent with the collision dispatcher. static void HK_CALL registerAgent(hkpCollisionDispatcher* dispatcher); // hkpCollisionAgent interface implementation. virtual void getPenetrations(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector ); // hkpCollisionAgent interface implementation. static void HK_CALL staticGetPenetrations(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector ); // hkpCollisionAgent interface implementation. virtual void processCollision(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& result); // hkpCollisionAgent interface implementation. virtual void getClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdPointCollector& pointDetails); // hkpCollisionAgent interface implementation. static void HK_CALL staticGetClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, class hkpCdPointCollector& collector ); // hkpCollisionAgent interface implementation. virtual void linearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector ); // hkpCollisionAgent interface implementation. static void HK_CALL staticLinearCast( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& collector, hkpCdPointCollector* startCollector ); // hkpCollisionAgent interface implementation. virtual void cleanup( hkCollisionConstraintOwner& constraintOwner ); protected: /// Constructor, called by the agent creation function. hkpPhantomAgent(const hkpCdBody& bodyA, const hkpCdBody& bodyB, hkpContactMgr* contactMgr); /// Agent creation function used by the hkpCollisionDispatcher. static hkpCollisionAgent* HK_CALL createPhantomAgent(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr); /// Creates no agent, but forwards the call to the phantom shape. static hkpCollisionAgent* HK_CALL createNoPhantomAgent(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr); const hkpCollidable* m_collidableA; const hkpCollidable* m_collidableB; hkpPhantomCallbackShape* m_shapeA; hkpPhantomCallbackShape* m_shapeB; hkpShapeType m_bodyTypeA; hkpShapeType m_bodyTypeB; }; #endif // HK_COLLIDE2_PHANTOM_AGENT_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, 92 ] ] ]
90dad87819da4a921439e2a11993f23a1b3316b0
2b80036db6f86012afcc7bc55431355fc3234058
/src/core/NonLibraryTrackHelper.cpp
c2e5c6bcc117fe0fb6a3d99c94a370299abf8df8
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
ISO-8859-9
C++
false
false
5,475
cpp
////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright © 2008, Daniel Önnerby // // 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 author nor the names of other 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 "pch.hpp" #include <core/NonLibraryTrackHelper.h> #include <boost/bind.hpp> #include <core/PluginFactory.h> #include <core/Plugin/IMetaDataReader.h> #include <core/filestreams/Factory.h> ////////////////////////////////////////////////////////////////////////////// using namespace musik::core; ////////////////////////////////////////////////////////////////////////////// NonLibraryTrackHelper NonLibraryTrackHelper::sInstance; NonLibraryTrackHelper::NonLibraryTrackHelper(void) :threadIsRunning(false) { } NonLibraryTrackHelper::~NonLibraryTrackHelper(void){ } NonLibraryTrackHelper& NonLibraryTrackHelper::Instance(){ return NonLibraryTrackHelper::sInstance; } boost::mutex& NonLibraryTrackHelper::TrackMutex(){ return NonLibraryTrackHelper::sInstance.trackMutex; } void NonLibraryTrackHelper::ReadTrack(musik::core::TrackPtr track){ bool threadRunning(false); { boost::mutex::scoped_lock lock(this->mutex); this->tracksToRead.push_back(TrackWeakPtr(track)); threadRunning = this->threadIsRunning; } if(!threadRunning){ if(this->helperThread){ this->helperThread->join(); } this->helperThread.reset(new boost::thread(boost::bind(&NonLibraryTrackHelper::ThreadLoop,this))); } } void NonLibraryTrackHelper::ThreadLoop(){ // Get the metadatareaders typedef Plugin::IMetaDataReader PluginType; typedef PluginFactory::DestroyDeleter<PluginType> Deleter; typedef std::vector<boost::shared_ptr<Plugin::IMetaDataReader> > MetadataReaderList; MetadataReaderList metadataReaders = PluginFactory::Instance().QueryInterface<PluginType, Deleter>("GetMetaDataReader"); // pop a track, read the metadata, notify and continue bool moreTracks(true); while(moreTracks){ moreTracks = false; musik::core::TrackPtr track; { boost::mutex::scoped_lock lock(this->mutex); if(!this->tracksToRead.empty()){ // is this a valid track track = this->tracksToRead.front().lock(); this->tracksToRead.pop_front(); } moreTracks = !this->tracksToRead.empty(); if(!moreTracks){ // Set to "not running". No locking beyond this point. this->threadIsRunning = false; } } if(track){ // check if this is a local file if(musik::core::filestreams::Factory::IsLocalFileStream(track->URL())){ utfstring url(track->URL()); utfstring::size_type lastDot = url.find_last_of(UTF(".")); if(lastDot!=utfstring::npos){ track->SetValue("extension",url.substr(lastDot+1).c_str()); } // Read track metadata typedef MetadataReaderList::iterator Iterator; Iterator it = metadataReaders.begin(); while (it != metadataReaders.end()) { if((*it)->CanReadTag(track->GetValue("extension")) ){ // Should be able to read the tag if( (*it)->ReadTag(track.get()) ){ // Successfully read the tag. // tagRead=true; } } it++; } // Lets notify that tracks has been read this->TrackMetadataUpdated(track); } } } }
[ "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e", "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 42 ], [ 44, 91 ], [ 93, 117 ], [ 135, 135 ], [ 138, 139 ], [ 142, 148 ] ], [ [ 43, 43 ], [ 92, 92 ], [ 118, 134 ], [ 136, 137 ], [ 140, 141 ] ] ]
b2543a55fe2151083531680e5a5fe0f3738977cf
233ea3a6f9eacb0214c91ca181e81d7849a0ebeb
/cpp/ootl/ootl_string.hpp
f916b4fd6cd276668e51c2a1242ca365b48af064
[ "LicenseRef-scancode-public-domain", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
graydon/cat
a5e438e64c182adb2fc2ebf2d672d2e8af78a17b
9cd5d62604dcf930f1acd989fe8833c50b2183c5
refs/heads/master
2016-09-06T19:13:42.282375
2008-05-11T07:25:34
2008-05-11T07:25:34
31,670,471
1
1
null
null
null
null
UTF-8
C++
false
false
2,724
hpp
// Public Domain by Christopher Diggins // http://www.ootl.org #ifndef OOTL_STRING_HPP #define OOTL_STRING_HPP #include "ootl_stack.hpp" namespace ootl { struct cstring { cstring() : m("") { } cstring(const char* x) : m(x) { } cstring(const cstring& x) : m(x.m) { } operator const char*() { return to_ptr(); } const char* to_ptr() { return m; } bool operator==(const cstring& x) const { const char* left = m; const char* right = x.m; while ((*left != '\0') && (*right != '\0')) if (*left++ != *right++) return false; return (*left == *right); } private: const char* m; }; struct string { struct dyn_buffer { dyn_buffer(const dyn_buffer& x) { size_t n = strlen(x.m); m = new char[n]; strcpy_s(m, n, x.m); } dyn_buffer(const string& s) { size_t n = s.count(); m = new char[n + 1]; s.copy_to_array(m); m[n] = '\0'; } ~dyn_buffer() { delete[] m; } operator const char*() const { return m; } private: dyn_buffer() { } char* m; }; typedef string self; string(const char* x) { assign(x); } string(const self& x) : m(x.m) { } self& assign(const char* x) { clear(); return concat(x); } self& assign(const self& x) { clear(); return concat(x); } char& operator[](int n) { return m[n]; } const char& operator[](int n) const { return m[n]; } size_t count() const { return m.count(); } template<typename T> self& concat(const T& x) { x.foreach(stacker(*this)); return *this; } self& concat(const char* x) { if (x == NULL) return *this; while (*x != 0) { m.push(*x++); } return *this; } void push(char x) { m.push(x); } char pop() { return m.pull(); } void clear() { m.clear(); } template<typename Proc> void foreach(Proc& x) { m.foreach(x); } template<typename Proc> void foreach(Proc& x) const { m.foreach(x); } self& operator=(const self& x) { return assign(x); } self& operator=(const char* x) { return assign(x); } self& operator+=(const self& x) { return concat(x); } self& operator+=(const char* x) { return concat(x); } const self& operator+(const self& x) const { return self(*this).concat(x); } const self& operator+(const char* x) const { return self(*this).concat(x); } void copy_to_array(char* x) const { m.copy_to_array(x); } dyn_buffer to_char_ptr() const { return dyn_buffer(*this); } private: stack<char> m; }; } #endif
[ "cdiggins@c3f59c99-e62b-0410-a2a3-eb39d943d493" ]
[ [ [ 1, 146 ] ] ]
0ccdd843fec83ffe905bfbeb1dbb6d5fcf84c8ca
da84305a9b9c14e4e195bf7db146daa7957c9842
/data_index.h
bad0149979ce7b9a34e171cedfe773031fcabd11
[]
no_license
xlvector/graph-layout
28c44ded972e2eaeb931c6f2f45d556fa8448e41
d815ae6275c43a7aaf492e949fbb2bcb84be4588
refs/heads/master
2021-01-25T10:14:27.912230
2009-08-15T15:46:50
2009-08-15T15:46:50
278,584
1
0
null
null
null
null
UTF-8
C++
false
false
2,052
h
#ifndef _DATA_INDEX_H_ #define _DATA_INDEX_H_ #include <vector> #include <map> #include <set> namespace pattern{ using namespace std; template <typename _Point> struct Cell2D{ double xmin,ymin,xmax,ymax; int N; double xg,yg; map< int, set<int> > c; vector< _Point> points; }; template <typename _Point> void buildCell2D(const vector< _Point > & ps, Cell2D< _Point > & cell){ cell.points = ps; cell.xmin = ps[0].first; cell.xmax = cell.xmin; cell.ymin = ps[0].second; cell.ymax = cell.ymin; for(int i = 0; i < ps.size(); ++i){ cell.xmin = min<double>(cell.xmin,ps[i].first); cell.xmax = max<double>(cell.xmax,ps[i].first); cell.ymin = min<double>(cell.ymin,ps[i].second); cell.ymax = max<double>(cell.ymax,ps[i].second); } cell.xg = (cell.xmax - cell.xmin)/((double)(cell.N)); cell.yg = (cell.ymax - cell.ymin)/((double)(cell.N)); for(int i = 0; i < ps.size(); ++i){ int xn = (int)((ps[i].first - cell.xmin) / cell.xg); int yn = (int)((ps[i].second - cell.ymin) / cell.yg); int id = xn * cell.N + yn; cell.c[id].insert(i); } } template <typename _Point> void searchCell2D(const Cell2D< _Point > & cell, _Point & p, int K, set< int > & rp){ int xn = (int)((p.first - cell.xmin) / cell.xg); int yn = (int)((p.second - cell.ymin) / cell.yg); for(int a = -1 * K; a <= K; ++a){ for(int b = -1 * K; b <= K; ++b){ int x = xn + a; int y = yn + b; int id = x * cell.N + y; map<int, set<int> >::const_iterator pp = cell.c.find(id); if(pp == cell.c.end()) continue; set< int > tp = pp->second; for(set<int>::iterator i = tp.begin(); i != tp.end(); ++i) rp.insert(*i); } } } }; #endif
[ [ [ 1, 56 ] ] ]
9274212653fa18c24a51cc3da044bb905a6ab830
485c5413e1a4769516c549ed7f5cd4e835751187
/Source/Engine/objMesh.cpp
e3844efaf469a7ee2a92502782cf52c420d3686d
[]
no_license
FranckLetellier/rvstereogram
44d0a78c47288ec0d9fc88efac5c34088af88d41
c494b87ee8ebb00cf806214bc547ecbec9ad0ca0
refs/heads/master
2021-05-29T12:00:15.042441
2010-03-25T13:06:10
2010-03-25T13:06:10
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
13,552
cpp
#include "objMesh.h" #include <iostream> #include <algorithm> using namespace std; #include <string> #include <sstream> #include <fstream> #include <assert.h> #define NEXT_INDICE do{i++;}while((buf[i]<'0')&&(buf[i]>'9')); #define BUFFER_OFFSET(i) ((void*)(i)) ObjMesh::ObjMesh() { m_iBufferId = 0; } bool ObjMesh::Load(const std::string& name) { bool ret = false; if(name.find(".obj") != std::string::npos) { ret = LoadFile(name); } else { std::cerr << "Le mesh " << name << " n'est pas dans un format valide" << std::endl; return false; } if(!ret) { std::cerr << "[Error] Impossible de charger le mesh " << name << std::endl; return false; } ComputeTangents(); build(); return true; } bool ObjMesh::build() { glGenBuffers(1, &m_iBufferId); assert(m_iBufferId); bind(); //Build the VBO if(!m_vPosition.empty()) m_iSizeVertex = m_vPosition.size()*sizeof(osg::Vec3); else { std::cerr << "[ERROR] No position data !" << std::endl; return false; } if(!m_vNormal.empty()) m_iSizeNormal = m_vNormal.size()*sizeof(osg::Vec3); if(!m_vTexcoord.empty()) m_iSizeTexture = m_vTexcoord.size()*sizeof(osg::Vec2); if(!m_vTangent.empty()) m_iSizeTangent = m_vTangent.size()*sizeof(osg::Vec3); //Link the buffer glBufferData(GL_ARRAY_BUFFER, m_iSizeVertex + m_iSizeNormal + m_iSizeTexture + m_iSizeTangent, 0, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER_ARB, 0, m_iSizeVertex, (const GLvoid*)(&m_vPosition[0])); if(m_vNormal.size()) glBufferSubData(GL_ARRAY_BUFFER_ARB, m_iSizeVertex, m_iSizeNormal, (const GLvoid*)(&m_vNormal[0])); if(m_vTexcoord.size()) glBufferSubData(GL_ARRAY_BUFFER_ARB, m_iSizeVertex + m_iSizeNormal, m_iSizeTexture, (const GLvoid*)(&m_vTexcoord[0])); if(m_vTangent.size()) glBufferSubData(GL_ARRAY_BUFFER_ARB, m_iSizeVertex + m_iSizeNormal + m_iSizeTexture, m_iSizeTangent, (const GLvoid*)(&m_vTangent[0])); unbind(); return true; } void ObjMesh::bind() { glBindBuffer(GL_ARRAY_BUFFER, m_iBufferId); } void ObjMesh::unbind() { glBindBuffer(GL_ARRAY_BUFFER, 0); } void ObjMesh::Destroy() { glDeleteBuffersARB(1, &m_iBufferId); m_iBufferId = 0; m_vPosition.clear(); m_vNormal.clear(); m_vTexcoord.clear(); m_vTangent.clear(); for(std::vector<sGroup>::iterator it=m_tGroup.begin(); it!=m_tGroup.end(); it++) (*it).tFace.clear(); m_tGroup.clear(); } bool ObjMesh::LoadFile(const std::string& filename) { ifstream fp(filename.c_str(), ios::binary); if(!fp) return false; sFace face; sGroup grp; osg::Vec3 pt3D; osg::Vec2 pt2D; // char buftmp[64]; long i,v,g; // compteur pour le stockage des données lors de la seconde passe GLuint indFacePosition; GLuint indFaceNormal; GLuint indFaceTexcoord; std::vector<osg::Vec3> tTempPosition; std::vector<osg::Vec3> tTempNormal; std::vector<osg::Vec2> tTempTexcoord; string strBuffer; while(std::getline(fp, strBuffer)) { stringstream strStream(strBuffer); const char* buf = strBuffer.c_str(); // lenbuf = strlen((const char *)buf); if (strBuffer.size() > 0) { // sscanf(buf,"%s",buftmp); string buftmp; strStream >> buftmp; // buftmp << strStream; if(buftmp == "#") { // on a trouvé un commentaire, on passe } else if(buftmp == "mtllib") { // on a trouvé un matérial à charger ? // materials->Load(&buf[7]); // on charge le fichier associé } else if(buftmp == "v") { // on a trouvé une vertice ? sscanf(&strBuffer[2],"%f%f%f",&pt3D.x(),&pt3D.y(),&pt3D.z()); tTempPosition.push_back(pt3D); } else if(buftmp == "vt") { // on a trouvé une coordonnée de texture ? sscanf(&strBuffer[2],"%f%f",&pt2D.x(),&pt2D.y()); pt2D.y() = 1.0f - pt2D.y(); tTempTexcoord.push_back(pt2D); } else if(buftmp == "vn") { // on a trouvé une normale ? sscanf(&strBuffer[2],"%f%f%f",&pt3D.x(),&pt3D.y(),&pt3D.z()); pt3D.normalize(); tTempNormal.push_back(pt3D); } else if(buftmp == "g") { // on a trouvé un groupe ? if(strBuffer.size() > 1) { grp.strName = &buf[2]; grp.nMaterial = 0; m_tGroup.push_back(grp); } } else if(buftmp == "usemtl") { // on a trouvé un matérial à utiliser ? if(m_tGroup.size() <= 0) { grp.strName = "No Name"; grp.nMaterial = 0; m_tGroup.push_back(grp); g = 0; } else { g = (long)m_tGroup.size() - 1; } // m_tGroup[g].Material = materials->GetId(&buf[7]); // on récupère son id } else if(buftmp == "f") { // on a trouvé une face ? int max; if( tTempPosition.size() >= tTempNormal.size() ) max = 0; else max = 1; if(max==0 && tTempTexcoord.size() > tTempPosition.size() ) max = 2; if(max==1 && tTempTexcoord.size() > tTempNormal.size() ) max = 2; // m_tNormal.resize( m_tPosition.size() ); // m_tTexcoord.resize( m_tPosition.size() ); switch(max) { case 0: { m_vPosition.resize( tTempPosition.size() ); m_vNormal.resize( tTempPosition.size() ); m_vTexcoord.resize( tTempPosition.size() ); break;} case 1: { m_vPosition.resize( tTempNormal.size() ); m_vNormal.resize( tTempNormal.size() ); m_vTexcoord.resize( tTempNormal.size() ); break;} case 2: { m_vPosition.resize( tTempTexcoord.size() ); m_vNormal.resize( tTempTexcoord.size() ); m_vTexcoord.resize( tTempTexcoord.size() ); break;} } if(m_tGroup.size() <= 0) { grp.strName = "No Name"; grp.nMaterial = 0; m_tGroup.push_back(grp); g = 0; } else { g = (long)m_tGroup.size() - 1; } for(i=0; (buf[i] < '0') || (buf[i] > '9') ;i++); // on se positionne à la première valeur for(v=0; v < 3 ;v++) { // triangles donc composés de 3 vertices indFacePosition = 0; for(; (buf[i] >= '0') && (buf[i] <= '9') ;i++) { // on la récupère indFacePosition *= 10; // première vertice indFacePosition += buf[i]-0x30; // 0x30 est la valeur ascii du caractère '0' } indFacePosition--; // indice n'est pas de 1 à nbFaces mais de 0 à nbFaces-1 NEXT_INDICE; // on se positionne à la valeur suivante indFaceTexcoord = 0; for(; (buf[i] >= '0') && (buf[i] <= '9') ;i++) { // on la récupère indFaceTexcoord *= 10; // première coordonnée de texture indFaceTexcoord += buf[i]-0x30; } indFaceTexcoord--; // indice n'est pas de 1 à nbFaces mais de 0 à nbFaces-1 NEXT_INDICE; // ect ... il y a 9 indices à récupérer indFaceNormal = 0; for(; (buf[i] >= '0') && (buf[i] <= '9') ;i++) { indFaceNormal *= 10; // première normale indFaceNormal += buf[i]-0x30; } indFaceNormal--; // indice n'est pas de 1 à nbFaces mais de 0 à nbFaces-1 if(v < 2) NEXT_INDICE; int idx = 0; switch(max) { case 0: {idx = indFacePosition; break;} case 1: {idx = indFaceNormal; break;} case 2: {idx = indFaceTexcoord; break;} } m_vPosition[idx] = tTempPosition[indFacePosition]; m_vNormal[idx] = tTempNormal[indFaceNormal]; m_vTexcoord[idx] = tTempTexcoord[indFaceTexcoord]; face.ind[v] = idx; /* m_tPosition.push_back( tTempPosition[ indFacePosition ] ); m_tNormal.push_back( tTempNormal[ indFaceNormal ] ); m_tTexcoord.push_back( tTempTexcoord[ indFaceTexcoord ] ); face.ind[v] = m_tPosition.size()-1; */ } m_tGroup[g].tFace.push_back(face); // on enregistre la face récupérée } } // delete[] buf; } fp.close(); /* cout << "m_tGroup.size() = " << m_tGroup.size() << endl; cout << "m_tPosition.size() = " << m_tPosition.size() << endl; cout << "m_tNormal.size() = " << m_tNormal.size() << endl; cout << "m_tTexcoord.size() = " << m_tTexcoord.size() << endl; cout << "tTempPosition.size() = " << tTempPosition.size() << endl; cout << "tTempNormal.size() = " << tTempNormal.size() << endl; cout << "tTempTexcoord.size() = " << tTempTexcoord.size() << endl; */ tTempPosition.clear(); tTempNormal.clear(); tTempTexcoord.clear(); GLuint nbFaces = 0; for(std::vector<sGroup>::iterator it=m_tGroup.begin(); it!=m_tGroup.end(); it++) nbFaces += (GLuint)(*it).tFace.size(); /* cout << "nbFaces = " << nbFaces << endl; */ return true; } void ObjMesh::ComputeBoundingBox() { } void ObjMesh::ComputeTangents() { m_vTangent.resize( m_vNormal.size() ); for(std::vector<sGroup>::iterator itG=m_tGroup.begin(); itG!=m_tGroup.end(); itG++) { for(std::vector<sFace>::iterator itF=(*itG).tFace.begin(); itF!=(*itG).tFace.end(); itF++) { GLuint* ind = ((GLuint*)(*itF).ind); osg::Vec3 vTangent; osg::Vec3 v0 = m_vPosition[ind[0]]; osg::Vec3 v1 = m_vPosition[ind[1]]; osg::Vec3 v2 = m_vPosition[ind[2]]; osg::Vec3 vect10 = v0-v1; osg::Vec3 vect12 = v2-v1; float deltaT10 = m_vTexcoord[ind[0]].y() - m_vTexcoord[ind[1]].y(); float deltaT12 = m_vTexcoord[ind[2]].y() - m_vTexcoord[ind[1]].y(); vTangent = (vect10 * deltaT12 ) - (vect12 * deltaT10 ); vTangent.normalize(); // std::cout << "vNormal = " << m_tNormal[ind[0]].x << ", " << m_tNormal[ind[0]].y << ", " << m_tNormal[ind[0]].z << std::endl; // std::cout << "vTangent = " << vTangent.x << ", " << vTangent.y << ", " << vTangent.z << std::endl; m_vTangent[ind[0]] = m_vTangent[ind[1]] = m_vTangent[ind[2]] = vTangent; } } /* m_tTangent.resize( m_tNormal.size() ); vec3 *tan1 = new vec3[m_tPosition.size() * 2]; vec3 *tan2 = tan1 + m_tPosition.size(); memset(tan1, 0, m_tPosition.size() * sizeof(vec3) * 2); for(std::vector<sGroup>::iterator itG=m_tGroup.begin(); itG!=m_tGroup.end(); itG++) { for(std::vector<sFace>::iterator itF=(*itG).tFace.begin(); itF!=(*itG).tFace.end(); itF++) { GLuint* ind = ((GLuint*)(*itF).ind); long i1 = ind[0]; long i2 = ind[1]; long i3 = ind[2]; const vec3& v1 = m_tPosition[i1]; const vec3& v2 = m_tPosition[i2]; const vec3& v3 = m_tPosition[i3]; const vec2& w1 = m_tTexcoord[i1]; const vec2& w2 = m_tTexcoord[i2]; const vec2& w3 = m_tTexcoord[i3]; float x1 = v2.x - v1.x; float x2 = v3.x - v1.x; float y1 = v2.y - v1.y; float y2 = v3.y - v1.y; float z1 = v2.z - v1.z; float z2 = v3.z - v1.z; float s1 = w2.x - w1.x; float s2 = w3.x - w1.x; float t1 = w2.y - w1.y; float t2 = w3.y - w1.y; float r = 1.0f / (s1 * t2 - s2 * t1); vec3 sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); vec3 tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; } } int a=0; for(std::vector<vec3>::iterator itV=m_tPosition.begin(); itV!=m_tPosition.end(); itV++) { const vec3& n = m_tNormal[a]; const vec3& t = tan1[a]; // Gram-Schmidt orthogonalize m_tTangent[a] = (t - n * Dot(n, t)); m_tTangent[a].normalize(); // Calculate handedness // m_tTangent[a].w = (Dot(Cross(n, t), tan2[a]) < 0.0F) ? -1.0F : 1.0F; a++; } delete[] tan1; */ } void ObjMesh::Draw() { bind(); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, 0, 0); if(!m_vNormal.empty()) { glNormalPointer( GL_FLOAT, 0, BUFFER_OFFSET(m_iSizeVertex)); } if (!m_vTexcoord.empty()) { glClientActiveTexture(GL_TEXTURE0); glTexCoordPointer( 2,GL_FLOAT, 0, BUFFER_OFFSET(m_iSizeVertex+m_iSizeNormal)); } //Tangent if (!m_vTangent.empty()) { glClientActiveTexture(GL_TEXTURE1); glTexCoordPointer( 3,GL_FLOAT, 0, BUFFER_OFFSET(m_iSizeVertex+m_iSizeNormal+m_iSizeTexture)); } for(std::vector<sGroup>::iterator it=m_tGroup.begin(); it!=m_tGroup.end(); it++) glDrawElements(GL_TRIANGLES, (GLsizei)(*it).tFace.size()*3, GL_UNSIGNED_INT, &((*it).tFace[0].ind[0])); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); unbind(); } void ObjMesh::Draw(GLuint group) { assert(group < (GLuint)m_tGroup.size()); bind(); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, 0, 0); if(!m_vNormal.empty()) { glNormalPointer( GL_FLOAT, 0, BUFFER_OFFSET(m_iSizeVertex)); } if (!m_vTexcoord.empty()) { glClientActiveTexture(GL_TEXTURE0); glTexCoordPointer( 2,GL_FLOAT, 0, BUFFER_OFFSET(m_iSizeVertex+m_iSizeNormal)); } //Tangent if (!m_vTangent.empty()) { glClientActiveTexture(GL_TEXTURE1); glTexCoordPointer( 3,GL_FLOAT, 0, BUFFER_OFFSET(m_iSizeVertex+m_iSizeNormal+m_iSizeTexture)); } glDrawElements(GL_TRIANGLES, (GLsizei)m_tGroup[group].tFace.size()*3, GL_UNSIGNED_INT, &(m_tGroup[group].tFace[0].ind[0])); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); unbind(); }
[ [ [ 1, 490 ] ] ]
d73f87d8a69d5169dce53a082fd0939bd6a40be4
847cccd728e768dc801d541a2d1169ef562311cd
/src/InputSystem/OISListener.cpp
5c85a6c7185012931c1298dc763f1c30c329755e
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,572
cpp
#include "Common.h" #include "InputMgr.h" #include "OISListener.h" #include "GfxSystem/GfxWindow.h" #include "Core/Application.h" #include "StringConverter.h" #include "IInputListener.h" #include <OISInputManager.h> #include <OISException.h> #ifdef __UNIX__ #include <X11/Xlib.h> #endif using namespace InputSystem; #define OIS_EXCEPTION_BEGIN try { #define OIS_EXCEPTION_END } catch (const OIS::Exception& e) { \ ocError << "OIS Exception: " << e.eText; \ CRITICAL_FAILURE("Last error was critical"); \ } InputSystem::OISListener::OISListener(): mOIS(0), mMouse(0), mKeyboard(0) { OIS_EXCEPTION_BEGIN ocInfo << "Initing OIS"; mMgr = InputMgr::GetSingletonPtr(); OIS::ParamList pl; // let the OIS know what window we have so that it can capture its events GfxSystem::WindowHandle hWnd = GfxSystem::GfxWindow::GetSingleton()._GetWindowHandle(); pl.insert(OIS::ParamList::value_type("WINDOW", StringConverter::ToString(hWnd))); // let the standard mouse cursor be pl.insert(OIS::ParamList::value_type("w32_mouse", "DISCL_BACKGROUND")); pl.insert(OIS::ParamList::value_type("w32_mouse", "DISCL_NONEXCLUSIVE")); pl.insert(OIS::ParamList::value_type("x11_mouse_grab", "false")); pl.insert(OIS::ParamList::value_type("x11_mouse_hide", "true")); pl.insert(OIS::ParamList::value_type("x11_keyboard_grab", "false")); pl.insert(OIS::ParamList::value_type("XAutoRepeatOn", "true")); mOIS = OIS::InputManager::createInputSystem(pl); ocInfo << "OIS created"; RecreateDevices(); OIS_EXCEPTION_END } InputSystem::OISListener::~OISListener() { OC_ASSERT(mOIS); OIS::InputManager::destroyInputSystem(mOIS); } bool InputSystem::OISListener::mouseMoved( const OIS::MouseEvent &evt ) { if (evt.state.Z.rel != 0) { // the wheel has moved; check if the mouse is still above the window; if not, ignore the event if (!gApp.HasFocus() || evt.state.X.abs < 0 || evt.state.X.abs >= evt.state.width || evt.state.Y.abs < 0 || evt.state.Y.abs >= evt.state.height) { return true; } } MouseInfo mi; mi.x = evt.state.X.abs; mi.dx = evt.state.X.rel; mi.y = evt.state.Y.abs; mi.dy = evt.state.Y.rel; mi.wheel = evt.state.Z.abs; mi.wheelDelta = evt.state.Z.rel; for (InputMgr::ListenersList::const_iterator i=mMgr->mListeners.begin(); i!=mMgr->mListeners.end(); ++i) { if ((*i)->MouseMoved(mi)) break; } return true; } bool InputSystem::OISListener::mousePressed( const OIS::MouseEvent &evt, OIS::MouseButtonID id ) { MouseInfo mi; mi.dx = 0; mi.dy = 0; mi.wheelDelta = 0; mi.x = evt.state.X.abs; mi.y = evt.state.Y.abs; mi.wheel = evt.state.Z.abs; eMouseButton btn = OisToMbtn(id); for (InputMgr::ListenersList::const_iterator i=mMgr->mListeners.begin(); i!=mMgr->mListeners.end(); ++i) { if ((*i)->MouseButtonPressed(mi, btn)) break; } return true; } bool InputSystem::OISListener::mouseReleased( const OIS::MouseEvent &evt, OIS::MouseButtonID id ) { MouseInfo mi; mi.dx = 0; mi.dy = 0; mi.wheelDelta = 0; mi.x = evt.state.X.abs; mi.y = evt.state.Y.abs; mi.wheel = evt.state.Z.abs; eMouseButton btn = OisToMbtn(id); for (InputMgr::ListenersList::const_iterator i=mMgr->mListeners.begin(); i!=mMgr->mListeners.end(); ++i) { //if ((*i)->MouseButtonReleased(mi, btn)) break; // mouse released must be propagated to all listeners ((*i)->MouseButtonReleased(mi, btn)); } return true; } bool InputSystem::OISListener::keyPressed( const OIS::KeyEvent &evt ) { KeyInfo ki; ki.keyCode = static_cast<eKeyCode>(evt.key); ki.charCode = evt.text; FixKeyInfo(ki); for (InputMgr::ListenersList::const_iterator i=mMgr->mListeners.begin(); i!=mMgr->mListeners.end(); ++i) { if ((*i)->KeyPressed(ki)) break; } return true; } bool InputSystem::OISListener::keyReleased( const OIS::KeyEvent &evt ) { KeyInfo ki; ki.keyCode = static_cast<eKeyCode>(evt.key); ki.charCode = evt.text; FixKeyInfo(ki); for (InputMgr::ListenersList::const_iterator i=mMgr->mListeners.begin(); i!=mMgr->mListeners.end(); ++i) { if ((*i)->KeyReleased(ki)) break; } return true; } void InputSystem::OISListener::CaptureInput() { if (mKeyboard) { mKeyboard->capture(); } if (mMouse) { mMouse->capture(); } } void InputSystem::OISListener::SetResolution( uint32 width, uint32 height ) { if (mMouse) { const OIS::MouseState &ms = mMouse->getMouseState(); ms.width = width; ms.height = height; } } InputSystem::eMouseButton InputSystem::OISListener::OisToMbtn( OIS::MouseButtonID id ) { switch (id) { case OIS::MB_Left: return MBTN_LEFT; case OIS::MB_Right: return MBTN_RIGHT; case OIS::MB_Middle: return MBTN_MIDDLE; default: break; } return MBTN_UNKNOWN; } bool InputSystem::OISListener::IsKeyDown( const eKeyCode k ) const { if (mKeyboard) { return mKeyboard->isKeyDown(static_cast<OIS::KeyCode>(k)); } return false; } void InputSystem::OISListener::GetMouseState( InputSystem::MouseState& state ) const { if (!mMouse) return; const OIS::MouseState& oisstate = mMouse->getMouseState(); state.x = oisstate.X.abs; state.y = oisstate.Y.abs; state.wheel = oisstate.Z.abs; state.buttons = MBTN_UNKNOWN; if (oisstate.buttonDown(OIS::MB_Left)) state.buttons |= MBTN_LEFT; if (oisstate.buttonDown(OIS::MB_Right)) state.buttons |= MBTN_RIGHT; if (oisstate.buttonDown(OIS::MB_Middle)) state.buttons |= MBTN_MIDDLE; } void InputSystem::OISListener::ReleaseAll( void ) { RecreateDevices(); } void InputSystem::OISListener::RecreateDevices() { OC_ASSERT(mOIS); int mouseWidth = 0; int mouseHeight = 0; #ifdef __WIN__ if (mKeyboard) mOIS->destroyInputObject(mKeyboard); if (mMouse) { const OIS::MouseState &ms = mMouse->getMouseState(); mouseWidth = ms.width; mouseHeight = ms.height; mOIS->destroyInputObject(mMouse); } mKeyboard = 0; mMouse = 0; #endif if (!mKeyboard) { OIS_EXCEPTION_BEGIN mKeyboard = static_cast<OIS::Keyboard*>(mOIS->createInputObject(OIS::OISKeyboard, true)); mKeyboard->setEventCallback(this); OIS_EXCEPTION_END } if (!mMouse) { OIS_EXCEPTION_BEGIN mMouse = static_cast<OIS::Mouse*>( #ifdef __WIN__ // We use modified OIS on Windows. mOIS->createInputObject(OIS::OISMouse, true, "", gGfxWindow.IsFullscreen()) #else mOIS->createInputObject(OIS::OISMouse, true, "") #endif ); mMouse->setEventCallback(this); OIS_EXCEPTION_END } if (mouseWidth != 0 && mouseHeight != 0) { const OIS::MouseState &ms = mMouse->getMouseState(); ms.width = mouseWidth; ms.height = mouseHeight; } ocInfo << "OIS keyboard & mouse recreated"; } void InputSystem::OISListener::FixKeyInfo( KeyInfo& keyInfo ) { switch (keyInfo.keyCode) { case KC_NUMPAD0: keyInfo.charCode = '0'; break; case KC_NUMPAD1: keyInfo.charCode = '1'; break; case KC_NUMPAD2: keyInfo.charCode = '2'; break; case KC_NUMPAD3: keyInfo.charCode = '3'; break; case KC_NUMPAD4: keyInfo.charCode = '4'; break; case KC_NUMPAD5: keyInfo.charCode = '5'; break; case KC_NUMPAD6: keyInfo.charCode = '6'; break; case KC_NUMPAD7: keyInfo.charCode = '7'; break; case KC_NUMPAD8: keyInfo.charCode = '8'; break; case KC_NUMPAD9: keyInfo.charCode = '9'; break; case KC_DECIMAL: keyInfo.charCode = '.'; break; case KC_DIVIDE: keyInfo.charCode = '/'; break; default: break; } }
[ [ [ 1, 8 ], [ 10, 10 ], [ 15, 16 ], [ 25, 25 ], [ 27, 27 ], [ 29, 34 ], [ 38, 39 ], [ 47, 50 ], [ 52, 178 ], [ 181, 208 ], [ 210, 218 ], [ 220, 222 ], [ 224, 231 ], [ 243, 243 ], [ 257, 264 ], [ 266, 307 ], [ 310, 310 ] ], [ [ 9, 9 ], [ 11, 14 ], [ 17, 24 ], [ 26, 26 ], [ 28, 28 ], [ 35, 37 ], [ 40, 46 ], [ 51, 51 ], [ 179, 180 ], [ 209, 209 ], [ 219, 219 ], [ 223, 223 ], [ 232, 242 ], [ 244, 247 ], [ 250, 256 ], [ 308, 309 ], [ 311, 311 ] ], [ [ 248, 249 ] ], [ [ 265, 265 ] ] ]
28af31c37d4de16c88f1b63dc352052d4319adce
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Tools/UIEditor/ScriptFrame.cpp
efcbfd5130d512f3f7952b09ba05788b57479001
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
2,168
cpp
// ScriptFrame.cpp : implementation of the CScriptFrame class // #include "stdafx.h" #include "UIEditor.h" #include "ScriptFrame.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CScriptFrame IMPLEMENT_DYNCREATE(CScriptFrame, CMDIChildWnd) BEGIN_MESSAGE_MAP(CScriptFrame, CMDIChildWnd) ON_COMMAND(ID_FILE_CLOSE, OnFileClose) ON_WM_SETFOCUS() ON_WM_CREATE() END_MESSAGE_MAP() // CScriptFrame construction/destruction CScriptFrame::CScriptFrame() { // TODO: add member initialization code here } CScriptFrame::~CScriptFrame() { } BOOL CScriptFrame::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying the CREATESTRUCT cs if( !CMDIChildWnd::PreCreateWindow(cs) ) return FALSE; cs.dwExStyle &= ~WS_EX_CLIENTEDGE; cs.lpszClass = AfxRegisterWndClass(0); return TRUE; } // CScriptFrame diagnostics #ifdef _DEBUG void CScriptFrame::AssertValid() const { CMDIChildWnd::AssertValid(); } void CScriptFrame::Dump(CDumpContext& dc) const { CMDIChildWnd::Dump(dc); } #endif //_DEBUG // CScriptFrame message handlers void CScriptFrame::OnFileClose() { // To close the frame, just send a WM_CLOSE, which is the equivalent // choosing close from the system menu. SendMessage(WM_CLOSE); } int CScriptFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIChildWnd::OnCreate(lpCreateStruct) == -1) return -1; // create a view to occupy the client area of the frame if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL)) { TRACE0("Failed to create view window\n"); return -1; } return 0; } void CScriptFrame::OnSetFocus(CWnd* pOldWnd) { CMDIChildWnd::OnSetFocus(pOldWnd); m_wndView.SetFocus(); } BOOL CScriptFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { // let the view have first crack at the command if (m_wndView.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo)) return TRUE; // otherwise, do default handling return CMDIChildWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); }
[ "acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 103 ] ] ]
349f77d777f63595ce07a6b46eb73442ad036416
e947bc69d8ee60ab0f1ccf28c9943027fa43f397
/YJReBar.h
c62c3d661c339229a2c295364d3c577085e278e8
[]
no_license
losywee/yjui
fc33d8034d707a6663afef6cb8b55b1483992fc5
caeea083b91597f7f3c46cb9e69dcb009258649a
refs/heads/master
2021-01-10T07:35:15.909900
2010-04-01T09:14:23
2010-04-01T09:14:23
45,093,947
0
0
null
null
null
null
UTF-8
C++
false
false
333
h
#pragma once #define WM_REBAR_CONTEXTMENU (WM_USER+1) class AFX_EXT_CLASS CYJReBar : public CReBar { DECLARE_DYNAMIC(CYJReBar) public: CYJReBar(); virtual ~CYJReBar(); void Lock( bool bLock =true ); protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnContextMenu(CWnd* /*pWnd*/, CPoint point); };
[ "Caiyj.84@3d1e88fc-ca97-11de-9d4f-f947ee5921c8" ]
[ [ [ 1, 20 ] ] ]
53c01ae97a41d9605b98fe0bb2de6dc5a62d06b1
1e5a2230acf1c2edfe8b9d226100438f9374e98a
/src/gecko-sdk/include/nsGenericFactory.h
c9bcb949ed61ded798a60d0c25a0e71e1e78ebba
[]
no_license
lifanxi/tabimswitch
258860fea291c935d3630abeb61436e20f5dcd09
f351fc4b04983e59d1ad2b91b85e396e1f4920ed
refs/heads/master
2020-05-20T10:53:41.990172
2008-10-15T11:15:41
2008-10-15T11:15:41
32,111,854
0
0
null
null
null
null
UTF-8
C++
false
false
4,224
h
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef nsGenericFactory_h___ #define nsGenericFactory_h___ #include "nsCOMPtr.h" #include "nsIGenericFactory.h" #include "nsIClassInfo.h" /** * Most factories follow this simple pattern, so why not just use a function * pointer for most creation operations? */ class nsGenericFactory : public nsIGenericFactory, public nsIClassInfo { public: NS_DEFINE_STATIC_CID_ACCESSOR(NS_GENERICFACTORY_CID); nsGenericFactory(const nsModuleComponentInfo *info = NULL); NS_DECL_ISUPPORTS NS_DECL_NSICLASSINFO /* nsIGenericFactory methods */ NS_IMETHOD SetComponentInfo(const nsModuleComponentInfo *info); NS_IMETHOD GetComponentInfo(const nsModuleComponentInfo **infop); NS_IMETHOD CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult); NS_IMETHOD LockFactory(PRBool aLock); static NS_METHOD Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr); private: ~nsGenericFactory(); const nsModuleComponentInfo *mInfo; }; //////////////////////////////////////////////////////////////////////////////// #include "nsIModule.h" #include "plhash.h" class nsGenericModule : public nsIModule { public: nsGenericModule(const char* moduleName, PRUint32 componentCount, const nsModuleComponentInfo* components, nsModuleConstructorProc ctor, nsModuleDestructorProc dtor); private: ~nsGenericModule(); public: NS_DECL_ISUPPORTS NS_DECL_NSIMODULE struct FactoryNode { FactoryNode(nsIGenericFactory* fact, FactoryNode* next) { mFactory = fact; mNext = next; } ~FactoryNode(){} nsCOMPtr<nsIGenericFactory> mFactory; FactoryNode* mNext; }; protected: nsresult Initialize(nsIComponentManager* compMgr); void Shutdown(); nsresult AddFactoryNode(nsIGenericFactory* fact); PRBool mInitialized; const char* mModuleName; PRUint32 mComponentCount; const nsModuleComponentInfo* mComponents; FactoryNode* mFactoriesNotToBeRegistered; nsModuleConstructorProc mCtor; nsModuleDestructorProc mDtor; }; #endif /* nsGenericFactory_h___ */
[ "ftofficer.zhangc@237747d1-5336-0410-8d3f-2982d197fc3e" ]
[ [ [ 1, 127 ] ] ]
0702d9e5567d8b0d4d7d73dcf0ec1b6b6725f40b
621cce176ba0cce5df41d4120c1d0bfdbeda48cd
/prog/ex4/ex4a.cc
22bdb12898fe9c97a809ed2a3cf40195c9ef607c
[]
no_license
AndreyShamis/perviygodmodul
9d65675217abad7fee2e3f833b89e299578550f4
09f0f425a536fab1bca2241dc9b8b071942f5aa6
refs/heads/master
2021-01-10T19:30:29.670776
2010-01-04T19:47:15
2010-01-04T19:47:15
32,789,934
0
0
null
null
null
null
UTF-8
C++
false
false
2,041
cc
/* * EX4A :: Income classification * ============================================================= * Writen by: Andrey Shamis, id: 321470882, login:andreysh * * Plan that defines an array of integers twenty cells. * The plan calls for the user natural number n less than * or equal to twenty, which indicates how many numbers the * user wants to enter the array. Then the program reads n numbers. * * Input: getting lentgh of array(between 1 20) * Output: sorted array */ //--------------- including section ------------- #include <iostream> //--------------- using section ------------- using std::cout; using std::cin; using std::endl; //--------------- main ------------- int main() { const int MAX_ARRAY_LENTGH=20; // Max lentgh of array int array_lentgh, // length of the array round[MAX_ARRAY_LENTGH],// Array count1,count2, // Counters for FORS save; // temp variable cin >> array_lentgh; // getting array lentgh (max=MAX_ARRAY_LENTGH) for(count1=0; count1<array_lentgh; count1++) // Getting value to arr cin >> round[count1]; // putting value into array for(count1=0; count1<array_lentgh; count1++) // Scaning what to change for(count2=count1; count2 >0; count2--) // Scaning to back if(round[count2] < round[count2-1]) { // if smaller index array have value biger then next array // change valus between array blocks save = round[count2] ; // save value into save round[count2] = round[count2-1];// change value between round[count2-1] = save; // putting from save new value } for(count1=0; count1<array_lentgh; count1++) // printing array cout << round[count1] << " "; // couting array cout << endl; return(0); // exiting from programm }
[ "lolnik@465b2a2a-c3d4-11de-a006-439b9ae3df91" ]
[ [ [ 1, 54 ] ] ]
fccca13a7183c9bcd5cc3f7037e7ff64499903ae
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/PropType.h
2ebc3d19ec8226f06cabf254812c09dcfb0b9308
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,567
h
// ----------------------------------------------------------------------- // // // MODULE : PropType.h // // PURPOSE : Model PropType - Definition // // CREATED : 4/26/2000 // // (c) 2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __PROP_TYPE_H__ #define __PROP_TYPE_H__ #include "Prop.h" #include "PropTypeMgr.h" LINKTO_MODULE( PropType ); class PropType : public Prop { public : const char* GetPropTypeName( ) { return m_sPropType.c_str(); } protected : uint32 EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData); bool SetPropType( char const* pszPropType ); bool Setup( ); protected: std::string m_sPropType; private : bool ReadProp(ObjectCreateStruct *pData); void Save(ILTMessage_Write *pMsg, uint32 dwSaveFlags); void Load(ILTMessage_Read *pMsg, uint32 dwLoadFlags); }; #ifndef __PSX2 class CPropTypePlugin : public CPropPlugin { public: virtual LTRESULT PreHook_EditStringList( const char* szRezPath, const char* szPropName, char** aszStrings, uint32* pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLength); virtual LTRESULT PreHook_Dims( const char* szRezPath, const char* szPropValue, char* szModelFilenameBuf, int nModelFilenameBufLen, LTVector & vDims); protected : CPropTypeMgrPlugin m_PropTypeMgrPlugin; }; #endif #endif // __PROP_H__
[ [ [ 1, 76 ] ] ]
d2c86f0c03326c5b88f7e2fe12ec5f75bd78bb83
842997c28ef03f8deb3422d0bb123c707732a252
/3rdparty/box2d-2.1.2/Contributions/Utilities/ConvexDecomposition/b2Polygon.h
fe534b508f63192d95fbbcced0725f868607d5cb
[]
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
3,751
h
/* * Copyright (c) 2007 Eric Jordan * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_POLYGON_H #define B2_POLYGON_H #include "Box2D.h" #include "b2Triangle.h" class b2Polygon; int32 remainder(int32 x, int32 modulus); int32 TriangulatePolygon(float32* xv, float32* yv, int32 vNum, b2Triangle* results); bool IsEar(int32 i, float32* xv, float32* yv, int32 xvLength); //Not for external use int32 PolygonizeTriangles(b2Triangle* triangulated, int32 triangulatedLength, b2Polygon* polys, int32 polysLength); int32 DecomposeConvex(b2Polygon* p, b2Polygon* results, int32 maxPolys); void DecomposeConvexAndAddTo(b2Polygon* p, b2Body* bd, b2FixtureDef* prototype); b2Polygon ConvexHull(b2Vec2* v, int nVert); b2Polygon ConvexHull(float32* cloudX, float32* cloudY, int32 nVert); void ReversePolygon(float32* x, float32* y, int n); b2Polygon TraceEdge(b2Polygon* p); //For use with self-intersecting polygons, finds outline class b2Polygon { public: const static int32 maxVerticesPerPolygon = b2_maxPolygonVertices; float32* x; //vertex arrays float32* y; int32 nVertices; float32 area; bool areaIsSet; b2Polygon(float32* _x, float32* _y, int32 nVert); b2Polygon(b2Vec2* v, int32 nVert); b2Polygon(); ~b2Polygon(); float32 GetArea(); void MergeParallelEdges(float32 tolerance); b2Vec2* GetVertexVecs(); b2Polygon(b2Triangle& t); void Set(const b2Polygon& p); bool IsConvex(); bool IsCCW(); bool IsUsable(bool printError); bool IsUsable(); bool IsSimple(); void AddTo(b2FixtureDef& pd); b2Polygon* Add(b2Triangle& t); void print(){ printFormatted(); // for (int32 i=0; i<nVertices; ++i){ // printf("i: %d, x:%f, y:%f\n",i,x[i],y[i]); // } } void printFormatted(){ printf("float xv[] = {"); for (int32 i=0; i<nVertices; ++i){ printf("%ff,",x[i]); } printf("};\nfloat yv[] = {"); for (int32 i=0; i<nVertices; ++i){ printf("%ff,",y[i]); } printf("};\n"); } b2Polygon(const b2Polygon& p){ nVertices = p.nVertices; area = p.area; areaIsSet = p.areaIsSet; x = new float32[nVertices]; y = new float32[nVertices]; memcpy(x, p.x, nVertices * sizeof(float32)); memcpy(y, p.y, nVertices * sizeof(float32)); } }; const int32 MAX_CONNECTED = 32; const float32 COLLAPSE_DIST_SQR = FLT_EPSILON*FLT_EPSILON;//0.1f;//1000*FLT_EPSILON*1000*FLT_EPSILON; class b2PolyNode{ public: b2Vec2 position; b2PolyNode* connected[MAX_CONNECTED]; int32 nConnected; bool visited; b2PolyNode(b2Vec2& pos); b2PolyNode(); void AddConnection(b2PolyNode& toMe); void RemoveConnection(b2PolyNode& fromMe); void RemoveConnectionByIndex(int32 index); bool IsConnectedTo(b2PolyNode& me); b2PolyNode* GetRightestConnection(b2PolyNode* incoming); b2PolyNode* GetRightestConnection(b2Vec2& incomingDir); }; #endif
[ [ [ 1, 122 ] ], [ [ 123, 123 ] ] ]
b9965cd063e147ad505e7cce20623b481c121391
1102f77e8dbf563a024cec0b885c0d9f9da2ef39
/view/loginview.cc
5329c38d3aa66dcd50024ebea51302e9f2a25bd4
[]
no_license
pgoodman/uwo-cooper
7c38c1bc0b3fc04cabb128cd5a3c984c67efc2f3
ea881e9794cb2c0ae64c0d73117facfd92c3f96b
refs/heads/master
2016-09-11T03:29:39.537161
2010-04-05T21:28:26
2010-04-05T21:28:26
32,091,588
0
0
null
null
null
null
UTF-8
C++
false
false
1,908
cc
#include "view/loginview.h" LoginView::LoginView() : QDialog(0) { setModal(true); this->setFixedSize(300,150); QPalette palette; QPixmap bgimage = QPixmap(QString("images/flowershort.jpg")); bgimage.scaledToWidth(300); bgimage.scaledToHeight(150); palette.setBrush(QPalette::Window,bgimage); this->setPalette(palette); this->setAutoFillBackground(true); FormLayoutPtr layout(this); titleLabel = layout [2] <<= "Please enter login name and password."; QFont font; font.setPointSize(8); font.setBold(true); titleLabel->setFixedSize(225,25); titleLabel->setFont(font); titleLabel->setAutoFillBackground(true); //logo = new QLabel(); //logo->setPixmap(QPixmap("images/flowershort.jpg")); //layout |= logo; nameLineEdit = layout << "Login Name: " |= new QLineEdit; pwdLineEdit = layout << "Password: " |= new QLineEdit; QPushButton *okPushButton(layout <<= new QPushButton("Login")); QPushButton *cancelPushButton(layout |= new QPushButton("Cancel")); nameLineEdit->setFocus(); okPushButton->setDefault(true); connect( okPushButton, SIGNAL(clicked()), this, SLOT(tryLogin()) ); connect( cancelPushButton, SIGNAL(clicked()), this, SLOT(reject()) ); setWindowTitle("Log In to Cooper"); pwdLineEdit->setEchoMode(QLineEdit::Password); } /** * Handle clicking the login button. */ void LoginView::tryLogin() { QString uname(nameLineEdit->text()); QString pass(pwdLineEdit->text()); if(!UserController::authorize(uname, pass)) { cout << "Failed to log in. " << endl; titleLabel->setText( "Login name and password don't match anyone in the system. " "Please try again." ); } else { done(QDialog::Accepted); } }
[ "peter.goodman@c307de66-1bdf-11df-a447-cf726199f266", "jlu.newera@c307de66-1bdf-11df-a447-cf726199f266" ]
[ [ [ 1, 5 ], [ 8, 8 ], [ 14, 15 ], [ 17, 17 ], [ 26, 26 ], [ 28, 31 ], [ 34, 63 ] ], [ [ 6, 7 ], [ 9, 13 ], [ 16, 16 ], [ 18, 25 ], [ 27, 27 ], [ 32, 33 ] ] ]