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
5f62ad8c3beac50ea7dcb832b6bb15d9e8365145
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/elements/vis_auto_elements.h
4b33c51472393fe3556769eda458ba535e591ce7
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,674
h
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) ** ** and SWARMS (www.swarms.de) ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the GNU General Public License, version 2. ** ************************************************************************/ #ifndef __SHAWN_TUBSAPPS_VIS_AUTO_ELEMENTS_H #define __SHAWN_TUBSAPPS_VIS_AUTO_ELEMENTS_H #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #include "apps/vis/base/visualization.h" #ifdef HAVE_BOOST_REGEX #include <boost/regex.hpp> #endif namespace shawn { class SimulationController; } namespace vis { /** \brief Visual element iterator. * * The AutoElements class allows to search in and iterate through visual * elements by name, regular expression on names and regular expressions * on a node's tag value. */ class AutoElements { public: ///@name Constructor/Destructor ///@{ AutoElements( shawn::SimulationController&, Visualization& ) throw( std::runtime_error ); virtual ~AutoElements(); ///@} ///@name Iteration ///@{ /** * Returns the current element. */ ElementHandle top( void ) const throw(); /** * Advances to the next element, if there is one. */ void pop( void ) throw(); ///@} protected: /** * Advances to the next element which fullfills the search constraint. Used * by pop method. */ void advance_infeasible( void ) throw(); private: /// List of available modes. Single searches just by name, Regex uses a /// regular expression and TagRegex a regular expression on a given tag. enum Mode { Single, Regex, TagRegex }; /// The current mode (see Mode enum). Mode mode_; /// The current element that is returned by top method. ElementHandle current_; /// The tag name, that is to be used in TagRegex mode. std::string tag_; #ifdef HAVE_BOOST_REGEX /// Boost-Regex object used for regular expression searches. boost::regex* regex_; /// Element iterator (current element). Visualization::ElementMap::iterator vis_cur_; /// Element iterator (last element). Visualization::ElementMap::iterator vis_end_; #endif }; } #endif #endif
[ [ [ 1, 86 ] ] ]
202974c81fba8bd5f536a5483f53e72b62c944dd
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/Shotgun.h
6812126d815d2bb6868af332d9e38ff5db8e477a
[]
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
UTF-8
C++
false
false
1,642
h
#include "Single.h" #pragma once class CShotgun : public CSingle { struct BeginReloadLoop; struct SliderBack; class ReloadOneShellAction; class ReloadEndAction; class ScheduleReload; protected: typedef struct SShotgunParams { SShotgunParams() { Reset(); }; void Reset(const IItemParamsNode *params=0, bool defaultInit=true) { CItemParamReader reader(params); ResetValue(pellets, 10); ResetValue(pelletdamage, 20); ResetValue(spread, .1f); } short pellets; short pelletdamage; float spread; } SShotgunParams; public: CShotgun(void); ~CShotgun(void); virtual void GetMemoryStatistics(ICrySizer * s) { s->Add(*this); CSingle::GetMemoryStatistics(s); } virtual void Activate(bool activate); virtual void Reload(int zoomed); virtual void StartReload(int zoomed); virtual void ReloadShell(int zoomed); virtual void EndReload(int zoomed); using CSingle::EndReload; virtual void CancelReload(); virtual bool CanCancelReload() { return false; }; virtual bool CanFire(bool considerAmmo) const; virtual bool Shoot(bool resetAnimation, bool autoreload = true , bool noSound = false ); virtual void NetShootEx(const Vec3 &pos, const Vec3 &dir, const Vec3 &vel, const Vec3 &hit, float extra, int ph); virtual void ResetParams(const struct IItemParamsNode *params); virtual void PatchParams(const struct IItemParamsNode *patch); virtual const char* GetType() const; protected: SShotgunParams m_shotgunparams; bool m_reload_pump; bool m_break_reload; bool m_reload_was_broken; int m_max_shells; };
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 45 ], [ 47, 57 ], [ 60, 60 ] ], [ [ 46, 46 ], [ 58, 59 ] ] ]
12da2a6e98dc49327c50d4c2f8514b63278c85de
8fd82049c092a6b80f63f402aca243096eb7b3c8
/MFCMailServer/MFCMailServer/MFCMailServerDlg.cpp
38269ec65cb0e79e0b073246d70d64de9a60716f
[]
no_license
phucnh/laptrinhmang-k52
47965acb82750b600b543cc5c43d00f59ce5bc54
b27a8a02f9ec8bf953b617402dce37293413bb0f
refs/heads/master
2021-01-18T22:22:24.692192
2010-12-09T02:00:10
2010-12-09T02:00:10
32,262,504
0
0
null
null
null
null
UTF-8
C++
false
false
12,474
cpp
// MFCMailServerDlg.cpp : implementation file // #include "stdafx.h" #include <stdarg.h> #include "MFCMailServer.h" #include "MFCMailServerDlg.h" #include "Pop3.h" #include "Smtp.h" #include "UserDlg.h" #include "NewUserDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CStringList AccountList; CString sMailStoreDirectory; // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CString GetAccountInfo(CString sUsername, int iIndex) { CString sReturn = ""; for (POSITION pos = AccountList.GetHeadPosition(); pos != NULL;) { CString sTemp = AccountList.GetNext(pos); int i = sTemp.Find(";"); int j = sTemp.Find(";", i+1); if ((i>0) && (j>0)) { CString s1 = sTemp.Left(i); CString s2 = sTemp.Mid(i+1, j-i-1); CString s3 = sTemp.Mid(j+1, sTemp.GetLength()-j-2); if (s2.CompareNoCase(sUsername) == 0) { switch (iIndex) { case 1 : return s1; case 2 : return s2; case 3 : return s3; } } } } return sReturn; } CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CMFCMailServerDlg dialog CMFCMailServerDlg::CMFCMailServerDlg(CWnd* pParent /*=NULL*/) : CDialog(CMFCMailServerDlg::IDD, pParent) , m_log(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); //AfxSocketInit(); //StartMailServer(); } void CMFCMailServerDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_LBString(pDX, IDC_LIST1, m_log); DDX_Control(pDX, IDC_LIST1, m_listBoxCtrl); //StartMailServer(); DDX_Control(pDX, IDC_BUTTON1, m_btnStartServer); DDX_Control(pDX, IDC_BUTTON2, m_btnStopServer); DDX_Control(pDX, IDC_BUTTON3, m_btnSettings); DDX_Control(pDX, IDC_BUTTON4, m_btnUsers); DDX_Control(pDX, IDC_BUTTON6, m_btnExit); } BEGIN_MESSAGE_MAP(CMFCMailServerDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDOK, &CMFCMailServerDlg::OnBnClickedOk) ON_COMMAND(ID_ACCOUNTS_MANAGEACCOUNTS, &CMFCMailServerDlg::OnAccountsManageaccounts) ON_COMMAND(ID_ACCOUNTS_NEWACCOUNT, &CMFCMailServerDlg::OnAccountsNewaccount) ON_BN_CLICKED(IDC_BUTTON1, &CMFCMailServerDlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_BUTTON2, &CMFCMailServerDlg::OnBnClickedButton2) ON_BN_CLICKED(IDC_BUTTON4, &CMFCMailServerDlg::OnBnClickedButton4) ON_BN_CLICKED(IDC_BUTTON3, &CMFCMailServerDlg::OnBnClickedButton3) ON_BN_CLICKED(IDC_BUTTON6, &CMFCMailServerDlg::OnBnClickedButton6) END_MESSAGE_MAP() // CMFCMailServerDlg message handlers BOOL CMFCMailServerDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon ShowWindow(SW_MAXIMIZE); // TODO: Add extra initialization here m_isIconShow = FALSE; InitStatusbar(); SetIconToButton(); StartMailServer(); return TRUE; // return TRUE unless you set the focus to a control } void CMFCMailServerDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMFCMailServerDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFCMailServerDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFCMailServerDlg::OnBnClickedOk() { //OnOK(); } BOOL CMFCMailServerDlg::StartMailServer() { serverPop3Socket = new CPop3(this); if (!serverPop3Socket->Create(settingPop3Port)) { AfxMessageBox(_T("Can not create POP3 server socket.")); return FALSE; } else { if (!serverPop3Socket->Listen(100)) { AfxMessageBox(_T("Can not listen from POP3 server.")); return FALSE; } } serverSmtpSocket = new CSmtp(this); if (!serverSmtpSocket->Create(settingSmtpPort)) { AfxMessageBox(_T("Can not create SMTP server socket.")); return FALSE; } else { if(!serverSmtpSocket->Listen(100)) { AfxMessageBox(_T("Can not listen from SMTP server")); return FALSE; } } pop3RequestId = 0; nPop3ConnectionsCount = 0; UpdateStatusbar(); CString message; message.Format(_T("%s - SMTP Server started. Listening on port 25"),GetCurrentTimeStr()); WriteLog(message); message.Format(_T("%s - POP3 Server started. Listening on port 110"),GetCurrentTimeStr()); WriteLog(message); return TRUE; } void CMFCMailServerDlg::WriteLog( CString message ) { UpdateData(TRUE); m_listBoxCtrl.AddString(message); UpdateData(FALSE); } void CMFCMailServerDlg::UpdateStatusbar() { CString strSMTPConnections; CString strPOP3Connections; strSMTPConnections.Format("SMTP Connections : %i ", nSmtpConnectionsCount); strPOP3Connections.Format("POP3 Connections : %i ", nPop3ConnectionsCount); m_wndStatusBar.SetText(strSMTPConnections, SBP_SMTPCONNECTION, 0); m_wndStatusBar.SetText(strPOP3Connections, SBP_POP3CONNECTION, 0); m_wndStatusBar.SetText("Mail Server", SBP_STATUS, SBT_NOBORDERS); } void CMFCMailServerDlg::InitStatusbar() { CRect rcDialog; GetWindowRect(&rcDialog); rcDialog.top = rcDialog.bottom - SB_HEIGHT; m_wndStatusBar.Create(WS_CHILD | WS_BORDER | WS_VISIBLE, rcDialog, this, AFX_IDW_STATUS_BAR); SBPartsSetting(rcDialog.Width(), rcDialog.Height()); UpdateStatusbar(); } void CMFCMailServerDlg::SBPartsSetting(int cxParent, int cyParent) { int nWidths[SBP_NUMPARTS]; CString strSMTPConnections; CString strPOP3Connections; strSMTPConnections.Format("SMTP Connections : %i ", 0x00); strPOP3Connections.Format("POP3 Connections : %i ", 0x00); int nSMTPConnectionWidth = m_wndStatusBar.GetDC()->GetTextExtent(strSMTPConnections).cx; int nPOP3ConnectionWidth = m_wndStatusBar.GetDC()->GetTextExtent(strPOP3Connections).cx; //int nTimerWidth = m_wndStatusBar.GetDC()->GetTextExtent(CString("88:88 PM ")).cx; nWidths[SBP_STATUS] = cxParent - 50 - nSMTPConnectionWidth- nPOP3ConnectionWidth; nWidths[SBP_SMTPCONNECTION] = nSMTPConnectionWidth + nWidths[SBP_STATUS]; nWidths[SBP_POP3CONNECTION] = nPOP3ConnectionWidth + nWidths[SBP_SMTPCONNECTION]; m_wndStatusBar.SetMinHeight(SB_HEIGHT); m_wndStatusBar.SetParts(SBP_NUMPARTS, nWidths); } void CMFCMailServerDlg::StopMailServer() { if (serverSmtpSocket) { serverSmtpSocket->Close(); delete serverSmtpSocket; serverSmtpSocket = NULL; CString message; message.Format(_T("%s - SMTP Server stopped."),GetCurrentTimeStr()); WriteLog("%s - SMTP Server stopped."); } if (serverPop3Socket) { serverPop3Socket->Close(); delete serverPop3Socket; serverPop3Socket = NULL; CString message; message.Format(_T("%s - POP3 Server stopped."),GetCurrentTimeStr()); WriteLog("%s - SMTP Server stopped."); } UpdateStatusbar(); } void CMFCMailServerDlg::OnDestroy() { CDialog::OnDestroy(); StopMailServer(); } void CMFCMailServerDlg::OnAccountsManageaccounts() { CUserDlg userDlg; userDlg.DoModal(); } void CMFCMailServerDlg::OnAccountsNewaccount() { CNewUserDlg newUserDlg; newUserDlg.DoModal(); } void CMFCMailServerDlg::SetIconToButton() { HICON hIcn= (HICON)LoadImage( AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_ICON_STARTSERVER), IMAGE_ICON, 32,32, // use actual size LR_DEFAULTCOLOR ); m_btnStartServer.SetIcon(hIcn); hIcn= (HICON)LoadImage( AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_ICON_STOPSERVER), IMAGE_ICON, 32,32, // use actual size LR_DEFAULTCOLOR ); m_btnStopServer.SetIcon(hIcn); hIcn= (HICON)LoadImage( AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_ICON_SETTINGS), IMAGE_ICON, 32,32, // use actual size LR_DEFAULTCOLOR ); m_btnSettings.SetIcon(hIcn); hIcn= (HICON)LoadImage( AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_ICON_USERS), IMAGE_ICON, 32,32, // use actual size LR_DEFAULTCOLOR ); m_btnUsers.SetIcon(hIcn); hIcn= (HICON)LoadImage( AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_ICON_EXIT), IMAGE_ICON, 32,32, // use actual size LR_DEFAULTCOLOR ); m_btnExit.SetIcon(hIcn); } void CMFCMailServerDlg::OnBnClickedButton1() { StartMailServer(); /*CWnd* pWnd = GetDlgItem(IDC_BUTTON2); pWnd->EnableWindow(TRUE); this->EnableWindow(FALSE);*/ } void CMFCMailServerDlg::testInsertNewMail() { MailUser* mail=new MailUser(); mail->_username="dangbka"; mail->_password="123456"; try { mail->InsertNewUser(mail); } catch (CException* e) { throw; } } void CMFCMailServerDlg::OnBnClickedButton2() { StopMailServer(); /*CWnd* pWnd = GetDlgItem(IDC_BUTTON1); pWnd->EnableWindow(TRUE); this->EnableWindow(FALSE);*/ } void CMFCMailServerDlg::OnBnClickedButton4() { OnAccountsNewaccount(); } void CMFCMailServerDlg::OnBnClickedButton3() { OnAccountsManageaccounts(); } void CMFCMailServerDlg::OnBnClickedButton6() { //this->OnDestroy(); CString username = "abc"; MailHeader* test = new MailHeader(); //test GETALLMAIL() CArray<MailHeader,MailHeader&>* listMailHeader=new CArray<MailHeader,MailHeader&>(); listMailHeader = test->getAllInboxMailByUser(username); INT resultTest = listMailHeader->GetCount(); CString result,temp; result.Format("Cac CC cua tat ca mail la :"); for(int i=0;i<listMailHeader->GetSize();i++) { temp.Format("%s",listMailHeader->GetAt(i).Cc); result+=temp; } m_listBoxCtrl.AddString(result); //test GetMailSentByUSername CString result2,temp2; result2.Format("Cac CC cua tat ca mail cua user dang la :"); m_listBoxCtrl.AddString(result2); CArray<MailHeader,MailHeader&>* listMailHeader2=new CArray<MailHeader,MailHeader&>(); listMailHeader2=test->getAllSentMailByUser("dang"); for(int i=0;i<listMailHeader2->GetSize();i++) { m_listBoxCtrl.AddString(listMailHeader2->GetAt(i).Cc); } CString result3,temp3; result2.Format("Cac CC cua mailinbox cua user [email protected] la :"); m_listBoxCtrl.AddString(result2); CArray<MailHeader,MailHeader&>* listMailHeader3=new CArray<MailHeader,MailHeader&>(); listMailHeader3=test->getAllInboxMailByUser("[email protected]"); for(int i=0;i<listMailHeader3->GetSize();i++) { m_listBoxCtrl.AddString(listMailHeader3->GetAt(i).Cc); } //int resul2 = listMailHeader->GetCount(); //bool isDeleted = test->deleteMail(3); //test delete Mail //MailHeader* mailH =new MailHeader(); //if(mailH->deleteMail(2)) // AfxMessageBox("OK"); //else // AfxMessageBox("False"); }
[ "nguyenhongphuc.hut@e1f3f65c-33eb-5b6a-8ef2-7789ca584060", "trungvt89.it@e1f3f65c-33eb-5b6a-8ef2-7789ca584060", "danglv.hut@e1f3f65c-33eb-5b6a-8ef2-7789ca584060" ]
[ [ [ 1, 18 ], [ 21, 39 ], [ 67, 101 ], [ 107, 116 ], [ 122, 353 ], [ 355, 366 ], [ 435, 435 ] ], [ [ 19, 20 ], [ 40, 66 ], [ 102, 106 ], [ 118, 121 ], [ 354, 354 ], [ 368, 415 ], [ 418, 421 ], [ 423, 423 ], [ 438, 459 ], [ 461, 461 ], [ 464, 467 ], [ 512, 512 ] ], [ [ 117, 117 ], [ 367, 367 ], [ 416, 417 ], [ 422, 422 ], [ 424, 434 ], [ 436, 437 ], [ 460, 460 ], [ 462, 463 ], [ 468, 511 ] ] ]
302f7efaab6db60a1575e89dc5b42c5835e17304
0045750d824d633aba04e1d92987e91fb87e0ee7
/graphics.h
187715f37008a58db457ebfb34b342301cd52670
[]
no_license
mirelon/vlaciky
eaab3cbae7d7438c4fcb87d2b5582b0492676efc
30f5155479a3f3556199aa2d845fcac0c9a2d225
refs/heads/master
2020-05-23T15:05:26.370548
2010-06-16T18:55:52
2010-06-16T18:55:52
33,381,959
0
0
null
null
null
null
UTF-8
C++
false
false
630
h
#ifndef GRAPHICS_H #define GRAPHICS_H #include<QThread> #include<QGraphicsView> #include<QGraphicsItem> #include<QGraphicsEllipseItem> #include<QPoint> #include<QColor> #include "settings.h" class Graphics : public QObject { Q_OBJECT public: Graphics(); void init(); void loadMap(); QBrush getBrush(int opacity); public slots: void setOpacity(int i,int opacity); void updateStatus(QString stat); public: QGraphicsView* graphicsView; QMap<int,QGraphicsEllipseItem*> item; QGraphicsTextItem* status; Settings* s; int r,n; qreal alpha,step; QString track; }; #endif // GRAPHICS_H
[ "mirelon@a6d88fff-da04-0f23-7c93-28760c376c6a" ]
[ [ [ 1, 33 ] ] ]
fed5c663a62cd81623bb8c205d0820042cbb0a41
4891542ea31c89c0ab2377428e92cc72bd1d078f
/Arcanoid/Arcanoid/Game.h
114b3cc98c8601dba8b36bafe367bc7103905af7
[]
no_license
koutsop/arcanoid
aa32c46c407955a06c6d4efe34748e50c472eea8
5bfef14317e35751fa386d841f0f5fa2b8757fb4
refs/heads/master
2021-01-18T14:11:00.321215
2008-07-17T21:50:36
2008-07-17T21:50:36
33,115,792
0
0
null
null
null
null
UTF-8
C++
false
false
2,339
h
/* * author: koutsop */ #ifndef GAME_H #define GAME_H #include <string> #include <allegro.h> #include <algorithm> #include "AI.h" #include "Ball.h" #include "Point.h" #include "Board.h" #include "MyTime.h" #include "PowerUp.h" #include "Terrain.h" #include "Animator.h" #include "NainSpin.h" #include "GameStats.h" #include "Animation.h" #include "KeyLogger.h" #include "StateHolder.h" #include "SpriteHolder.h" #include "BitmapLoader.h" #include "InputManager.h" #include "LoadFilmsInfo.h" #include "LoadFilmsInfo.h" #include "AnimatorHolder.h" #include "MovingAnimator.h" #include "MovingAnimation.h" #include "AnimationHolder.h" #include "CollisionChecker.h" #include "FrameRangeAnimator.h" #include "FrameRangeAnimation.h" #include "AnimationFilmHolder.h" #define SCORE_MAX_DIGIT 6 class Game { private: AI* ai; NainSpin * nain; BITMAP * buffer; BITMAP * baground; BITMAP * game_over; Ball * theBall; Board * theBoard; int currLevel; animid_t countAnimationID; Terrain * terrain; BitmapLoader * bitmaps; SpriteHolder * spriteH; LoadFilmsInfo * filmsInfo; MovingAnimator * board; MovingAnimator * ball; MovingAnimation * movBall; MovingAnimation * movBoard; AnimationHolder * animationH; CollisionChecker * collisionC; AnimationFilmHolder*animationFH; string nainID; FrameRangeAnimator* nainAr; FrameRangeAnimation*nainAn; //PowerUp * powerup; MIDI *theme, *ping, *pong; //SAMPLE *theme; int scoreDigit[SCORE_MAX_DIGIT]; int scoreDigitPos[2]; int lifeDigitPos[2]; int levelDigitPos[2]; char *digit_string; void InitiallizingFilmsInfo(void); void InitiallizingBitmapLoader(void); NainSpin * CreateNain(void); Board * CreatingBoard(int playerNo); Ball * CreatingBall(void); void CreateAll(void); void DeleteAll(void); void SystemLoopDispatching(void); void CheckF1(void); void CheckBoardInput(void); void GameLoop(void); void DisplayALL(void); void DisplayScore(BITMAP *buffy); void DisplayLife(BITMAP *buffy); void DisplayLevel(BITMAP *buffy); void SetUpStats(void); void NextLevel(void); void ResetBall(void); void ResetBoard(void); //void ExecuteBonus(); public: void PlayGame(void); Game(); ~Game(); }; #endif
[ "koutsop@5c4dd20e-9542-0410-abe3-ad2d610f3ba4", "apixkernel@5c4dd20e-9542-0410-abe3-ad2d610f3ba4" ]
[ [ [ 1, 4 ], [ 6, 24 ], [ 28, 29 ], [ 32, 38 ], [ 40, 40 ], [ 45, 48 ], [ 50, 69 ], [ 71, 71 ], [ 80, 93 ], [ 102, 103 ], [ 105, 107 ], [ 109, 113 ] ], [ [ 5, 5 ], [ 25, 27 ], [ 30, 31 ], [ 39, 39 ], [ 41, 44 ], [ 49, 49 ], [ 70, 70 ], [ 72, 79 ], [ 94, 101 ], [ 104, 104 ], [ 108, 108 ] ] ]
c8fbfe958fb5f35f7e7dbcbc93b7b72220688cd2
61e4e71a9ad4ac3fdce3c1595c627b9c79a68c29
/src/ISearchFilter.cpp
1aae64c9508b25a66a05dc868e1e74c889a4e231
[]
no_license
oot/signpost
c2ff81bdb3ab75a5511eedd18798d637cd080526
8a8e5c6c693217daf56398e6bb59f89563f9689b
refs/heads/master
2016-09-05T19:52:41.876837
2010-11-19T08:07:48
2010-11-19T08:07:48
32,301,199
0
0
null
null
null
null
UTF-8
C++
false
false
135
cpp
#include "oot.h" #include "ISearchFilter.h" ISearchFilter::ISearchFilter(void) { } ISearchFilter::~ISearchFilter(void) { }
[ "[email protected]@067241ac-f43e-11dd-9d1a-b59b2e1864b6" ]
[ [ [ 1, 10 ] ] ]
03f4f97d4a896f1fa25ca54ea2e4f95d8eeda7ff
e3a67b819e6c8072ea587f070214c2c075b2dee3
/IntegratedImpedanceSensingSystem/Measurement.h
f8b545d755555c529e5267568893f0ae82a25a0e
[]
no_license
pmanandhar1452/ImpedanceSensingSystem
46f32a57d3c19ebc011c539746fab5facf5e0c71
0c4a0472c75f280857d549630fabb881c452e791
refs/heads/master
2021-01-17T16:43:17.019071
2011-11-15T01:40:45
2011-11-15T01:40:45
62,420,080
0
0
null
null
null
null
UTF-8
C++
false
false
616
h
#ifndef MEASUREMENT_H_ #define MEASUREMENT_H_ #include <complex> #include <QVector> class PositionMeasurement { public: long t; //time in ms int pos; //position }; class ImpedanceMeasurement { public: ImpedanceMeasurement(); ImpedanceMeasurement(double fc, double fs, long t, int Nc); long t; // time in ms double fc; // frequency in Hz double fs; // sampling frequency in Hz QVector< std::complex<double> > X;// carrier voltage, impedance, temperature (in C) or humidity (RH%) QVector<double> r; // residual error after measurement long N; // number of samples }; #endif
[ "jaa_saaymi@d83832b1-3638-4858-8a38-9f153b6b3474" ]
[ [ [ 1, 25 ] ] ]
520b2cec491d1d5fd7e94daed35002ba9d064a93
54dfb0046228832dcdec6dc5a18c5c23ada6f9ee
/MainProgram/PhataBlob.h
3edcb296ca91de1b0f22521b0c891b942b32cda0
[]
no_license
github188/piglets-monitoring
3f6ec92e576d334762cc805727d358d9799ca053
620b6304384534eb71113c26a054c36ce3800ed8
refs/heads/master
2021-01-22T12:45:45.159790
2011-11-08T15:37:18
2011-11-08T15:37:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
178
h
#pragma once #include "../GoogleCode_video-tracker/opencv_cvBlobsLibV8.3/Blob.h" class PhataBlob:public CBlob { public: PhataBlob(void); virtual ~PhataBlob(void); };
[ [ [ 1, 9 ] ] ]
1b1a4f0acf6e8d3fbbf12310cf3f2c0c9729a5fb
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_video_capture/include/CamCaptureLinux.h
d0d6797d43194753cb9c31e47dd4696c3b3c8452
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
11,672
h
// CONTROL IDENTIFIERS #pragma once #ifndef DEVCAM_H #define DEVCAM_H /////////////////////////////////////////////////////////////////////////////// #include <linux/videodev.h> #include <linux/videodev2.h> #include <dirent.h> #include <stdlib.h> #include <string.h> #include <stdio.h> // for snprintf() #include <string> #include <deque> #include "iptv_shared/shared/ithread.h" #include "iptv_shared/shared/semaphore.h" #include "iptv_media_util/pixel_formats.h" #include "iptv_media_util/global_error.h" #include "iptv_media_util/media_utilities.h" #include "VideoCapture.h" #include "CamCapture.h" /////////////////////////////////////////////////////////////////////////////// namespace tv { namespace ip { /////////////////////////////////////////////////////////////////////////////// // Control id #define CONTRAST 0 #define HUE 1 #define SATURATION 2 #define BRIGHTNESS 3 // Constants #define MAX_FRAME_SIZE 1024*1024*2 #define INFINITE_TIME 1000000 #define BUFFERS_TO_MAP 4 #define V4L_PIXFMT_COUNT 8 #define COMMON_FRAME_DIMENSIONS_COUNT 9 // Device Access #define MAX_PATH_LENGTH 256 #define DEVICE_PATH "/dev" #define DEVICE_NAME_PREFIX "video" #define DEVICE_NAME_STR "/dev/video%d" #define DEVICE_NAME_PREFIX_LENGTH 5 /////////////////////////////////////////////////////////////////////////////// enum DeviceType{V4L_DEVICE_CAPTURE, V4L2_DEVICE_CAPTURE}; /////////////////////////////////////////////////////////////////////////////// struct VideoBufferInfo { unsigned char * pStartAddress; }; /////////////////////////////////////////////////////////////////////////////// struct V4L_VideoBufferInfo : VideoBufferInfo { unsigned frameSize, index, pixFmt; video_mbuf mbuf; FrameDimension dimension; }; /////////////////////////////////////////////////////////////////////////////// struct V4L2_VideoBufferInfo : VideoBufferInfo { unsigned index, bufLength; }; /////////////////////////////////////////////////////////////////////////////// class CDevice { private: int m_Fd; bool m_DevOpened; std::string m_DevId; _SEMAPHORE m_Semaph; virtual unsigned InitMMap() = 0; virtual unsigned FinishMMap() = 0; virtual unsigned SetFramePtr(unsigned & _index) = 0; virtual unsigned ReleaseFramePtr(unsigned _index) = 0; virtual unsigned TranslateFromPixFmt(PixFmt _srcPixFmt, unsigned & _dstPixFmt) = 0; virtual unsigned TranslateToPixFmt(unsigned _srcPixFmt, PixFmt & _dstPixFmt) = 0; virtual unsigned TranslateToAnagStd(v4l2_std_id std_id, AnagVideoStd & _videoStd) =0; virtual unsigned TranslateFromAnagStd(AnagVideoStd _videoStd, v4l2_std_id & std_id)=0; protected: IThread * m_pGrabFrames; DeviceType m_DevType; bool m_ReadyToCapture, m_ThreadRunning, m_bNewFrame; unsigned char *m_pCurFrame; unsigned m_CurFrameLen, m_CurFrameTimestamp; static int GrabFrames(IThread *_pThread, void *_pParam); public: CDevice(std::string & _devId); virtual ~CDevice(); virtual unsigned GetInputList(DEVICEINPUT_LIST& _inputList) = 0; virtual unsigned SelectInput(unsigned _inputIndex) = 0; virtual unsigned EnumAnagStd(unsigned _index, ANALOGVIDEO_LIST & _videoStdList) = 0; virtual unsigned GetAnagStdCount(unsigned & standardsCount) = 0; virtual unsigned SelectAnagStd(AnagVideoStd _videoStd) = 0; virtual unsigned StartCapture() = 0; virtual unsigned StopCapture() = 0; virtual unsigned GetControlValue(int _controlId, int & _value) = 0; virtual unsigned SetControlValue(int _controlId, int _value) = 0; virtual unsigned GetSupportedPixelFmt(std::deque<PixFmt> & _pixFmtList) = 0; virtual unsigned GetSupportedDimensions(PixFmt _pixFmt, std::deque<FrameDimension> & _dimensionsList) = 0; virtual unsigned SetFormat(unsigned _width, unsigned _height, PixFmt _pixFmt) = 0; virtual unsigned GetFormat(unsigned & _width, unsigned & _height, PixFmt & _pixFmt) = 0; bool NewFrame() {return m_bNewFrame; } unsigned Open(); unsigned Close(); unsigned GetFd(int & _fd); unsigned GetLastFrame(CVideoFrame & videoFrame, unsigned _dstWidth, unsigned _dstHeight, PixFmt _dstPixFmt); std::string & GetDevId() { return m_DevId; } DeviceType GetDeviceType() { return m_DevType; } bool DeviceOpened() { return m_DevOpened; } bool V4L2Device() { return ( m_DevType == V4L2_DEVICE_CAPTURE); } bool V4LDevice() { return ( m_DevType == V4L_DEVICE_CAPTURE); } }; /////////////////////////////////////////////////////////////////////////////// class CDeviceV4L2 : public CDevice { private: std::deque<V4L2_VideoBufferInfo> m_BufferList; CDeviceV4L2(std::string & _devId); virtual unsigned InitMMap(); virtual unsigned FinishMMap(); virtual unsigned SetFramePtr(unsigned & _index); virtual unsigned ReleaseFramePtr(unsigned _index); virtual unsigned TranslateFromPixFmt(PixFmt _srcPixFmt, unsigned & _v4l2DstPixFmt); virtual unsigned TranslateToPixFmt(unsigned _v4l2SrcPixFmt, PixFmt & _dstPixFmt); virtual unsigned TranslateToAnagStd(v4l2_std_id std_id, AnagVideoStd & _videoStd); virtual unsigned TranslateFromAnagStd(AnagVideoStd _videoStd, v4l2_std_id & std_id); unsigned TranslateCtrlId(int _controlId, int & _v4l2ControlId); unsigned StartStreaming(); unsigned FinishStreaming(); unsigned GetV4L2Fmt(v4l2_format & fmt); unsigned SetV4L2Fmt(v4l2_format & fmt); public: ~CDeviceV4L2(); friend class CDeviceGrabber; virtual unsigned GetInputList(DEVICEINPUT_LIST& _inputList); virtual unsigned SelectInput(unsigned _inputIndex); virtual unsigned EnumAnagStd(unsigned _index, ANALOGVIDEO_LIST & _videoStdList); virtual unsigned GetAnagStdCount(unsigned & standardsCount); virtual unsigned SelectAnagStd(AnagVideoStd _videoStd); virtual unsigned StartCapture(); virtual unsigned StopCapture(); virtual unsigned GetControlValue(int _controlId, int & _value); virtual unsigned SetControlValue(int _controlId, int _value); virtual unsigned GetSupportedPixelFmt(std::deque<PixFmt> & _pixFmtList); virtual unsigned GetSupportedDimensions(PixFmt _pixFmt, std::deque<FrameDimension> & _dimensionsList); virtual unsigned SetFormat(unsigned _width, unsigned _height, PixFmt _pixFmt); virtual unsigned GetFormat(unsigned & _width, unsigned & _height, PixFmt & _pixFmt); }; /////////////////////////////////////////////////////////////////////////////// class CDeviceV4L : public CDevice { private: static struct V4LPixFmt { unsigned v4lPixFmt; std::string pixFmtDesc; } v4lPixFmtList[V4L_PIXFMT_COUNT]; static FrameDimension CommonFrameDimensions[COMMON_FRAME_DIMENSIONS_COUNT]; V4L_VideoBufferInfo m_VideoInfo; CDeviceV4L(std::string & _devId); virtual unsigned InitMMap(); virtual unsigned FinishMMap(); virtual unsigned SetFramePtr(unsigned & _index); virtual unsigned ReleaseFramePtr(unsigned _index); virtual unsigned TranslateFromPixFmt(PixFmt _srcPixFmt, unsigned & _v4lDstPixFmt); virtual unsigned TranslateToPixFmt(unsigned v4lSrcPixFmt, PixFmt & _dstPixFmt); virtual unsigned TranslateToAnagStd(v4l2_std_id std_id, AnagVideoStd & _videoStd) {return 0;} virtual unsigned TranslateFromAnagStd(AnagVideoStd _videoStd, v4l2_std_id & std_id){return 0;} unsigned GetV4LPixFmtDepth(unsigned _pixFmt, unsigned & _depth); unsigned GetV4LPixFmt(video_picture & _picture); unsigned SetV4LPixFmt(video_picture & _picture); unsigned GetV4LDimensions(video_window & _clipArea); unsigned SetV4LDimensions(video_window & _clipArea); public: ~CDeviceV4L(); friend class CDeviceGrabber; virtual unsigned GetInputList(DEVICEINPUT_LIST& _inputList) { return RET_OK; } virtual unsigned SelectInput(unsigned _inputIndex) { return RET_OK; } virtual unsigned EnumAnagStd(unsigned _index, ANALOGVIDEO_LIST & _videoStdList) { return RET_OK; } virtual unsigned GetAnagStdCount(unsigned & standardsCount) { standardsCount = 0; return RET_OK; } virtual unsigned SelectAnagStd(AnagVideoStd _videoStd) { return 0;} virtual unsigned StartCapture(); virtual unsigned StopCapture(); virtual unsigned GetControlValue(int _controlId, int & _value); virtual unsigned SetControlValue(int _controlId, int _value); virtual unsigned GetSupportedPixelFmt(std::deque<PixFmt> & _pixFmtList); virtual unsigned GetSupportedDimensions(PixFmt _pixFmt, std::deque<FrameDimension> & _dimensionsList); virtual unsigned SetFormat(unsigned _width, unsigned _height, PixFmt _pixFmt); virtual unsigned GetFormat(unsigned & _width, unsigned & _height, PixFmt & _pixFmt); }; /////////////////////////////////////////////////////////////////////////////// class CDeviceGrabber { private: CDevice * m_pDevice; public: CDeviceGrabber(); CDeviceGrabber(std::string & _devId); ~CDeviceGrabber(); unsigned Init(std::string & _devId); bool deviceGrabbed() { bool ret; m_pDevice ? ret = true : ret = false; return ret; } CDevice *GetDevicePtr() {return m_pDevice; } }; /////////////////////////////////////////////////////////////////////////////// class CameraCaptureDeviceLinux : public CameraDevice { private: CDeviceGrabber m_devGrabber; unsigned SelectBestFmt(unsigned & _uSelectedWidth, unsigned & _uSelectedHeight, PixFmt & _uSelectedPixFmt); public: CameraCaptureDeviceLinux(); ~CameraCaptureDeviceLinux(); virtual unsigned SetControlValue(int _controlId, int _value); virtual unsigned GetControlValue(int _controlId, int & _value); CDevice * GetDevice(); virtual unsigned SelectInput(unsigned _inputIndex); virtual unsigned GetInputList(DEVICEINPUT_LIST& _inputList); virtual unsigned EnumAnagStd(unsigned _index, ANALOGVIDEO_LIST & _videoStdList); virtual unsigned GetAnagStdCount(unsigned & standardsCount); virtual unsigned SelectAnagStd(AnagVideoStd _videoStd); virtual unsigned Init(unsigned _index); virtual unsigned SelectFormat(unsigned _width, unsigned _height, PixFmt _pixFmt); virtual unsigned StartCapture(); virtual unsigned GrabFrame(CVideoFrame & _videoFrame); virtual unsigned StopCapture(); virtual unsigned Close(); virtual bool NewFrame(); }; /////////////////////////////////////////////////////////////////////////////// class LinuxCamDeviceCtrl : public DeviceEnumerator { public: LinuxCamDeviceCtrl() {} ~LinuxCamDeviceCtrl() {} std::string GetDeviceName(unsigned index); virtual unsigned GetVideoDeviceList(VIDEODEVICEINFO_LIST & _videoDevList); virtual unsigned ReleaseCamera(VideoDevice*_pCamDevice); virtual VideoDevice* GetDevice(unsigned _index); }; /////////////////////////////////////////////////////////////////////////////// }} // namespace tv::ip #endif // DEVCAM_H
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 322 ] ] ]
d3a31fa02b47e07af0204ab5e0690f266182797f
afd610f0d62541d28f8d3b0a04bbb1ab3379b375
/trunk/QueueDelete/src/QueueDeleteDlg.h
3e3666aa8c6c2ec55742c548a24c92958e4fd372
[]
no_license
yoiang/Google-Code-Dump
d252f978eb787a2f1ce5bb64a453438671545326
e505b1ef9fe4f822abc44afd16d818f0e387fc2d
refs/heads/master
2021-01-18T20:20:23.263456
2008-07-23T21:17:25
2008-07-23T21:17:25
23,433,560
1
0
null
null
null
null
UTF-8
C++
false
false
2,529
h
// QueueDeleteDlg.h : header file // #if !defined(AFX_QUEUEDELETEDLG_H__498AF0BF_00EB_4FDC_91EB_086BB4F23545__INCLUDED_) #define AFX_QUEUEDELETEDLG_H__498AF0BF_00EB_4FDC_91EB_086BB4F23545__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 ///////////////////////////////////////////////////////////////////////////// // CQueueDeleteDlg dialog #include <vector> #include <string> class CQueueDeleteDlg : public CDialog { // Construction public: CQueueDeleteDlg(char *szAppPath, bool bAutoDelete = true, bool bAutoShutdown = false, CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CQueueDeleteDlg) enum { IDD = IDD_QUEUEDELETE_DIALOG }; CListCtrl m_cFileList; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CQueueDeleteDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL void ShowWindow( int nCmdShow ); // Implementation protected: HICON m_hIcon; NOTIFYICONDATA m_niData; CMenu m_MainMenu; bool m_bAutoDelete, m_bAutoShutdown, m_bAlwaysRun; char m_szAppPath[MAX_PATH+1]; void SplitPath(char *szPath, std::string &strLocation, std::string &strFileName); void AddFileToList(char *szPath, bool bPrompt = true, bool bRecurseSubfolders = false); void RemoveFileFromList(int iSelection, int iCount); void ReadQueueFile(); void WriteQueueFile(); bool Duplicate(char *szPath); void DeleteFiles(); bool DeleteFileRegardless(char *szPath); // Generated message map functions //{{AFX_MSG(CQueueDeleteDlg) afx_msg void OnOK(); virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnClickFilelist(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDblclkFilelist(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnDropFiles(HDROP hDropped); afx_msg void OnDestroy(); afx_msg void OnKeyDownFilelist(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnOptionsDeleteFilesNow(); afx_msg void OnOptionsToggleAutoStart(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnSystemTrayMessage(WPARAM wParam, LPARAM lParam); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_QUEUEDELETEDLG_H__498AF0BF_00EB_4FDC_91EB_086BB4F23545__INCLUDED_)
[ "yo.ian.g@d559ecde-2541-0410-ba37-b79e5d9e5dcd" ]
[ [ [ 1, 82 ] ] ]
636291ff24d837a9ee41c644d70b5a8208810a7f
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Applications/Graphics/MorphingFace/MorphingFace.h
1c68f9e746a234341576575901fca5ea96bb53a4
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
1,031
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef MORPHINGFACE_H #define MORPHINGFACE_H #include "WmlApplication.h" using namespace Wml; class MorphingFace : public Application { public: MorphingFace (); virtual bool OnInitialize (); virtual void OnTerminate (); virtual void OnIdle (); virtual void OnKeyDown (unsigned char ucKey, int iX, int iY); protected: void DrawStatistics (int iX, int iY, const ColorRGB& rkColor); // morph scene graph NodePtr m_spkScene; WireframeStatePtr m_spkWireframeState; // animation time float m_fBaseTime; float m_fCurrTime; bool m_bInitialized; }; #endif
[ [ [ 1, 41 ] ] ]
958af1a5a67a8bbc048329a93815ee00accc2dcd
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/Engine/dll/Assimp/include/aiMatrix4x4.inl
d1dfce9c2bbf4591604fe5695e35458ec9b49534
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
ISO-8859-1
C++
false
false
14,091
inl
/** @file Inline implementation of the 4x4 matrix operators */ #ifndef AI_MATRIX4x4_INL_INC #define AI_MATRIX4x4_INL_INC #include "aiMatrix4x4.h" #ifdef __cplusplus #include "aiMatrix3x3.h" #include <algorithm> #include <limits> #include <math.h> #include "aiAssert.h" #include "aiQuaternion.h" // --------------------------------------------------------------------------- inline aiMatrix4x4::aiMatrix4x4( const aiMatrix3x3& m) { a1 = m.a1; a2 = m.a2; a3 = m.a3; a4 = 0.0f; b1 = m.b1; b2 = m.b2; b3 = m.b3; b4 = 0.0f; c1 = m.c1; c2 = m.c2; c3 = m.c3; c4 = 0.0f; d1 = 0.0f; d2 = 0.0f; d3 = 0.0f; d4 = 1.0f; } // --------------------------------------------------------------------------- inline aiMatrix4x4& aiMatrix4x4::operator *= (const aiMatrix4x4& m) { *this = aiMatrix4x4( m.a1 * a1 + m.b1 * a2 + m.c1 * a3 + m.d1 * a4, m.a2 * a1 + m.b2 * a2 + m.c2 * a3 + m.d2 * a4, m.a3 * a1 + m.b3 * a2 + m.c3 * a3 + m.d3 * a4, m.a4 * a1 + m.b4 * a2 + m.c4 * a3 + m.d4 * a4, m.a1 * b1 + m.b1 * b2 + m.c1 * b3 + m.d1 * b4, m.a2 * b1 + m.b2 * b2 + m.c2 * b3 + m.d2 * b4, m.a3 * b1 + m.b3 * b2 + m.c3 * b3 + m.d3 * b4, m.a4 * b1 + m.b4 * b2 + m.c4 * b3 + m.d4 * b4, m.a1 * c1 + m.b1 * c2 + m.c1 * c3 + m.d1 * c4, m.a2 * c1 + m.b2 * c2 + m.c2 * c3 + m.d2 * c4, m.a3 * c1 + m.b3 * c2 + m.c3 * c3 + m.d3 * c4, m.a4 * c1 + m.b4 * c2 + m.c4 * c3 + m.d4 * c4, m.a1 * d1 + m.b1 * d2 + m.c1 * d3 + m.d1 * d4, m.a2 * d1 + m.b2 * d2 + m.c2 * d3 + m.d2 * d4, m.a3 * d1 + m.b3 * d2 + m.c3 * d3 + m.d3 * d4, m.a4 * d1 + m.b4 * d2 + m.c4 * d3 + m.d4 * d4); return *this; } // --------------------------------------------------------------------------- inline aiMatrix4x4 aiMatrix4x4::operator* (const aiMatrix4x4& m) const { aiMatrix4x4 temp( *this); temp *= m; return temp; } // --------------------------------------------------------------------------- inline aiMatrix4x4& aiMatrix4x4::Transpose() { // (float&) don't remove, GCC complains cause of packed fields std::swap( (float&)b1, (float&)a2); std::swap( (float&)c1, (float&)a3); std::swap( (float&)c2, (float&)b3); std::swap( (float&)d1, (float&)a4); std::swap( (float&)d2, (float&)b4); std::swap( (float&)d3, (float&)c4); return *this; } // --------------------------------------------------------------------------- inline float aiMatrix4x4::Determinant() const { return a1*b2*c3*d4 - a1*b2*c4*d3 + a1*b3*c4*d2 - a1*b3*c2*d4 + a1*b4*c2*d3 - a1*b4*c3*d2 - a2*b3*c4*d1 + a2*b3*c1*d4 - a2*b4*c1*d3 + a2*b4*c3*d1 - a2*b1*c3*d4 + a2*b1*c4*d3 + a3*b4*c1*d2 - a3*b4*c2*d1 + a3*b1*c2*d4 - a3*b1*c4*d2 + a3*b2*c4*d1 - a3*b2*c1*d4 - a4*b1*c2*d3 + a4*b1*c3*d2 - a4*b2*c3*d1 + a4*b2*c1*d3 - a4*b3*c1*d2 + a4*b3*c2*d1; } // --------------------------------------------------------------------------- inline aiMatrix4x4& aiMatrix4x4::Inverse() { // Compute the reciprocal determinant float det = Determinant(); if(det == 0.0f) { // Matrix not invertible. Setting all elements to nan is not really // correct in a mathematical sense but it is easy to debug for the // programmer. const float nan = std::numeric_limits<float>::quiet_NaN(); *this = aiMatrix4x4( nan,nan,nan,nan, nan,nan,nan,nan, nan,nan,nan,nan, nan,nan,nan,nan); return *this; } float invdet = 1.0f / det; aiMatrix4x4 res; res.a1 = invdet * (b2 * (c3 * d4 - c4 * d3) + b3 * (c4 * d2 - c2 * d4) + b4 * (c2 * d3 - c3 * d2)); res.a2 = -invdet * (a2 * (c3 * d4 - c4 * d3) + a3 * (c4 * d2 - c2 * d4) + a4 * (c2 * d3 - c3 * d2)); res.a3 = invdet * (a2 * (b3 * d4 - b4 * d3) + a3 * (b4 * d2 - b2 * d4) + a4 * (b2 * d3 - b3 * d2)); res.a4 = -invdet * (a2 * (b3 * c4 - b4 * c3) + a3 * (b4 * c2 - b2 * c4) + a4 * (b2 * c3 - b3 * c2)); res.b1 = -invdet * (b1 * (c3 * d4 - c4 * d3) + b3 * (c4 * d1 - c1 * d4) + b4 * (c1 * d3 - c3 * d1)); res.b2 = invdet * (a1 * (c3 * d4 - c4 * d3) + a3 * (c4 * d1 - c1 * d4) + a4 * (c1 * d3 - c3 * d1)); res.b3 = -invdet * (a1 * (b3 * d4 - b4 * d3) + a3 * (b4 * d1 - b1 * d4) + a4 * (b1 * d3 - b3 * d1)); res.b4 = invdet * (a1 * (b3 * c4 - b4 * c3) + a3 * (b4 * c1 - b1 * c4) + a4 * (b1 * c3 - b3 * c1)); res.c1 = invdet * (b1 * (c2 * d4 - c4 * d2) + b2 * (c4 * d1 - c1 * d4) + b4 * (c1 * d2 - c2 * d1)); res.c2 = -invdet * (a1 * (c2 * d4 - c4 * d2) + a2 * (c4 * d1 - c1 * d4) + a4 * (c1 * d2 - c2 * d1)); res.c3 = invdet * (a1 * (b2 * d4 - b4 * d2) + a2 * (b4 * d1 - b1 * d4) + a4 * (b1 * d2 - b2 * d1)); res.c4 = -invdet * (a1 * (b2 * c4 - b4 * c2) + a2 * (b4 * c1 - b1 * c4) + a4 * (b1 * c2 - b2 * c1)); res.d1 = -invdet * (b1 * (c2 * d3 - c3 * d2) + b2 * (c3 * d1 - c1 * d3) + b3 * (c1 * d2 - c2 * d1)); res.d2 = invdet * (a1 * (c2 * d3 - c3 * d2) + a2 * (c3 * d1 - c1 * d3) + a3 * (c1 * d2 - c2 * d1)); res.d3 = -invdet * (a1 * (b2 * d3 - b3 * d2) + a2 * (b3 * d1 - b1 * d3) + a3 * (b1 * d2 - b2 * d1)); res.d4 = invdet * (a1 * (b2 * c3 - b3 * c2) + a2 * (b3 * c1 - b1 * c3) + a3 * (b1 * c2 - b2 * c1)); *this = res; return *this; } // --------------------------------------------------------------------------- inline float* aiMatrix4x4::operator[](unsigned int p_iIndex) { return &this->a1 + p_iIndex * 4; } // --------------------------------------------------------------------------- inline const float* aiMatrix4x4::operator[](unsigned int p_iIndex) const { return &this->a1 + p_iIndex * 4; } // --------------------------------------------------------------------------- inline bool aiMatrix4x4::operator== (const aiMatrix4x4 m) const { return (a1 == m.a1 && a2 == m.a2 && a3 == m.a3 && a4 == m.a4 && b1 == m.b1 && b2 == m.b2 && b3 == m.b3 && b4 == m.b4 && c1 == m.c1 && c2 == m.c2 && c3 == m.c3 && c4 == m.c4 && d1 == m.d1 && d2 == m.d2 && d3 == m.d3 && d4 == m.d4); } // --------------------------------------------------------------------------- inline bool aiMatrix4x4::operator!= (const aiMatrix4x4 m) const { return !(*this == m); } // --------------------------------------------------------------------------- inline void aiMatrix4x4::Decompose (aiVector3D& scaling, aiQuaternion& rotation, aiVector3D& position) const { const aiMatrix4x4& _this = *this; // extract translation position.x = _this[0][3]; position.y = _this[1][3]; position.z = _this[2][3]; // extract the rows of the matrix aiVector3D vRows[3] = { aiVector3D(_this[0][0],_this[1][0],_this[2][0]), aiVector3D(_this[0][1],_this[1][1],_this[2][1]), aiVector3D(_this[0][2],_this[1][2],_this[2][2]) }; // extract the scaling factors scaling.x = vRows[0].Length(); scaling.y = vRows[1].Length(); scaling.z = vRows[2].Length(); // and remove all scaling from the matrix if(scaling.x) { vRows[0] /= scaling.x; } if(scaling.y) { vRows[1] /= scaling.y; } if(scaling.z) { vRows[2] /= scaling.z; } // build a 3x3 rotation matrix aiMatrix3x3 m(vRows[0].x,vRows[1].x,vRows[2].x, vRows[0].y,vRows[1].y,vRows[2].y, vRows[0].z,vRows[1].z,vRows[2].z); // and generate the rotation quaternion from it rotation = aiQuaternion(m); } // --------------------------------------------------------------------------- inline void aiMatrix4x4::DecomposeNoScaling (aiQuaternion& rotation, aiVector3D& position) const { const aiMatrix4x4& _this = *this; // extract translation position.x = _this[0][3]; position.y = _this[1][3]; position.z = _this[2][3]; // extract rotation rotation = aiQuaternion((aiMatrix3x3)_this); } // --------------------------------------------------------------------------- inline void aiMatrix4x4::FromEulerAnglesXYZ(const aiVector3D& blubb) { FromEulerAnglesXYZ(blubb.x,blubb.y,blubb.z); } // --------------------------------------------------------------------------- inline void aiMatrix4x4::FromEulerAnglesXYZ(float x, float y, float z) { aiMatrix4x4& _this = *this; float cr = cos( x ); float sr = sin( x ); float cp = cos( y ); float sp = sin( y ); float cy = cos( z ); float sy = sin( z ); _this.a1 = cp*cy ; _this.a2 = cp*sy; _this.a3 = -sp ; float srsp = sr*sp; float crsp = cr*sp; _this.b1 = srsp*cy-cr*sy ; _this.b2 = srsp*sy+cr*cy ; _this.b3 = sr*cp ; _this.c1 = crsp*cy+sr*sy ; _this.c2 = crsp*sy-sr*cy ; _this.c3 = cr*cp ; } // --------------------------------------------------------------------------- inline bool aiMatrix4x4::IsIdentity() const { // Use a small epsilon to solve floating-point inaccuracies const static float epsilon = 10e-3f; return (a2 <= epsilon && a2 >= -epsilon && a3 <= epsilon && a3 >= -epsilon && a4 <= epsilon && a4 >= -epsilon && b1 <= epsilon && b1 >= -epsilon && b3 <= epsilon && b3 >= -epsilon && b4 <= epsilon && b4 >= -epsilon && c1 <= epsilon && c1 >= -epsilon && c2 <= epsilon && c2 >= -epsilon && c3 <= epsilon && c3 >= -epsilon && d1 <= epsilon && d1 >= -epsilon && d2 <= epsilon && d2 >= -epsilon && d3 <= epsilon && d3 >= -epsilon && a1 <= 1.f+epsilon && a1 >= 1.f-epsilon && b2 <= 1.f+epsilon && b2 >= 1.f-epsilon && c3 <= 1.f+epsilon && c3 >= 1.f-epsilon && d4 <= 1.f+epsilon && d4 >= 1.f-epsilon); } // --------------------------------------------------------------------------- inline aiMatrix4x4& aiMatrix4x4::RotationX(float a, aiMatrix4x4& out) { /* | 1 0 0 0 | M = | 0 cos(A) -sin(A) 0 | | 0 sin(A) cos(A) 0 | | 0 0 0 1 | */ out = aiMatrix4x4(); out.b2 = out.c3 = cos(a); out.b3 = -(out.c2 = sin(a)); return out; } // --------------------------------------------------------------------------- inline aiMatrix4x4& aiMatrix4x4::RotationY(float a, aiMatrix4x4& out) { /* | cos(A) 0 sin(A) 0 | M = | 0 1 0 0 | | -sin(A) 0 cos(A) 0 | | 0 0 0 1 | */ out = aiMatrix4x4(); out.a1 = out.c3 = cos(a); out.c1 = -(out.a3 = sin(a)); return out; } // --------------------------------------------------------------------------- inline aiMatrix4x4& aiMatrix4x4::RotationZ(float a, aiMatrix4x4& out) { /* | cos(A) -sin(A) 0 0 | M = | sin(A) cos(A) 0 0 | | 0 0 1 0 | | 0 0 0 1 | */ out = aiMatrix4x4(); out.a1 = out.b2 = cos(a); out.a2 = -(out.b1 = sin(a)); return out; } // --------------------------------------------------------------------------- // Returns a rotation matrix for a rotation around an arbitrary axis. inline aiMatrix4x4& aiMatrix4x4::Rotation( float a, const aiVector3D& axis, aiMatrix4x4& out) { float c = cos( a), s = sin( a), t = 1 - c; float x = axis.x, y = axis.y, z = axis.z; // Many thanks to MathWorld and Wikipedia out.a1 = t*x*x + c; out.a2 = t*x*y - s*z; out.a3 = t*x*z + s*y; out.b1 = t*x*y + s*z; out.b2 = t*y*y + c; out.b3 = t*y*z - s*x; out.c1 = t*x*z - s*y; out.c2 = t*y*z + s*x; out.c3 = t*z*z + c; out.a4 = out.b4 = out.c4 = 0.0f; out.d1 = out.d2 = out.d3 = 0.0f; out.d4 = 1.0f; return out; } // --------------------------------------------------------------------------- inline aiMatrix4x4& aiMatrix4x4::Translation( const aiVector3D& v, aiMatrix4x4& out) { out = aiMatrix4x4(); out.a4 = v.x; out.b4 = v.y; out.c4 = v.z; return out; } // --------------------------------------------------------------------------- /** A function for creating a rotation matrix that rotates a vector called * "from" into another vector called "to". * Input : from[3], to[3] which both must be *normalized* non-zero vectors * Output: mtx[3][3] -- a 3x3 matrix in colum-major form * Authors: Tomas Möller, John Hughes * "Efficiently Building a Matrix to Rotate One Vector to Another" * Journal of Graphics Tools, 4(4):1-4, 1999 */ // --------------------------------------------------------------------------- inline aiMatrix4x4& aiMatrix4x4::FromToMatrix(const aiVector3D& from, const aiVector3D& to, aiMatrix4x4& mtx) { const aiVector3D v = from ^ to; const float e = from * to; const float f = (e < 0)? -e:e; if (f > 1.0 - 0.00001f) /* "from" and "to"-vector almost parallel */ { aiVector3D u,v; /* temporary storage vectors */ aiVector3D x; /* vector most nearly orthogonal to "from" */ x.x = (from.x > 0.0)? from.x : -from.x; x.y = (from.y > 0.0)? from.y : -from.y; x.z = (from.z > 0.0)? from.z : -from.z; if (x.x < x.y) { if (x.x < x.z) { x.x = 1.0; x.y = x.z = 0.0; } else { x.z = 1.0; x.y = x.z = 0.0; } } else { if (x.y < x.z) { x.y = 1.0; x.x = x.z = 0.0; } else { x.z = 1.0; x.x = x.y = 0.0; } } u.x = x.x - from.x; u.y = x.y - from.y; u.z = x.z - from.z; v.x = x.x - to.x; v.y = x.y - to.y; v.z = x.z - to.z; const float c1 = 2.0f / (u * u); const float c2 = 2.0f / (v * v); const float c3 = c1 * c2 * (u * v); for (unsigned int i = 0; i < 3; i++) { for (unsigned int j = 0; j < 3; j++) { mtx[i][j] = - c1 * u[i] * u[j] - c2 * v[i] * v[j] + c3 * v[i] * u[j]; } mtx[i][i] += 1.0; } } else /* the most common case, unless "from"="to", or "from"=-"to" */ { /* ... use this hand optimized version (9 mults less) */ const float h = 1.0f/(1.0f + e); /* optimization by Gottfried Chen */ const float hvx = h * v.x; const float hvz = h * v.z; const float hvxy = hvx * v.y; const float hvxz = hvx * v.z; const float hvyz = hvz * v.y; mtx[0][0] = e + hvx * v.x; mtx[0][1] = hvxy - v.z; mtx[0][2] = hvxz + v.y; mtx[1][0] = hvxy + v.z; mtx[1][1] = e + h * v.y * v.y; mtx[1][2] = hvyz - v.x; mtx[2][0] = hvxz - v.y; mtx[2][1] = hvyz + v.x; mtx[2][2] = e + hvz * v.z; } return mtx; } #endif // __cplusplus #endif // AI_MATRIX4x4_INL_INC
[ "marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21" ]
[ [ [ 1, 429 ] ] ]
f1a0d5109a001f3b2c5f6ed0990f57a012576f10
8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab
/src-ginga-editing/gingancl-cpp/include/model/CascadingDescriptor.h
4fc6bb941d2a7b42e5081b0ec5d7db5554d65320
[]
no_license
BrunoSSts/ginga-wac
7436a9815427a74032c9d58028394ccaac45cbf9
ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c
refs/heads/master
2020-05-20T22:21:33.645904
2011-10-17T12:34:32
2011-10-17T12:34:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,344
h
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Direitos Autorais Reservados (c) 1989-2007 PUC-Rio/Laboratorio TeleMidia Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: ncl @ telemidia.puc-rio.br http://www.ncl.org.br http://www.ginga.org.br http://www.telemidia.puc-rio.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright: 1989-2007 PUC-RIO/LABORATORIO TELEMIDIA, All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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 version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: ncl @ telemidia.puc-rio.br http://www.ncl.org.br http://www.ginga.org.br http://www.telemidia.puc-rio.br *******************************************************************************/ #ifndef _CASCADINGDESCRIPTOR_H_ #define _CASCADINGDESCRIPTOR_H_ #include "util/functions.h" #include "util/Color.h" #include "ncl/Parameter.h" using namespace ::br::pucrio::telemidia::ncl; #include "ncl/descriptor/Descriptor.h" #include "ncl/descriptor/GenericDescriptor.h" using namespace ::br::pucrio::telemidia::ncl::descriptor; #include "ncl/layout/LayoutRegion.h" using namespace ::br::pucrio::telemidia::ncl::layout; #include "ncl/switches/DescriptorSwitch.h" using namespace ::br::pucrio::telemidia::ncl::switches; #include "ncl/navigation/FocusDecoration.h" #include "ncl/navigation/KeyNavigation.h" using namespace ::br::pucrio::telemidia::ncl::navigation; #include "ncl/transition/Transition.h" using namespace ::br::pucrio::telemidia::ncl::transition; #include "FormatterRegion.h" using namespace ::br::pucrio::telemidia::ginga::ncl::model::presentation; #include <string> #include <map> #include <vector> #include <set> using namespace std; namespace br { namespace pucrio { namespace telemidia { namespace ginga { namespace ncl { namespace model { namespace presentation { class FormatterLayout; class CascadingDescriptor { protected: set<string> typeSet; private: string id; vector<GenericDescriptor*>* descriptors; vector<GenericDescriptor*>* unsolvedDescriptors; map<string, string>* parameters; double explicitDuration; string playerName; long repetitions; bool freeze; LayoutRegion* region; FormatterRegion* formatterRegion; string focusIndex, moveUp, moveDown, moveLeft, moveRight; string focusSrc, selectionSrc; Color* focusBorderColor; Color* selBorderColor; int focusBorderWidth; double focusBorderTransparency; vector<Transition*>* inputTransitions; vector<Transition*>* outputTransitions; void cascadeDescriptor(Descriptor* descriptor); public: CascadingDescriptor(GenericDescriptor* firstDescriptor); CascadingDescriptor(CascadingDescriptor* descriptor); ~CascadingDescriptor(); protected: void initializeCascadingDescriptor(); public: bool instanceOf(string s); string getId(); bool isLastDescriptor(GenericDescriptor* descriptor); void cascade(GenericDescriptor* preferredDescriptor); GenericDescriptor* getFirstUnsolvedDescriptor(); vector<GenericDescriptor*>* getUnsolvedDescriptors(); void cascadeUnsolvedDescriptor(); double getExplicitDuration(); bool getFreeze(); string getPlayerName(); LayoutRegion* getRegion(); FormatterRegion* getFormatterRegion(); void setFormatterRegion(FormatterRegion* region); void setFormatterRegion(FormatterLayout* formatterLayout); long getRepetitions(); vector<Parameter*>* getParameters(); string getParameterValue(string paramName); vector<GenericDescriptor*>* getNcmDescriptors(); Color* getFocusBorderColor(); double getFocusBorderTransparency(); int getFocusBorderWidth(); string getFocusIndex(); string getFocusSrc(); string getSelectionSrc(); string getMoveDown(); string getMoveLeft(); string getMoveRight(); string getMoveUp(); Color* getSelBorderColor(); vector<Transition*>* getInputTransitions(); vector<Transition*>* getOutputTransitions(); }; } } } } } } } #endif //_CASCADINGDESCRIPTOR_H_
[ [ [ 1, 169 ] ] ]
0e40632f13db8432b02043b22c77320875e01ca6
0033659a033b4afac9b93c0ac80b8918a5ff9779
/game/server/so2/so_player.cpp
4c1015d0abf90e77640f571a8f493fee942e4d01
[]
no_license
jonnyboy0719/situation-outbreak-two
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
50037e27e738ff78115faea84e235f865c61a68f
refs/heads/master
2021-01-10T09:59:39.214171
2011-01-11T01:15:33
2011-01-11T01:15:33
53,858,955
1
0
null
null
null
null
UTF-8
C++
false
false
26,468
cpp
#include "cbase.h" #include "so_player.h" #include "team.h" #include "in_buttons.h" #include "ai_basenpc.h" #include "bone_setup.h" #include "so_gamerules.h" #include "studio.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // Add support for CS:S player animations // -------------------------------------------------------------------------------- // // Player animation event. Sent to the client when a player fires, jumps, reloads, etc.. // -------------------------------------------------------------------------------- // class CTEPlayerAnimEvent : public CBaseTempEntity { public: DECLARE_CLASS( CTEPlayerAnimEvent, CBaseTempEntity ); DECLARE_SERVERCLASS(); CTEPlayerAnimEvent( const char *name ) : CBaseTempEntity( name ) { } CNetworkHandle( CBasePlayer, m_hPlayer ); CNetworkVar( int, m_iEvent ); CNetworkVar( int, m_nData ); }; #define THROWGRENADE_COUNTER_BITS 3 IMPLEMENT_SERVERCLASS_ST_NOBASE( CTEPlayerAnimEvent, DT_TEPlayerAnimEvent ) SendPropEHandle( SENDINFO( m_hPlayer ) ), SendPropInt( SENDINFO( m_iEvent ), Q_log2( PLAYERANIMEVENT_COUNT ) + 1, SPROP_UNSIGNED ), SendPropInt( SENDINFO( m_nData ), 32 ) END_SEND_TABLE() static CTEPlayerAnimEvent g_TEPlayerAnimEvent( "PlayerAnimEvent" ); void TE_PlayerAnimEvent( CBasePlayer *pPlayer, PlayerAnimEvent_t event, int nData ) { CPVSFilter filter( (const Vector&)pPlayer->EyePosition() ); //Tony; use prediction rules. filter.UsePredictionRules(); g_TEPlayerAnimEvent.m_hPlayer = pPlayer; g_TEPlayerAnimEvent.m_iEvent = event; g_TEPlayerAnimEvent.m_nData = nData; g_TEPlayerAnimEvent.Create( filter, 0 ); } #define MODEL_CHANGE_DELAY 10.0f LINK_ENTITY_TO_CLASS( player, CSO_Player ); extern void SendProxy_Origin( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); BEGIN_SEND_TABLE_NOBASE( CSO_Player, DT_SOLocalPlayerExclusive ) END_SEND_TABLE() BEGIN_SEND_TABLE_NOBASE( CSO_Player, DT_SONonLocalPlayerExclusive ) END_SEND_TABLE() IMPLEMENT_SERVERCLASS_ST( CSO_Player, DT_SO_Player ) // Add support for CS:S player animations SendPropInt( SENDINFO(m_iThrowGrenadeCounter), THROWGRENADE_COUNTER_BITS, SPROP_UNSIGNED ), // Do not allow players to fire weapons on ladders // http://articles.thewavelength.net/724/ // Do not allow players to fire weapons while sprinting SendPropEHandle( SENDINFO( m_hHolsteredWeapon ) ), END_SEND_TABLE() BEGIN_DATADESC( CSO_Player ) END_DATADESC() #pragma warning( disable : 4355 ) // Health regeneration system extern ConVar so_health_regen; extern ConVar so_health_regen_delay; extern ConVar so_health_regen_amount; // Rework respawning system extern ConVar so_respawn; extern ConVar so_respawn_time; CSO_Player::CSO_Player() { // Add support for CS:S player animations m_SOPlayerAnimState = CreateSOPlayerAnimState( this ); UseClientSideAnimation(); // Health regeneration system m_flHealthRegenDelay = 0.0f; // Do not allow players to fire weapons on ladders // http://articles.thewavelength.net/724/ // Do not allow players to fire weapons while sprinting m_hHolsteredWeapon = NULL; // Base each player's speed on their health m_flSpeedCheckDelay = 0.0f; // Add support for CS:S player animations DoAnimationEvent( PLAYERANIMEVENT_SPAWN ); m_iThrowGrenadeCounter = 0; // Character customization system m_pCurrentHeadgear = NULL; m_pCurrentMask = NULL; m_pCurrentGlasses = NULL; m_pCurrentCommDevice = NULL; } CSO_Player::~CSO_Player( void ) { // Add support for CS:S player animations m_SOPlayerAnimState->Release(); } void CSO_Player::PickDefaultSpawnTeam( void ) { if ( GetTeamNumber() == 0 ) { if ( SOGameRules() && !SOGameRules()->IsTeamplay() ) { if ( !GetModelPtr() ) ChangeTeam( TEAM_UNASSIGNED ); } } } void CSO_Player::Precache( void ) { BaseClass::Precache(); // Add rain splashes to func_precipitation // TODO: Perhaps find a better place to do this? PrecacheParticleSystem( "rainsplash" ); // Precache player models for ( int i = 0; i < ARRAYSIZE(PlayerModels); i++ ) PrecacheModel( PlayerModels[i] ); } void CSO_Player::Spawn( void ) { BaseClass::Spawn(); // Do not allow players to fire weapons on ladders // http://articles.thewavelength.net/724/ // Do not allow players to fire weapons while sprinting m_hHolsteredWeapon = NULL; // weapon is no longer holstered (we just spawned); reset variable } void CSO_Player::ChangeTeam( int iTeam ) { if ( iTeam != TEAM_SPECTATOR ) iTeam = TEAM_UNASSIGNED; // players are not allowed to change teams CBasePlayer::ChangeTeam( iTeam ); // skip over CHL2MP_Player::ChangeTeam SetPlayerModel(); if ( iTeam == TEAM_SPECTATOR ) { RemoveAllItems( true ); State_Transition( STATE_OBSERVER_MODE ); } } void CSO_Player::GiveAllItems( void ) { // Impulse 101 doesn't do much anymore // All it does now is resupply us with our default weapons and ammo // There are simply too many weapons in the game to give the player everything all at once GiveDefaultItems(); } void CSO_Player::GiveDefaultItems( void ) { // Give us the maximum amount of ammo we can carry at a time when we spawn // (the actual amount of ammo we get depends on the maximum amount of ammo each weapon can hold, which is defined in so_gamerules.cpp) CBasePlayer::GiveAmmo( 9999, "pistol" ); CBasePlayer::GiveAmmo( 9999, "heavypistol" ); CBasePlayer::GiveAmmo( 9999, "smg" ); CBasePlayer::GiveAmmo( 9999, "rifle" ); CBasePlayer::GiveAmmo( 9999, "shotgun" ); CBasePlayer::GiveAmmo( 9999, "machinegun" ); CBasePlayer::GiveAmmo( 9999, "grenade" ); CBasePlayer::GiveAmmo( 9999, "sniper" ); // Equip and switch to our default weapon, the knife, automatically GiveNamedItem( "weapon_knife" ); Weapon_Switch( Weapon_OwnsThisType( "weapon_knife" ) ); } bool CSO_Player::ValidatePlayerModel( const char *pModel ) { for ( int i = 0; i < ARRAYSIZE(PlayerModels); i++ ) { if ( !Q_stricmp(PlayerModels[i], pModel) ) return true; } return false; } void CSO_Player::SetPlayerModel() { const char *szDesiredModelName = engine->GetClientConVarValue( engine->IndexOfEdict( edict() ), "cl_playermodel" ); while ( !ValidatePlayerModel(szDesiredModelName) || (Q_strlen(szDesiredModelName) == 0) || (modelinfo->GetModelIndex(szDesiredModelName) == -1) ) { // The player needs their model changed, but an invalid one is specified for cl_playermodel // Randomly choose a valid player model for them instead and write the new model name to cl_playermodel to correct the problem const char *tempModelName = PlayerModels[RandomInt(0, ARRAYSIZE(PlayerModels) - 1)]; char szReturnString[512]; Q_snprintf( szReturnString, sizeof(szReturnString), "cl_playermodel %s\n", tempModelName ); engine->ClientCommand( edict(), szReturnString ); szDesiredModelName = tempModelName; } SetModel( szDesiredModelName ); // Character customization system // Our player model must be valid before we start applying bodygroups and stuff SetPlayerBodygroups( BODYGROUP_HEADGEAR ); SetPlayerBodygroups( BODYGROUP_GLASSES ); SetPlayerBodygroups( BODYGROUP_COMMDEVICE ); m_flModelChangeDelay = gpGlobals->curtime + MODEL_CHANGE_DELAY; } // Character customization system void CSO_Player::SetPlayerBodygroups( int bodygroup ) { switch ( bodygroup ) { case BODYGROUP_HEADGEAR: { m_pCurrentHeadgear = engine->GetClientConVarValue(engine->IndexOfEdict(edict()), "cl_playermodel_headgear"); char szReturnString[32]; Q_snprintf( szReturnString, sizeof(szReturnString), "cl_playermodel_headgear %s\n", m_pCurrentHeadgear ); engine->ClientCommand( edict(), szReturnString ); SetBodygroup( BODYGROUP_HEADGEAR, atoi(m_pCurrentHeadgear) ); break; } case BODYGROUP_GLASSES: { m_pCurrentGlasses = engine->GetClientConVarValue(engine->IndexOfEdict(edict()), "cl_playermodel_glasses"); char szReturnString[32]; Q_snprintf( szReturnString, sizeof(szReturnString), "cl_playermodel_glasses %s\n", m_pCurrentGlasses ); engine->ClientCommand( edict(), szReturnString ); SetBodygroup( BODYGROUP_GLASSES, atoi(m_pCurrentGlasses) ); break; } case BODYGROUP_COMMDEVICE: { m_pCurrentCommDevice = engine->GetClientConVarValue(engine->IndexOfEdict(edict()), "cl_playermodel_commdevice"); char szReturnString[32]; Q_snprintf( szReturnString, sizeof(szReturnString), "cl_playermodel_commdevice %s\n", m_pCurrentCommDevice ); engine->ClientCommand( edict(), szReturnString ); SetBodygroup( BODYGROUP_COMMDEVICE, atoi(m_pCurrentCommDevice) ); break; } default: { // When in doubt, do nothing! break; } } } void CSO_Player::PostThink( void ) { CHL2_Player::PostThink(); // skip over CHL2MP_Player::PostThink if ( GetFlags() & FL_DUCKING ) SetCollisionBounds( VEC_CROUCH_TRACE_MIN, VEC_CROUCH_TRACE_MAX ); QAngle angles = GetLocalAngles(); angles[PITCH] = 0; SetLocalAngles( angles ); // Add support for CS:S player animations // Store the eye angles pitch so the client can compute its animation state correctly. m_angEyeAngles = EyeAngles(); m_SOPlayerAnimState->Update( m_angEyeAngles[YAW], m_angEyeAngles[PITCH] ); // Health regeneration system if ( gpGlobals->curtime >= m_flHealthRegenDelay ) { // Don't regenerate the health of those who aren't alive or playing if ( GetTeamNumber() == TEAM_SPECTATOR || !IsAlive() ) return; if ( so_health_regen.GetBool() ) { int currentHealth = GetHealth(); int newHealth = currentHealth; int maxHealth = GetMaxHealth(); if ( currentHealth < maxHealth ) // we're wounded, so start regenerating health newHealth = currentHealth + so_health_regen_amount.GetInt(); else if ( currentHealth > maxHealth ) // don't allow us to go over our maximum health newHealth = maxHealth; if ( newHealth != currentHealth ) SetHealth( newHealth ); // actually set our new health value (assuming our health has changed) } m_flHealthRegenDelay = gpGlobals->curtime + so_health_regen_delay.GetFloat(); } // Base each player's speed on their health // The original SetMaxSpeed function has been overrided to make this all work properly (see player.h) if ( gpGlobals->curtime >= m_flSpeedCheckDelay ) { // There's no need for any speed alterations when we're not alive or playing if ( (GetTeamNumber() != TEAM_SPECTATOR) && IsAlive() ) { if ( IsWalking() ) SetMaxSpeed( SO_WALK_SPEED ); else if ( IsSprinting() ) SetMaxSpeed( SO_SPRINT_SPEED ); else SetMaxSpeed( SO_NORM_SPEED ); } m_flSpeedCheckDelay = gpGlobals->curtime + 0.5f; // this should be often enough without overloading servers...hopefully... } } // Taken and modified from CHL2MP_Player::BumpWeapon extern int gEvilImpulse101; bool CSO_Player::BumpWeapon( CBaseCombatWeapon *pWeapon ) { if ( !pWeapon ) // you never know... return false; CBaseCombatCharacter *pOwner = pWeapon->GetOwner(); // Can I have this weapon type? if ( !IsAllowedToPickupWeapons() ) return false; if ( pOwner || !Weapon_CanUse( pWeapon ) || !g_pGameRules->CanHavePlayerItem(this, pWeapon) ) { if ( gEvilImpulse101 ) UTIL_Remove( pWeapon ); return false; } // Don't let the player fetch weapons through walls (use MASK_SOLID so that you can't pickup through windows) if( !pWeapon->FVisible(this, MASK_SOLID) && !(GetFlags() & FL_NOTARGET) ) return false; bool bOwnsWeaponAlready = !!Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ); if ( bOwnsWeaponAlready == true ) { //If we have room for the ammo, then "take" the weapon too. if ( Weapon_EquipAmmoOnly(pWeapon) ) { pWeapon->CheckRespawn(); UTIL_Remove( pWeapon ); return true; } else { return false; } } // Only allow players to carry one weapon per bucket for ( int i = 0; i < WeaponCount(); i++ ) { CBaseCombatWeapon *pSearch = GetWeapon( i ); if ( pSearch && (pSearch->GetSlot() == pWeapon->GetSlot()) ) return false; } pWeapon->CheckRespawn(); Weapon_Equip( pWeapon ); // Switch to the weapon we just picked up, regardless of its power or worth // Why? Chances are we did so willingly, and if we were actually able to pickup a weapon, we must have not had a weapon of its type or at least not full ammo for it Weapon_Switch( pWeapon ); return true; } // Much of this function should resemble CHL2MP_Player::ClientCommand bool CSO_Player::ClientCommand( const CCommand &args ) { if ( FStrEq( args[0], "spectate" ) ) { if ( ShouldRunRateLimitedCommand( args ) ) { // instantly join spectators HandleCommand_JoinTeam( TEAM_SPECTATOR ); } return true; } else if ( FStrEq( args[0], "jointeam" ) ) { if ( args.ArgC() < 2 ) Warning( "Player sent bad jointeam syntax\n" ); if ( ShouldRunRateLimitedCommand( args ) ) { int iTeam = atoi( args[1] ); // Do not allow players to willingly join whatever teams they want other than spectator if ( iTeam != TEAM_SPECTATOR ) { Warning( "You cannot willingly switch teams like that! Nice try though. :P\n" ); return true; } HandleCommand_JoinTeam( iTeam ); } return true; } else if ( FStrEq( args[0], "joingame" ) ) { return true; } return CHL2_Player::ClientCommand( args ); // skip over CHL2MP_Player::ClientCommand since most of it is here already, etc } // Much of this function should resemble CHL2MP_Player::HandleCommand_JoinTeam bool CSO_Player::HandleCommand_JoinTeam( int team ) { if ( !GetGlobalTeam( team ) || (team == 0) ) { Warning( "HandleCommand_JoinTeam( %d ) - invalid team index.\n", team ); return false; } if ( team == TEAM_SPECTATOR ) { // Prevent this is the cvar is set if ( !mp_allowspectators.GetInt() ) { ClientPrint( this, HUD_PRINTCENTER, "#Cannot_Be_Spectator" ); return false; } if ( !IsDead() ) { m_fNextSuicideTime = gpGlobals->curtime; // allow the suicide to work CommitSuicide(); } ChangeTeam( TEAM_SPECTATOR ); return true; } else { StopObserverMode(); State_Transition( STATE_ACTIVE ); } // Switch their actual team... ChangeTeam( team ); return true; } // Allow players to drop their active weapons void CC_Player_Drop( void ) { CSO_Player *pPlayer = ToSOPlayer( UTIL_GetCommandClient() ); if ( !pPlayer ) return; CWeaponSOBase *pWeapon = dynamic_cast<CWeaponSOBase*>( pPlayer->GetActiveWeapon() ); if ( !pWeapon ) return; // Only drop weapons we're allowed to drop if ( pWeapon->CanDrop() ) { // Weapon scope system // Unscope when dropping a weapon with a scope (prevents bugs) if ( pWeapon->HasScope() ) pWeapon->ExitScope(); pPlayer->Weapon_Drop( pWeapon, NULL, NULL ); } } static ConCommand drop( "drop", CC_Player_Drop, "If possible, drops one's equipped weapon" ); // This function may need to be reworked in the future, so I've decided to copy and paste all BaseClass versions // In fact, I've already made some changes... void CSO_Player::Weapon_Drop( CBaseCombatWeapon *pWeapon, const Vector *pvecTarget, const Vector *pVelocity ) { if ( pWeapon ) // should prevent some rare and strange crashes { bool bWasActiveWeapon = false; if ( pWeapon == GetActiveWeapon() ) bWasActiveWeapon = true; if ( pWeapon ) { if ( bWasActiveWeapon ) pWeapon->SendWeaponAnim( ACT_VM_IDLE ); } // If I'm an NPC, fill the weapon with ammo before I drop it. if ( GetFlags() & FL_NPC ) { if ( pWeapon->UsesClipsForAmmo1() ) pWeapon->m_iClip1 = pWeapon->GetDefaultClip1(); if ( pWeapon->UsesClipsForAmmo2() ) pWeapon->m_iClip2 = pWeapon->GetDefaultClip2(); } if ( IsPlayer() ) { Vector vThrowPos = Weapon_ShootPosition() - Vector(0,0,12); if( UTIL_PointContents(vThrowPos) & CONTENTS_SOLID ) Msg("Weapon spawning in solid!\n"); pWeapon->SetAbsOrigin( vThrowPos ); QAngle gunAngles; VectorAngles( BodyDirection2D(), gunAngles ); pWeapon->SetAbsAngles( gunAngles ); } else { int iBIndex = -1; int iWeaponBoneIndex = -1; CStudioHdr *hdr = pWeapon->GetModelPtr(); // If I have a hand, set the weapon position to my hand bone position. if ( hdr && hdr->numbones() > 0 ) { // Assume bone zero is the root for ( iWeaponBoneIndex = 0; iWeaponBoneIndex < hdr->numbones(); ++iWeaponBoneIndex ) { iBIndex = LookupBone( hdr->pBone( iWeaponBoneIndex )->pszName() ); // Found one! if ( iBIndex != -1 ) break; } if ( iBIndex == -1 ) iBIndex = LookupBone( "ValveBiped.Weapon_bone" ); } else { iBIndex = LookupBone( "ValveBiped.Weapon_bone" ); } if ( iBIndex != -1) { Vector origin; QAngle angles; matrix3x4_t transform; // Get the transform for the weapon bonetoworldspace in the NPC GetBoneTransform( iBIndex, transform ); // find offset of root bone from origin in local space // Make sure we're detached from hierarchy before doing this!!! pWeapon->StopFollowingEntity(); pWeapon->SetAbsOrigin( Vector( 0, 0, 0 ) ); pWeapon->SetAbsAngles( QAngle( 0, 0, 0 ) ); pWeapon->InvalidateBoneCache(); matrix3x4_t rootLocal; pWeapon->GetBoneTransform( iWeaponBoneIndex, rootLocal ); // invert it matrix3x4_t rootInvLocal; MatrixInvert( rootLocal, rootInvLocal ); matrix3x4_t weaponMatrix; ConcatTransforms( transform, rootInvLocal, weaponMatrix ); MatrixAngles( weaponMatrix, angles, origin ); pWeapon->Teleport( &origin, &angles, NULL ); } // Otherwise just set in front of me. else { Vector vFacingDir = BodyDirection2D(); vFacingDir = vFacingDir * 10.0; pWeapon->SetAbsOrigin( Weapon_ShootPosition() + vFacingDir ); } } Vector vecThrow; if (pvecTarget) { // I've been told to throw it somewhere specific. vecThrow = VecCheckToss( this, pWeapon->GetAbsOrigin(), *pvecTarget, 0.2, 1.0, false ); } else { if ( pVelocity ) { vecThrow = *pVelocity; float flLen = vecThrow.Length(); if (flLen > 400) { VectorNormalize(vecThrow); vecThrow *= 400; } } else { // Nowhere in particular; just drop it. float throwForce = ( IsPlayer() ) ? 400.0f : random->RandomInt( 64, 128 ); vecThrow = BodyDirection3D() * throwForce; } } pWeapon->Drop( vecThrow ); Weapon_Detach( pWeapon ); if ( HasSpawnFlags( SF_NPC_NO_WEAPON_DROP ) ) { // Don't drop weapons when the super physgun is happening. UTIL_Remove( pWeapon ); } if ( bWasActiveWeapon ) { if (!SwitchToNextBestWeapon( NULL )) { CBaseViewModel *vm = GetViewModel(); if ( vm ) vm->AddEffects( EF_NODRAW ); } } // Make weapons that are on the ground blink so that they are easier for players to see pWeapon->AddEffects( EF_ITEM_BLINK ); } } int CSO_Player::OnTakeDamage( const CTakeDamageInfo &inputInfo ) { return BaseClass::OnTakeDamage( inputInfo ); } void CSO_Player::Event_Killed( const CTakeDamageInfo &info ) { //update damage info with our accumulated physics force CTakeDamageInfo subinfo = info; subinfo.SetDamageForce( m_vecTotalBulletForce ); // Note: since we're dead, it won't draw us on the client, but we don't set EF_NODRAW // because we still want to transmit to the clients in our PVS. CreateRagdollEntity(); DetonateTripmines(); CHL2_Player::Event_Killed( subinfo ); if ( info.GetDamageType() & DMG_DISSOLVE ) { if ( m_hRagdoll ) m_hRagdoll->GetBaseAnimating()->Dissolve( NULL, gpGlobals->curtime, false, ENTITY_DISSOLVE_NORMAL ); } CSO_Player *pAttackerPlayer = ToSOPlayer( info.GetAttacker() ); if ( pAttackerPlayer ) { if ( pAttackerPlayer != this ) GetGlobalTeam( pAttackerPlayer->GetTeamNumber() )->AddScore( 1 ); } FlashlightTurnOff(); m_lifeState = LIFE_DEAD; RemoveEffects( EF_NODRAW ); // still draw player body StopZooming(); // Do not allow players to fire weapons on ladders // http://articles.thewavelength.net/724/ // Do not allow players to fire weapons while sprinting m_hHolsteredWeapon = NULL; // weapon is no longer holstered (we're dead); reset variable } // Rework respawning system // Much of the contents of this function are identical to CBasePlayer::PlayerDeathThink void CSO_Player::PlayerDeathThink( void ) { float flForward; SetNextThink( gpGlobals->curtime + 0.1f ); if ( GetFlags() & FL_ONGROUND ) { flForward = GetAbsVelocity().Length() - 20; if ( flForward <= 0 ) { SetAbsVelocity( vec3_origin ); } else { Vector vecNewVelocity = GetAbsVelocity(); VectorNormalize( vecNewVelocity ); vecNewVelocity *= flForward; SetAbsVelocity( vecNewVelocity ); } } // we drop the guns here because weapons that have an area effect and can kill their user // will sometimes crash coming back from CBasePlayer::Killed() if they kill their owner because the // player class sometimes is freed. It's safer to manipulate the weapons once we know // we aren't calling into any of their code anymore through the player pointer. if ( HasWeapons() ) PackDeadPlayerItems(); if ( GetModelIndex() && !IsSequenceFinished() && (m_lifeState == LIFE_DYING) ) { StudioFrameAdvance(); m_iRespawnFrames++; if ( m_iRespawnFrames < 60 ) // animations should be no longer than this return; } if ( m_lifeState == LIFE_DYING ) { m_lifeState = LIFE_DEAD; m_flDeathAnimTime = gpGlobals->curtime; } StopAnimation(); AddEffects( EF_NOINTERP ); m_flPlaybackRate = 0.0; if ( SOGameRules()->FPlayerCanRespawn(this) && (gpGlobals->curtime >= (m_flDeathTime + DEATH_ANIMATION_TIME + so_respawn_time.GetInt())) ) { m_nButtons = 0; m_iRespawnFrames = 0; Spawn(); // respawn the player ClientPrint( this, HUD_PRINTTALK, "You have been redeployed." ); SetNextThink( TICK_NEVER_THINK ); } else if ( (gpGlobals->curtime >= (m_flDeathTime + DEATH_ANIMATION_TIME)) && !IsObserver() ) { StartObserverMode( OBS_MODE_ROAMING ); // start roaming around as an observer now that we've been dead for a little while } } // Much of the contents of this function are identical to CBasePlayer::StartObserverMode bool CSO_Player::StartObserverMode( int mode ) { VPhysicsDestroyObject(); if ( !IsObserver() ) { // set position to last view offset SetAbsOrigin( GetAbsOrigin() + GetViewOffset() ); SetViewOffset( vec3_origin ); } Assert( mode > OBS_MODE_NONE ); m_afPhysicsFlags |= PFLAG_OBSERVER; // Holster weapon immediately, to allow it to cleanup if ( GetActiveWeapon() ) GetActiveWeapon()->Holster(); // clear out the suit message cache so we don't keep chattering SetSuitUpdate( NULL, FALSE, 0 ); SetGroundEntity( (CBaseEntity *)NULL ); RemoveFlag( FL_DUCKING ); AddSolidFlags( FSOLID_NOT_SOLID ); SetObserverMode( mode ); if ( gpGlobals->eLoadType != MapLoad_Background ) ShowViewPortPanel( "specgui" , ModeWantsSpectatorGUI(mode) ); // Setup flags m_Local.m_iHideHUD = HIDEHUD_HEALTH; m_takedamage = DAMAGE_NO; // Become invisible AddEffects( EF_NODRAW ); m_iHealth = 1; m_lifeState = LIFE_DEAD; // Can't be dead, otherwise movement doesn't work right. m_flDeathAnimTime = gpGlobals->curtime; // Fix roaming (free look) mode for observers and spectators // This flag prevents players from moving...what were you thinking, Valve!? //pl.deadflag = true; pl.deadflag = false; return true; } // Add support for CS:S player animations void CSO_Player::DoAnimationEvent( PlayerAnimEvent_t event, int nData ) { if ( event == PLAYERANIMEVENT_ATTACK_GRENADE ) { // Grenade throwing has to synchronize exactly with the player's grenade weapon going away, // and events get delayed a bit, so we let CCSPlayerAnimState pickup the change to this // variable. m_iThrowGrenadeCounter = (m_iThrowGrenadeCounter+1) % (1<<THROWGRENADE_COUNTER_BITS); } else { m_SOPlayerAnimState->DoAnimationEvent( event, nData ); TE_PlayerAnimEvent( this, event, nData ); // Send to any clients who can see this guy. } } // Add support for CS:S player animations void CSO_Player::SetupBones( matrix3x4_t *pBoneToWorld, int boneMask ) { VPROF_BUDGET( "CSO_Player::SetupBones", VPROF_BUDGETGROUP_SERVER_ANIM ); // Set the mdl cache semaphore. MDLCACHE_CRITICAL_SECTION(); // Get the studio header. Assert( GetModelPtr() ); CStudioHdr *pStudioHdr = GetModelPtr( ); Vector pos[MAXSTUDIOBONES]; Quaternion q[MAXSTUDIOBONES]; // Adjust hit boxes based on IK driven offset. Vector adjOrigin = GetAbsOrigin() + Vector( 0, 0, m_flEstIkOffset ); // FIXME: pass this into Studio_BuildMatrices to skip transforms CBoneBitList boneComputed; if ( m_pIk ) { m_iIKCounter++; m_pIk->Init( pStudioHdr, GetAbsAngles(), adjOrigin, gpGlobals->curtime, m_iIKCounter, boneMask ); GetSkeleton( pStudioHdr, pos, q, boneMask ); m_pIk->UpdateTargets( pos, q, pBoneToWorld, boneComputed ); CalculateIKLocks( gpGlobals->curtime ); m_pIk->SolveDependencies( pos, q, pBoneToWorld, boneComputed ); } else { GetSkeleton( pStudioHdr, pos, q, boneMask ); } CBaseAnimating *pParent = dynamic_cast< CBaseAnimating* >( GetMoveParent() ); if ( pParent ) { // We're doing bone merging, so do special stuff here. CBoneCache *pParentCache = pParent->GetBoneCache(); if ( pParentCache ) { BuildMatricesWithBoneMerge( pStudioHdr, m_SOPlayerAnimState->GetRenderAngles(), adjOrigin, pos, q, pBoneToWorld, pParent, pParentCache ); return; } } Studio_BuildMatrices( pStudioHdr, m_SOPlayerAnimState->GetRenderAngles(), adjOrigin, pos, q, -1, pBoneToWorld, boneMask ); }
[ "MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61" ]
[ [ [ 1, 915 ] ] ]
a8a71e8e9603f8d14fa0191c1f8cb1316cc9f837
d249c8f9920b1267752342f77d6f12592cb32636
/moteurGraphique/src/Moteur3D/Camera.h
bd801e10d0ac50aa261a8480d0f08379349217d2
[]
no_license
jgraulle/stage-animation-physique
4c9fb0f96b9f4626420046171ff60f23fe035d5d
f1b0c69c3ab48f256d5ac51b4ffdbd48b1c001ae
refs/heads/master
2021-12-23T13:46:07.677761
2011-03-08T22:47:53
2011-03-08T22:47:53
33,616,188
0
0
null
2021-10-05T10:41:29
2015-04-08T15:41:32
C++
ISO-8859-1
C++
false
false
2,354
h
/* * Camera.h * * Created on: 6 fevr. 2009 * Author: jeremie GRAULLE */ #ifndef CAMERA_H_ #define CAMERA_H_ #include "../Math/Vector3.h" #include "../Type.h" #include "../Erreur.h" class Camera { public: // constructeur Camera(const Vector3 & centreObservation=Vector3(0.0,0.0,0.0), f32 rotX=0.0, f32 rotY=0.0, f32 distance=0.0); // destructeur virtual ~Camera(); // accesseur sur le centre d'observation const Vector3 & getCentreObser() const; // reinitialiser le centre d'observation void setCentreObser(const Vector3 &); // deplacer le centre d'observation par rapport a un vecteur deplacement // ou l'axe des Z pointe vers la camera // (prend en compte la rotation de gauche-droite de la camera) void moveCentreObser(const Vector3 &); // accesseur sur la rotation gauche-droite de la camera f32 getRotX() const; // accesseur sur la rotation haut-bas de la camera f32 getRotY() const; // reinitialiser la rotation de de la camera en degres void setRot(f32 gaucheDroite, f32 hautBas); // prend le modulo 360 des angles // modifier le rotation en ajoutant un f32 a chaque axe void addRot(f32 gaucheDroite, f32 hautBas); // modifier le rotation gauche-droite en ajoutant un f32 void addRotX(f32); // modifier le rotation haut-bas en ajoutant un f32 void addRotY(f32); // accesseur sur la distance de la camera au centre d'observation f32 getDistance() const; // reinitialiser la distance de la camera au centre d'observation void setDistance(f32); // erreur DistanceNegative si negatif // erreur si la distance entre la camera au centre d'observation est negative class DistanceNegative : public Erreur { public: DistanceNegative():Erreur("Impossible de donnée une distance négative pour la camera"){} }; // modifier la distance en ajoutant un f32 void addDistance(f32); // si negatif sera ramener a 0.0 // faire les transformations openGL necessaire pour bien placer la camera void positionner() const; // dessiner le centre de la camera void display() const; private: Vector3 centre; // centre d'observation de la camera f32 rx; // rotation gauche-droite en ° f32 ry; // rotation haut-bas en ° f32 dist; // distance de la camera au centre d'observation }; #endif /* CAMERA_H_ */
[ "jgraulle@74bb1adf-7843-2a67-e58d-b22fe9da3ebb", "jeremie@74bb1adf-7843-2a67-e58d-b22fe9da3ebb" ]
[ [ [ 1, 25 ], [ 27, 36 ], [ 38, 39 ], [ 41, 55 ], [ 57, 70 ], [ 75, 83 ] ], [ [ 26, 26 ], [ 37, 37 ], [ 40, 40 ], [ 56, 56 ], [ 71, 74 ] ] ]
6fbdb718c6d0bfaf06d060e9e459cc8b280b7ca0
00a4dc4a9ea1fc6657a81607e285055fc29bda29
/Engine/source/Sprite.cpp
322902e979fb68c1fe54bcdc964eb7c199bd01dd
[]
no_license
etgarcia/AS3-for-Airplay-SDK
d5d5e2443879b37aff7486d8f07453769568cbfc
470f2cc49d19642128f49dcc5618702671a1f851
refs/heads/master
2016-09-05T10:21:56.570562
2011-01-27T06:25:13
2011-01-27T06:25:13
1,380,021
0
0
null
null
null
null
UTF-8
C++
false
false
176
cpp
#include "Sprite.h" Sprite::Sprite(void) { } Sprite::~Sprite(void) { for (uint32 i = 0; i < children.size(); i++) delete children[i]; children.clear(); }
[ "etgarcia@d6d0176c-4ec9-df4c-96f2-63634c7079df" ]
[ [ [ 1, 14 ] ] ]
e0751a34c6141560a8eeb1a8373b8d35eba5c49a
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/sc/UT_SingleChip/include/UT_SingleChip.h
fc956338078e7c8bff4b661b724ccece9acdb209
[]
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
2,764
h
#ifndef __Orz_Test_OrzAR_h__ #define __Orz_Test_OrzAR_h__ #include "config.h" #include <iostream> #include <orz/Framework_Base/FrameworkBase.h> #include <orz/Framework_Base/System.h> #include <orz/Toolkit_Base/TimerManager.h> #include <orz/Toolkit_Base/DynLibManager.h> #include <orz/Toolkit_Base/LogManager.h> #include <orz/View_OGRE3D/OgreGraphicsManager.h> #include <orz/View_CEGUI/CEGUIManager.h> #include <orz/View_OIS/OISInputManager.h> #include <orz/View_Fmod/FmodSoundManager.h> #include <orz/Toolkit_Base/Singleton.h> #include <boost/property_tree/detail/rapidxml.hpp> #include <Ogre/Ogre.h> class Listener_:public Orz::SingleChipListener { public: virtual void read(boost::circular_buffer<unsigned char> & data) { std::cout<<1<<std::endl; } virtual void readFromSCM(unsigned int id, unsigned char c) { std::cout<<id<<":"<<unsigned int(c)<<std::endl; } }; BOOST_AUTO_TEST_SUITE( SingleChipManager_ts ) struct F { F() { using namespace Orz; system.reset(new SystemList<boost::mpl::list<SimpleTimerManager, OgreGraphicsManager, SingleChipManager, OISInputManager> >()); } ~F() { } Orz::SystemPtr system; }; //#if TRACKER_SINGLE BOOST_FIXTURE_TEST_CASE(simple, F) { using namespace rapidxml; Orz::SystemInterface::getSingleton().setParame<bool>("OGRE_NO_OUT", true); Listener_ l; if(system->init()) { unsigned char c = 0; { using namespace Ogre; DataStreamPtr pStream; pStream = ResourceGroupManager::getSingleton().openResource( "sc.xml", "xml" ); String data = pStream->getAsString(); xml_document<> doc; doc.parse<0>(&data[0]); rapidxml::xml_node<> *node = doc.first_node("single-chips"); Orz::SingleChipManager::getSingleton().loadXML(node); std::cout<<Orz::SingleChipManager::getSingleton().getSCMAmount()<<std::endl; Orz::SingleChipManager::getSingleton().addListener(0,&l); Orz::MsgBuffer buffer; buffer.push_back(0XFF); buffer.push_back(0XFF); buffer.push_back(0X80); buffer.push_back(0X00); buffer.push_back(0X8D); buffer.push_back(0X00); buffer.push_back(0X00); buffer.push_back(0X00); buffer.push_back(0X9E); buffer.push_back(0X30); Orz::SingleChipManager::getSingleton().write(0, buffer); } //boost::shared_ptr<OgreNewtRunning> runing(new OgreNewtRunning()); //Orz::TimerPtr timer(new Orz::Timer("DemoRuning", boost::bind(&OgreNewtRunning::update, runing.get() ))); // timer->start(WORLD_UPDATE_INTERVAL); system->run(); //runing.reset(); system->shutdown(); } } //____________________________________________________________________________// BOOST_AUTO_TEST_SUITE_END() #endif
[ [ [ 1, 118 ] ] ]
ff896839b1497469e076741390d037b9da2fc167
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/impl/DOMNotationImpl.hpp
1e43e893974af0d79d4a25c110839ab869a0d81d
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
2,710
hpp
#ifndef DOMNotationImpl_HEADER_GUARD_ #define DOMNotationImpl_HEADER_GUARD_ /* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMNotationImpl.hpp,v 1.5 2004/09/08 13:55:52 peiyongz Exp $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/DOM.hpp> for the entire // DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/XercesDefs.hpp> #include <xercesc/dom/DOMNotation.hpp> XERCES_CPP_NAMESPACE_BEGIN #include "DOMNodeImpl.hpp" class DOMDocument; class CDOM_EXPORT DOMNotationImpl: public DOMNotation { public: DOMNodeImpl fNode; const XMLCh * fName; const XMLCh * fPublicId; const XMLCh * fSystemId; const XMLCh * fBaseURI; public: DOMNotationImpl(DOMDocument *ownerDoc, const XMLCh *); DOMNotationImpl(const DOMNotationImpl &other, bool deep=false); virtual ~DOMNotationImpl(); // Declare all of the functions from DOMNode. DOMNODE_FUNCTIONS; // // The Public Identifier for this Notation. If no public identifier // was specified, this will be null. virtual const XMLCh * getPublicId() const; // The System Identifier for this Notation. If no system identifier // was specified, this will be null. virtual const XMLCh * getSystemId() const; // NON-DOM: The Public Identifier for this Notation. If no public // identifier was specified, this will be null. virtual void setPublicId(const XMLCh *arg); // NON-DOM: The System Identifier for this Notation. If no system // identifier was specified, this will be null. virtual void setSystemId(const XMLCh *arg); // NON-DOM: set base uri virtual void setBaseURI(const XMLCh *arg); private: // unimplemented DOMNotationImpl& operator= (const DOMNotationImpl& other); }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 89 ] ] ]
86051e40159cb11ceb5f8c86bdfd71bde3e9d43c
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/TestSMPreprocessing/stdafx.cpp
59ddb70ffd036e60099e6a49e40c17132bc20ce9
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
// stdafx.cpp : source file that includes just the standard includes // TestSMPreprocessing.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 8 ] ] ]
10d9232961251040aa5f57a89cd474b7373800d8
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SETools/SEManagedFramework/SEManagedRendering/SEManagedCamera.cpp
8ae7aa83e33362d0a7dfe6d99a901187bda6ca2f
[]
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
UTF-8
C++
false
false
8,492
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 "SEManagedFrameworkPCH.h" #include "SEManagedCamera.h" using namespace Swing; using namespace Swing::Tools::ManagedFramework; //--------------------------------------------------------------------------- ManagedCamera::ManagedCamera() { m_pspCamera = SE_NEW SECameraPtr; (*m_pspCamera) = SE_NEW SECamera; } //--------------------------------------------------------------------------- ManagedCamera::ManagedCamera(SECamera* pCamera) { m_pspCamera = SE_NEW SECameraPtr; (*m_pspCamera) = pCamera; } //--------------------------------------------------------------------------- ManagedCamera::~ManagedCamera() { SE_DELETE m_pspCamera; m_pspCamera = 0; } //--------------------------------------------------------------------------- void ManagedCamera::SetFrame(ManagedVector3f^ thLocation, ManagedVector3f^ thRVector, ManagedVector3f^ thUVector, ManagedVector3f^ thDVector) { SE_NULL_ARGUMENT_CHECK(thLocation, "thLocation"); SE_NULL_ARGUMENT_CHECK(thRVector, "thRVector"); SE_NULL_ARGUMENT_CHECK(thUVector, "thUVector"); SE_NULL_ARGUMENT_CHECK(thDVector, "thDVector"); SEVector3f vec3fLoc, vec3fR, vec3fU, vec3fD; thLocation->ToVector3f(vec3fLoc); thRVector->ToVector3f(vec3fR); thUVector->ToVector3f(vec3fU); thDVector->ToVector3f(vec3fD); SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); (*m_pspCamera)->SetFrame(vec3fLoc, vec3fR, vec3fU, vec3fD); } //--------------------------------------------------------------------------- void ManagedCamera::SetLocation(ManagedVector3f^ thLocation) { SE_NULL_ARGUMENT_CHECK(thLocation, "thLocation"); SEVector3f vec3fLoc; thLocation->ToVector3f(vec3fLoc); SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); (*m_pspCamera)->SetLocation(vec3fLoc); } //--------------------------------------------------------------------------- void ManagedCamera::SetAxes(ManagedVector3f^ thRVector, ManagedVector3f^ thUVector, ManagedVector3f^ thDVector) { SE_NULL_ARGUMENT_CHECK(thRVector, "thRVector"); SE_NULL_ARGUMENT_CHECK(thUVector, "thUVector"); SE_NULL_ARGUMENT_CHECK(thDVector, "thDVector"); SEVector3f vec3fR, vec3fU, vec3fD; thRVector->ToVector3f(vec3fR); thUVector->ToVector3f(vec3fU); thDVector->ToVector3f(vec3fD); SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); (*m_pspCamera)->SetAxes(vec3fR, vec3fU, vec3fD); } //--------------------------------------------------------------------------- ManagedVector3f^ ManagedCamera::GetLocation() { ManagedVector3f^ thRes = gcnew ManagedVector3f; SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); thRes->FromVector3f((*m_pspCamera)->GetLocation()); return thRes; } //--------------------------------------------------------------------------- ManagedVector3f^ ManagedCamera::GetRVector() { ManagedVector3f^ thRes = gcnew ManagedVector3f; SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); thRes->FromVector3f((*m_pspCamera)->GetRVector()); return thRes; } //--------------------------------------------------------------------------- ManagedVector3f^ ManagedCamera::GetUVector() { ManagedVector3f^ thRes = gcnew ManagedVector3f; SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); thRes->FromVector3f((*m_pspCamera)->GetUVector()); return thRes; } //--------------------------------------------------------------------------- ManagedVector3f^ ManagedCamera::GetDVector() { ManagedVector3f^ thRes = gcnew ManagedVector3f; SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); thRes->FromVector3f((*m_pspCamera)->GetDVector()); return thRes; } //--------------------------------------------------------------------------- SECamera* ManagedCamera::GetNativeCamera() { SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); return (SECamera*)(*m_pspCamera); } //--------------------------------------------------------------------------- void ManagedCamera::SetFrustum(float fRMin, float fRMax, float fUMin, float fUMax, float fDMin, float fDMax) { SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); (*m_pspCamera)->SetFrustum(fRMin, fRMax, fUMin, fUMax, fDMin, fDMax); } //--------------------------------------------------------------------------- void ManagedCamera::GetFrustum(float% trfRMin, float% trfRMax, float% trfUMin, float% trfUMax, float% trfDMin, float% trfDMax) { float fRMin = trfRMin; float fRMax = trfRMax; float fUMin = trfUMin; float fUMax = trfUMax; float fDMin = trfDMin; float fDMax = trfDMax; SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); (*m_pspCamera)->GetFrustum(fRMin, fRMax, fUMin, fUMax, fDMin, fDMax); trfRMin = fRMin; trfRMax = fRMax; trfUMin = fUMin; trfUMax = fUMax; trfDMin = fDMin; trfDMax = fDMax; } //--------------------------------------------------------------------------- void ManagedCamera::SetPerspective(bool bPerspective) { SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); (*m_pspCamera)->SetPerspective(bPerspective); } //--------------------------------------------------------------------------- bool ManagedCamera::IsPerspective() { SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); return (*m_pspCamera)->IsPerspective(); } //--------------------------------------------------------------------------- bool ManagedCamera::GetPickRay(int iX, int iY, int iWidth, int iHeight, ManagedRay3f^ thRay) { SE_NULL_ARGUMENT_CHECK(thRay, "thRay"); SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); SERay3f tempRay; bool bRes = (*m_pspCamera)->GetPickRay(iX, iY, iWidth, iHeight, tempRay); thRay->FromRay3f(tempRay); return bRes; } //--------------------------------------------------------------------------- bool ManagedCamera::GetTrackBallRotate(float fX0, float fY0, float fX1, float fY1, ManagedMatrix3f^ thMat) { SE_NULL_ARGUMENT_CHECK(thMat, "thMat"); SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); SEMatrix3f mat3fRot; bool bRes = (*m_pspCamera)->GetTrackBallRotate(fX0, fY0, fX1, fY1, mat3fRot); thMat->FromMatrix3f(mat3fRot); return bRes; } //--------------------------------------------------------------------------- void ManagedCamera::SetName(String^ thName) { SE_NULL_ARGUMENT_CHECK(thName, "thName"); SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); const char* acName = ManagedUtility::StringToNativeCharBuffer(thName); std::string tempName(acName); ManagedUtility::FreeNativeCharBuffer(acName); (*m_pspCamera)->SetName(tempName); } //--------------------------------------------------------------------------- String^ ManagedCamera::GetName() { SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); return gcnew String((*m_pspCamera)->GetName().c_str()); } //--------------------------------------------------------------------------- int ManagedCamera::GetNativeReferences() { SE_NULL_REFERENCE_CHECK(m_pspCamera, "Native pointer is null"); return (*m_pspCamera)->GetReferences(); } //---------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 227 ] ] ]
11a663f186f046c5f1908355f9e7461060545613
d01196cdfc4451c4e1c88343bdb1eb4db9c5ac18
/source/server/ents/basefx.cpp
d79bcfdf89b47918e7fac3576632a6ab4c16a33e
[]
no_license
ferhan66h/Xash3D_ancient
7491cd4ff1c7d0b48300029db24d7e08ba96e88a
075e0a6dae12a0952065eb9b2954be4a8827c72f
refs/heads/master
2021-12-10T07:55:29.592432
2010-05-09T00:00:00
2016-07-30T17:37:36
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
84,326
cpp
//======================================================================= // Copyright (C) XashXT Group 2006 //======================================================================= #include "extdll.h" #include "defaults.h" #include "utils.h" #include "cbase.h" #include "basebeams.h" #include "baseweapon.h" #include "decals.h" #include "basebrush.h" #include "shake.h" #include "monsters.h" #include "client.h" #include "player.h" #include "soundent.h" //======================================================================= // main functions () //======================================================================= class CBaseParticle : public CBaseLogic { public: void Spawn( void ); void Precache( void ){ pev->netname = UTIL_PrecacheAurora( pev->message ); } void KeyValue( KeyValueData *pkvd ); void PostActivate( void ){ Switch(); } void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void Switch( void ); }; void CBaseParticle :: KeyValue( KeyValueData *pkvd ) { if ( FStrEq( pkvd->szKeyName, "aurora" )) { pev->message = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseLogic::KeyValue( pkvd ); } void CBaseParticle::Switch( void ) { int renderfx = (m_iState ? kRenderFxAurora : kRenderFxNone ); if( pev->target ) { CBaseEntity *pTarget = UTIL_FindEntityByTargetname( NULL, STRING( pev->target ), m_hActivator ); while ( pTarget ) { UTIL_SetAurora( pTarget, pev->netname ); pTarget->pev->renderfx = renderfx; pTarget = UTIL_FindEntityByTargetname( pTarget, STRING( pev->target ), m_hActivator ); } } else { UTIL_SetAurora( this, pev->netname ); pev->renderfx = renderfx; } } void CBaseParticle::Spawn( void ) { Precache(); SetObjectClass( ED_NORMAL ); pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NOCLIP; if( pev->spawnflags & SF_START_ON || FStringNull( pev->targetname )) m_iState = STATE_ON; else m_iState = STATE_OFF; } void CBaseParticle::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if ( useType == USE_TOGGLE ) { if( m_iState == STATE_ON ) useType = USE_OFF; else useType = USE_ON; } if ( useType == USE_ON ) { m_iState = STATE_ON; Switch(); } else if ( useType == USE_OFF ) { m_iState = STATE_OFF; Switch(); } else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; Msg( "State: %s, ParticleName: %s\n", GetStringForState( GetState()), STRING( pev->netname )); if ( pev->target ) Msg( "Attach to: %s\n", STRING( pev->target )); else Msg( "\n" ); } } LINK_ENTITY_TO_CLASS( env_particle, CBaseParticle ); //========================================================= // env_sky, an unreal tournament - style sky effect //========================================================= class CEnvSky : public CBaseLogic { public: void Spawn( void ); }; LINK_ENTITY_TO_CLASS( env_sky, CEnvSky ); void CEnvSky :: Spawn( void ) { // Xash3D engine feature SetObjectClass( ED_SKYPORTAL ); } //========================================================= // UTIL_ScreenFade (fade screen) //========================================================= #define SF_FADE_IN 0x0001 // Fade in, not out #define SF_FADE_MODULATE 0x0002 // Modulate, don't blend #define SF_FADE_ALL 0x0004 // fade all clients #define SF_FADE_CAMERA 0x0008 // fading only for camera class CFade : public CBaseLogic { public: void Spawn( void ) { m_iState = STATE_OFF; } void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void KeyValue( KeyValueData *pkvd ); }; LINK_ENTITY_TO_CLASS( env_fade, CFade ); void CFade::KeyValue( KeyValueData *pkvd ) { if (FStrEq( pkvd->szKeyName, "duration" )) { pev->dmg_take = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq( pkvd->szKeyName, "holdtime" )) { pev->dmg_save = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CFade::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "Fadecolor: %g %g %g, Fadealpha: %g, Fadetime: %g\n", pev->rendercolor.x, pev->rendercolor.y, pev->rendercolor.z, pev->renderamt, pev->dmg_take ); ALERT( at_console, "HoldTime %g, Mode: %s, Modulate: %s\n", pev->dmg_save, pev->spawnflags & SF_FADE_IN ? "FADE IN" : "FADE OUT", pev->spawnflags & SF_FADE_MODULATE ? "YES" : "NO" ); } else { // setup fade flags int fadeFlags = 0; if ( pev->spawnflags & SF_FADE_IN ) fadeFlags |= FFADE_IN; else fadeFlags |= FFADE_OUT; if ( pev->spawnflags & SF_FADE_MODULATE ) fadeFlags |= FFADE_MODULATE; if ( pev->spawnflags & SF_FADE_CAMERA ) fadeFlags |= FFADE_CUSTOMVIEW; // apply fade if ( pev->spawnflags & SF_FADE_ALL ) UTIL_ScreenFadeAll( pev->rendercolor, pev->dmg_take, pev->dmg_save, pev->renderamt, fadeFlags ); else UTIL_ScreenFade( pev->rendercolor, pev->dmg_take, pev->dmg_save, pev->renderamt, fadeFlags ); } } //===================================================== // env_customhud: change player hud //===================================================== class CEnvHud : public CBaseLogic { void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void KeyValue( KeyValueData* ); void SetHUD( int hud_num ); void ResetHUD( void ); char* GetStringForMode( void ); }; void CEnvHud :: KeyValue( KeyValueData* pkvd ) { if (FStrEq( pkvd->szKeyName, "hud" )) { pev->skin = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CEnvHud :: SetHUD( int hud_num ) { if( m_hActivator != NULL ) { m_iState = STATE_ON; ((CBasePlayer *)((CBaseEntity *)m_hActivator))->m_iWarHUD = pev->skin = hud_num; } } void CEnvHud :: ResetHUD( void ) { if( m_hActivator != NULL ) { m_iState = STATE_OFF; ((CBasePlayer *)((CBaseEntity *)m_hActivator))->m_iWarHUD = 0; ((CBasePlayer *)((CBaseEntity *)m_hActivator))->fadeNeedsUpdate = 1; } } void CEnvHud :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if( pActivator && pActivator->IsPlayer( )) // only at player { m_hActivator = pActivator; // save activator } else if( !IsMultiplayer( )) { m_hActivator = UTIL_PlayerByIndex( 1 ); } else { ALERT( at_warning, "%s: %s activator not player. Ignored.\n", STRING( pev->classname ), STRING( pev->targetname )); return; } if ( useType == USE_TOGGLE ) { if ( m_iState == STATE_OFF ) useType = USE_ON; else useType = USE_OFF; } if ( useType == USE_ON ) SetHUD( pev->skin ); else if ( useType == USE_OFF ) ResetHUD(); else if ( useType == USE_SET ) { if ( value ) SetHUD( value ); else ResetHUD(); } else if ( useType == USE_RESET ) ResetHUD(); else if ( useType == USE_SHOWINFO ) { ALERT( at_console, "======/Xash Debug System/======\n" ); ALERT( at_console, "classname: %s\n", STRING( pev->classname )); ALERT( at_console, "State: %s, HUD Mode: %s\n", GetStringForState( GetState()), GetStringForMode()); SHIFT; } } char* CEnvHud :: GetStringForMode( void ) { switch(pev->skin) { case 0: return "Disable Custom HUD"; case 1: return "Draw Redeemer HUD"; case 2: return "Draw Redeemer Underwater HUD"; case 3: return "Draw Redeemer Noise Screen"; case 4: return "Draw Security Camera Screen"; default: return "Draw None"; } } LINK_ENTITY_TO_CLASS( env_customhud, CEnvHud ); //======================================================================= // env_zoom - change fov for player //======================================================================= class CEnvZoom : public CBaseLogic { void Spawn (void ){ if( !pev->frags ) pev->frags = 90.0f; } void EXPORT Think( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void KeyValue( KeyValueData* pkvd ); void SetFadeTime( void ); }; LINK_ENTITY_TO_CLASS( env_zoom, CEnvZoom ); void CEnvZoom::KeyValue( KeyValueData* pkvd ) { if( FStrEq( pkvd->szKeyName, "duration" )) { pev->takedamage = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else if ( FStrEq( pkvd->szKeyName, "fov" )) { pev->frags = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CEnvZoom::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if( !pActivator || !pActivator->IsPlayer()) pActivator = UTIL_PlayerByIndex( 1 ); m_hActivator = pActivator; // save activator if( m_iState == STATE_ON ) return; if( useType == USE_TOGGLE || useType == USE_ON ) SetFadeTime(); else if( useType == USE_OFF ) ((CBasePlayer *)pActivator)->pev->fov = 90.0f; else if( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "State: %s, Fade time %.00f\n", GetStringForState( GetState()), pev->takedamage ); ALERT( at_console, "Current FOV: %g, Final FOV: %g\n", ((CBasePlayer *)pActivator)->pev->fov, pev->frags ); } } void CEnvZoom::SetFadeTime( void ) { float CurFOV; float Length; if( pev->takedamage == 0 ) // instant apply fov { ((CBasePlayer *)(CBaseEntity *)m_hActivator)->pev->fov = pev->frags; return; } else { CurFOV = ((CBasePlayer *)(CBaseEntity *)m_hActivator)->pev->fov; if( CurFOV == 0.0f ) CurFOV = ((CBasePlayer *)(CBaseEntity *)m_hActivator)->pev->fov = 90.0f; if( CurFOV > pev->frags ) Length = CurFOV - pev->frags; else if( CurFOV < pev->frags ) { Length = pev->frags - CurFOV; pev->body = 1; // increment fov } else return; // no change pev->health = pev->takedamage / Length; SetNextThink ( pev->health ); } } void CEnvZoom::Think( void ) { if( Q_rint(((CBasePlayer *)(CBaseEntity *)m_hActivator)->pev->fov ) == Q_rint( pev->frags )) { // time is expired SetThink( NULL ); DontThink(); m_iState = STATE_OFF; // fire target after finished // transmit final fov UTIL_FireTargets( pev->target, m_hActivator, this, USE_TOGGLE, pev->frags ); return; } else { if( pev->body ) ((CBasePlayer *)(CBaseEntity *)m_hActivator)->pev->fov += 0.5f * gpGlobals->frametime; else ((CBasePlayer *)(CBaseEntity *)m_hActivator)->pev->fov -= 0.5f * gpGlobals->frametime; } m_iState = STATE_ON; SetNextThink ( pev->health ); } //===================================================== // env_render: change render parameters //===================================================== #define SF_RENDER_MASKFX (1<<0) #define SF_RENDER_MASKAMT (1<<1) #define SF_RENDER_MASKMODE (1<<2) #define SF_RENDER_MASKCOLOR (1<<3) class CRenderFxManager : public CBaseLogic { public: void Affect( void ); void KeyValue( KeyValueData *pkvd ); void Use ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; Affect(); } }; LINK_ENTITY_TO_CLASS( env_render, CRenderFxManager ); void CRenderFxManager :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "fadetime")) { pev->speed = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CRenderFxManager::Affect( void ) { BOOL first = TRUE; if(FStringNull(pev->target)) return; CBaseEntity* pTarget = UTIL_FindEntityByTargetname( NULL, STRING(pev->target), m_hActivator); while ( pTarget != NULL ) { entvars_t *pevTarget = pTarget->pev; if (pev->speed == 0) // aplly settings instantly ? { if ( !FBitSet( pev->spawnflags, SF_RENDER_MASKAMT ) ) pevTarget->renderamt = pev->renderamt; if ( !FBitSet( pev->spawnflags, SF_RENDER_MASKCOLOR ) ) pevTarget->rendercolor = pev->rendercolor; if ( !FBitSet( pev->spawnflags, SF_RENDER_MASKFX ) ) pevTarget->renderfx = pev->renderfx; if ( !FBitSet( pev->spawnflags, SF_RENDER_MASKMODE ) ) pevTarget->rendermode = pev->rendermode; pevTarget->scale = pev->scale; pevTarget->framerate = pev->framerate; if (first) UTIL_FireTargets( pev->netname, pTarget, this, USE_TOGGLE ); } else { if (!pevTarget->renderamt && !pevTarget->rendermode) pevTarget->renderamt = 255; pevTarget->renderfx = pev->renderfx; pevTarget->rendermode = pev->rendermode; CBaseEntity *pFader = Create( "faderent", pev->origin, pev->angles, pTarget->edict()); pFader->pev->renderamt = pevTarget->renderamt; pFader->pev->rendercolor = pevTarget->rendercolor; pFader->pev->scale = pevTarget->scale; if (pFader->pev->scale == 0) pFader->pev->scale = 1; pFader->pev->spawnflags = pev->spawnflags; if (first) pFader->pev->target = pev->netname; pFader->pev->max_health = pev->framerate - pevTarget->framerate; pFader->pev->health = pev->renderamt - pevTarget->renderamt; pFader->pev->movedir.x = pev->rendercolor.x - pevTarget->rendercolor.x; pFader->pev->movedir.y = pev->rendercolor.y - pevTarget->rendercolor.y; pFader->pev->movedir.z = pev->rendercolor.z - pevTarget->rendercolor.z; if ( pev->scale ) pFader->pev->frags = pev->scale - pevTarget->scale; else pFader->pev->frags = 0; pFader->pev->dmgtime = gpGlobals->time; pFader->pev->speed = pev->speed; pFader->SetNextThink( 0 ); pFader->Spawn(); } first = FALSE;//not a first target pTarget = UTIL_FindEntityByTargetname( pTarget, STRING(pev->target), m_hActivator ); } } //========================================================= // display message //========================================================= class CMessage : public CPointEntity { public: void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { CBaseEntity *pPlayer = NULL; if ( IsMultiplayer() ) UTIL_ShowMessageAll( STRING(pev->message) ); else { if ( pActivator && pActivator->IsPlayer() ) pPlayer = pActivator; else pPlayer = UTIL_PlayerByIndex( 1 ); } if ( pPlayer ) UTIL_ShowMessage( STRING(pev->message), pPlayer ); if ( pev->spawnflags & 1 ) UTIL_Remove( this ); } }; LINK_ENTITY_TO_CLASS( env_message, CMessage ); //========================================================= // set global fog on a map //========================================================= class CEnvFog : public CBaseLogic { public: void PostActivate( void ); void KeyValue( KeyValueData *pkvd ); void TurnOn( void ); void TurnOff( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); }; LINK_ENTITY_TO_CLASS( env_fog, CEnvFog ); void CEnvFog :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "startdist" )) { pev->dmg_take = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "enddist" )) { pev->dmg_save = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq( pkvd->szKeyName, "fadetime" )) { m_flDelay = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CEnvFog :: PostActivate ( void ) { if ( pev->spawnflags & SF_START_ON ) { TurnOn(); ClearBits(pev->spawnflags, SF_START_ON); } } void CEnvFog :: TurnOn ( void ) { m_iState = STATE_ON; UTIL_SetFogAll(pev->rendercolor, m_flDelay, pev->dmg_take, pev->dmg_save ); } void CEnvFog :: TurnOff ( void ) { m_iState = STATE_OFF; UTIL_SetFogAll(pev->rendercolor, -m_flDelay, pev->dmg_take, pev->dmg_save ); } void CEnvFog :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_TOGGLE ) { if ( m_iState == STATE_ON ) useType = USE_OFF; else useType = USE_ON; } if ( useType == USE_ON ) TurnOn(); else if ( useType == USE_OFF ) TurnOff(); } //========================================================= // env_rain, custom client weather effects //========================================================= class CEnvRain : public CPointEntity { public: void KeyValue( KeyValueData *pkvd ) { if ( FStrEq( pkvd->szKeyName, "radius" )) { pev->armorvalue = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else if ( FStrEq( pkvd->szKeyName, "mode" )) { pev->button = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } } void Precache( void ) { if( pev->button ) { // snow UTIL_PrecacheModel( "sprites/snowflake.spr" ); } else { // it's a rainy day :) UTIL_PrecacheModel( "sprites/hi_rain.spr" ); UTIL_PrecacheModel( "sprites/waterring.spr" ); } } void Spawn() { Precache(); } }; LINK_ENTITY_TO_CLASS( env_rain, CEnvRain ); //========================================================= // UTIL_RainModify (set new rain or snow) //========================================================= void CEnvRainModify::Spawn() { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; pev->effects |= EF_NODRAW; if( IsMultiplayer() || FStringNull( pev->targetname )) SetBits( pev->spawnflags, SF_START_ON ); } LINK_ENTITY_TO_CLASS( env_rainmodify, CEnvRainModify ); TYPEDESCRIPTION CEnvRainModify::m_SaveData[] = { DEFINE_FIELD( CEnvRainModify, randXY, FIELD_RANGE ), DEFINE_FIELD( CEnvRainModify, windXY, FIELD_RANGE ), }; IMPLEMENT_SAVERESTORE( CEnvRainModify, CPointEntity ); void CEnvRainModify::KeyValue( KeyValueData *pkvd ) { if (FStrEq( pkvd->szKeyName, "drips" )) { pev->button = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq( pkvd->szKeyName, "fadetime")) { pev->dmg = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq( pkvd->szKeyName, "rand" )) { randXY = RandomRange( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq( pkvd->szKeyName, "wind" )) { windXY = RandomRange( pkvd->szValue ); pkvd->fHandled = TRUE; } } void CEnvRainModify::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "Wind X: %g Y: %g. Rand X: %g Y: %g\n", windXY[1], windXY[0], randXY[1], randXY[0] ); ALERT( at_console, "Fade time %g. Drips per second %d\n", pev->dmg, pev->button ); } else if( !pev->spawnflags & SF_START_ON ) { for ( int i = 0; i < gpGlobals->maxClients; i++ ) { CBasePlayer *pPlayer = (CBasePlayer *)UTIL_PlayerByIndex( i+1 ); if( FNullEnt( pPlayer->pev )) continue; if ( pev->dmg ) { pPlayer->Rain_ideal_dripsPerSecond = pev->button; pPlayer->Rain_ideal_randX = randXY[1]; pPlayer->Rain_ideal_randY = randXY[0]; pPlayer->Rain_ideal_windX = windXY[1]; pPlayer->Rain_ideal_windY = windXY[0]; pPlayer->Rain_endFade = gpGlobals->time + pev->dmg; pPlayer->Rain_nextFadeUpdate = gpGlobals->time + 1; } else { pPlayer->Rain_dripsPerSecond = pev->button; pPlayer->Rain_randX = randXY[1]; pPlayer->Rain_randY = randXY[0]; pPlayer->Rain_windX = windXY[1]; pPlayer->Rain_windY = windXY[0]; pPlayer->rainNeedsUpdate = 1; } } } } //======================================================================= // env_sprite - classic HALF-LIFE sprites //======================================================================= void CSprite::Spawn( void ) { Precache(); UTIL_SetModel( ENT(pev), pev->model ); // Smart Field System © if( !pev->renderamt ) pev->renderamt = 200; // light transparency if( !pev->framerate ) pev->framerate = Frames(); // play sequence at one second if( !pev->rendermode ) pev->rendermode = kRenderTransAdd; pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NOCLIP; pev->frame = 0; SetBits( pFlags, PF_POINTENTITY ); pev->angles.x = -pev->angles.x; pev->angles.y = 180 - pev->angles.y; pev->angles[1] = 0 - pev->angles[1]; TurnOff(); } void CSprite::PostSpawn( void ) { m_pGoalEnt = UTIL_FindEntityByTargetname( NULL, STRING( pev->target )); if( m_pGoalEnt ) UTIL_SetOrigin( this, m_pGoalEnt->pev->origin ); } void CSprite::Think( void ) { SetNextThink( 0 ); if( pev->spawnflags & SF_TEMPSPRITE && gpGlobals->time > pev->dmg_take ) UTIL_Remove(this); else if( pev->framerate ) Animate( pev->framerate * (gpGlobals->time - pev->dmgtime) ); Move(); pev->dmgtime = gpGlobals->time; } void CSprite::Move( void ) { // Not moving on a path, return if( !m_pGoalEnt ) return; // Subtract movement from the previous frame pev->frags -= pev->speed * gpGlobals->frametime; // Have we moved enough to reach the target? if ( pev->frags <= 0 ) { // Fire the passtarget if there is one if ( m_pGoalEnt->pev->message ) { UTIL_FireTargets( m_pGoalEnt->pev->message, this, this, USE_TOGGLE, 0 ); if ( FBitSet( m_pGoalEnt->pev->spawnflags, SF_CORNER_FIREONCE ) ) m_pGoalEnt->pev->message = 0; } if ( FBitSet( m_pGoalEnt->pev->spawnflags, SF_CORNER_TELEPORT ) ) { m_pGoalEnt = m_pGoalEnt->GetNext(); if ( m_pGoalEnt ) UTIL_AssignOrigin( this, m_pGoalEnt->pev->origin ); } if ( FBitSet( m_pGoalEnt->pev->spawnflags, SF_CORNER_WAITFORTRIG ) ) { TurnOff(); //wait for retrigger return; } // Time to go to the next target m_pGoalEnt = m_pGoalEnt->GetNext(); // Set up next corner if ( !m_pGoalEnt ) UTIL_SetVelocity( this, g_vecZero ); else { pev->target = m_pGoalEnt->pev->targetname; // save last corner pev->armorvalue = m_pGoalEnt->pev->speed; Vector delta = m_pGoalEnt->pev->origin - pev->origin; pev->frags = delta.Length(); pev->movedir = delta.Normalize(); m_flDelay = gpGlobals->time + m_pGoalEnt->GetDelay(); } } if ( m_flDelay > gpGlobals->time ) pev->speed = UTIL_Approach( 0, pev->speed, 5 * gpGlobals->frametime ); else pev->speed = UTIL_Approach( pev->armorvalue, pev->speed, 5 * gpGlobals->frametime ); float fraction = 2 * gpGlobals->frametime; UTIL_SetVelocity( this, ((pev->movedir * pev->speed) * fraction) + (pev->velocity * (1-fraction))); } void CSprite::TurnOff( void ) { SetBits( pev->effects, EF_NODRAW ); m_iState = STATE_OFF; if( m_pGoalEnt ) m_pGoalEnt = m_pGoalEnt->GetPrev(); UTIL_SetVelocity( this, g_vecZero ); DontThink(); } void CSprite::TurnOn( void ) { pev->dmgtime = gpGlobals->time; ClearBits( pev->effects, EF_NODRAW ); pev->frame = 0; m_iState = STATE_ON; pev->armorvalue = pev->speed; m_flDelay = gpGlobals->time; pev->frags = 0; Move(); SetNextThink( 0 ); } void CSprite::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { pActivator = m_hActivator; if ( useType == USE_TOGGLE ) { if( m_iState == STATE_ON ) useType = USE_OFF; else useType = USE_ON; } if ( useType == USE_ON ) TurnOn(); else if ( useType == USE_OFF ) TurnOff(); else if ( useType == USE_SET ) ClearBits( pev->effects, EF_NODRAW ); else if ( useType == USE_RESET ) SetBits( pev->effects, EF_NODRAW ); else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "State: %s, speed %g\n", GetStringForState( GetState()), pev->speed ); if( m_pGoalEnt ) ALERT( at_console, "NextPath: %s, framerate %g\n", STRING( m_pGoalEnt->pev->targetname ), pev->framerate ); else ALERT( at_console, "NextPath: no path, framerate %g\n", pev->framerate ); } } LINK_ENTITY_TO_CLASS( env_glow, CSprite ); LINK_ENTITY_TO_CLASS( env_sprite, CSprite ); //================================================================= // env_model: like env_sprite, except you can specify a sequence. //================================================================= #define SF_DROPTOFLOOR 4 class CEnvModel : public CBaseAnimating { void Spawn( void ); void Precache( void ){ UTIL_PrecacheModel( pev->model ); } void EXPORT Animate( void ); void KeyValue( KeyValueData *pkvd ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } void SetAnim( void ); }; LINK_ENTITY_TO_CLASS( env_model, CEnvModel ); void CEnvModel::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "mode")) { pev->button = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "m_iszSequence")) { pev->netname = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseAnimating::KeyValue( pkvd ); } void CEnvModel :: Spawn( void ) { Precache(); UTIL_SetModel( ENT(pev), pev->model ); UTIL_SetOrigin( this, pev->origin ); pev->takedamage = DAMAGE_NO; if ( !( pev->spawnflags & SF_NOTSOLID )) { pev->solid = SOLID_SLIDEBOX; UTIL_AutoSetSize(); } if ( pev->spawnflags & SF_DROPTOFLOOR ) { pev->origin.z += 1; DROP_TO_FLOOR ( ENT(pev) ); } InitBoneControllers(); ResetSequenceInfo( ); m_iState = STATE_OFF; if(pev->spawnflags & SF_START_ON) Use( this, this, USE_ON, 0 ); } void CEnvModel::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_TOGGLE ) { if( m_iState == STATE_ON ) useType = USE_OFF; else useType = USE_ON; } if ( useType == USE_ON ) { SetAnim(); SetThink( Animate ); SetNextThink( 0.1 ); m_iState = STATE_ON; } else if ( useType == USE_OFF ) { m_iState = STATE_OFF; DontThink(); } else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; } } void CEnvModel::SetAnim( void ) { pev->sequence = LookupSequence( STRING( pev->netname )); if (pev->sequence == -1)pev->sequence = 0; pev->frame = 0; ResetSequenceInfo(); } void CEnvModel::Animate( void ) { SetNextThink( 0.1 ); StudioFrameAdvance(); if (m_fSequenceFinished ) { if(pev->button) { //pev->frame = 0; m_iState = STATE_OFF; DontThink(); } else SetAnim(); } } //======================================================================= // env_counter - digital 7 segment indicator as default //======================================================================= class CDecLED : public CBaseLogic { public: void Spawn( void ); void CheckState( void ); void Precache( void ){ UTIL_PrecacheModel( pev->model, "sprites/decimal.spr" ); } void KeyValue( KeyValueData *pkvd ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); float Frames( void ) { return MODEL_FRAMES( pev->modelindex ) - 1; } float flashtime; float curframe( void ) { if( pev->frame - floor( pev->frame ) > 0.5f ) return ceil( pev->frame ); return floor( pev->frame ); } }; LINK_ENTITY_TO_CLASS( env_counter, CDecLED ); LINK_ENTITY_TO_CLASS( logic_indicator, CDecLED ); // Xash 0.2 name void CDecLED :: Spawn( void ) { Precache( ); UTIL_SetModel( ENT(pev), pev->model, "sprites/decimal.spr" ); // Smart Field System © if( !pev->rendermode ) pev->rendermode = kRenderTransAdd; if( !pev->frags ) pev->frags = Frames(); if( !pev->impulse ) pev->impulse = -1; CheckState(); pev->solid = SOLID_NOT; pev->effects = EF_NOINTERP; // g-cont. criticall stuff, don't touch! pev->movetype = MOVETYPE_NONE; pev->angles.x = -pev->angles.x; pev->angles.y = 180 - pev->angles.y; pev->angles[1] = 0 - pev->angles[1]; } void CDecLED :: CheckState( void ) { switch( pev->skin ) { case 1: if( pev->impulse >= curframe() ) m_iState = STATE_ON; else m_iState = STATE_OFF; break; case 2: if( pev->impulse <= curframe() ) m_iState = STATE_ON; else m_iState = STATE_OFF; break; default: if( pev->impulse == curframe() ) m_iState = STATE_ON; else m_iState = STATE_OFF; break; } } void CDecLED :: KeyValue( KeyValueData *pkvd ) { if (FStrEq( pkvd->szKeyName, "maxframe" )) { pev->frags = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq( pkvd->szKeyName, "keyframe" )) { pev->impulse = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq( pkvd->szKeyName, "type" )) { pev->skin = atoi( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseLogic::KeyValue( pkvd ); } void CDecLED :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_ON || useType == USE_TOGGLE ) { if( pev->frame >= pev->frags ) { UTIL_FireTargets( pev->target, pActivator, this, useType, value ); pev->frame = 0; } else pev->frame++; pev->effects &= ~EF_NODRAW; flashtime = gpGlobals->time + 0.5f; } else if ( useType == USE_OFF ) { if( pev->frame <= 0.0f ) { UTIL_FireTargets( pev->target, pActivator, this, useType, value ); pev->frame = pev->frags; } else pev->frame--; pev->effects &= ~EF_NODRAW; flashtime = gpGlobals->time + 0.5f; } else if ( useType == USE_SET ) // set custom frame { if ( value != 0.0f ) { pev->frame = fmod( value, pev->frags + 1.0f ); float next = value / ( pev->frags + 1.0f ); if( (int)next ) UTIL_FireTargets( pev->target, pActivator, this, useType, (int)next ); pev->effects &= ~EF_NODRAW; flashtime = gpGlobals->time + 0.5f; } else if( gpGlobals->time > flashtime ) { if( pev->effects & EF_NODRAW ) { pev->effects &= ~EF_NODRAW; } else { pev->effects |= EF_NODRAW; } } } else if ( useType == USE_RESET ) // immediately reset { pev->frame = 0; pev->effects &= ~EF_NODRAW; } else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; Msg( "Current frame: %.0f, Keyframe %d\n", pev->frame, pev->impulse ); Msg( "State: %s, Maxframe %g\n", GetStringForState( GetState()), pev->frags ); } CheckState(); } //======================================================================= // env_shake - earthquake (screen shake) //======================================================================= class CShake : public CBaseLogic { public: void Spawn( void ){ m_iState = STATE_OFF; } void Think( void ) { m_iState = STATE_OFF; }; void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if( useType == USE_SHOWINFO ) { DEBUGHEAD; Msg( "State: %s, Amplitude: %g, Frequency: %g\n", GetStringForState( GetState()), pev->scale, pev->dmg_save ); Msg( "Radius: %g, Duration: %d\n", pev->dmg, pev->dmg_take ); } else { UTIL_ScreenShake( pev->origin, Amplitude(), Frequency(), Duration(), Radius() ); m_iState = STATE_ON; SetNextThink( Duration() ); } } void KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "amplitude" )) { SetAmplitude( atof(pkvd->szValue )); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "frequency" )) { SetFrequency( atof( pkvd->szValue )); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "duration")) { SetDuration( atof(pkvd->szValue) ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "radius")) { SetRadius( atof(pkvd->szValue) ); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } inline float Amplitude( void ) { return pev->scale; } inline float Frequency( void ) { return pev->dmg_save; } inline float Duration( void ) { return pev->dmg_take; } inline float Radius( void ) { return pev->dmg; } inline void SetAmplitude( float amplitude ) { pev->scale = amplitude; } inline void SetFrequency( float frequency ) { pev->dmg_save = frequency; } inline void SetDuration( float duration ) { pev->dmg_take = duration; } inline void SetRadius( float radius ) { pev->dmg = radius; } }; LINK_ENTITY_TO_CLASS( env_shake, CShake ); //======================================================================= // env_sparks - classic HALF-LIFE sparks //======================================================================= class CEnvSpark : public CBaseLogic { public: void Spawn(void); void Think(void); void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); }; LINK_ENTITY_TO_CLASS(env_spark, CEnvSpark); void CEnvSpark::Spawn(void) { if( !m_flDelay ) m_flDelay = 1.0; // Smart field system ® if( pev->spawnflags & SF_START_ON ) Use( this, this, USE_ON, 0 ); } void CEnvSpark::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_TOGGLE) { if ( m_iState == STATE_ON ) useType = USE_OFF; else useType = USE_ON; } if ( useType == USE_ON ) { m_iState = STATE_ON; SetNextThink( m_flDelay ); } else if ( useType == USE_OFF ) { m_iState = STATE_OFF; DontThink(); } else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "State: %s, MaxDelay %.2f\n\n", GetStringForState( GetState()), m_flDelay ); } } void CEnvSpark::Think( void ) { float flVolume = RANDOM_FLOAT ( 0.25 , 0.75 ) * 0.4; // random volume range switch( RANDOM_LONG( 0, 5 )) { case 0: EMIT_SOUND(ENT(pev), CHAN_VOICE, "materials/spark1.wav", flVolume, ATTN_NORM); break; case 1: EMIT_SOUND(ENT(pev), CHAN_VOICE, "materials/spark2.wav", flVolume, ATTN_NORM); break; case 2: EMIT_SOUND(ENT(pev), CHAN_VOICE, "materials/spark3.wav", flVolume, ATTN_NORM); break; case 3: EMIT_SOUND(ENT(pev), CHAN_VOICE, "materials/spark4.wav", flVolume, ATTN_NORM); break; case 4: EMIT_SOUND(ENT(pev), CHAN_VOICE, "materials/spark5.wav", flVolume, ATTN_NORM); break; case 5: EMIT_SOUND(ENT(pev), CHAN_VOICE, "materials/spark6.wav", flVolume, ATTN_NORM); break; } UTIL_Sparks( pev->origin + pev->size * 0.5 ); if( m_iState == STATE_ON ) SetNextThink( 0.1 + RANDOM_FLOAT( 0, m_flDelay )); //!!! } //========================================================= // env_explosion (classic explode ) //========================================================= class CEnvExplosion : public CBaseLogic { public: void KeyValue( KeyValueData *pkvd ); void Precache( void ) { if( pev->message ) pev->button = UTIL_PrecacheModel( pev->message ); } void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void Explode( void ); }; LINK_ENTITY_TO_CLASS( env_explosion, CEnvExplosion ); void CEnvExplosion::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "radius")) { pev->dmg = atoi(pkvd->szValue); if(pev->dmg < 10) pev->dmg = 10; pkvd->fHandled = TRUE; } if (FStrEq(pkvd->szKeyName, "sprite")) { pev->message = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CEnvExplosion::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( useType == USE_TOGGLE || useType == USE_ON ) { Explode(); } else if ( useType == USE_SET ) { pev->dmg = value; if( pev->dmg < 10 ) pev->dmg = 10; } else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "Radius %g\n", pev->dmg ); SHIFT; } } void CEnvExplosion::Explode( void ) { TraceResult tr; Vector vecSpot = pev->origin;// trace starts here! UTIL_TraceLine ( vecSpot + Vector( 0, 0, 8 ), vecSpot + Vector ( 0, 0, -32 ), ignore_monsters, ENT(pev), &tr); // Pull out of the wall a bit if ( tr.flFraction != 1.0 && tr.vecPlaneNormal[2] < 0.7f ) pev->origin = tr.vecEndPos + (tr.vecPlaneNormal * (pev->dmg - 24) * 0.6); int iContents = UTIL_PointContents ( pev->origin ); entvars_t *pevOwner; if ( pev->owner ) pevOwner = VARS( pev->owner ); else pevOwner = NULL; pev->owner = NULL; // can't traceline attack owner if this is set if ( pev->dmg <= 0 ) pev->dmg = 100; // Smart field system ® if( iContents == CONTENTS_WATER ) { SFX_Explode( g_sModelIndexWExplosion, pev->origin, pev->dmg, TE_EXPLFLAG_NONE ); RadiusDamage ( pev->origin, pev, pevOwner, pev->dmg / 2, pev->dmg * 2.5, CLASS_NONE, DMG_BLAST ); } else { CSoundEnt::InsertSound ( bits_SOUND_COMBAT, pev->origin, pev->dmg * 5, 3.0 ); // custom sprite if( pev->button ) SFX_Explode( pev->button, pev->origin, pev->dmg, TE_EXPLFLAG_NONE ); else SFX_Explode( g_sModelIndexFireball, pev->origin, pev->dmg, TE_EXPLFLAG_NONE ); RadiusDamage ( pev->origin, pev, pevOwner, pev->dmg, pev->dmg * 2.5, CLASS_NONE, DMG_BLAST ); CBaseEntity *pWreckage = Create( "smokeent", pev->origin, pev->angles ); pWreckage->SetNextThink( 0.2 ); pWreckage->pev->impulse = ( pev->dmg - 50) * 0.6; pWreckage->pev->dmgtime = gpGlobals->time + 1.5; int sparkCount = RANDOM_LONG( 0, 3 ); //make sparks for ( int i = 0; i < sparkCount; i++ ) Create( "sparkleent", pev->origin, tr.vecPlaneNormal, NULL ); if ( RANDOM_FLOAT( 0 , 1 ) < 0.5 ) UTIL_DecalTrace( &tr, DECAL_SCORCH1 ); else UTIL_DecalTrace( &tr, DECAL_SCORCH2 ); } if( pev->spawnflags & SF_FIREONCE ) UTIL_Remove( this ); } //========================================================= // gibs (sprite or models gib) //========================================================= void CGib :: Spawn( const char *szGibModel ) { pev->movetype = MOVETYPE_BOUNCE; pev->friction = 0.55; // deading the bounce a bit pev->renderamt = 255; pev->rendermode = kRenderNormal; pev->renderfx = kRenderFxNone; pev->solid = SOLID_TRIGGER; pev->classname = MAKE_STRING( "gib" ); SetObjectClass( ED_NORMAL ); UTIL_SetModel( ENT( pev ), szGibModel ); UTIL_SetSize( pev, g_vecZero, g_vecZero ); m_lifeTime = MAX_GIB_LIFETIME; m_material = None; m_cBloodDecals = 5;// how many blood decals this gib can place (1 per bounce until none remain). } void CGib :: WaitTillLand ( void ) { if (!IsInWorld()) { UTIL_Remove( this ); return; } if ( pev->velocity == g_vecZero ) { if(m_lifeTime == -1) //waiting for pvs { SetThink( PVSRemove ); SetNextThink( MAX_GIB_LIFETIME ); } else { SetThink( Fadeout ); SetNextThink( m_lifeTime ); } if(m_bloodColor != DONT_BLEED) { CSoundEnt::InsertSound ( bits_SOUND_MEAT, pev->origin, 384, 25 ); } } else SetNextThink( 0.5 ); } void CGib :: BounceGibTouch ( CBaseEntity *pOther ) { Vector vecSpot; TraceResult tr; if ( pOther != g_pWorld) UTIL_FireTargets( pev->target, pOther, this, USE_ON ); else UTIL_FireTargets( pev->target, pOther, this, USE_SET ); //world touch if( pev->flags & FL_ONGROUND ) { pev->velocity = pev->velocity * 0.9; pev->angles.x = 0; pev->angles.z = 0; pev->avelocity.x = 0; pev->avelocity.z = 0; } else { if (m_cBloodDecals > 0 && m_bloodColor != DONT_BLEED ) { vecSpot = pev->origin + Vector ( 0 , 0 , 8 ); //move up a bit, and trace down. UTIL_TraceLine ( vecSpot, vecSpot + Vector ( 0, 0, -24 ), ignore_monsters, ENT(pev), & tr); UTIL_BloodDecalTrace( &tr, m_bloodColor ); m_cBloodDecals--; } if ( m_material != None && RANDOM_LONG(0,2) == 0 ) { float volume; float zvel = fabs(pev->velocity.z); volume = 0.8 * min(1.0, ((float)zvel) / 450.0); CBaseBrush::PlayRandomSound( edict(), (Materials)m_material, volume ); } } } void CGib :: StickyGibTouch ( CBaseEntity *pOther ) { Vector vecSpot; TraceResult tr; if(m_lifeTime == -1) //waiting for pvs { SetThink( PVSRemove ); SetNextThink( MAX_GIB_LIFETIME ); } else { SetThink( Fadeout ); SetNextThink( m_lifeTime ); } if ( pOther != g_pWorld ) { UTIL_FireTargets( pev->target, pOther, this, USE_ON ); UTIL_Remove( this ); return; } else UTIL_FireTargets( pev->target, pOther, this, USE_SET ); //world touch UTIL_TraceLine ( pev->origin, pev->origin + pev->velocity * 32, ignore_monsters, ENT(pev), & tr); UTIL_BloodDecalTrace( &tr, m_bloodColor ); pev->velocity = tr.vecPlaneNormal * -1; pev->angles = UTIL_VecToAngles ( pev->velocity ); pev->velocity = g_vecZero; pev->avelocity = g_vecZero; pev->movetype = MOVETYPE_NONE; } CGib *CGib :: CreateGib( CBaseEntity *pVictim, const char *szGibModel, int gibtype ) { CGib *pGib = GetClassPtr( (CGib *)NULL ); pGib->Spawn( szGibModel ); dstudiohdr_t *pstudiohdr = (dstudiohdr_t *)(GET_MODEL_PTR( ENT(pGib->pev) )); if (! pstudiohdr) return NULL; dstudiobodyparts_t *pbodypart = (dstudiobodyparts_t *)((byte *)pstudiohdr + pstudiohdr->bodypartindex); if ( pVictim ) //spawn at gibbed monster { if(gibtype == 1) //skull gib { pGib->pev->body = 0; //spawn skull pGib->pev->origin = pVictim->pev->origin + pVictim->pev->view_ofs; edict_t *pentPlayer = FIND_CLIENT_IN_PVS( pGib->edict()); if ( RANDOM_LONG ( 0, 100 ) <= 5 && pentPlayer ) { // 5% chance head will be thrown at player's face. entvars_t *pevPlayer; pevPlayer = VARS( pentPlayer ); pGib->pev->velocity = ( ( pevPlayer->origin + pevPlayer->view_ofs ) - pGib->pev->origin ).Normalize() * 300; pGib->pev->velocity.z += 100; } else pGib->pev->velocity = Vector (RANDOM_FLOAT(-100,100), RANDOM_FLOAT(-100,100), RANDOM_FLOAT(200,300)); } else { pGib->pev->body = RANDOM_LONG(1, pbodypart->nummodels - 1); //random gibs // spawn the gib somewhere in the monster's bounding volume pGib->pev->origin.x = pVictim->pev->absmin.x + pVictim->pev->size.x * (RANDOM_FLOAT ( 0 , 1 ) ); pGib->pev->origin.y = pVictim->pev->absmin.y + pVictim->pev->size.y * (RANDOM_FLOAT ( 0 , 1 ) ); pGib->pev->origin.z = pVictim->pev->absmin.z + pVictim->pev->size.z * (RANDOM_FLOAT ( 0 , 1 ) ) + 1; // make the gib fly away from the attack vector pGib->pev->velocity = g_vecAttackDir * -1; // mix in some noise pGib->pev->velocity.x += RANDOM_FLOAT ( -0.25, 0.25 ); pGib->pev->velocity.y += RANDOM_FLOAT ( -0.25, 0.25 ); pGib->pev->velocity.z += RANDOM_FLOAT ( -0.25, 0.25 ); pGib->pev->velocity = pGib->pev->velocity * RANDOM_FLOAT ( 300, 400 ); } //shared settings pGib->pev->avelocity.x = RANDOM_FLOAT ( 100, 200 ); pGib->pev->avelocity.y = RANDOM_FLOAT ( 100, 300 ); pGib->m_bloodColor = (CBaseEntity::Instance(pVictim->edict()))->BloodColor(); if ( pVictim->pev->health > -50) pGib->pev->velocity = pGib->pev->velocity * 0.7; else if ( pVictim->pev->health > -200) pGib->pev->velocity = pGib->pev->velocity * 2; else pGib->pev->velocity = pGib->pev->velocity * 4; //LimitVelocity float length = pGib->pev->velocity.Length(); if ( length > (MAX_VELOCITY / 2)) pGib->pev->velocity = pGib->pev->velocity.Normalize() * MAX_VELOCITY / 2; } // global settings UTIL_SetSize ( pGib->pev, g_vecZero, g_vecZero ); if(gibtype == 0 || gibtype == 1) //normal random gibs { pGib->pev->solid = SOLID_BBOX; pGib->SetTouch( BounceGibTouch ); pGib->SetThink( WaitTillLand ); pGib->SetNextThink( 4 ); } if(gibtype == 2) //sticky gib { pGib->pev->movetype = MOVETYPE_TOSS; pGib->SetTouch( StickyGibTouch ); } return pGib; } //========================================================= // env_shooter (sprite or models shooter) //========================================================= class CEnvShooter : public CBaseLogic { void Precache( void ) { if(ParseGibFile()) Setup(); } void KeyValue( KeyValueData *pkvd ); void Spawn( void ); int ParseGibFile( void ); void Setup( void ); void Think( void ); CBaseEntity *CreateGib( Vector vecPos, Vector vecVel ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); //this is will be restoring on precache - no need to save Materials m_Material; Physics m_Physics; string_t entity; RandomRange velocity; RandomRange variance; RandomRange lifetime; }; LINK_ENTITY_TO_CLASS( env_shooter, CEnvShooter ); void CEnvShooter::Spawn( void ) { Precache(); pev->effects = EF_NODRAW; if ( m_flDelay == 0 ) m_flDelay = 0.1; UTIL_LinearVector( this );//movement direction } void CEnvShooter :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "file")) { pev->message = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "gibcount")) { pev->impulse = pev->button = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "gibname")) { m_sSet = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "gibtarget")) { pev->netname = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseLogic::KeyValue( pkvd ); } void CEnvShooter::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; SetNextThink( 0 ); } void CEnvShooter :: Think ( void ) { TraceResult tr; //don't create stack monsters UTIL_TraceLine ( pev->origin, pev->origin - Vector ( 0, 0, 2048 ), ignore_monsters, ENT(pev), &tr ); Vector mins = pev->origin - Vector( 34, 34, 0 ); Vector maxs = pev->origin + Vector( 34, 34, 0 ); maxs.z = pev->origin.z; mins.z = tr.vecEndPos.z; CBaseEntity *pList[2]; if (UTIL_EntitiesInBox( pList, 2, mins, maxs, FL_CLIENT|FL_MONSTER )) { // don't build a stack of monsters! SetNextThink( m_flDelay ); return; } Vector vecShootDir = pev->movedir; vecShootDir = vecShootDir + gpGlobals->v_up * variance.Random(); vecShootDir = vecShootDir + gpGlobals->v_right * variance.Random(); vecShootDir = vecShootDir + gpGlobals->v_forward * variance.Random(); vecShootDir = vecShootDir.Normalize(); CBaseEntity *pGib = CreateGib(pev->origin, vecShootDir * velocity.Random() ); if ( pGib )UTIL_FireTargets( pev->target, pGib, this, USE_TOGGLE, 0 ); if(pev->button > 0) pev->impulse--; if ( pev->impulse <= 0 ) { if ( pev->spawnflags & SF_FIREONCE ) { UTIL_Remove( this ); return; } else { pev->impulse = pev->button; DontThink(); } } SetNextThink( m_flDelay ); } void CEnvShooter :: Setup( void ) { //Smart field system ® if(!FStringNull( m_sMaster )) UTIL_PrecacheModel( m_sMaster ); if(!FStringNull( entity )) UTIL_PrecacheEntity( entity ); if(velocity.m_flMax == 0) velocity.m_flMax = 100; if(velocity.m_flMax > MAX_VELOCITY) velocity.m_flMax = MAX_VELOCITY; if(lifetime.Random() == 0)lifetime = RandomRange( -1.0 ); if(pev->scale == 0)pev->scale = 1; CBaseBrush::MaterialSoundPrecache( m_Material ); //setup physics pev->solid = SOLID_SLIDEBOX; switch( m_Physics ) { case Noclip: pev->team = MOVETYPE_NOCLIP; pev->solid = SOLID_NOT; break; case Bounce: pev->team = MOVETYPE_BOUNCE; break; case Sticky: pev->team = MOVETYPE_TOSS; pev->solid = SOLID_BBOX; break; case Fly: pev->team = MOVETYPE_FLY; break; case Toss: pev->team = MOVETYPE_TOSS; break; } } int CEnvShooter :: ParseGibFile( void ) { char *token; char *afile = (char *)LOAD_FILE( STRING( pev->message ), NULL ); const char *pfile = afile; if( !pfile ) { ALERT( at_warning, "Gib script file for %s not found!\n", STRING( pev->targetname )); return 0; } else { while( pfile ) { token = COM_ParseToken( &pfile ); if ( !FStriCmp( token, "model" )) { token = COM_ParseToken( &pfile ); m_sMaster = ALLOC_STRING( token ); } else if ( !FStriCmp( token, "entity" )) { token = COM_ParseToken( &pfile ); entity = ALLOC_STRING( token ); } else if ( !FStriCmp( token, "speed" )) { token = COM_ParseToken( &pfile ); velocity = RandomRange((char *)STRING(ALLOC_STRING(token))); } else if ( !FStriCmp( token, "variance" )) { token = COM_ParseToken( &pfile ); variance = RandomRange((char *)STRING(ALLOC_STRING(token))); } else if ( !FStriCmp( token, "livetime" )) { token = COM_ParseToken( &pfile ); lifetime = RandomRange((char *)STRING(ALLOC_STRING(token))); } else if ( !FStriCmp( token, "friction" )) { token = COM_ParseToken( &pfile ); RandomRange((char *)STRING(ALLOC_STRING(token))); pev->friction = RANDOM_FLOAT( m_flMin, m_flMax ); } else if ( !FStriCmp( token, "scale" )) { token = COM_ParseToken( &pfile ); RandomRange((char *)STRING(ALLOC_STRING(token))); pev->scale = RANDOM_FLOAT( m_flMin, m_flMax ); } else if ( !FStriCmp( token, "body" )) { token = COM_ParseToken( &pfile ); RandomRange((char *)STRING(ALLOC_STRING(token))); pev->body = RANDOM_FLOAT( m_flMin, m_flMax - 1 ); } else if ( !FStriCmp( token, "skin" )) { token = COM_ParseToken( &pfile ); RandomRange((char *)STRING(ALLOC_STRING(token))); pev->skin = RANDOM_FLOAT( m_flMin, m_flMax ); } else if ( !FStriCmp( token, "frame" )) { token = COM_ParseToken( &pfile ); RandomRange((char *)STRING(ALLOC_STRING(token))); pev->frame = RANDOM_FLOAT( m_flMin, m_flMax ); } else if ( !FStriCmp( token, "alpha" )) { token = COM_ParseToken( &pfile ); RandomRange((char *)STRING(ALLOC_STRING(token))); pev->renderamt = RANDOM_FLOAT( m_flMin, m_flMax ); } else if ( !FStriCmp( token, "color" )) { token = COM_ParseToken( &pfile ); UTIL_StringToVector((float *)pev->rendercolor, token ); } else if ( !FStriCmp( token, "rendermode" )) { token = COM_ParseToken( &pfile ); if ( !FStriCmp( token, "normal" )) pev->rendermode = kRenderNormal; else if ( !FStriCmp( token, "color" )) pev->rendermode = kRenderTransColor; else if ( !FStriCmp( token, "texture" )) pev->rendermode = kRenderTransTexture; else if ( !FStriCmp( token, "glow" )) pev->rendermode = kRenderGlow; else if ( !FStriCmp( token, "solid" )) pev->rendermode = kRenderTransAlpha; else if ( !FStriCmp( token, "additive" )) pev->rendermode = kRenderTransAdd; } else if ( !FStriCmp( token, "sfx" )) { token = COM_ParseToken( &pfile ); if ( !FStriCmp( token, "hologramm" )) pev->renderfx = kRenderFxHologram; else if ( !FStriCmp( token, "glowshell" )) pev->renderfx = kRenderFxGlowShell; } else if ( !FStriCmp( token, "size" )) { UTIL_StringToVector((float*)pev->size, token); pev->size = pev->size/2; } else if ( !FStriCmp( token, "material" )) { token = COM_ParseToken( &pfile ); if ( !FStriCmp( token, "none" )) m_Material = None; else if ( !FStriCmp( token, "bones" )) m_Material = Bones; else if ( !FStriCmp( token, "flesh" )) m_Material = Flesh; else if ( !FStriCmp( token, "cinder block" )) m_Material = CinderBlock; else if ( !FStriCmp( token, "concrete" )) m_Material = Concrete; else if ( !FStriCmp( token, "rocks" )) m_Material = Rocks; else if ( !FStriCmp( token, "computer" )) m_Material = Computer; else if ( !FStriCmp( token, "glass" )) m_Material = Glass; else if ( !FStriCmp( token, "metalplate" )) m_Material = MetalPlate; else if ( !FStriCmp( token, "metal" )) m_Material = Metal; else if ( !FStriCmp( token, "airduct" )) m_Material = AirDuct; else if ( !FStriCmp( token, "ceiling tile" )) m_Material = CeilingTile; else if ( !FStriCmp( token, "wood" )) m_Material = Wood; } else if ( !FStriCmp( token, "physics" )) { token = COM_ParseToken( &pfile ); if ( !FStriCmp( token, "bounce" )) m_Physics = Bounce; else if ( !FStriCmp( token, "sticky" )) m_Physics = Sticky; else if ( !FStriCmp( token, "noclip" )) m_Physics = Noclip; else if ( !FStriCmp( token, "fly" )) m_Physics = Fly; else if ( !FStriCmp( token, "toss" )) m_Physics = Toss; } } COM_FreeFile( afile ); if( FStringNull( m_sMaster) && FStringNull( entity )) { ALERT( at_warning, "model or entity not specified for %s\n", STRING( pev->targetname )); return 0; } return 1; } } CBaseEntity *CEnvShooter :: CreateGib ( Vector vecPos, Vector vecVel ) { if( !FStringNull( entity ))//custom precached entity { CBaseEntity *pEnt = CBaseEntity::CreateGib( (char *)STRING( entity ), (char *)STRING( m_sMaster)); //CBaseEntity *pEnt = CBaseEntity::Create( (char *)STRING( entity ), pev->origin, g_vecZero, edict() ); //if(!pEnt && pEnt->edict()) return NULL; if(!pEnt) return NULL; //UTIL_SetOrigin( pEnt, vecPos ); pEnt->pev->origin = vecPos; pEnt->pev->velocity = vecVel; pEnt->pev->renderamt = pev->renderamt; //pEnt->pev->model = m_sMaster; pEnt->pev->rendermode = pev->rendermode; pEnt->pev->rendercolor = pev->rendercolor; pEnt->pev->renderfx = pev->renderfx; pEnt->pev->target = pev->netname; pEnt->pev->skin = pev->skin; pEnt->pev->body = pev->body; pEnt->pev->scale = pev->scale; pEnt->pev->frame = pev->frame; pEnt->pev->friction = pev->friction; pEnt->pev->movetype = pev->team; pEnt->pev->solid = pev->solid; pEnt->pev->targetname = m_sSet; //UTIL_SetModel(ENT(pEnt->pev), m_sMaster ); return pEnt; } else if(m_Physics == Bounce || m_Physics == Sticky) // normal or sticky gib { CGib *pGib = CGib::CreateGib( NULL, (char *)STRING( m_sMaster ), m_Physics ); if(!pGib && pGib->edict()) return NULL; pGib->pev->body = pev->body; pGib->pev->origin = vecPos; pGib->pev->velocity = vecVel; pGib->m_material = m_Material; pGib->pev->rendermode = pev->rendermode; pGib->pev->renderamt = pev->renderamt; pGib->pev->rendercolor = pev->rendercolor; pGib->pev->renderfx = pev->renderfx; pGib->pev->target = pev->netname; pGib->pev->friction = pev->friction; pGib->pev->scale = pev->scale; pGib->pev->skin = pev->skin; pGib->pev->avelocity.x = RANDOM_FLOAT ( 100, 200 ); pGib->pev->avelocity.y = RANDOM_FLOAT ( 100, 300 ); pGib->m_lifeTime = pev->health; pGib->pev->scale = pev->scale; pGib->pev->frame = pev->frame; pGib->pev->targetname = m_sSet; return pGib; } else //not custom entity, other physics type { CShot *pShot = CShot::CreateShot ( (char *)STRING( m_sMaster ), pev->size ); if(!pShot && pShot->edict()) return NULL; pShot->pev->origin = vecPos; pShot->pev->velocity = vecVel; pShot->pev->renderamt = pev->renderamt; pShot->pev->rendermode = pev->rendermode; pShot->pev->rendercolor = pev->rendercolor; pShot->pev->renderfx = pev->renderfx; pShot->pev->target = pev->netname; pShot->pev->skin = pev->skin; pShot->pev->body = pev->body; pShot->pev->scale = pev->scale; pShot->pev->frame = pev->frame; pShot->pev->framerate = pev->framerate; pShot->pev->friction = pev->friction; pShot->pev->movetype = pev->team; pShot->pev->targetname = m_sSet; if (pev->health || pev->health == -1) { //animate it if (pShot->pev->framerate && pShot->Frames() > 1.0) { pShot->AnimateAndDie( 10 ); pShot->pev->dmg_take = gpGlobals->time + pev->health; pShot->SetNextThink( 0 ); pShot->pev->dmgtime = gpGlobals->time; } else if( pev->health ) { pShot->SetThink( Fadeout ); pShot->SetNextThink(pev->health); } else { pShot->SetThink( PVSRemove ); pShot->SetNextThink( MAX_GIB_LIFETIME ); } } return pShot; } return NULL; } //========================================================= // LRC - Decal effect //========================================================= class CEnvDecal : public CPointEntity { public: void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void KeyValue( KeyValueData *pkvd ); }; LINK_ENTITY_TO_CLASS( env_decal, CEnvDecal ); void CEnvDecal :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "texture")) { pev->message = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CEnvDecal::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if( useType == USE_SHOWINFO) { DEBUGHEAD; Msg("Decal name %s\n\n", GetStringForDecalName( pev->message )); } else { int m_decal = UTIL_LoadDecalPreset( pev->message ); switch(m_decal) { case 1: pev->skin = gDecals[ DECAL_GUNSHOT1 + RANDOM_LONG(0,4)].index; break; case 2: pev->skin = gDecals[ DECAL_BLOOD1 + RANDOM_LONG(0,5)].index; break; case 3: pev->skin = gDecals[ DECAL_YBLOOD1 + RANDOM_LONG(0,5)].index; break; case 4: pev->skin = gDecals[ DECAL_GLASSBREAK1 + RANDOM_LONG(0,2)].index; break; case 5: pev->skin = gDecals[ DECAL_BIGSHOT1 + RANDOM_LONG(0,4)].index; break; case 6: pev->skin = gDecals[ DECAL_SCORCH1 + RANDOM_LONG(0,1)].index; break; case 7: pev->skin = gDecals[ DECAL_SPIT1 + RANDOM_LONG(0,1)].index; break; default: pev->skin = DECAL_INDEX(STRING(m_decal)); break; } Vector vecPos = pev->origin; UTIL_MakeVectors(pev->angles); Vector vecOffs = gpGlobals->v_forward; vecOffs = vecOffs.Normalize() * MAP_HALFSIZE; TraceResult trace; UTIL_TraceLine( vecPos, vecPos+vecOffs, ignore_monsters, NULL, &trace ); if (trace.flFraction == 1.0) return; // didn't hit anything, oh well int entityIndex = (short)ENTINDEX(trace.pHit); SFX_Decal( trace.vecEndPos, pev->skin, entityIndex, (int)VARS(trace.pHit)->modelindex ); } } //========================================================= // env_warpball //========================================================= #define SF_REMOVE_ON_FIRE 0x0001 #define SF_KILL_CENTER 0x0002 class CEnvWarpBall : public CBaseLogic { public: void Precache( void ); void Spawn( void ) { Precache(); } void KeyValue( KeyValueData *pkvd ); void Think( void ); void Affect( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); Vector vecOrigin; }; LINK_ENTITY_TO_CLASS( env_warpball, CEnvWarpBall ); void CEnvWarpBall :: KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "radius")) { pev->button = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } if (FStrEq(pkvd->szKeyName, "warp_target")) { pev->message = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } if (FStrEq(pkvd->szKeyName, "damage_delay")) { pev->frags = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CBaseEntity::KeyValue( pkvd ); } void CEnvWarpBall::Precache( void ) { UTIL_PrecacheModel( "sprites/lgtning.spr" ); UTIL_PrecacheModel( "sprites/Fexplo1.spr" ); UTIL_PrecacheSound( "debris/beamstart2.wav" ); UTIL_PrecacheSound( "debris/beamstart7.wav" ); } void CEnvWarpBall::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { pActivator = m_hActivator; //save it for later if (useType == USE_TOGGLE || useType == USE_ON) Affect(); else if( useType == USE_SET && value > 10) pev->button = value; else if( useType == USE_RESET ) pev->button = 100; //default radius else if( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "Radius: %d, Warp target %s\n\n", pev->button, STRING( pev->message )); } } void CEnvWarpBall::Affect( void ) { int iTimes = 0; int iDrawn = 0; TraceResult tr; Vector vecDest; CBeam *pBeam; CBaseEntity *pEntity = UTIL_FindEntityByTargetname ( NULL, STRING(pev->message)); edict_t *pos; if(pEntity)//target found ? { vecOrigin = pEntity->pev->origin; pos = pEntity->edict(); } else { //use as center vecOrigin = pev->origin; pos = edict(); } EMIT_SOUND( pos, CHAN_BODY, "debris/beamstart2.wav", 1, ATTN_NORM ); UTIL_ScreenShake( vecOrigin, 6, 160, 1.0, pev->button ); CSprite *pSpr = CSprite::SpriteCreate( "sprites/Fexplo1.spr", vecOrigin, TRUE ); pSpr->SetTransparency(kRenderGlow, 77, 210, 130, 255, kRenderFxNoDissipation); pSpr->AnimateAndDie( 18 ); EMIT_SOUND( pos, CHAN_ITEM, "debris/beamstart7.wav", 1, ATTN_NORM ); int iBeams = RANDOM_LONG(20, 40); while (iDrawn < iBeams && iTimes < (iBeams * 3)) { vecDest = pev->button * (Vector(RANDOM_FLOAT(-1,1), RANDOM_FLOAT(-1,1), RANDOM_FLOAT(-1,1)).Normalize()); UTIL_TraceLine( vecOrigin, vecOrigin + vecDest, ignore_monsters, NULL, &tr); if (tr.flFraction != 1.0) { // we hit something. iDrawn++; pBeam = CBeam::BeamCreate("sprites/lgtning.spr", 200); pBeam->PointsInit( vecOrigin, tr.vecEndPos ); pBeam->SetColor( 20, 243, 20 ); pBeam->SetNoise( 65 ); pBeam->SetBrightness( 220 ); pBeam->SetWidth( 30 ); pBeam->SetScrollRate( 35 ); pBeam->SetThink( Remove ); pBeam->pev->nextthink = gpGlobals->time + RANDOM_FLOAT(0.5, 1.6); } iTimes++; } if ( pev->spawnflags & SF_REMOVE_ON_FIRE ) UTIL_Remove( this ); else SetNextThink( pev->frags ); } void CEnvWarpBall::Think( void ) { UTIL_FireTargets( pev->target, this, this, USE_TOGGLE ); if ( pev->spawnflags & SF_KILL_CENTER ) // Blue-Shift strange feature { CBaseEntity *pMonster = NULL; while ((pMonster = UTIL_FindEntityInSphere( pMonster, vecOrigin, 72 )) != NULL) { if ( FBitSet( pMonster->pev->flags, FL_MONSTER ) || FBitSet( pMonster->pev->flags, FL_CLIENT )) pMonster->TakeDamage ( pev, pev, 100, DMG_GENERIC ); } } if ( pev->spawnflags & SF_REMOVE_ON_FIRE ) UTIL_Remove( this ); } //======================================================================= // base beams () //======================================================================= LINK_ENTITY_TO_CLASS( beam, CBeam ); void CBeam::Spawn( void ) { pev->solid = SOLID_NOT; } const Vector &CBeam::GetStartPos( void ) { int type = GetType(); if( type == BEAM_ENTS ) { edict_t *pent = GetStartEntity(); if ( pent ) return pent->v.origin; } return pev->origin; } const Vector &CBeam::GetEndPos( void ) { int type = GetType(); if( type == BEAM_ENTS || type == BEAM_ENTPOINT ) { edict_t *pent = GetEndEntity(); if ( pent ) return pent->v.oldorigin; } return pev->oldorigin; } CBeam *CBeam::BeamCreate( const char *pSpriteName, int width ) { // Create a new entity with CBeam private data CBeam *pBeam = GetClassPtr( (CBeam *)NULL ); pBeam->pev->classname = MAKE_STRING( "beam" ); pBeam->BeamInit( pSpriteName, width ); return pBeam; } void CBeam::BeamInit( const char *pSpriteName, int width ) { SetObjectClass( ED_BEAM ); SetColor( 255, 255, 255 ); SetBrightness( 255 ); SetNoise( 0 ); SetFrame( 0 ); SetScrollRate( 0 ); pev->model = MAKE_STRING( pSpriteName ); SetTexture( UTIL_PrecacheModel( pev->model ) ); SetWidth( width ); pev->skin = 0; pev->sequence = 0; pev->rendermode = 0; } void CBeam::PointsInit( const Vector &start, const Vector &end ) { SetType( BEAM_POINTS ); SetStartPos( start ); SetEndPos( end ); SetStartAttachment( 0 ); SetEndAttachment( 0 ); RelinkBeam(); } void CBeam::HoseInit( const Vector &start, const Vector &direction ) { SetType( BEAM_HOSE ); SetStartPos( start ); SetEndPos( direction ); SetStartAttachment( 0 ); SetEndAttachment( 0 ); RelinkBeam(); } void CBeam::PointEntInit( const Vector &start, edict_t *pEnd ) { SetType( BEAM_ENTPOINT ); SetStartPos( start ); SetEndEntity( pEnd ); SetStartAttachment( 0 ); SetEndAttachment( 0 ); RelinkBeam(); } void CBeam::EntsInit( edict_t *pStart, edict_t *pEnd ) { SetType( BEAM_ENTS ); SetStartEntity( pStart ); SetEndEntity( pEnd ); SetStartAttachment( 0 ); SetEndAttachment( 0 ); RelinkBeam(); } void CBeam::RelinkBeam( void ) { const Vector &startPos = GetStartPos(), &endPos = GetEndPos(); pev->mins.x = min( startPos.x, endPos.x ); pev->mins.y = min( startPos.y, endPos.y ); pev->mins.z = min( startPos.z, endPos.z ); pev->maxs.x = max( startPos.x, endPos.x ); pev->maxs.y = max( startPos.y, endPos.y ); pev->maxs.z = max( startPos.z, endPos.z ); pev->mins = pev->mins - pev->origin; pev->maxs = pev->maxs - pev->origin; UTIL_SetSize( pev, pev->mins, pev->maxs ); UTIL_SetOrigin( this, pev->origin ); } void CBeam::SetObjectCollisionBox( void ) { const Vector &startPos = GetStartPos(), &endPos = GetEndPos(); pev->absmin.x = min( startPos.x, endPos.x ); pev->absmin.y = min( startPos.y, endPos.y ); pev->absmin.z = min( startPos.z, endPos.z ); pev->absmax.x = max( startPos.x, endPos.x ); pev->absmax.y = max( startPos.y, endPos.y ); pev->absmax.z = max( startPos.z, endPos.z ); } void CBeam::Touch( CBaseEntity *pOther ) { if ( pOther->pev->flags & (FL_CLIENT | FL_MONSTER) ) { if ( pev->owner ) { CBaseEntity *pOwner = CBaseEntity::Instance(pev->owner); pOwner->Use( pOther, this, USE_TOGGLE, 0 ); } } } CBaseEntity* CBeam::GetTripEntity( TraceResult *ptr ) { CBaseEntity* pTrip; if (ptr->flFraction == 1.0 || ptr->pHit == NULL) return NULL; pTrip = CBaseEntity::Instance(ptr->pHit); if (pTrip == NULL) return NULL; if (pTrip->pev->flags & (FL_CLIENT | FL_MONSTER ) && !pTrip->IsPushable())//physics ents can move too return pTrip; return NULL; } void CBeam::BeamDamage( TraceResult *ptr ) { RelinkBeam(); if ( ptr->flFraction != 1.0 && ptr->pHit != NULL ) { CBaseEntity *pHit = CBaseEntity::Instance(ptr->pHit); if ( pHit ) { if ( pev->dmg > 0 ) { ClearMultiDamage(); pHit->TraceAttack( pev, pev->dmg * (gpGlobals->time - pev->dmgtime), (ptr->vecEndPos - pev->origin).Normalize(), ptr, DMG_ENERGYBEAM ); ApplyMultiDamage( pev, pev ); if ( pev->dmg > 40 && pHit->IsBSPModel())//wall damage { UTIL_DecalTrace( ptr, DECAL_BIGSHOT1 + RANDOM_LONG(0,4) ); } } else pHit->TakeHealth( -(pev->dmg * (gpGlobals->time - pev->dmgtime)), DMG_GENERIC ); } } pev->dmgtime = gpGlobals->time; } CBaseEntity *CBeam::RandomTargetname( const char *szName ) { int total = 0; CBaseEntity *pEntity = NULL; CBaseEntity *pNewEntity = NULL; while ((pNewEntity = UTIL_FindEntityByTargetname( pNewEntity, szName )) != NULL) { total++; if (RANDOM_LONG(0,total-1) < 1) pEntity = pNewEntity; } return pEntity; } void CBeam::DoSparks( const Vector &start, const Vector &end ) { if ( pev->dmg > 100 ) UTIL_Sparks( start ); if ( pev->dmg > 40 ) UTIL_Sparks( end ); } //======================================================================= // env_beam - toggleable beam //======================================================================= class CEnvBeam : public CBeam { public: void Spawn( void ); void Precache( void ); void KeyValue( KeyValueData *pkvd ); void Activate( void ); void Think( void ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); int IsPointEntity( CBaseEntity *pEnt ); void BeamUpdatePoints( void ); void BeamUpdateVars( void ); CBaseEntity *pEnd; }; LINK_ENTITY_TO_CLASS( env_beam, CEnvBeam ); void CEnvBeam::Precache( void ) { pev->team = UTIL_PrecacheModel( pev->message, "sprites/laserbeam.spr" ); CBeam::Precache(); } int CEnvBeam::IsPointEntity( CBaseEntity *pEnt ) { if( pEnt->pev->modelindex && ( pEnt->m_iClassType != ED_BEAM )) return 0; return 1; } void CEnvBeam::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "endpoint")) { pev->netname = ALLOC_STRING( pkvd->szValue ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "damage")) { pev->dmg = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "sprite")) { pev->message = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "width")) { SetWidth( atoi(pkvd->szValue)); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "noisewidth")) { SetNoise( atoi(pkvd->szValue)); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "shade")) { pev->frags = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CBeam::KeyValue( pkvd ); } void CEnvBeam::BeamUpdateVars( void ) { pev->skin = 0; pev->sequence = 0; pev->rendermode = 0; SetTexture( pev->team ); BeamUpdatePoints(); SetFrame( 0 ); SetScrollRate( pev->speed ); if ( pev->frags == 1 ) SetFlags( FBEAM_SHADEIN ); if ( pev->frags == 2 ) SetFlags( FBEAM_SHADEOUT ); if ( pev->renderamt == 255 ) SetFlags( FBEAM_SOLID ); else SetFlags( 0 ); } void CEnvBeam::Activate( void ) { BeamUpdateVars(); CBeam::Activate(); } void CEnvBeam::BeamUpdatePoints( void ) { int beamType; pEnd = UTIL_FindEntityByTargetname ( NULL, STRING(pev->netname) ); if( !pEnd ) return; int pointEnd = IsPointEntity( pEnd ); beamType = BEAM_ENTS; if ( !pointEnd ) beamType = BEAM_ENTPOINT; else beamType = BEAM_POINTS; SetType( beamType ); if ( beamType == BEAM_POINTS || beamType == BEAM_ENTPOINT || beamType == BEAM_HOSE ) { SetStartPos( pev->origin ); if ( beamType == BEAM_POINTS || beamType == BEAM_HOSE ) SetEndPos( pEnd->pev->origin ); else SetEndEntity( ENT( pEnd->pev ) ); } else { SetStartEntity( ENT( pev ) ); SetEndEntity( ENT( pEnd->pev ) ); } RelinkBeam(); } void CEnvBeam::Spawn( void ) { SetObjectClass( ED_BEAM ); UTIL_SetModel( edict(), "sprites/null.spr" ); // beam start point pev->solid = SOLID_NOT; // remove model & collisions Precache(); if( FStringNull( pev->netname )) { ALERT( at_warning, "%s end entity not found!\n", STRING( pev->classname )); UTIL_Remove( this ); return; } pev->dmgtime = gpGlobals->time; if( pev->rendercolor == g_vecZero ) pev->rendercolor = Vector( 255, 255, 255 ); if( pev->spawnflags & SF_START_ON ) Use( this, this, USE_ON, 0 ); } void CEnvBeam::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if (useType == USE_TOGGLE) { if(m_iState == STATE_ON) useType = USE_OFF; else useType = USE_ON; } if (useType == USE_ON) { m_iState = STATE_ON; BeamUpdatePoints(); pev->effects &= ~EF_NODRAW; SetNextThink( 0 ); pev->dmgtime = gpGlobals->time; } else if (useType == USE_OFF) { m_iState = STATE_OFF; pev->effects |= EF_NODRAW; DontThink(); } else if(useType == USE_SET) //set new damage level { pev->dmg = value; } else if(useType == USE_RESET) //set new brightness { if(value)pev->renderamt = value; BeamUpdateVars(); } else if (useType == USE_SHOWINFO) { DEBUGHEAD; Msg( "State: %s, Damage %g\n", GetStringForState( GetState()), pev->dmg ); Msg("Beam model %s\n", STRING( pev->message )); } } void CEnvBeam::Think( void ) { if ( pev->dmg || !FStringNull( pev->target )) // apply damage & trip entity { TraceResult tr; UTIL_TraceLine( pev->origin, pEnd->pev->origin, dont_ignore_monsters, NULL, &tr ); BeamDamage( &tr ); CBaseEntity* pTrip = GetTripEntity( &tr ); if (pTrip) { if (!FBitSet(pev->spawnflags, SF_BEAM_TRIPPED)) { UTIL_FireTargets(pev->target, pTrip, this, USE_TOGGLE); pev->spawnflags |= SF_BEAM_TRIPPED; } } else pev->spawnflags &= ~SF_BEAM_TRIPPED; } SetNextThink( 0.1 ); } //======================================================================= // env_laser - classic HALF-LIFE laser //======================================================================= LINK_ENTITY_TO_CLASS( env_laser, CLaser ); TYPEDESCRIPTION CLaser::m_SaveData[] = { DEFINE_FIELD( CLaser, m_pStartSprite, FIELD_CLASSPTR ), DEFINE_FIELD( CLaser, m_pEndSprite, FIELD_CLASSPTR ), }; IMPLEMENT_SAVERESTORE( CLaser, CBeam ); void CLaser::Spawn( void ) { SetObjectClass( ED_BEAM ); pev->frame = 0; pev->solid = SOLID_NOT; // Remove model & collisions Precache(); } void CLaser::Activate( void ) { if ( m_pStartSprite && m_pEndSprite ) EntsInit( m_pStartSprite->edict(), m_pEndSprite->edict() ); } void CLaser::SetObjectCollisionBox( void ) { if ( m_pStartSprite && m_pEndSprite ) { const Vector &startPos = m_pStartSprite->pev->origin, &endPos = m_pEndSprite->pev->origin; pev->absmin.x = min( startPos.x, endPos.x ); pev->absmin.y = min( startPos.y, endPos.y ); pev->absmin.z = min( startPos.z, endPos.z ); pev->absmax.x = max( startPos.x, endPos.x ); pev->absmax.y = max( startPos.y, endPos.y ); pev->absmax.z = max( startPos.z, endPos.z ); } else { pev->absmin = g_vecZero; pev->absmax = g_vecZero; } } void CLaser::PostSpawn( void ) { if ( !FStringNull( pev->netname )) { m_pStartSprite = CSprite::SpriteCreate( STRING( pev->netname ), pev->origin, TRUE ); if ( m_pStartSprite ) m_pStartSprite->SetTransparency( kRenderGlow, pev->rendercolor.x, pev->rendercolor.y, pev->rendercolor.z, pev->renderamt, pev->renderfx ); else m_pStartSprite = CSprite::SpriteCreate( "sprites/null.spr", pev->origin, TRUE ); } else m_pStartSprite = CSprite::SpriteCreate( "sprites/null.spr", pev->origin, TRUE ); m_pEndSprite = CSprite::SpriteCreate( "sprites/null.spr", pev->origin, TRUE ); if ( pev->spawnflags & SF_START_ON ) { TurnOn(); } else { TurnOff(); } } void CLaser::Precache( void ) { UTIL_PrecacheModel( pev->message, "sprites/laserbeam.spr" ); if( pev->netname ) UTIL_PrecacheModel( pev->netname ); } void CLaser::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "sprite")) { pev->message = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "startsprite")) { pev->netname = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "width")) { SetWidth( atof(pkvd->szValue) ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "noisewidth")) { SetNoise( atoi(pkvd->szValue) ); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "damage")) { pev->dmg = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else CBeam::KeyValue( pkvd ); } void CLaser::TurnOff( void ) { SetBits(pev->effects, EF_NODRAW ); m_iState = STATE_OFF; if ( m_pStartSprite ) { m_pStartSprite->TurnOff(); UTIL_SetVelocity(m_pStartSprite, g_vecZero); } if ( m_pEndSprite ) { m_pEndSprite->TurnOff(); UTIL_SetVelocity(m_pEndSprite, g_vecZero); } DontThink(); } void CLaser::TurnOn( void ) { ClearBits( pev->effects, EF_NODRAW ); if ( m_pStartSprite ) m_pStartSprite->TurnOn(); if ( m_pEndSprite ) m_pEndSprite->TurnOn(); pev->dmgtime = gpGlobals->time; m_iState = STATE_ON; SetScrollRate( pev->speed ); SetFlags( FBEAM_SHADEOUT ); SetNextThink( 0 ); } void CLaser::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if (useType == USE_TOGGLE) { if(m_iState == STATE_ON) useType = USE_OFF; else useType = USE_ON; } if ( useType == USE_ON ) TurnOn(); else if ( useType == USE_OFF ) TurnOff(); else if ( useType == USE_SET ) // set new damage level { pev->dmg = value; } else if( useType == USE_RESET ) // set new brightness { if( value ) pev->renderamt = value; RelinkBeam(); } else if ( useType == USE_SHOWINFO ) { DEBUGHEAD; ALERT( at_console, "State: %s, Damage %g\n", GetStringForState( GetState()), pev->dmg ); ALERT( at_console, "Laser model %s\n", STRING( pev->message )); } } void CLaser::FireAtPoint( Vector startpos, TraceResult &tr ) { if ( m_pStartSprite && m_pEndSprite ) { UTIL_SetVelocity( m_pStartSprite, ( startpos - m_pStartSprite->pev->origin ) * 100 ); UTIL_SetVelocity( m_pEndSprite, ( tr.vecEndPos - m_pEndSprite->pev->origin ) * 100 ); } BeamDamage( &tr ); DoSparks( startpos, tr.vecEndPos ); } void CLaser:: Think( void ) { Vector startpos = pev->origin; TraceResult tr; UTIL_MakeVectors( pev->angles ); Vector vecProject = startpos + gpGlobals->v_forward * MAP_HALFSIZE; UTIL_TraceLine( startpos, vecProject, dont_ignore_monsters, ignore_glass, NULL, &tr ); FireAtPoint( startpos, tr ); if( m_iState == STATE_ON ) SetNextThink( 0.01 ); //!!! } //========================================================= // env_lightning - random zap strike //========================================================= class CEnvLightning : public CBeam { public: void Spawn( void ); void Precache( void ); void KeyValue( KeyValueData *pkvd ); void Think( void ); void RandomPoint( Vector &vecSrc ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void BeamDamage( TraceResult *ptr ); }; LINK_ENTITY_TO_CLASS( env_lightning, CEnvLightning ); void CEnvLightning::Precache( void ) { pev->team = UTIL_PrecacheModel( pev->message, "sprites/laserbeam.spr" ); CBeam::Precache(); } void CEnvLightning::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "lifetime"))//beam lifetime (leave blank for toggle beam) { pev->armorvalue = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "damage")) { pev->dmg = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "sprite")) { pev->message = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "width")) { pev->button = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "noisewidth")) { pev->impulse = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "radius")) { pev->frags = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBeam::KeyValue( pkvd ); } void CEnvLightning::BeamDamage( TraceResult *ptr ) { RelinkBeam(); if ( ptr->flFraction != 1.0 && ptr->pHit != NULL ) { CBaseEntity *pHit = CBaseEntity::Instance(ptr->pHit); if ( pHit ) { if (pev->dmg > 0) { ClearMultiDamage(); pHit->TraceAttack( pev, pev->dmg * (gpGlobals->time - pev->dmgtime), (ptr->vecEndPos - pev->origin).Normalize(), ptr, DMG_ENERGYBEAM ); ApplyMultiDamage( pev, pev ); if ( pev->dmg > 40 && pHit->IsBSPModel())//wall damage { UTIL_DecalTrace( ptr, DECAL_BIGSHOT1 + RANDOM_LONG(0,4) ); } } else pHit->TakeHealth( -(pev->dmg * (gpGlobals->time - pev->dmgtime)), DMG_GENERIC ); } } pev->dmgtime = gpGlobals->time; } void CEnvLightning::RandomPoint( Vector &vecSrc ) { int iLoops = 0; for (iLoops = 0; iLoops < 10; iLoops++) { Vector vecDir1 = Vector( RANDOM_FLOAT( -1.0, 1.0 ), RANDOM_FLOAT( -1.0, 1.0 ),RANDOM_FLOAT( -1.0, 1.0 ) ); vecDir1 = vecDir1.Normalize(); TraceResult tr1; UTIL_TraceLine( vecSrc, vecSrc + vecDir1 * pev->frags, ignore_monsters, ENT(pev), &tr1 ); if ((tr1.vecEndPos - vecSrc).Length() < pev->frags * 0.1) continue; if (tr1.flFraction == 1.0) continue; SFX_Zap ( pev, vecSrc, tr1.vecEndPos ); DoSparks( vecSrc, tr1.vecEndPos ); BeamDamage( &tr1 ); UTIL_FireTargets( pev->target, this, this, USE_TOGGLE ); break; } } void CEnvLightning::Spawn( void ) { UTIL_SetModel(edict(), "sprites/null.spr");//beam start point pev->solid = SOLID_NOT; // Remove model & collisions Precache(); pev->dmgtime = gpGlobals->time; if (pev->rendercolor == g_vecZero) pev->rendercolor = Vector(255, 255, 255); if(pev->spawnflags & SF_START_ON) Use( this, this, USE_ON, 0 ); } void CEnvLightning::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if (useType == USE_TOGGLE) { if(m_iState == STATE_ON) useType = USE_OFF; else useType = USE_ON; } if (useType == USE_ON) { m_iState = STATE_ON; pev->effects &= ~EF_NODRAW; SetNextThink( 0 ); pev->dmgtime = gpGlobals->time; } else if (useType == USE_OFF) { m_iState = STATE_OFF; pev->effects |= EF_NODRAW; DontThink(); } else if(useType == USE_SET) { } else if (useType == USE_SHOWINFO) { DEBUGHEAD; ALERT( at_console, "State: %s, MaxDelay %.2f\n\n", GetStringForState( GetState()), m_flDelay ); } } void CEnvLightning::Think( void ) { RandomPoint( pev->origin ); SetNextThink( pev->armorvalue + RANDOM_FLOAT( 0, m_flDelay ) ); } //======================================================================= // env_beamring - make ring from beams //======================================================================= class CEnvBeamRing : public CBeam { public: void Spawn( void ); void Think( void ); void Precache( void ); void KeyValue( KeyValueData *pkvd ); void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); }; LINK_ENTITY_TO_CLASS( env_beamring, CEnvBeamRing ); void CEnvBeamRing::Precache( void ) { pev->team = UTIL_PrecacheModel( pev->message, "sprites/laserbeam.spr" ); CBeam::Precache(); } void CEnvBeamRing::KeyValue( KeyValueData *pkvd ) { if (FStrEq(pkvd->szKeyName, "lifetime"))//beam lifetime (leave blank for toggle beam) { pev->armorvalue = atof(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "sprite")) { pev->message = ALLOC_STRING(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "width")) { pev->button = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "noisewidth")) { pev->impulse = atoi(pkvd->szValue); pkvd->fHandled = TRUE; } else if (FStrEq(pkvd->szKeyName, "radius")) { pev->frags = atof( pkvd->szValue ); pkvd->fHandled = TRUE; } else CBeam::KeyValue( pkvd ); } void CEnvBeamRing::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if (useType == USE_TOGGLE) { if(m_iState == STATE_ON) useType = USE_OFF; else useType = USE_ON; } if (useType == USE_ON) { m_iState = STATE_ON; pev->effects &= ~EF_NODRAW; SetNextThink( 0 ); pev->dmgtime = gpGlobals->time; } else if (useType == USE_OFF) { m_iState = STATE_OFF; pev->effects |= EF_NODRAW; DontThink(); } else if(useType == USE_SET) { } else if (useType == USE_SHOWINFO) { DEBUGHEAD; ALERT( at_console, "State: %s, MaxDelay %.2f\n\n", GetStringForState( GetState()), m_flDelay ); } } void CEnvBeamRing::Spawn( void ) { UTIL_SetModel(edict(), "sprites/null.spr");//beam start point pev->solid = SOLID_NOT; // Remove model & collisions Precache(); pev->dmgtime = gpGlobals->time; if (pev->rendercolor == g_vecZero) pev->rendercolor = Vector(255, 255, 255); if(pev->frags == 0)pev->frags = 20; //create second point Vector vecAngles, vecPos; vecAngles = pev->angles; UTIL_MakeVectors(vecAngles); vecPos = pev->origin + (gpGlobals->v_forward * pev->frags); CBaseEntity *pRing = CBaseEntity::Create( "info_target", vecPos, vecAngles, edict() ); if(m_iParent)pRing->m_iParent = m_iParent; pev->enemy = pRing->edict(); //save our pointer if(pev->spawnflags & SF_START_ON) Use( this, this, USE_ON, 0 ); } void CEnvBeamRing::Think( void ) { CBaseEntity *pRing = CBaseEntity::Instance(pev->enemy); SFX_Ring( pev, pRing->pev ); SetNextThink( pev->armorvalue + RANDOM_FLOAT( 0, m_flDelay ) ); }
[ [ [ 1, 2913 ] ] ]
eb3c0e856c1678026ea36ea9a1a5fca5f843b355
515e917815568d213e75bfcbd3fb9f0e08cf2677
/common/math/geometry.h
af54aa7381324bb7743a188ccdd1fe8e8d27c1fa
[ "BSD-2-Clause" ]
permissive
dfk789/CodenameInfinite
bd183aec6b9e60e20dda6764d99f4e8d8a945add
aeb88b954b65f6beca3fb221fe49459b75e7c15f
refs/heads/master
2020-05-30T15:46:20.450963
2011-10-15T00:21:38
2011-10-15T00:21:38
5,652,791
2
0
null
null
null
null
UTF-8
C++
false
false
14,719
h
#ifndef LW_GEOMETRY_H #define LW_GEOMETRY_H #include "vector.h" #include <EASTL/vector.h> class Rect { public: Rect() { x = 0; y = 0; w = 0; h = 0; } Rect(int X, int Y, int W, int H) { x = X; y = Y; w = W; h = H; } int x, y, w, h; }; class Ray { public: Ray(Vector vecPos, Vector vecDir); Vector m_vecPos; Vector m_vecDir; }; inline Ray::Ray(Vector vecPos, Vector vecDir) { m_vecPos = vecPos; m_vecDir = vecDir; } class AABB { public: AABB() {}; AABB(Vector vecMins, Vector vecMaxs); Vector Center() const; Vector Size() const; bool Inside(const AABB& oBox) const; bool Intersects(const AABB& oBox) const; Vector m_vecMins; Vector m_vecMaxs; }; inline AABB::AABB(Vector vecMins, Vector vecMaxs) { m_vecMins = vecMins; m_vecMaxs = vecMaxs; } inline Vector AABB::Center() const { return (m_vecMins + m_vecMaxs)/2; } inline Vector AABB::Size() const { return m_vecMaxs - m_vecMins; } inline bool AABB::Inside(const AABB& oBox) const { if (m_vecMins.x < oBox.m_vecMins.x) return false; if (m_vecMins.y < oBox.m_vecMins.y) return false; if (m_vecMins.z < oBox.m_vecMins.z) return false; if (m_vecMins.x > oBox.m_vecMins.x) return false; if (m_vecMins.y > oBox.m_vecMins.y) return false; if (m_vecMins.z > oBox.m_vecMins.z) return false; return true; } inline bool AABB::Intersects(const AABB& oBox) const { if (m_vecMins.x > oBox.m_vecMaxs.x) return false; if (oBox.m_vecMins.x > m_vecMaxs.x) return false; if (m_vecMins.y > oBox.m_vecMaxs.y) return false; if (oBox.m_vecMins.y > m_vecMaxs.y) return false; if (m_vecMins.z > oBox.m_vecMaxs.z) return false; if (oBox.m_vecMins.z > m_vecMaxs.z) return false; return true; } // Geometry-related functions inline bool SameSide(Vector p1, Vector p2, Vector a, Vector b) { Vector ba = b-a; Vector cp1 = ba.Cross(p1-a); Vector cp2 = ba.Cross(p2-a); return (cp1.Dot(cp2) > 0); } inline bool PointInTriangle(Vector p, Vector a, Vector b, Vector c) { return (SameSide(p, a, b, c) && SameSide(p, b, a, c) && SameSide(p, c, a, b)); } inline float DistanceToLine(Vector p, Vector v1, Vector v2) { Vector v = v2 - v1; Vector w = p - v1; float c1 = w.Dot(v); float c2 = v.Dot(v); float b = c1/c2; Vector vb = v1 + v*b; return (vb - p).Length(); } inline float DistanceToLineSegment(Vector p, Vector v1, Vector v2, Vector* i = NULL) { Vector v = v2 - v1; Vector w = p - v1; float c1 = w.Dot(v); if (c1 < 0) { if (i) *i = v1; return (v1-p).Length(); } float c2 = v.Dot(v); if (c2 < c1) { if (i) *i = v2; return (v2-p).Length(); } if (c2 < 0.001f) return 0; float b = c1/c2; Vector vb = v1 + v*b; if (i) *i = vb; return (vb - p).Length(); } inline float DistanceToPlane(Vector p, Vector v, Vector n) { float sb, sn, sd; sn = -n.Dot(p - v); sd = n.Dot(n); sb = sn/sd; Vector b = p + n * sb; return (p - b).Length(); } inline float DistanceToPolygon(Vector p, eastl::vector<Vector>& v, Vector n) { float flPlaneDistance = DistanceToPlane(p, v[0], n); size_t i; bool bFoundPoint = false; for (i = 0; i < v.size()-2; i++) { if (PointInTriangle(p, v[0], v[i+1], v[i+2])) { bFoundPoint = true; break; } } if (bFoundPoint) return flPlaneDistance; float flClosestPoint = -1; for (i = 0; i < v.size(); i++) { float flPointDistance = (v[i] - p).Length(); if (flClosestPoint == -1 || (flPointDistance < flClosestPoint)) flClosestPoint = flPointDistance; float flLineDistance; if (i == v.size() - 1) flLineDistance = DistanceToLineSegment(p, v[i], v[0]); else flLineDistance = DistanceToLineSegment(p, v[i], v[i+1]); if (flClosestPoint == -1 || (flLineDistance < flClosestPoint)) flClosestPoint = flLineDistance; } return flClosestPoint; } inline float TriangleArea(Vector a, Vector b, Vector c) { return (a-b).Cross(a-c).Length()/2; } inline bool RayIntersectsTriangle(Ray vecRay, Vector v0, Vector v1, Vector v2, Vector* pvecHit = NULL) { Vector u = v1 - v0; Vector v = v2 - v0; Vector n = u.Cross(v); Vector w0 = vecRay.m_vecPos - v0; float a = -n.Dot(w0); float b = n.Dot(vecRay.m_vecDir); float ep = 1e-4f; if (fabs(b) < ep) { if (a == 0) // Ray is parallel return false; // Ray is inside plane else return false; // Ray is somewhere else } float r = a/b; if (r < 0) return false; // Ray goes away from the triangle Vector vecPoint = vecRay.m_vecPos + vecRay.m_vecDir*r; if (pvecHit) *pvecHit = vecPoint; float uu = u.Dot(u); float uv = u.Dot(v); float vv = v.Dot(v); Vector w = vecPoint - v0; float wu = w.Dot(u); float wv = w.Dot(v); float D = uv * uv - uu * vv; float s, t; s = (uv * wv - vv * wu) / D; if (s < 0 || s > 1) // Intersection point is outside the triangle return false; t = (uv * wu - uu * wv) / D; if (t < 0 || (s+t) > 1) // Intersection point is outside the triangle return false; return true; } inline bool ClipRay(float flMin, float flMax, float a, float d, float& tmin, float& tmax) { const float flEpsilon = 1e-5f; if (fabs(d) < flEpsilon) { if (d >= 0.0f) return (a <= flMax); else return (a >= flMin); } float umin = (flMin - a)/d; float umax = (flMax - a)/d; if (umin > umax) { float yar = umin; umin = umax; umax = yar; } if (umax < tmin || umin > tmax) return false; tmin = (umin>tmin)?umin:tmin; tmax = (umax<tmax)?umax:tmax; return (tmax>tmin); } inline bool RayIntersectsAABB(const Ray& r, const AABB& b) { float tmin = 0; float tmax = b.Size().LengthSqr(); // It's a ray so make tmax effectively infinite. if (tmax < 1) tmax = 100; float flDistToBox = (r.m_vecPos - b.Center()).LengthSqr(); if (flDistToBox < 1) flDistToBox = 100; tmax *= flDistToBox * 100; if (!ClipRay(b.m_vecMins.x, b.m_vecMaxs.x, r.m_vecPos.x, r.m_vecDir.x, tmin, tmax)) return false; if (!ClipRay(b.m_vecMins.y, b.m_vecMaxs.y, r.m_vecPos.y, r.m_vecDir.y, tmin, tmax)) return false; if (!ClipRay(b.m_vecMins.z, b.m_vecMaxs.z, r.m_vecPos.z, r.m_vecDir.z, tmin, tmax)) return false; return true; } inline bool ClipSegment(float flMin, float flMax, float a, float b, float d, float& tmin, float& tmax) { const float flEpsilon = 1e-5f; if (fabs(d) < flEpsilon) { if (d >= 0.0f) return !(b < flMin || a > flMax); else return !(a < flMin || b > flMax); } float umin = (flMin - a)/d; float umax = (flMax - a)/d; if (umin > umax) { float yar = umin; umin = umax; umax = yar; } if (umax < tmin || umin > tmax) return false; tmin = (umin>tmin)?umin:tmin; tmax = (umax<tmax)?umax:tmax; return (tmax>tmin); } inline bool SegmentIntersectsAABB(const Vector& v1, const Vector& v2, const AABB& b) { float tmin = 0; float tmax = 1; Vector vecDir = v2 - v1; if (!ClipSegment(b.m_vecMins.x, b.m_vecMaxs.x, v1.x, v2.x, vecDir.x, tmin, tmax)) return false; if (!ClipSegment(b.m_vecMins.y, b.m_vecMaxs.y, v1.y, v2.y, vecDir.y, tmin, tmax)) return false; if (!ClipSegment(b.m_vecMins.z, b.m_vecMaxs.z, v1.z, v2.z, vecDir.z, tmin, tmax)) return false; return true; } inline bool LineSegmentIntersectsTriangle(Vector s0, Vector s1, Vector v0, Vector v1, Vector v2, Vector* pvecHit = NULL) { Vector u = v1 - v0; Vector v = v2 - v0; Vector n = u.Cross(v); Vector w0 = s0 - v0; float a = -n.Dot(w0); float b = n.Dot(s1-s0); float ep = 1e-4f; if (fabs(b) < ep) { if (a == 0) // Segment is parallel return true; // Segment is inside plane else return false; // Segment is somewhere else } float r = a/b; if (r < 0) return false; // Segment goes away from the triangle if (r > 1) return false; // Segment goes away from the triangle Vector vecPoint = s0 + (s1-s0)*r; if (pvecHit) *pvecHit = vecPoint; float uu = u.Dot(u); float uv = u.Dot(v); float vv = v.Dot(v); Vector w = vecPoint - v0; float wu = w.Dot(u); float wv = w.Dot(v); float D = uv * uv - uu * vv; float s, t; s = (uv * wv - vv * wu) / D; if (s <= ep || s >= 1) // Intersection point is outside the triangle return false; t = (uv * wu - uu * wv) / D; if (t <= ep || (s+t) >= 1) // Intersection point is outside the triangle return false; return true; } inline bool LineSegmentIntersectsSphere(const Vector& v1, const Vector& v2, const Vector& s, float flRadius, Vector& vecPoint) { Vector vecLine = v2 - v1; Vector vecSphere = v1 - s; float flA = vecLine.LengthSqr(); float flB = 2 * vecSphere.Dot(vecLine); float flC1 = s.LengthSqr() + v1.LengthSqr(); float flC2 = (s.Dot(v1)*2); float flC = flC1 - flC2 - flRadius*flRadius; float flBB4AC = flB*flB - 4*flA*flC; if (flBB4AC < 0) return false; float flSqrt = sqrt(flBB4AC); float flPlus = (-flB + flSqrt)/(2*flA); float flMinus = (-flB - flSqrt)/(2*flA); return false; // Unimplemented: Doesn't clip the intersection to the segment only. // Also probably buggy and fully of bugs. // See sp_common.cpp for a better implementation that's actually used. float flDistance = vecLine.Length(); Vector vecDirection = vecLine / flDistance; Vector vecPlus = v1 + vecDirection * (flPlus * flDistance); Vector vecMinus = v1 + vecDirection * (flMinus * flDistance); if ((vecPlus - v1).LengthSqr() < (vecMinus - v1).LengthSqr()) vecPoint = vecPlus; else vecPoint = vecMinus; return true; } inline bool PointInsideAABB( AABB oBox, Vector v ) { const float flEpsilon = 1e-4f; for (size_t i = 0; i < 3; i++) { float flVI = v[i]; if (flVI < oBox.m_vecMins[i] - flEpsilon || flVI > oBox.m_vecMaxs[i] + flEpsilon) return false; } return true; } inline bool TriangleIntersectsAABB( AABB oBox, Vector v0, Vector v1, Vector v2) { // Trivial case rejection: If any of the points are inside the box, return true immediately. if (PointInsideAABB(oBox, v0)) return true; if (PointInsideAABB(oBox, v1)) return true; if (PointInsideAABB(oBox, v2)) return true; size_t i; // Trivial case rejection: If all three points are on one side of the box then the triangle must be outside of it. for (i = 0; i < 3; i++) { float flBoxMax = oBox.m_vecMaxs[i]; float flBoxMin = oBox.m_vecMins[i]; float flV0 = v0[i]; float flV1 = v1[i]; float flV2 = v2[i]; if (flV0 > flBoxMax && flV1 > flBoxMax && flV2 > flBoxMax) return false; if (flV0 < flBoxMin && flV1 < flBoxMin && flV2 < flBoxMin) return false; } if (SegmentIntersectsAABB(v0, v1, oBox)) return true; if (SegmentIntersectsAABB(v1, v2, oBox)) return true; if (SegmentIntersectsAABB(v0, v2, oBox)) return true; Vector c0 = oBox.m_vecMins; Vector c1 = Vector(oBox.m_vecMins.x, oBox.m_vecMins.y, oBox.m_vecMaxs.z); Vector c2 = Vector(oBox.m_vecMins.x, oBox.m_vecMaxs.y, oBox.m_vecMins.z); Vector c3 = Vector(oBox.m_vecMins.x, oBox.m_vecMaxs.y, oBox.m_vecMaxs.z); Vector c4 = Vector(oBox.m_vecMaxs.x, oBox.m_vecMins.y, oBox.m_vecMins.z); Vector c5 = Vector(oBox.m_vecMaxs.x, oBox.m_vecMins.y, oBox.m_vecMaxs.z); Vector c6 = Vector(oBox.m_vecMaxs.x, oBox.m_vecMaxs.y, oBox.m_vecMins.z); Vector c7 = oBox.m_vecMaxs; // Build a list of line segments in the cube to test against the triangle. Vector aLines[32]; // Bottom four aLines[0] = c0; aLines[1] = c1; aLines[2] = c1; aLines[3] = c2; aLines[4] = c2; aLines[5] = c3; aLines[6] = c3; aLines[7] = c0; // Sides aLines[8] = c0; aLines[9] = c4; aLines[10] = c1; aLines[11] = c5; aLines[12] = c2; aLines[13] = c6; aLines[14] = c3; aLines[15] = c7; // Top aLines[16] = c4; aLines[17] = c5; aLines[18] = c5; aLines[19] = c6; aLines[20] = c6; aLines[21] = c7; aLines[22] = c7; aLines[23] = c4; // Diagonals aLines[24] = c0; aLines[25] = c6; aLines[26] = c1; aLines[27] = c7; aLines[28] = c2; aLines[29] = c4; aLines[30] = c3; aLines[31] = c5; // If any of the segments intersects with the triangle then we have a winner. for (i = 0; i < 32; i+=2) { if (LineSegmentIntersectsTriangle(aLines[i], aLines[i+1], v0, v1, v2)) return true; } return false; } inline size_t FindEar(const eastl::vector<Vector>& avecPoints) { size_t iPoints = avecPoints.size(); // A triangle is always an ear. if (iPoints <= 3) return 0; size_t i; Vector vecFaceNormal; // Calculate the face normal. for (i = 0; i < iPoints; i++) { size_t iNext = (i+1)%iPoints; Vector vecPoint = avecPoints[i]; Vector vecNextPoint = avecPoints[iNext]; vecFaceNormal.x += (vecPoint.y - vecNextPoint.y) * (vecPoint.z + vecNextPoint.z); vecFaceNormal.y += (vecPoint.z - vecNextPoint.z) * (vecPoint.x + vecNextPoint.x); vecFaceNormal.z += (vecPoint.x - vecNextPoint.x) * (vecPoint.y + vecNextPoint.y); } vecFaceNormal.Normalize(); for (i = 0; i < iPoints; i++) { size_t iLast = i==0?iPoints-1:i-1; size_t iNext = i==iPoints-1?0:i+1; Vector vecLast = avecPoints[iLast]; Vector vecThis = avecPoints[i]; Vector vecNext = avecPoints[iNext]; // Concave ones can not be ears. if ((vecLast-vecThis).Cross(vecLast-vecNext).Dot(vecFaceNormal) < 0) continue; bool bFoundPoint = false; for (size_t j = 0; j < iPoints; j++) { if (j == i || j == iLast || j == iNext) continue; if (PointInTriangle(avecPoints[j], vecLast, vecThis, vecNext)) { bFoundPoint = true; break; } } if (!bFoundPoint) return i; } return 0; } inline void FindLaunchVelocity(const Vector& vecOrigin, const Vector& vecTarget, float flGravity, Vector& vecForce, float& flTime, float flCurve = -0.03f) { Vector vecDistance = vecTarget - vecOrigin; float flY = vecDistance.y; vecDistance.y = 0; float flX = vecDistance.Length(); float flA = flCurve; float flH = (flX*flX - (flY/flA))/(2*flX); float flK = -flA*flH*flH; float flB = -2*flH*flA; float flForce = sqrt(2*-flGravity*flK); float flTimeToVertex = -flForce/flGravity; float flTimeToLand = sqrt(2*-(flK-flY)/flGravity); flTime = flTimeToVertex + flTimeToLand; Vector vecDirection = vecDistance.Normalized() * flX / flTime; vecDirection.y = flForce; vecForce = vecDirection; } #endif
[ [ [ 1, 6 ], [ 29, 457 ], [ 461, 469 ], [ 475, 700 ] ], [ [ 7, 28 ], [ 458, 460 ], [ 470, 474 ] ] ]
36762fa2b3dc6ccd92a330edd221b14eac23d177
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Application/SysCAD/GRFDOC/GRFCMCMD.CPP
7e12ae4b3d6b657747f402a4652646dc53c2ed78
[]
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
5,669
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #define __GRFCMCMD_CPP #include "sc_defs.h" #include "syscad.h" #include "gpfuncs.h" #include "gpwfuncs.h" #include "dlgbusy.h" #include "fixedit.h" #include "executiv.h" #include "drwhdr.h" #include "grf3drw.h" #include "cmdmenu.h" #include "grfcmcmd.h" #include "grfwnd.h" #include "grfdoc.h" #include "errorlog.h" #include "debugnew.h" // must follow all IMPLEMENT_DYNCREATE & IMPLEMENT_SERIAL #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif //=========================================================================== GrfComCmdBlk::GrfComCmdBlk(int ExtraCmds, int ExtraCIS): DocCmdBlk(10+ExtraCmds, 0+ExtraCIS) { //pDoc=NULL; pDsp=NULL; //pWnd=NULL; pGrf=NULL; pMdl=NULL; EO_Register("RootCmds", EOExec_None, 0, 0); } //--------------------------------------------------------------------------- GrfComCmdBlk::~GrfComCmdBlk() { EO_DeRegister(); } //--------------------------------------------------------------------------- void GrfComCmdBlk::InitForCmd() { } //--------------------------------------------------------------------------- void GrfComCmdBlk::OnActivateDoc(flag bActivate) { }; //--------------------------------------------------------------------------- /* void GrfComCmdBlk::OpenVNT() { }; */ //--------------------------------------------------------------------------- void GrfComCmdBlk::BuildVNT() { SETVNT("ACTivate", "Flwsheet_Cmds", N_A, 1, (CmdFn)&GrfCmdBlk::DoActivate, EF_ERS); SETVNT("ACTivate", "Instrument_Cmds", N_A, 1, (CmdFn)&GrfCmdBlk::DoActivate, EF_ERS); //SETVNT("LOad", "DOcument", AName, 1, (CmdFn)&GrfCmdBlk::DoLoad, EF_ERS); //SETVNT("SAve", "DOcument", AName, 1, (CmdFn)&GrfCmdBlk::DoSave, EF_ERS); //SETVNT("CLear", "DOcument", N_A, 1, (CmdFn)&GrfCmdBlk::DoClear, EF_ERS); SETCIS(ID_GRF_FlowsheetCommands, "ACTIVATE FLWSHEET_CMDS\r"); //VERIFY(NCmds<MaxCmds); //TRACE("Open Root VNT"); DocCmdBlk::BuildVNT(); } //--------------------------------------------------------------------------- void GrfComCmdBlk::DoActivate() { switch (When) { case EX_EXEC: { CGrfDoc*pGDoc=(CGrfDoc*)pDoc; switch (Noun) { case 1: pGDoc->pCurrentCB=&pGDoc->FCB; break; case 2: // pGDoc->pCurrentCB=&pGDoc->ICB; break; } /** CFrameWnd *pWndFrame= (CFrameWnd *)pWnd->GetParent(); ASSERT(pWndFrame->IsKindOf(RUNTIME_CLASS(CFrameWnd))); SysCAD.m_pMainWnd->PostMessage(WM_USER_ACTCMD, 0, (LONG)pWndFrame); **/ gs_pCmd->VNTChanged(); TRACE("=================REWRITE GrfComCmdBlk::DoActivate ! ================"); } break; } }; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void GrfComCmdBlk::DumpErrors() { Strng Buff(""); /* while (SFE.RequestError(Buff)) gs_pCmd->Print("%s\n", Buff.Str()); */ } //=========================================================================== void GrfComCmdBlk::AttachDoc(pDocRoot pDoc_, pGrfComCmdBlk pGrf_, pGrfComCmdBlk pMdl_) { DocCmdBlk::AttachDoc(pDoc_); pGWnd=(CGrfWnd*)pWnd; pDsp=&(pGWnd->Dsp); pDsp->Open(); // Create Viewports etc. if neccessary pDsp->Close(); //dbgpln("GrfComCmdBlk::AttachDoc %#10x %#10x %#10x", pDoc_, pGrf_, pMdl_); pGrf=pGrf_; pMdl=pMdl_; }; //=========================================================================== // //flag GrfComCmdBlk::ModelsAttached() { return FALSE;}; // ////--------------------------------------------------------------------------- // //pNodeGrfInfo GrfComCmdBlk::GetNodeDrawings() // { // LogError("SysCAD", 0, "GetNodeDrawings NOT Implemented"); // return NULL; // } // //--------------------------------------------------------------------------- flag GrfComCmdBlk::TestModelTagUnique(pchar pTag, CUniqueTagRulesBlk & TRB/*pchar pHdr, char SepChar*/, Strng &UniqueTag, flag HdrAsIs) { return True; } //--------------------------------------------------------------------------- flag GrfComCmdBlk::TestSymbolNameUnique(Strng &Sym, CUniqueTagRulesBlk & TRB/*pchar pHdr, char SepChar*/, Strng &UniqueSym) { UniqueSym.Set("%s%c?",TRB.BaseTag(),TRB.SepChar()); return False; }; //--------------------------------------------------------------------------- BOOL GrfComCmdBlk::DoReadDocument(const char *pszPathName, FILE* pFile) { if (!feof(pFile)) { char c=fgetc(pFile); while (c=='r') { CGrfDoc* pGDoc=(CGrfDoc*)pDoc; char what[512], buff[512]; fscanf(pFile, " %s %s ", what, buff); if (strcmp(what, "a")==0) { } c=fgetc(pFile); } if (c!=EOF) ungetc(c, pFile); } return True; }; //--------------------------------------------------------------------------- BOOL GrfComCmdBlk::DoWriteDocument(const char *pszPathName, FILE* pFile) { return True; }; //===========================================================================
[ [ [ 1, 74 ], [ 80, 205 ] ], [ [ 75, 79 ] ] ]
9ba8a73fb82ef121461ccff5b1918cebe11eb73d
29241c06548ec3ac6ef859ba32656cb60d8b89bf
/coolsb_mfctest/coolsb_mfctest.cpp
044ef3ea60b67d9868ac2fcdb85ab75c9728c05f
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
jsleroy/CoolSB
791fbc80619762d81a4ae21145c4892a6c1210c1
472051497f176f5853eae03677f63260ad4eed44
refs/heads/master
2021-01-16T21:49:36.856083
2009-06-17T14:52:35
2009-06-17T14:52:35
249,513
3
2
null
null
null
null
UTF-8
C++
false
false
4,259
cpp
// coolsb_mfctest.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "coolsb_mfctest.h" #include "MainFrm.h" #include "coolsb_mfctestDoc.h" #include "coolsb_mfctestView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCoolsb_mfctestApp BEGIN_MESSAGE_MAP(CCoolsb_mfctestApp, CWinApp) //{{AFX_MSG_MAP(CCoolsb_mfctestApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCoolsb_mfctestApp construction CCoolsb_mfctestApp::CCoolsb_mfctestApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CCoolsb_mfctestApp object CCoolsb_mfctestApp theApp; ///////////////////////////////////////////////////////////////////////////// // CCoolsb_mfctestApp initialization BOOL CCoolsb_mfctestApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(0); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CCoolsb_mfctestDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CCoolsb_mfctestView)); AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it. m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About 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) // No message handlers //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() // App command to run the dialog void CCoolsb_mfctestApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CCoolsb_mfctestApp message handlers
[ [ [ 1, 152 ] ] ]
c6a149d1688cd2fd2cad67d79020304b58026f37
298e23006861f9c9179b90f7ea27d43bec28538c
/Vertex.cpp
43569658cc851d9b9c3be5a12b27efaf1321d7e9
[]
no_license
NIA/D3DMorphing
cfea1fcea2768964a604907c3577c7c343b4ab28
68eb47064d82414ba96cd9dbf3e9cff23f2ca7f9
refs/heads/master
2021-01-10T20:19:28.480748
2009-10-12T04:59:48
2009-10-12T04:59:48
326,170
0
1
null
null
null
null
UTF-8
C++
false
false
310
cpp
#include "Vertex.h" const D3DFORMAT INDEX_FORMAT = D3DFMT_INDEX32; const D3DVERTEXELEMENT9 VERTEX_DECL_ARRAY[] = { {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0}, D3DDECL_END() };
[ [ [ 1, 10 ] ] ]
076d81d69500e743cbc67912ca134447ce40a7d2
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/XYLib/2D_LNORM.CPP
992c2086ff03b67fac97bb708d7bec9c2f10300f
[]
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
2,511
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #include "stdafx.h" #define __2D_LNORM_CPP #include "sc_defs.h" #include "2d_fn.h" #include "2d_lnorm.h" // ========================================================================= IMPLEMENT_2D_MODEL(C2DLNorm, "2D_LNorm", "", TOC_SYSTEM, "Log-Normal Distribution", "Log-Normal Size Distribution"); // ========================================================================= /*#D:#T:Log-Normal Distribution #X:#n#u<#l<#b<General Description>>>#PThis fits the log-normal distribution curve to data, for example when determining the particle size distribution of granular materials, according tho the following formula : dF/d(lnX)=XdF/dX= 1/ln(... #P#u<#l<#b<Variables to be supplied by the user>>>#n #p#b<Gm Std Dev :>#NThe geometrical standard deviation of dF/dX, equivalent to X84% / X50% ie the particle size fraction at 84 % divided by the particle size fraction at 50%. This cannot be zero. #p#b<Gm Mean :>#NThe geometrical mean of dF/dX. */ double C2DLNorm::Const1 = 1.0 / (sqrt(2 * PI)); pchar C2DLNorm::ParmDescs[LNormNoOfParms] = {"Gm_Std_Dev", "Gm_Mean", "Gain", "Offset" }; // ========================================================================= C2DLNorm::C2DLNorm(pTagObjClass pClass_, pchar pTag, pTaggedObject pAttach, TagObjAttachment eAttach) : C2DModel(pClass_, pTag, pAttach, eAttach) { Clear(); } // ------------------------------------------------------------------------- C2DLNorm::~C2DLNorm() { } //--------------------------------------------------------------------------- void C2DLNorm::Clear() { CBaseMdl::Clear(); SetNParms(LNormNoOfParms); Parms[0] = 1.0; //GStdDev Parms[1] = 0.5; //GMean Parms[2] = 1.0; //Gain Parms[3] = 0.0; //Offset } // ------------------------------------------------------------------------- double C2DLNorm::Yx(double Xi) { Parms[0]=Max(Parms[0], 1.0e-10); Parms[1]=Max(Parms[1], 1.0e-10); double a = log(Parms[0]); double b = log(Parms[1]); return (Const1 / GTZ(a) * Exps(- Sqr((log(GTZ(Xi))-b) / GTZ(2. * a * a))) * Parms[2]) + Parms[3]; } //--------------------------------------------------------------------------- // =========================================================================
[ [ [ 1, 72 ] ] ]
1dec0262bdf1799cc89f9e4035fd7059267527d1
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nspatial/src/nspatial/noccludingspherevisitor.cc
297544b895c01aef257dae011f94471a633e2cc1
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,031
cc
#include "precompiled/pchnspatial.h" //-------------------------------------------------- // noccludingspherevisitor.cc // (C) 2004 Gary Haussmann //-------------------------------------------------- #include "nspatial/noccludingspherevisitor.h" nOccludingSphereVisitor::nOccludingSphereVisitor(const sphere &viewsphere) : nVisibleSphereVisitor(viewsphere) { } nOccludingSphereVisitor::~nOccludingSphereVisitor() { } void nOccludingSphereVisitor::Reset() { // clear out the occluders m_occluders.Clear(); nVisibleSphereVisitor::Reset(); } void nOccludingSphereVisitor::Visit(nSpatialSector *visitee, int recursedepth) { // bug out if we're hit the bottom of our allowed recursion if (recursedepth < 1) return; nOctNode *rootnode = visitee->GetRoot(); nSphereClipper::result_info clipinfo; nSphereClipper sphereclip = m_sphereclipperstack.Back(); // record the size of the occluder array before doing this sector int previousoccludersize = m_occluders.Size(); // get up to 3 occluders for this sector CollectOccluders(rootnode, sphereclip, clipinfo, 3); // if in debug mode, render the view frustum and occluders if (m_gfxdebug) { sphereclip.VisualizeSphere(m_gfxdebug, vector4(1.0f,1.0f,1.0f,0.5f)); // draw the occluders for (nArray<nBBoxOccluder>::iterator bboxi = m_occluders.Begin(); bboxi != m_occluders.End(); bboxi++) { bboxi->VisualizeBBox(m_gfxdebug, vector4(0.0f,1.0f,1.0f,1.0f)); } } // recursively descend the octree checking each node for clipping CheckOctNode(rootnode, sphereclip, clipinfo, recursedepth); // wipe out any occluders added to the stack upon entering this sector while (m_occluders.Size() > previousoccludersize) { m_occluders.Erase(m_occluders.End()-1); } } void nOccludingSphereVisitor::CheckOctNode(nOctNode *testnode, nSphereClipper &clipper, nSphereClipper::result_info clipstatus, int recursivedepth) { // if the node is totally enclosed, trivially accept all the children nodes. otherwise, do a frustum clip test bbox3 nodebbox ( (testnode->minCorner + testnode->maxCorner)*0.5, (testnode->maxCorner - testnode->minCorner)*0.5); if (clipstatus.active_flag != 0) { clipstatus = clipper.TestBBox(nodebbox, clipstatus); } // if the node is culled, then ignore this node and all nodes below it if (clipstatus.culled) return; // if the node is occluded, ignore this node and all nodes below it if (IsOccluded(sphere(nodebbox.center(), nodebbox.extents().len()))) return; // this node is not culled. Test all the elements in this node, and then recurse to child nodes. nOctElement *oe; for (oe = (nOctElement *) testnode->elm_list.GetHead(); oe; oe = (nOctElement *) oe->GetSucc()) { bbox3 thisbbox( (oe->minCorner + oe->maxCorner)*0.5, (oe->maxCorner - oe->minCorner)*0.5); nSphereClipper::result_info ri(clipper.TestBBox(thisbbox, clipstatus)); if (!ri.culled) { nSpatialElement *se = (nSpatialElement *)oe; // is this element occluded? skip if it is if (!IsOccluded(sphere(se->pos, se->radius))) se->Accept(*this, recursivedepth); } } // now check the children of this node if (testnode->c[0]) for (int childix=0; childix < 8; childix++) { this->CheckOctNode(testnode->c[childix], clipper, clipstatus, recursivedepth); } } // recursive collection of occluders in this octree int nOccludingSphereVisitor::CollectOccluders(nOctNode *collectnode, nSphereClipper &clipper, nSphereClipper::result_info clipstatus, int maxoccluders) { // if the node is totally enclosed, trivially accept all the children nodes. otherwise, do a frustum clip test bbox3 nodebbox ( (collectnode->minCorner + collectnode->maxCorner)*0.5, (collectnode->maxCorner - collectnode->minCorner)*0.5); if (clipstatus.active_flag != 0) { clipstatus = clipper.TestBBox(nodebbox, clipstatus); } // if the node is culled, then ignore this node and all nodes below it if (clipstatus.culled) return maxoccluders; // if the node is occluded, ignore this node and all nodes below it if (IsOccluded(sphere(nodebbox.center(), nodebbox.extents().len()))) return maxoccluders; // this node is not culled. Test all the elements in this node, and then recurse to child nodes. nOctElement *oe; for (oe = (nOctElement *) collectnode->elm_list.GetHead(); oe; oe = (nOctElement *) oe->GetSucc()) { bbox3 thisbbox( (oe->minCorner + oe->maxCorner)*0.5, (oe->maxCorner - oe->minCorner)*0.5); nSphereClipper::result_info ri(clipper.TestBBox(thisbbox, clipstatus)); if (!ri.culled) { nSpatialElement *se = (nSpatialElement *)oe; // if it's an occluder then add to the occluder set if (se->GetSpatialType() & nSpatialElement::N_SPATIAL_OCCLUDER) { // stuff a new sphereoccluder on the array m_occluders.PushBack(nBBoxOccluder(GetViewPoint(), thisbbox)); maxoccluders -= 1; } } } // now check the children of this node if (collectnode->c[0]) for (int childix=0; childix < 8; childix++) { maxoccluders = this->CollectOccluders(collectnode->c[childix], clipper, clipstatus, maxoccluders); } return maxoccluders; } bool nOccludingSphereVisitor::VisibilityTest(nSpatialElement *visitee) { // test against the current sphere clipper nSphereClipper &clipper = GetSphereClipper(); nSphereClipper::result_info in, out; bbox3 totest( (visitee->minCorner + visitee->maxCorner)*0.5, (visitee->maxCorner - visitee->minCorner)*0.5); out = clipper.TestBBox( totest, in); return !out.culled; } // checks that a given sphere is not blocked by any occluders bool nOccludingSphereVisitor::IsOccluded(const sphere &testsphere) { // now check against all occluders as well for (nArray<nBBoxOccluder>::iterator occluderiter = m_occluders.Begin(); occluderiter != m_occluders.End(); occluderiter++) { // does this one occlude it? nBBoxOccluder::result_info occludetest; occludetest = occluderiter->TestSphere(testsphere, occludetest); if (occludetest.culled) return true; } // not occluded return false; } void nOccludingSphereVisitor::EnterLocalSpace(matrix44 &warp) { nVisibilityVisitor::EnterLocalSpace(warp); } void nOccludingSphereVisitor::LeaveLocalSpace() { nVisibilityVisitor::LeaveLocalSpace(); }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 196 ] ] ]
15eb65b535346a51cf24a0d3715f001372e27087
fec97339b4f90ddcc8d49d39c048140f05b2db6e
/AnyPointRotate/MainWindow.h
9043efbbe3e6f5fd323554ae201d5f26dc78c96f
[]
no_license
SirEOF/geomdef
55ea012b898029baaf60fae8fc236ca8ab855cfb
0e9508539703b697882df82c84fb92d34a3e3dff
refs/heads/master
2021-05-29T06:43:54.986200
2010-02-01T11:24:21
2010-02-01T11:24:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
570
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> class QImage; class QGraphicsScene; class RotateImage; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); protected: void changeEvent(QEvent *e); private: Ui::MainWindow *ui; const QImage *image; QImage *rotatedImage; QGraphicsScene *scene; RotateImage *rot; private slots: void dialSlot(int value); }; #endif // MAINWINDOW_H
[ "grzesiek.kurek@e2a736ec-deac-11de-b357-fb893c5a43fa" ]
[ [ [ 1, 36 ] ] ]
1eb1910cde33f750faa288b64b24cb88d6397d6d
587b66524cf73c9231180b3d2c9e0f0e15634c68
/com_response.cpp
d08df3f1b45632b7f39cf6f137e019a3709ae484
[]
no_license
jjfahner/httpd
3a9c4917656b2cd3d2e8a1875717a65f0d926b9c
e086f009f81c42d84a24cd915808389a05690512
refs/heads/master
2021-01-01T05:02:07.547322
2008-10-21T19:05:28
2008-10-21T19:05:28
56,080,927
0
0
null
null
null
null
UTF-8
C++
false
false
4,320
cpp
#include "precomp.h" #include "com_response.h" #include "httpd.h" #include "response.h" ////////////////////////////////////////////////////////////////////////// /*static*/ HRESULT ResponseHeader::Create(http_response* response, String const& key, IDispatch** pDisp) { // Clear result value *pDisp = 0; // Create instance of Site class CComObject<ResponseHeader>* pObject; if(FAILED(pObject->CreateInstance(&pObject))) { delete pObject; return E_UNEXPECTED; } // Set header proxy pObject->m_response = response; pObject->m_key = key; // Query for IDispatch return pObject->QueryInterface(IID_IDispatch, (void**)pDisp); } HRESULT STDMETHODCALLTYPE ResponseHeader::get_Name(BSTR *name) { *name = m_key.AllocSysString(); return S_OK; } HRESULT STDMETHODCALLTYPE ResponseHeader::get_Value(BSTR *value) { *value = m_response->headers[m_key].as_str().AllocSysString(); return S_OK; } HRESULT STDMETHODCALLTYPE ResponseHeader::put_Value(BSTR value) { m_response->headers[m_key] = String(value); return S_OK; } ////////////////////////////////////////////////////////////////////////// /*static*/ HRESULT ResponseHeaders::Create(http_response* response, IDispatch** pDisp) { // Clear result value *pDisp = 0; // Create instance of Site class CComObject<ResponseHeaders>* pObject; if(FAILED(pObject->CreateInstance(&pObject))) { delete pObject; return E_UNEXPECTED; } // Set header proxy pObject->m_response = response; // Query for IDispatch return pObject->QueryInterface(IID_IDispatch, (void**)pDisp); } HRESULT STDMETHODCALLTYPE ResponseHeaders::get__NewEnum(IUnknown **ppUnk) { *ppUnk = 0; return S_OK; } HRESULT STDMETHODCALLTYPE ResponseHeaders::get_Item(VARIANT index, IResponseHeader **pSite) { if(index.vt == VT_BSTR) { return ResponseHeader::Create(m_response, index.bstrVal, (IDispatch**)pSite); } return E_INVALIDARG; } HRESULT STDMETHODCALLTYPE ResponseHeaders::get_Count(long *pVal) { *pVal = m_response->headers.size(); return S_OK; } ////////////////////////////////////////////////////////////////////////// void Response::Init(http_response* response) { m_response = response; } HRESULT STDMETHODCALLTYPE Response::get_Version(HttpVersion *version) { if(m_response->version() == httpver_1_0) { *version = HTTP_1_0; } else if(m_response->version() == httpver_1_1) { *version = HTTP_1_1; } else { return E_UNEXPECTED; } return S_OK; } HRESULT STDMETHODCALLTYPE Response::get_Status(BSTR *status) { *status = m_response->status().AllocSysString(); return S_OK; } HRESULT STDMETHODCALLTYPE Response::put_Status(BSTR status) { m_response->set_status(status); return S_OK; } HRESULT STDMETHODCALLTYPE Response::GetHeader(BSTR name, BSTR *value) { *value = m_response->headers[name].as_str().AllocSysString(); return S_OK; } HRESULT STDMETHODCALLTYPE Response::SetHeader(BSTR name, BSTR value) { m_response->headers[name] = String(value); return S_OK; } HRESULT STDMETHODCALLTYPE Response::SendHeaders() { m_response->send_headers(); return S_OK; } HRESULT STDMETHODCALLTYPE Response::get_Buffer(VARIANT_BOOL *result) { *result = m_response->buffered() ? VARIANT_TRUE : VARIANT_FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE Response::put_Buffer(VARIANT_BOOL value) { m_response->set_buffered(value != VARIANT_FALSE); return S_OK; } HRESULT STDMETHODCALLTYPE Response::SendHeaders(VARIANT_BOOL *result) { m_response->send_headers(); *result = VARIANT_TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE Response::SendError(int error, VARIANT_BOOL *result) { m_response->send_error(error); *result = VARIANT_TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE Response::Send(void *data, int length) { m_response->send((char*)data, length); return S_OK; } HRESULT STDMETHODCALLTYPE Response::Flush() { m_response->flush(); return S_OK; } HRESULT STDMETHODCALLTYPE Response::Finish() { m_response->finish(); return S_OK; }
[ [ [ 1, 212 ] ] ]
56e7467bd817cebdea2e4148832579ba697df34d
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/UIPanel.h
a15ad32d7c540cf07f1608ab98f20d66da8bf07b
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
1,829
h
#pragma once #ifndef __HALAK_UIPANEL_H__ #define __HALAK_UIPANEL_H__ # include <Halak/FWD.h> # include <Halak/UIVisual.h> # include <Halak/Signal.h> # include <vector> namespace Halak { class UIPanel : public UIVisual { public: typedef std::vector<UIVisualPtr> VisualCollection; public: UIPanel(); explicit UIPanel(int childrenCapacity); virtual ~UIPanel(); UIVisual* FindChild(const String& name, bool searchAllChildren) const; inline const VisualCollection& GetChildren() const; virtual bool IsPanel() const; protected: void Add(UIVisual* item); void Insert(int index, UIVisual* item); bool Remove(UIVisual* item); bool RemoveAt(int index); void RemoveAll(); void DrawChildren(UIDrawingContext& context); virtual void OnDraw(UIDrawingContext& context); virtual void OnPick(UIPickingContext& context); virtual void OnChildAdded(UIVisual* child); virtual void OnChildRemoved(UIVisual* child); virtual void OnChildrenAdded(const VisualCollection& children); virtual void OnChildrenRemoved(const VisualCollection& children); private: void RemoveByIterator(VisualCollection::iterator it); void BringChildToFront(UIVisual* child); void SendChildToBack(UIVisual* child); private: VisualCollection children; friend class UIVisual; }; } # include <Halak/UIPanel.inl> #endif
[ [ [ 1, 59 ] ] ]
61ddb3cdfadd40052b63ece233a8c285d0d45bc4
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/PlayerSoundFX.cpp
6d26180344eea530491490329e151310ba04d2f6
[]
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
2,602
cpp
// ----------------------------------------------------------------------- // // // MODULE : PlayerSoundFX.cpp // // PURPOSE : Player sound special FX - Implementation // // CREATED : 7/28/98 (was WeaponSoundFX) // // (c) 1998-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "PlayerSoundFX.h" #include "GameClientShell.h" #include "iltclient.h" #include "MsgIds.h" extern CGameClientShell* g_pGameClientShell; // ----------------------------------------------------------------------- // // // ROUTINE: CPlayerSoundFX::Init // // PURPOSE: Init the fx // // ----------------------------------------------------------------------- // LTBOOL CPlayerSoundFX::Init(SFXCREATESTRUCT* psfxCreateStruct) { if (!CSpecialFX::Init(psfxCreateStruct)) return LTFALSE; PLAYERSOUNDCREATESTRUCT* pPSCS = (PLAYERSOUNDCREATESTRUCT*)psfxCreateStruct; m_vPos = pPSCS->vPos; m_nClientId = pPSCS->nClientId; m_nType = pPSCS->nType; m_nWeaponId = pPSCS->nWeaponId; return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CPlayerSoundFX::CreateObject // // PURPOSE: Create object associated with the CPlayerSoundFX // // ----------------------------------------------------------------------- // LTBOOL CPlayerSoundFX::CreateObject(ILTClient *pClientDE) { if (!CSpecialFX::CreateObject(pClientDE)) return LTFALSE; uint32 dwId; if (m_pClientDE->GetLocalClientID(&dwId) != LT_OK) return LTFALSE; // Don't play sounds for this client... if (int(dwId) == m_nClientId) return LTFALSE; PlayerSoundId eSndType = (PlayerSoundId)m_nType; if (::IsWeaponSound(eSndType)) { WEAPON const *pWeapon = g_pWeaponMgr->GetWeapon(m_nWeaponId); if (!pWeapon) return LTFALSE; PlayWeaponSound(pWeapon, m_vPos, (PlayerSoundId)m_nType); } else { switch (eSndType) { case PSI_JUMP : { char* pSounds[] = { "Chars\\Snd\\jump1.wav", "Chars\\Snd\\jump2.wav" }; g_pClientSoundMgr->PlaySoundFromPos(m_vPos, pSounds[GetRandom(0,1)], 1000.0f, SOUNDPRIORITY_MISC_HIGH); } break; case PSI_LAND : { char* pSounds[] = { "Chars\\Snd\\player\\landing1.wav", "Chars\\Snd\\player\\landing2.wav" }; g_pClientSoundMgr->PlaySoundFromPos(m_vPos, pSounds[GetRandom(0,1)], 1000.0f, SOUNDPRIORITY_MISC_HIGH); } break; default : break; } } return LTFALSE; // Delete me, I'm done :) }
[ [ [ 1, 97 ] ] ]
64d7b128a77adbe0bd72989e9ae5099ba7ae585c
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/instructions/MAX.h
0cc1eb1312a0f4d591c276c5f24eb46087c4beea
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
h
template< > struct AllegrexInstructionTemplate< 0x0000002c, 0xfc0007ff > : AllegrexInstructionUnknown { static AllegrexInstructionTemplate &self() { static AllegrexInstructionTemplate insn; return insn; } static AllegrexInstruction *get_instance() { return &AllegrexInstructionTemplate::self(); } virtual AllegrexInstruction *instruction(u32 opcode) { return this; } virtual char const *opcode_name() { return "MAX"; } virtual void interpret(Processor &processor, u32 opcode); virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment); protected: AllegrexInstructionTemplate() {} }; typedef AllegrexInstructionTemplate< 0x0000002c, 0xfc0007ff > AllegrexInstruction_MAX; namespace Allegrex { extern AllegrexInstruction_MAX &MAX; } #ifdef IMPLEMENT_INSTRUCTION AllegrexInstruction_MAX &Allegrex::MAX = AllegrexInstruction_MAX::self(); #endif
[ [ [ 1, 41 ] ] ]
fa9541d78fdf7f33d2b22b92851a4f9ce08eac5e
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/bit_stream/bit_stream_kernel_c.h
2db0b9299c6c953fce3023ff705f685811286f7e
[ "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
4,937
h
// Copyright (C) 2003 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_BIT_STREAM_KERNEl_C_ #define DLIB_BIT_STREAM_KERNEl_C_ #include "bit_stream_kernel_abstract.h" #include "../algs.h" #include "../assert.h" #include <iosfwd> namespace dlib { template < typename bit_stream_base // implements bit_stream/bit_stream_kernel_abstract.h > class bit_stream_kernel_c : public bit_stream_base { public: void set_input_stream ( std::istream& is ); void set_output_stream ( std::ostream& os ); void close ( ); void write ( int bit ); bool read ( int& bit ); }; template < typename bit_stream_base > inline void swap ( bit_stream_kernel_c<bit_stream_base>& a, bit_stream_kernel_c<bit_stream_base>& b ) { a.swap(b); } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // member function definitions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename bit_stream_base > void bit_stream_kernel_c<bit_stream_base>:: set_input_stream ( std::istream& is ) { // make sure requires clause is not broken DLIB_CASSERT(( this->is_in_write_mode() == false ) && ( this->is_in_read_mode() == false ), "\tvoid bit_stream::set_intput_stream" << "\n\tbit_stream must not be in write or read mode" << "\n\tthis: " << this ); // call the real function bit_stream_base::set_input_stream(is); } // ---------------------------------------------------------------------------------------- template < typename bit_stream_base > void bit_stream_kernel_c<bit_stream_base>:: set_output_stream ( std::ostream& os ) { // make sure requires clause is not broken DLIB_CASSERT(( this->is_in_write_mode() == false ) && ( this->is_in_read_mode() == false ), "\tvoid bit_stream::set_output_stream" << "\n\tbit_stream must not be in write or read mode" << "\n\tthis: " << this ); // call the real function bit_stream_base::set_output_stream(os); } // ---------------------------------------------------------------------------------------- template < typename bit_stream_base > void bit_stream_kernel_c<bit_stream_base>:: close ( ) { // make sure requires clause is not broken DLIB_CASSERT(( this->is_in_write_mode() == true ) || ( this->is_in_read_mode() == true ), "\tvoid bit_stream::close" << "\n\tyou can't close a bit_stream that isn't open" << "\n\tthis: " << this ); // call the real function bit_stream_base::close(); } // ---------------------------------------------------------------------------------------- template < typename bit_stream_base > void bit_stream_kernel_c<bit_stream_base>:: write ( int bit ) { // make sure requires clause is not broken DLIB_CASSERT(( this->is_in_write_mode() == true ) && ( bit == 0 || bit == 1 ), "\tvoid bit_stream::write" << "\n\tthe bit stream bust be in write mode and bit must be either 1 or 0" << "\n\tis_in_write_mode() == " << this->is_in_write_mode() << "\n\tbit == " << bit << "\n\tthis: " << this ); // call the real function bit_stream_base::write(bit); } // ---------------------------------------------------------------------------------------- template < typename bit_stream_base > bool bit_stream_kernel_c<bit_stream_base>:: read ( int& bit ) { // make sure requires clause is not broken DLIB_CASSERT(( this->is_in_read_mode() == true ), "\tbool bit_stream::read" << "\n\tyou can't read from a bit_stream that isn't in read mode" << "\n\tthis: " << this ); // call the real function return bit_stream_base::read(bit); } // ---------------------------------------------------------------------------------------- } #endif // DLIB_BIT_STREAM_KERNEl_C_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 172 ] ] ]
5b8d4607f463424c06e3fc9fc70debd53fa6e9f4
e419dcb4a688d0c7b743c52c2d3c4c2edffc3ab8
/Raytrace/raytrace/RayCaster.cpp
890413b9781e230120533ba0b56bdd5701e9528f
[]
no_license
Jazzinghen/DTU-Rendering
d7f833c01836fadb4401133d8a5c17523e04bf49
b03692ce19d0ea765d61e88e19cd8113da99b7fe
refs/heads/master
2021-01-01T15:29:49.250365
2011-12-20T00:49:32
2011-12-20T00:49:32
2,505,173
0
0
null
null
null
null
UTF-8
C++
false
false
3,313
cpp
// 02562 Rendering Framework // Written by Jeppe Revall Frisvad, 2011 // Copyright (c) DTU Informatics 2011 #include <iostream> #include <optix_world.h> #include "mt_random.h" #include "Shader.h" #include "HitInfo.h" #include "RayCaster.h" using namespace std; using namespace optix; float3 RayCaster::compute_pixel(unsigned int x, unsigned int y) const { float3 result = make_float3(0.0f); // Use the scene and its camera // to cast a ray that computes the color of the pixel at index (x, y). // // Input: x, y (pixel index) // // Return: Result of tracing a ray through the pixel at index (x, y). // // Relevant data fields that are available (see RayCaster.h and Scene.h) // win_to_ip (pixel size (width, height) in the image plane) // lower_left (lower left corner of the film in the image plane) // scene (scene with access to the functions closest_hit and any_hit) // scene->get_camera() (camera in the scene) // // Hints: (a) Use the function get_shader(...) to get the shader of the // intersected material after the ray has been traced. // (b) Use get_background(...) if the ray does not hit anything. float temp1 = win_to_ip.x; for (int a=0; a<subdivs; a++) { // three lines below were added instead of the fourth commented, step is already in world coordinates(distance between pixels on a plane) for(int b=0; b<subdivs; b++) { int temp = subdivs; float x_pos=(float)x*win_to_ip.x - step.x/2.0 + a*step.x/subdivs + jitter[a*subdivs + b].x; float y_pos=(float)y*win_to_ip.y - step.y/2.0 + b*step.y/subdivs + jitter[a*subdivs + b].y; Ray r = scene->get_camera()->get_ray( optix::make_float2( x_pos - lower_left.x, y_pos - lower_left.y )); //Ray r = scene->get_camera()->get_ray( optix::make_float2( ((float)x)*win_to_ip.x - lower_left.x, ((float)y)*win_to_ip.y - lower_left.y )); HitInfo hit; scene->closest_hit(r,hit); if( hit.has_hit ) { result += get_shader(hit)->shade(r,hit); } else { result += get_background(); } } } return result/float(subdivs*subdivs); } float3 RayCaster::get_background(const float3& dir) const { if(!sphere_tex) return background; return make_float3(sphere_tex->sample_linear(dir)); } void RayCaster::increment_pixel_subdivs() { ++subdivs; compute_jitters(); cout << "Rays per pixel: " << subdivs*subdivs << endl; } void RayCaster::decrement_pixel_subdivs() { if(subdivs > 1) { --subdivs; compute_jitters(); } cout << "Rays per pixel: " << subdivs*subdivs << endl; } void RayCaster::compute_jitters() { float aspect = width/static_cast<float>(height); win_to_ip.x = aspect/static_cast<float>(width); win_to_ip.y = 1.0f/static_cast<float>(height); lower_left = make_float2(aspect*0.5f + win_to_ip.x*0.5f, 0.5f - win_to_ip.y*0.25f); step = win_to_ip/static_cast<float>(subdivs); jitter.resize(subdivs*subdivs); for(unsigned int i = 0; i < subdivs; ++i) for(unsigned int j = 0; j < subdivs; ++j) { jitter[i*subdivs + j].x = static_cast<float>(safe_mt_random() + j)*step.x; jitter[i*subdivs + j].y = static_cast<float>(safe_mt_random() + i)*step.y; } }
[ [ [ 1, 103 ] ] ]
aac014841bbf376cf53231d28534a4a89cdce91c
f0c08b3ddefc91f1fa342f637b0e947a9a892556
/branches/develop/calcioIA/GlutApp/Application.h
ad55578e831486fc2296b069cb244c08f4c30b73
[]
no_license
BackupTheBerlios/coffeestore-svn
1db0f60ddb85ccbbdfeb9b3271a687b23e29fc8f
ddee83284fe9875bf0d04e6b7da7a2113e85a040
refs/heads/master
2021-01-01T05:30:22.345767
2009-10-11T08:55:35
2009-10-11T08:55:35
40,725,038
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
h
#ifndef APPLICATION_H #define APPLICATION_H #include <string> #include "GlutLoggerWriter.h" class Point; class Application { public: enum SpecialKey { SpecialKey_None, SpecialKey_Up, SpecialKey_Down, SpecialKey_Left, SpecialKey_Right, }; Application(int width, int height); virtual ~Application(); void initialize(int argc, char** argv); virtual void display() = 0; virtual void update() = 0; virtual void keyboard(unsigned char key) = 0; virtual std::string title() const; virtual void specialKeyUp(SpecialKey specialKey); virtual void specialKeyDown(SpecialKey specialKey); int width() const; int height() const; void writeString(const Point& position, const std::string& str) const; private: int _width; int _height; GlutLoggerWriter _loggerWriter; static void _idle(); static void _display(); static void _keyboard(unsigned char key, int x, int y); static void _special(int key, int x, int y); static void _specialUp(int key, int x, int y); static Application* _instance; }; #endif
[ "fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb" ]
[ [ [ 1, 54 ] ] ]
045d00d52158746ba9a004d8a6ba50ef1d046f5f
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/serialization/test/test_smart_cast.cpp
f98ef79819f6f43e580dd48b037cea67194e6023
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
6,308
cpp
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // test_smart_cast.cpp: // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // <[email protected]> #include <exception> #include <boost/smart_cast.hpp> #include <boost/test/test_tools.hpp> #include <boost/noncopyable.hpp> using namespace boost; class Base1 : public boost::noncopyable { char a; }; class Base2 { int b; }; class Derived : public Base1, public Base2 { long c; }; BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(Base1) BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(Base2) BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(Derived) // if compiler doesn't support TPS, the smart_cast syntax doesn't // work for references. One has to use the smart_cast_reference // syntax (tested below ) instead. void test_static_reference_cast_2(){ Derived d; Base1 & b1 = static_cast<Base1 &>(d); Base2 & b2 = static_cast<Base2 &>(d); Base1 & scb1 = smart_cast<Base1 &, Derived &>(d); Base2 & scb2 = smart_cast<Base2 &, Derived &>(d); BOOST_CHECK_EQUAL(& b1, & scb1); BOOST_CHECK_EQUAL(& b2, & scb2); // downcast // BOOST_CHECK_EQUAL(& d, & (smart_cast<Derived &, Base1 &>(b1))); // BOOST_CHECK_EQUAL(& d, & (smart_cast<Derived &, Base2 &>(b2))); // crosscast pointers fails at compiler time // BOOST_CHECK_EQUAL(pB2,smart_cast<B2 *>(pB1)); // though explicit cross cast will always work BOOST_CHECK_EQUAL(& b2,( & smart_cast<Base2 &, Derived &>( smart_cast<Derived &, Base1 &>(b1) )) ); } void test_static_reference_cast_1(){ Derived d; Base1 & b1 = static_cast<Base1 &>(d); Base2 & b2 = static_cast<Base2 &>(d); Base1 & scb1 = smart_cast_reference<Base1 &>(d); Base2 & scb2 = smart_cast_reference<Base2 &>(d); BOOST_CHECK_EQUAL(& b1, & scb1); BOOST_CHECK_EQUAL(& b2, & scb2); // downcast BOOST_CHECK_EQUAL(& d, & (smart_cast_reference<Derived &>(b1))); BOOST_CHECK_EQUAL(& d, & (smart_cast_reference<Derived &>(b2))); // crosscast pointers fails at compiler time // BOOST_CHECK_EQUAL(pB2,smart_cast<B2 *>(pB1)); // though explicit cross cast will always work BOOST_CHECK_EQUAL(& b2,( & smart_cast_reference<Base2 &>( smart_cast_reference<Derived &>(b1) )) ); } void test_static_pointer_cast(){ // pointers Derived d; Derived *pD = & d; Base1 *pB1 = pD; Base2 *pB2 = pD; // upcast BOOST_CHECK_EQUAL(pB1, smart_cast<Base1 *>(pD)); BOOST_CHECK_EQUAL(pB2, smart_cast<Base2 *>(pD)); // downcast BOOST_CHECK_EQUAL(pD, smart_cast<Derived *>(pB1)); BOOST_CHECK_EQUAL(pD, smart_cast<Derived *>(pB2)); // crosscast pointers fails at compiler time // BOOST_CHECK_EQUAL(pB2, smart_cast<Base2 *>(pB1)); // though explicit cross cast will always work BOOST_CHECK_EQUAL(pB2, smart_cast<Base2 *>( smart_cast<Derived *>(pB1) ) ); } class VBase1 : public boost::noncopyable { char a; public: virtual ~VBase1(){}; }; class VBase2 { int b; public: virtual ~VBase2(){}; }; class VDerived : public VBase1, public VBase2 { long c; public: virtual ~VDerived(){}; }; BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(VBase1) BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(VBase2) BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(VDerived) // see above void test_dynamic_reference_cast_2(){ VDerived d; VBase1 &b1 = dynamic_cast<VBase1 &>(d); VBase2 &b2 = static_cast<VBase2 &>(d); VBase1 & vb1 = smart_cast<VBase1 &, VDerived &>(d); BOOST_CHECK_EQUAL(& b1, & vb1); BOOST_CHECK_EQUAL(& b2, (& smart_cast<VBase2 &, VDerived &>(d))); // downcast BOOST_CHECK_EQUAL(& d, (& smart_cast<VDerived &, VBase1 &>(b1))); BOOST_CHECK_EQUAL(& d, (& smart_cast<VDerived &, VBase2 &>(b2))); // crosscast BOOST_CHECK_EQUAL(& b2, (& smart_cast<VBase2 &, VBase1 &>(b1))); // explicit cross cast should always work BOOST_CHECK_EQUAL(& b2, ( & smart_cast<VBase2 &, VDerived &>( smart_cast<VDerived &, VBase1 &>(b1) )) ); } void test_dynamic_reference_cast_1(){ VDerived d; VBase1 &b1 = dynamic_cast<VBase1 &>(d); VBase2 &b2 = static_cast<VBase2 &>(d); VBase1 & vb1 = smart_cast_reference<VBase1 &>(d); BOOST_CHECK_EQUAL(& b1, & vb1); BOOST_CHECK_EQUAL(& b2, (& smart_cast_reference<VBase2 &>(d))); // downcast BOOST_CHECK_EQUAL(& d, (& smart_cast_reference<VDerived &>(b1))); BOOST_CHECK_EQUAL(& d, (& smart_cast_reference<VDerived &>(b2))); // crosscast BOOST_CHECK_EQUAL(& b2, (& smart_cast_reference<VBase2 &>(b1))); // explicit cross cast should always work BOOST_CHECK_EQUAL(& b2, ( & smart_cast_reference<VBase2 &>( smart_cast_reference<VDerived &>(b1) )) ); } void test_dynamic_pointer_cast(){ // pointers VDerived d; VDerived *pD = & d; VBase1 *pB1 = pD; VBase2 *pB2 = pD; // upcast BOOST_CHECK_EQUAL(pB1, smart_cast<VBase1 *>(pD)); BOOST_CHECK_EQUAL(pB2, smart_cast<VBase2 *>(pD)); // downcast BOOST_CHECK_EQUAL(pD, smart_cast<VDerived *>(pB1)); BOOST_CHECK_EQUAL(pD, smart_cast<VDerived *>(pB2)); // crosscast pointers fails at compiler time BOOST_CHECK_EQUAL(pB2, smart_cast<VBase2 *>(pB1)); // though explicit cross cast will always work BOOST_CHECK_EQUAL(pB2, smart_cast<VBase2 *>( smart_cast<VDerived *>(pB1) ) ); } int test_main(int /* argc */, char * /* argv */[]) { test_static_reference_cast_2(); test_static_reference_cast_1(); test_static_pointer_cast(); test_dynamic_reference_cast_2(); test_dynamic_reference_cast_1(); test_dynamic_pointer_cast(); return boost::exit_success; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 227 ] ] ]
ffe980b4815cec8cf4580fb3d398876cbeb1294a
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/SMDataExtraction/stdhead.h
004647e7e74772e07c8e4459eba1531f3f7c35f8
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
254
h
#pragma once /** Slandered header used in almost all code files*/ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sql.h> #include <sqlext.h> #include <comdef.h> #include <vector> #include <gsodbc.h>
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1", "samfernandopulle@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 1 ], [ 4, 12 ] ], [ [ 2, 3 ] ] ]
03acade1a2d6ac4dcc19d7e984e8f3d7f68ba0da
1dba10648f60dea02c9be242c668f3488ae8dec4
/kalibrator/src/moc_mainform.cpp
750dbe739043c83755517cbd71ac9d8fa78e209b
[]
no_license
hateom/si-air
f02ffc8ba9fac9777d12a40627f06044c92865f0
2094c98a04a6785078b4c8bcded8f8b4450c8b92
refs/heads/master
2021-01-15T17:42:12.887029
2007-01-21T17:48:48
2007-01-21T17:48:48
32,139,237
0
0
null
null
null
null
UTF-8
C++
false
false
4,086
cpp
/**************************************************************************** ** MainForm meta object code from reading C++ file 'mainform.h' ** ** Created: N 7. sty 16:28:19 2007 ** by: The Qt MOC ($Id: moc_yacc.cpp,v 1.1.1.13 2006/05/05 17:43:42 chehrlic Exp $) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #undef QT_NO_COMPAT #include "mainform.h" #include <qmetaobject.h> #include <qapplication.h> #include <private/qucomextra_p.h> #if !defined(Q_MOC_OUTPUT_REVISION) || (Q_MOC_OUTPUT_REVISION != 26) #error "This file was generated using the moc from 3.3.6. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif const char *MainForm::className() const { return "MainForm"; } QMetaObject *MainForm::metaObj = 0; static QMetaObjectCleanUp cleanUp_MainForm( "MainForm", &MainForm::staticMetaObject ); #ifndef QT_NO_TRANSLATION QString MainForm::tr( const char *s, const char *c ) { if ( qApp ) return qApp->translate( "MainForm", s, c, QApplication::DefaultCodec ); else return QString::fromLatin1( s ); } #ifndef QT_NO_TRANSLATION_UTF8 QString MainForm::trUtf8( const char *s, const char *c ) { if ( qApp ) return qApp->translate( "MainForm", s, c, QApplication::UnicodeUTF8 ); else return QString::fromUtf8( s ); } #endif // QT_NO_TRANSLATION_UTF8 #endif // QT_NO_TRANSLATION QMetaObject* MainForm::staticMetaObject() { if ( metaObj ) return metaObj; QMetaObject* parentObject = QDialog::staticMetaObject(); static const QUParameter param_slot_0[] = { { 0, &static_QUType_int, 0, QUParameter::Out } }; static const QUMethod slot_0 = {"btn1_func", 1, param_slot_0 }; static const QUParameter param_slot_1[] = { { 0, &static_QUType_int, 0, QUParameter::Out } }; static const QUMethod slot_1 = {"btn2_func", 1, param_slot_1 }; static const QUParameter param_slot_2[] = { { 0, &static_QUType_int, 0, QUParameter::Out } }; static const QUMethod slot_2 = {"btn3_func", 1, param_slot_2 }; static const QUParameter param_slot_3[] = { { 0, &static_QUType_int, 0, QUParameter::Out } }; static const QUMethod slot_3 = {"btn0_func", 1, param_slot_3 }; static const QUMethod slot_4 = {"languageChange", 0, 0 }; static const QUMethod slot_5 = {"init", 0, 0 }; static const QMetaData slot_tbl[] = { { "btn1_func()", &slot_0, QMetaData::Public }, { "btn2_func()", &slot_1, QMetaData::Public }, { "btn3_func()", &slot_2, QMetaData::Public }, { "btn0_func()", &slot_3, QMetaData::Public }, { "languageChange()", &slot_4, QMetaData::Protected }, { "init()", &slot_5, QMetaData::Protected } }; metaObj = QMetaObject::new_metaobject( "MainForm", parentObject, slot_tbl, 6, 0, 0, #ifndef QT_NO_PROPERTIES 0, 0, 0, 0, #endif // QT_NO_PROPERTIES 0, 0 ); cleanUp_MainForm.setMetaObject( metaObj ); return metaObj; } void* MainForm::qt_cast( const char* clname ) { if ( !qstrcmp( clname, "MainForm" ) ) return this; return QDialog::qt_cast( clname ); } bool MainForm::qt_invoke( int _id, QUObject* _o ) { switch ( _id - staticMetaObject()->slotOffset() ) { case 0: static_QUType_int.set(_o,btn1_func()); break; case 1: static_QUType_int.set(_o,btn2_func()); break; case 2: static_QUType_int.set(_o,btn3_func()); break; case 3: static_QUType_int.set(_o,btn0_func()); break; case 4: languageChange(); break; case 5: init(); break; default: return QDialog::qt_invoke( _id, _o ); } return TRUE; } bool MainForm::qt_emit( int _id, QUObject* _o ) { return QDialog::qt_emit(_id,_o); } #ifndef QT_NO_PROPERTIES bool MainForm::qt_property( int id, int f, QVariant* v) { return QDialog::qt_property( id, f, v); } bool MainForm::qt_static_property( QObject* , int , int , QVariant* ){ return FALSE; } #endif // QT_NO_PROPERTIES
[ "jasinski.andrzej@9b5b1781-be22-0410-ac8e-a76ce1d23082" ]
[ [ [ 1, 128 ] ] ]
17424e301e838608c06d68cf377f274550083e5d
aa825896cc7c672140405ab51634d00d28fad09b
/zomgatron/Thingie.cpp
0ead52861cc8de462657af8a2dc1e3a603d6e4b9
[]
no_license
kllrnohj/zomgatron
856fa6693b924d629f166c82cdd4db7524f3255d
099955f0ab84eb432ab87d351b8defd3123a8991
refs/heads/master
2021-01-10T08:26:13.826555
2009-01-27T17:21:45
2009-01-27T17:21:45
46,742,521
0
0
null
null
null
null
UTF-8
C++
false
false
4,279
cpp
#include "Thingie.h" Thingie::Thingie(){ position = Vector3(0, 0, 0); forward = Vector3(0, 0, 1); right = Vector3(1, 0, 0); up = Vector3(0, 1, 0); } Thingie::Thingie(Vector3 position, Vector3 dirOrLookAt, bool lookAt){ this->position = position; forward = Vector3(0, 0, 1); right = Vector3(1, 0, 0); up = Vector3(0, 1, 0); Vector3 lookV; if(lookAt) lookV = dirOrLookAt; else lookV = Vector3(position.x + dirOrLookAt.x, position.y + dirOrLookAt.y, position.z + dirOrLookAt.z); this->LookAt(lookV); } void Thingie::LookAt(Vector3 position, float percent){ Vector3 soonLookDir(position.x - this->position.x, position.y - this->position.y, position.z - this->position.z); soonLookDir = Operations3D::Normifyilation(soonLookDir); Vector3 axisOfRotation = Operations3D::CrossProduct(forward, soonLookDir); if(Operations3D::Magnitude(axisOfRotation) == 0.0f) return; float val = Operations3D::DotProduct(forward, soonLookDir) / (Operations3D::Magnitude(forward) * Operations3D::Magnitude(soonLookDir)); if(val > 1.0f) val = 1.0f; if(val < -1.0f) val = -1.0f; float angle = acos(val); Quaternion rotation(axisOfRotation, angle * (percent / 100.0f)); forward = rotation * forward; right = rotation * right; up = rotation * up; forward = Operations3D::Normifyilation(forward); right = Operations3D::Normifyilation(right); up = Operations3D::Normifyilation(up); } void Thingie::SetPosition(Vector3 position){ this->position = position; } void Thingie::TurnRight(float angle){ Quaternion rotation(up, angle); forward = rotation * forward; right = rotation * right; up = rotation * up; forward = Operations3D::Normifyilation(forward); right = Operations3D::Normifyilation(right); up = Operations3D::Normifyilation(up); } void Thingie::TurnUp(float angle){ Quaternion rotation(right, angle); forward = rotation * forward; right = rotation * right; up = rotation * up; forward = Operations3D::Normifyilation(forward); right = Operations3D::Normifyilation(right); up = Operations3D::Normifyilation(up); } void Thingie::RotateByForward(float angle){ Quaternion rotation(forward, angle); forward = rotation * forward; right = rotation * right; up = rotation * up; forward = Operations3D::Normifyilation(forward); right = Operations3D::Normifyilation(right); up = Operations3D::Normifyilation(up); } void Thingie::RotateAt(Vector3 axis, float angle){ if(Operations3D::Magnitude(axis) == 0.0f) return; Quaternion rotation(axis, angle); forward = rotation * forward; right = rotation * right; up = rotation * up; forward = Operations3D::Normifyilation(forward); right = Operations3D::Normifyilation(right); up = Operations3D::Normifyilation(up); } void Thingie::MoveRight(float amount){ Vector3 offset = Operations3D::Normifyilation(right, amount); position = position + offset; } void Thingie::MoveUp(float amount){ Vector3 offset = Operations3D::Normifyilation(up, amount); position = position + offset; } void Thingie::MoveForward(float amount){ Vector3 offset = Operations3D::Normifyilation(forward, amount); position = position + offset; } Quaternion Thingie::GetQuaternion(){ Vector3 zForward(0, 0, 1); Vector3 axis = Operations3D::CrossProduct(zForward, this->forward); //D3DXVec3Normalize(&axis, &axis); float val = Operations3D::DotProduct(zForward, this->forward); if(val != 0.0f){ val /= (Operations3D::Magnitude(zForward) * Operations3D::Magnitude(this->forward)); if(val > 1.0f) val = 1.0f; if(val < -1.0f) val = -1.0f; val = acos(val); } Quaternion fromForward(axis, val); Vector3 fakeUp = fromForward * Vector3(0, 1, 0); fakeUp = Operations3D::Normifyilation(fakeUp); axis = Operations3D::CrossProduct(fakeUp, this->up); float val2 = Operations3D::DotProduct(fakeUp, this->up); if(val2 != 0.0f){ val2 /= (Operations3D::Magnitude(fakeUp) * Operations3D::Magnitude(this->up)); if(val2 > 1.0f) val2 = 1.0f; if(val2 < -1.0f) val2 = -1.0f; val2 = acos(val2); } Quaternion forwardRot(axis, val2); return (forwardRot * fromForward); } Matrix Thingie::GetMatrix(){ return (Matrix)GetQuaternion(); }
[ "Kivu.Rako@54144a58-e977-11dd-a550-c997509ed985" ]
[ [ [ 1, 150 ] ] ]
40fe36eed8e2b5984cf4f6e2636d4359b749d057
aa5491d8b31750da743472562e85dd4987f1258a
/Main/server/pedpool.cpp
83ffa3035ef8b8faf182ddeb83e971fad4de38b2
[]
no_license
LBRGeorge/jmnvc
d841ad694eaa761d0a45ab95b210758c50750d17
064402f0a9f1536229b99cf45f6e7536e1ae7bb5
refs/heads/master
2016-08-04T03:12:18.402941
2009-05-31T18:40:42
2009-05-31T18:40:42
39,416,169
2
0
null
null
null
null
UTF-8
C++
false
false
1,711
cpp
/* TODO: Write code to sync the peds controls and position etc */ #include "netgame.h" CPedPool::CPedPool() { BYTE bytePedID = 0; while(bytePedID != MAX_PEDS) { m_bPedSlotState[bytePedID] = FALSE; m_pPeds[bytePedID] = NULL; bytePedID++; } } BOOL CPedPool::InitialiseFromConfig(CConfig *pConfig) { int iPedArrayCount; BYTE d=1; int iModelID; VECTOR vecPos; float fRotation; int iColor1, iColor2; char * szConfigLine; iPedArrayCount = pConfig->GetConfigArrayCount("PED"); iPedArrayCount++; while((int)d < iPedArrayCount) { szConfigLine = pConfig->GetConfigEntryAsString("PED",d); sscanf(szConfigLine,"%d%f%f%f%f%d%d",&iModelID, &vecPos.X,&vecPos.Y,&vecPos.Z,&fRotation,&iColor1,&iColor2); New(d,(BYTE)iModelID,&vecPos,fRotation,iColor1,iColor2); d++; } return TRUE; } CPedPool::~CPedPool() { BYTE bytePedID = 0; while(bytePedID != MAX_PEDS) { Delete(bytePedID); bytePedID++; } } BOOL CPedPool::New(BYTE bytePedID, BYTE bytePedType, VECTOR * vecPos, float fRotation, int iColor1, int iColor2) { m_pPeds[bytePedID] = new CPed(bytePedType,vecPos,fRotation,iColor1,iColor2); if(m_pPeds[bytePedID]) { m_pPeds[bytePedID]->SetID(bytePedID); m_bPedSlotState[bytePedID] = TRUE; return TRUE; } else { return FALSE; } } BOOL CPedPool::Delete(BYTE bytePedID) { if(!GetSlotState(bytePedID) || !m_pPeds[bytePedID]) { return FALSE; } m_bPedSlotState[bytePedID] = FALSE; delete m_pPeds[bytePedID]; m_pPeds[bytePedID] = NULL; return TRUE; } void CPedPool::Process() { }
[ "jacks.mini.net@45e629aa-34f5-11de-82fb-7f665ef830f7" ]
[ [ [ 1, 89 ] ] ]
c802a6977a111b3a9736f4831e9f858257dde5e7
324524076ba7b05d9d8cf5b65f4cd84072c2f771
/Checkers/Libraries/Common/eSockets/EspoSock.cpp
2cda7a52df1490d5d33ac8ceedf1dffe4d45e9ef
[ "BSD-2-Clause" ]
permissive
joeyespo-archive/checkers-c
3bf9ff11f5f1dee4c17cd62fb8af9ba79246e1c3
477521eb0221b747e93245830698d01fafd2bd66
refs/heads/master
2021-01-01T05:32:45.964978
2011-03-13T04:53:08
2011-03-13T04:53:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,883
cpp
// EspoSock.cpp // Espo Sockets Implementation File // By Joe Esposito #pragma once // Include Header File: #include "EspoSock.h" // Include Source Files // --------------------- #include "DFD.cpp" #include "SocketGroup.cpp" bool WSAStartup (BYTE major, BYTE minor, LPWSADATA lpWSAData) { WSADATA wsaData; if (!WSAStartup(MAKEWORD(major, minor), &wsaData)) return false; if ((LOBYTE(wsaData.wVersion) != major) || ((HIBYTE(wsaData.wVersion) != minor))) { WSACleanup(); return false; } if (lpWSAData != NULL) memcpy(lpWSAData, &wsaData, sizeof(WSADATA)); return true; } char *WSAGetLastErrorMessage () { switch (WSAGetLastError()) { // Windows Sockets definitions of regular Microsoft C error constants case WSAEINTR: return "WSAEINTR"; case WSAEBADF: return "WSAEBADF"; case WSAEACCES: return "WSAEACCES"; case WSAEFAULT: return "WSAEFAULT"; case WSAEINVAL: return "WSAEINVAL"; case WSAEMFILE: return "WSAEMFILE"; // Windows Sockets definitions of regular Berkeley error constants case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK"; case WSAEINPROGRESS: return "WSAEINPROGRESS"; case WSAEALREADY: return "WSAEALREADY"; case WSAENOTSOCK: return "WSAENOTSOCK"; case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ"; case WSAEMSGSIZE: return "WSAEMSGSIZE"; case WSAEPROTOTYPE: return "WSAEPROTOTYPE"; case WSAENOPROTOOPT: return "WSAENOPROTOOPT"; case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT"; case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT"; case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP"; case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT"; case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT"; case WSAEADDRINUSE: return "WSAEADDRINUSE"; case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL"; case WSAENETDOWN: return "WSAENETDOWN"; case WSAENETUNREACH: return "WSAENETUNREACH"; case WSAENETRESET: return "WSAENETRESET"; case WSAECONNABORTED: return "WSAECONNABORTED"; case WSAECONNRESET: return "WSAECONNRESET"; case WSAENOBUFS: return "WSAENOBUFS"; case WSAEISCONN: return "WSAEISCONN"; case WSAENOTCONN: return "WSAENOTCONN"; case WSAESHUTDOWN: return "WSAESHUTDOWN"; case WSAETOOMANYREFS: return "WSAETOOMANYREFS"; case WSAETIMEDOUT: return "WSAETIMEDOUT"; case WSAECONNREFUSED: return "WSAECONNREFUSED"; case WSAELOOP: return "WSAELOOP"; case WSAENAMETOOLONG: return "WSAENAMETOOLONG"; case WSAEHOSTDOWN: return "WSAEHOSTDOWN"; case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH"; case WSAENOTEMPTY: return "WSAENOTEMPTY"; case WSAEPROCLIM: return "WSAEPROCLIM"; case WSAEUSERS: return "WSAEUSERS"; case WSAEDQUOT: return "WSAEDQUOT"; case WSAESTALE: return "WSAESTALE"; case WSAEREMOTE: return "WSAEREMOTE"; case WSAEDISCON: return "WSAEDISCON"; // Extended Windows Sockets error constant definitions case WSASYSNOTREADY: return "WSASYSNOTREADY"; case WSAVERNOTSUPPORTED: return "WSAVERNOTSUPPORTED"; case WSANOTINITIALISED: return "WSANOTINITIALISED"; // Other case WSAHOST_NOT_FOUND: return "WSAHOST_NOT_FOUND"; case WSATRY_AGAIN: return "WSATRY_AGAIN"; case WSANO_RECOVERY: return "WSANO_RECOVERY"; case WSANO_DATA: return "WSANO_DATA"; // Default case 0: return "NO ERROR"; default: return "UNKNOWN ERROR"; } } /* char *GetLocalIP() { hostent *HostEnt; in_addr addr_in; char *LocalHost; LocalHost = new char[256]; gethostname(LocalHost, 256); HostEnt = gethostbyname(LocalHost); addr_in.S_un.S_un_b.s_b1 = HostEnt->h_addr_list[0][0]; addr_in.S_un.S_un_b.s_b2 = HostEnt->h_addr_list[0][1]; addr_in.S_un.S_un_b.s_b3 = HostEnt->h_addr_list[0][2]; addr_in.S_un.S_un_b.s_b4 = HostEnt->h_addr_list[0][3]; LocalHost = inet_ntoa(addr_in); return LocalHost; } */
[ [ [ 1, 134 ] ] ]
d04e96449b4abc60d4a3037739df1115bb64507c
51e4aeb0d5e29ae1e8a9d8cf467797da2054b0f1
/src/mainMenu.cpp
cebd972541845f711a2ed60d2471ccf927ea208e
[]
no_license
vashero/tachyon-game
b3340272ee58c11077eef077485f8a01e4c81881
5fc2daac314c0b3b19b7336f8eb29d81a5e05729
refs/heads/master
2016-09-09T23:47:14.315285
2009-05-10T17:47:53
2009-05-10T17:47:53
32,647,791
0
0
null
null
null
null
UTF-8
C++
false
false
6,844
cpp
/*============================================================== * Copyright (c) 2009 Blake Fisher. All Rights Reserved. * * This software is released under the BSD License * <http://www.opensource.org/licenses/bsd-license.php> *============================================================== */ #include "mainMenu.hpp" #include "elements/CEGUIPushButton.h" MainMenu::MainMenu(Core *core, RenderWindow *win, const String &shipConfigFilename) { mCameraControl = false; mCore = core; mWin = win; mRotateSpeed = MAIN_MENU_DEF_ROTATE_SPEED; mSceneMgr = NULL; mArenaView = NULL; mGameMenu = NULL; // Create the main menu scene this->create_scene(shipConfigFilename); // Create the actual menu object mGameMenu = new GameMenu(mWin, mSceneMgr); // subscribe to be the input listener for main menu events mCore->get_state_machine()->request_state_change(CORE_MAIN_MENU); mCore->get_input_router()->register_listener(this, CORE_MAIN_MENU); mCore->get_frame_router()->register_listener(this, CORE_MAIN_MENU); } MainMenu::~MainMenu() { if (mArenaView) { delete mArenaView; } if (mGameMenu) { delete mGameMenu; } } void MainMenu::quit() { mCore->get_state_machine()->request_state_change(CORE_SHUTDOWN); } void MainMenu::show() { this->set_callbacks(mGameMenu->push_state(MAIN_MENU_ROOT)); } bool MainMenu::New_Game_OnClick(const CEGUI::EventArgs &args) { return true; } bool MainMenu::Options_OnClick(const CEGUI::EventArgs &args) { this->set_callbacks(mGameMenu->push_state(MAIN_MENU_OPTIONS)); return true; } bool MainMenu::Model_OnClick(const CEGUI::EventArgs &args) { this->set_callbacks(mGameMenu->push_state(MAIN_MENU_MODEL)); return true; } bool MainMenu::Quit_OnClick(const CEGUI::EventArgs &args) { this->quit(); return true; } bool MainMenu::Back_OnClick(const CEGUI::EventArgs &args) { this->menu_back(); return true; } bool MainMenu::More_OnClick(const CEGUI::EventArgs &args) { this->set_callbacks(mGameMenu->push_state(MAIN_MENU_OPTIONS_MORE)); return true; } bool MainMenu::Cruiser_OnClick(const CEGUI::EventArgs &args) { this->switch_model(SHIP_VIEW_CRUISER); return true; } bool MainMenu::Superiority_OnClick(const CEGUI::EventArgs &args) { this->switch_model(SHIP_VIEW_SUPERIORITY); return true; } bool MainMenu::Test_OnClick(const CEGUI::EventArgs &args) { this->switch_model(SHIP_VIEW_NONE); return true; } bool MainMenu::mouseMoved(const OIS::MouseEvent &evt) { if (mCameraControl) { mArenaView->rotate_camera(Radian((float)evt.state.X.rel/10), Radian((float)evt.state.Y.rel/10)); } if (!mGameMenu) { return true; } return mGameMenu->mouseMoved(evt); } bool MainMenu::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID mouseButtonID) { if (!mGameMenu || !mGameMenu->mousePressed(evt, mouseButtonID)) { // If a mouse button has been pressed outside of the gui, take // control of the camera mCameraControl = true; CEGUI::MouseCursor::getSingleton().hide(); } return true; } bool MainMenu::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID mouseButtonID) { mCameraControl = false; CEGUI::MouseCursor::getSingleton().show(); if (!mGameMenu) { return true; } return mGameMenu->mouseReleased(evt, mouseButtonID); } bool MainMenu::keyPressed(const OIS::KeyEvent &evt) { if (evt.key == OIS::KC_ESCAPE) { this->menu_back(); } if (!mGameMenu) { return true; } return mGameMenu->keyPressed(evt); } bool MainMenu::keyReleased(const OIS::KeyEvent &evt) { if (!mGameMenu) { return true; } return mGameMenu->keyReleased(evt); } bool MainMenu::frameStarted(const FrameEvent &evt) { if (!mCameraControl) { mArenaView->rotate_camera(Degree(mRotateSpeed * evt.timeSinceLastFrame), Degree(0)); } return true; } void MainMenu::set_callbacks(CEGUI::Window *window) { String prefixName = mGameMenu->get_prefix_name(); for (unsigned int i = 0; i < window->getChildCount(); i++) { CEGUI::Window *childWin = window->getChildAtIdx(i); CEGUI::String winName = childWin->getName(); // The prefix is not needed for assigning callbacks winName = winName.substr(prefixName.length()); if (winName == "cmd_New_Game") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::New_Game_OnClick, this)); } else if (winName == "cmd_Options") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::Options_OnClick, this)); } else if (winName == "cmd_Model") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::Model_OnClick, this)); } else if (winName == "cmd_Quit") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::Quit_OnClick, this)); } else if (winName == "cmd_Back") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::Back_OnClick, this)); } else if (winName == "cmd_More") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::More_OnClick, this)); } else if (winName == "cmd_Cruiser") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::Cruiser_OnClick, this)); } else if (winName == "cmd_Superiority") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::Superiority_OnClick, this)); } else if (winName == "cmd_Test") { childWin->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MainMenu::Test_OnClick, this)); } } } bool MainMenu::create_scene(const String &shipConfigFilename) { if (!mWin) { // Need a window to render in return false; } if (mSceneMgr) { // If we already have created a scene manager, just empty it mSceneMgr->clearScene(); } else { mSceneMgr = Root::getSingletonPtr()->createSceneManager(ST_GENERIC, "GUIManager"); } // Create the view that will be in the background mArenaView = new ArenaView(mWin, shipConfigFilename, "GUIManager"); // Rotate the camera so we're not directly above the model mArenaView->rotate_camera(Radian(0), Radian(Degree(45))); // Add a ship to the arena view this->switch_model(SHIP_VIEW_CRUISER); return true; } void MainMenu::switch_model(const ShipViewType &newModel) { mArenaView->clear_ships(); if (newModel != SHIP_VIEW_NONE) { mArenaView->add_ship(newModel, Vector3::ZERO, Radian(0)); } } void MainMenu::menu_back() { if (mGameMenu) { if (!mGameMenu->pop_state()) { this->quit(); } } }
[ "[email protected]@b90cb52e-2f47-11de-8816-6191455234fe" ]
[ [ [ 1, 255 ] ] ]
349b0127ac916eb6042ac515d4e2b0ee6bc192ec
39f755afd5f4f3abe91a24342746774781704fa7
/cob_undercarriage_ctrl/common/src/UndercarriageCtrlGeom.cpp
b4257eaee0d68ec831ae001c88c1055c4df88b01
[]
no_license
attilaachenbach/cob_driver
b1e280259521a47a07838a13fd35f218ae0c0f24
46acb2fe8114f04ce9909ef9488b6302d2530f9e
refs/heads/master
2021-01-15T20:48:35.405544
2011-04-29T17:28:25
2011-04-29T17:28:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,254
cpp
/**************************************************************** * * Copyright (c) 2010 * * Fraunhofer Institute for Manufacturing Engineering * and Automation (IPA) * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Project name: care-o-bot * ROS stack name: cob_driver * ROS package name: cob_undercarriage_ctrl * Description: * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Author: Christian Connette, email:[email protected] * Supervised by: Christian Connette, email:[email protected] * * Date of creation: April 2010: * ToDo: * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Fraunhofer Institute for Manufacturing * Engineering and Automation (IPA) nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License LGPL as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License LGPL for more details. * * You should have received a copy of the GNU Lesser General Public * License LGPL along with this program. * If not, see <http://www.gnu.org/licenses/>. * ****************************************************************/ #include <cob_undercarriage_ctrl/UndercarriageCtrlGeom.h> // Constructor UndercarriageCtrlGeom::UndercarriageCtrlGeom(std::string sIniDirectory) { m_sIniDirectory = sIniDirectory; // init EMStop flag m_bEMStopActive = false; IniFile iniFile; iniFile.SetFileName(m_sIniDirectory + "Platform.ini", "UnderCarriageCtrlGeom.cpp"); iniFile.GetKeyInt("Config", "NumberOfWheels", &m_iNumberOfDrives, true); // init vectors m_vdVelGearDriveRadS.assign(4,0); m_vdVelGearSteerRadS.assign(4,0); m_vdDltAngGearDriveRad.assign(4,0); m_vdAngGearSteerRad.assign(4,0); //m_vdVelGearDriveIntpRadS.assign(4,0); //m_vdVelGearSteerIntpRadS.assign(4,0); //m_vdAngGearSteerIntpRad.assign(4,0); m_vdVelGearDriveCmdRadS.assign(4,0); m_vdVelGearSteerCmdRadS.assign(4,0); m_vdAngGearSteerCmdRad.assign(4,0); m_vdWheelXPosMM.assign(4,0); m_vdWheelYPosMM.assign(4,0); m_vdWheelDistMM.assign(4,0); m_vdWheelAngRad.assign(4,0); m_vdExWheelXPosMM.assign(4,0); m_vdExWheelYPosMM.assign(4,0); m_vdExWheelDistMM.assign(4,0); m_vdExWheelAngRad.assign(4,0); m_vdAngGearSteerTarget1Rad.assign(4,0); m_vdVelGearDriveTarget1RadS.assign(4,0); m_vdAngGearSteerTarget2Rad.assign(4,0); m_vdVelGearDriveTarget2RadS.assign(4,0); m_vdAngGearSteerTargetRad.assign(4,0); m_vdVelGearDriveTargetRadS.assign(4,0); m_dCmdVelLongMMS = 0; m_dCmdVelLatMMS = 0; m_dCmdRotRobRadS = 0; m_dCmdRotVelRadS = 0; m_UnderCarriagePrms.WheelNeutralPos.assign(4,0); m_UnderCarriagePrms.vdSteerDriveCoupling.assign(4,0); m_UnderCarriagePrms.vdFactorVel.assign(4,0); m_vdCtrlVal.assign( 4, std::vector<double> (2,0.0) ); //m_vdDeltaAngIntpRad.assign(4,0); //m_vdDeltaDriveIntpRadS.assign(4,0); // init Prms of Impedance-Ctrlr m_dSpring = 10.0; m_dDamp = 2.5; m_dVirtM = 0.1; m_dDPhiMax = 12.0; m_dDDPhiMax = 100.0; /*// Logging for debugging // Init timestamp for startup of the robot m_StartTime.SetNow(); // open Files for PltfVel m_pfileDesVel = fopen("LogCtrl/DesPltfVel.txt","w"); m_pfileMeasVel = fopen("LogCtrl/MeasPltfVel.txt","w"); // open Files for corresponding Joint-Configuration m_pfileSteerAngTarget1 = fopen("LogCtrl/SteerAngTarget1.txt","w"); m_pfileSteerAngTarget2 = fopen("LogCtrl/SteerAngTarget2.txt","w"); m_pfileSteerAngTarget = fopen("LogCtrl/SteerAngTarget.txt","w"); m_pfileDriveVelTarget = fopen("LogCtrl/DriveVelTarget.txt","w"); // open Files for resulting Joint-Commands m_pfileSteerAngCmd = fopen("LogCtrl/SteerAngCmd.txt","w"); m_pfileSteerVelCmd = fopen("LogCtrl/SteerVelCmd.txt","w"); m_pfileDriveVelCmd = fopen("LogCtrl/DriveVelCmd.txt","w");*/ } // Destructor UndercarriageCtrlGeom::~UndercarriageCtrlGeom(void) { /*fclose(m_pfileDesVel); fclose(m_pfileMeasVel); fclose(m_pfileSteerAngTarget1); fclose(m_pfileSteerAngTarget2); fclose(m_pfileSteerAngTarget); fclose(m_pfileDriveVelTarget); fclose(m_pfileSteerAngCmd); fclose(m_pfileSteerVelCmd); fclose(m_pfileDriveVelCmd);*/ } // Initialize Parameters for Controller and Kinematics void UndercarriageCtrlGeom::InitUndercarriageCtrl(void) { //LOG_OUT("Initializing Undercarriage-Controller (Geom)"); IniFile iniFile; iniFile.SetFileName(m_sIniDirectory + "Platform.ini", "UnderCarriageCtrlGeom.cpp"); iniFile.GetKeyInt("Geom", "DistWheels", &m_UnderCarriagePrms.iDistWheels, true); iniFile.GetKeyInt("Geom", "RadiusWheel", &m_UnderCarriagePrms.iRadiusWheelMM, true); iniFile.GetKeyInt("Geom", "DistSteerAxisToDriveWheelCenter", &m_UnderCarriagePrms.iDistSteerAxisToDriveWheelMM, true); iniFile.GetKeyDouble("Geom", "Wheel1XPos", &m_vdWheelXPosMM[0], true); iniFile.GetKeyDouble("Geom", "Wheel1YPos", &m_vdWheelYPosMM[0], true); iniFile.GetKeyDouble("Geom", "Wheel2XPos", &m_vdWheelXPosMM[1], true); iniFile.GetKeyDouble("Geom", "Wheel2YPos", &m_vdWheelYPosMM[1], true); iniFile.GetKeyDouble("Geom", "Wheel3XPos", &m_vdWheelXPosMM[2], true); iniFile.GetKeyDouble("Geom", "Wheel3YPos", &m_vdWheelYPosMM[2], true); iniFile.GetKeyDouble("Geom", "Wheel4XPos", &m_vdWheelXPosMM[3], true); iniFile.GetKeyDouble("Geom", "Wheel4YPos", &m_vdWheelYPosMM[3], true); iniFile.GetKeyDouble("DrivePrms", "MaxDriveRate", &m_UnderCarriagePrms.dMaxDriveRateRadpS, true); iniFile.GetKeyDouble("DrivePrms", "MaxSteerRate", &m_UnderCarriagePrms.dMaxSteerRateRadpS, true); iniFile.GetKeyDouble("DrivePrms", "Wheel1SteerDriveCoupling", &m_UnderCarriagePrms.vdSteerDriveCoupling[0], true); iniFile.GetKeyDouble("DrivePrms", "Wheel2SteerDriveCoupling", &m_UnderCarriagePrms.vdSteerDriveCoupling[1], true); iniFile.GetKeyDouble("DrivePrms", "Wheel3SteerDriveCoupling", &m_UnderCarriagePrms.vdSteerDriveCoupling[2], true); iniFile.GetKeyDouble("DrivePrms", "Wheel4SteerDriveCoupling", &m_UnderCarriagePrms.vdSteerDriveCoupling[3], true); iniFile.GetKeyDouble("DrivePrms", "Wheel1NeutralPosition", &m_UnderCarriagePrms.WheelNeutralPos[0], true); iniFile.GetKeyDouble("DrivePrms", "Wheel2NeutralPosition", &m_UnderCarriagePrms.WheelNeutralPos[1], true); iniFile.GetKeyDouble("DrivePrms", "Wheel3NeutralPosition", &m_UnderCarriagePrms.WheelNeutralPos[2], true); iniFile.GetKeyDouble("DrivePrms", "Wheel4NeutralPosition", &m_UnderCarriagePrms.WheelNeutralPos[3], true); for(int i = 0; i<4; i++) { m_UnderCarriagePrms.WheelNeutralPos[i] = MathSup::convDegToRad(m_UnderCarriagePrms.WheelNeutralPos[i]); // provisorial --> skip interpolation m_vdAngGearSteerCmdRad[i] = m_UnderCarriagePrms.WheelNeutralPos[i]; //m_vdAngGearSteerIntpRad[i] = m_UnderCarriagePrms.WheelNeutralPos[i]; // also Init choosen Target angle m_vdAngGearSteerTargetRad[i] = m_UnderCarriagePrms.WheelNeutralPos[i]; } iniFile.GetKeyDouble("Thread", "ThrUCarrCycleTimeS", &m_UnderCarriagePrms.dCmdRateS, true); // Read Values for Steering Position Controller from IniFile iniFile.SetFileName(m_sIniDirectory + "MotionCtrl.ini", "PltfHardwareCoB3.h"); // Prms of Impedance-Ctrlr iniFile.GetKeyDouble("SteerCtrl", "Spring", &m_dSpring, true); iniFile.GetKeyDouble("SteerCtrl", "Damp", &m_dDamp, true); iniFile.GetKeyDouble("SteerCtrl", "VirtMass", &m_dVirtM, true); iniFile.GetKeyDouble("SteerCtrl", "DPhiMax", &m_dDPhiMax, true); iniFile.GetKeyDouble("SteerCtrl", "DDPhiMax", &m_dDDPhiMax, true); // calculate polar coords of Wheel Axis in robot coordinate frame for(int i=0; i<4; i++) { m_vdWheelDistMM[i] = sqrt( (m_vdWheelXPosMM[i] * m_vdWheelXPosMM[i]) + (m_vdWheelYPosMM[i] * m_vdWheelYPosMM[i]) ); m_vdWheelAngRad[i] = MathSup::atan4quad(m_vdWheelXPosMM[i], m_vdWheelYPosMM[i]); } // Calculate exact position of wheels in cart. and polar coords in robot coordinate frame CalcExWheelPos(); // calculate compensation factor for velocity for(int i = 0; i<4; i++) { m_UnderCarriagePrms.vdFactorVel[i] = - m_UnderCarriagePrms.vdSteerDriveCoupling[i] +(double(m_UnderCarriagePrms.iDistSteerAxisToDriveWheelMM) / double(m_UnderCarriagePrms.iRadiusWheelMM)); } } // Set desired value for Plattfrom Velocity to UndercarriageCtrl (Sollwertvorgabe) void UndercarriageCtrlGeom::SetDesiredPltfVelocity(double dCmdVelLongMMS, double dCmdVelLatMMS, double dCmdRotRobRadS, double dCmdRotVelRadS) { // declare auxiliary variables double dCurrentPosWheelRAD; double dtempDeltaPhi1RAD, dtempDeltaPhi2RAD; // difference between possible steering angels and current steering angle double dtempDeltaPhiCmd1RAD, dtempDeltaPhiCmd2RAD; // difference between possible steering angels and last target steering angle double dtempWeightedDelta1RAD, dtempWeightedDelta2RAD; // weighted Summ of the two distance values // copy function parameters to member variables m_dCmdVelLongMMS = dCmdVelLongMMS; m_dCmdVelLatMMS = dCmdVelLatMMS; m_dCmdRotRobRadS = dCmdRotRobRadS; m_dCmdRotVelRadS = dCmdRotVelRadS; CalcInverse(); // determine optimal Pltf-Configuration for (int i = 0; i<4; i++) { // Normalize Actual Wheel Position before calculation dCurrentPosWheelRAD = m_vdAngGearSteerRad[i]; MathSup::normalizePi(dCurrentPosWheelRAD); // Calculate differences between current config to possible set-points dtempDeltaPhi1RAD = m_vdAngGearSteerTarget1Rad[i] - dCurrentPosWheelRAD; dtempDeltaPhi2RAD = m_vdAngGearSteerTarget2Rad[i] - dCurrentPosWheelRAD; MathSup::normalizePi(dtempDeltaPhi1RAD); MathSup::normalizePi(dtempDeltaPhi2RAD); // Calculate differences between last steering target to possible set-points dtempDeltaPhiCmd1RAD = m_vdAngGearSteerTarget1Rad[i] - m_vdAngGearSteerTargetRad[i]; dtempDeltaPhiCmd2RAD = m_vdAngGearSteerTarget2Rad[i] - m_vdAngGearSteerTargetRad[i]; MathSup::normalizePi(dtempDeltaPhiCmd1RAD); MathSup::normalizePi(dtempDeltaPhiCmd2RAD); // determine optimal setpoint value // 1st which set point is closest to current cinfog // but: avoid permanent switching (if next target is about PI/2 from current config) // 2nd which set point is closest to last set point // "fitness criteria" to choose optimal set point: // calculate accumulted (+ weighted) difference between targets, current config. and last command dtempWeightedDelta1RAD = 0.6*fabs(dtempDeltaPhi1RAD) + 0.4*fabs(dtempDeltaPhiCmd1RAD); dtempWeightedDelta2RAD = 0.6*fabs(dtempDeltaPhi2RAD) + 0.4*fabs(dtempDeltaPhiCmd2RAD); // check which set point "minimizes fitness criteria" if (dtempWeightedDelta1RAD <= dtempWeightedDelta2RAD) { // Target1 is "optimal" m_vdVelGearDriveTargetRadS[i] = m_vdVelGearDriveTarget1RadS[i]; m_vdAngGearSteerTargetRad[i] = m_vdAngGearSteerTarget1Rad[i]; } else { // Target2 is "optimal" m_vdVelGearDriveTargetRadS[i] = m_vdVelGearDriveTarget2RadS[i]; m_vdAngGearSteerTargetRad[i] = m_vdAngGearSteerTarget2Rad[i]; } // provisorial --> skip interpolation and always take Target1 //m_vdVelGearDriveCmdRadS[i] = m_vdVelGearDriveTarget1RadS[i]; //m_vdAngGearSteerCmdRad[i] = m_vdAngGearSteerTarget1Rad[i]; /*// interpolate between last setpoint and theone of the new setpoint, which is closest to the current configuration if (fabs(dtempDeltaPhi1RAD) <= fabs(dtempDeltaPhi2RAD)) { // difference between new target orientation and last (interpolated) target orientation dtempDeltaPhi1RAD = m_vdAngGearSteerTarget1Rad[i] - m_vdAngGearSteerIntpRad[i]; MathSup::normalizePi(dtempDeltaPhi1RAD); // calculate interpolation step sizes, to reach target at end of the cycle m_vdDeltaAngIntpRad[i] = dtempDeltaPhi1RAD; m_vdDeltaDriveIntpRadS[i] = (m_vdVelGearDriveTarget1RadS[i] - m_vdVelGearDriveIntpRadS[i]); // additionally calculate meen change in angular config for feedforward cmd //m_vdVelGearSteerIntpRadS[i] = dtempDeltaPhi1RAD/m_UnderCarriagePrms.dCmdRateS; } else { // difference between new target orientation and last (interpolated) target orientation dtempDeltaPhi2RAD = m_vdAngGearSteerTarget2Rad[i] - m_vdAngGearSteerIntpRad[i]; MathSup::normalizePi(dtempDeltaPhi2RAD); // calculate interpolation step sizes, to reach target at end of the cycle m_vdDeltaAngIntpRad[i] = dtempDeltaPhi2RAD; m_vdDeltaDriveIntpRadS[i] = (m_vdVelGearDriveTarget2RadS[i] - m_vdVelGearDriveIntpRadS[i]); // additionally calculate meen change in angular config for feedforward cmd //m_vdVelGearSteerIntpRadS[i] = dtempDeltaPhi2RAD/m_UnderCarriagePrms.dCmdRateS; }*/ } /*// Logging for debugging // get current time m_RawTime.SetNow(); m_dNowTime = m_RawTime - m_StartTime; // Log out Pltf-Velocities fprintf(m_pfileDesVel, "%f %f %f %f \n", m_dNowTime, dCmdVelLongMMS, dCmdVelLatMMS, dCmdRotRobRadS); fprintf(m_pfileMeasVel, "%f %f %f %f \n", m_dNowTime, m_dVelLongMMS, m_dVelLatMMS, m_dRotRobRadS); // Log out corresponding Joint-Configuration fprintf(m_pfileSteerAngTarget1, "%f %f %f %f %f \n", m_dNowTime, m_vdAngGearSteerTarget1Rad[0], m_vdAngGearSteerTarget1Rad[1], m_vdAngGearSteerTarget1Rad[2], m_vdAngGearSteerTarget1Rad[3]); fprintf(m_pfileSteerAngTarget2, "%f %f %f %f %f \n", m_dNowTime, m_vdAngGearSteerTarget2Rad[0], m_vdAngGearSteerTarget2Rad[1], m_vdAngGearSteerTarget2Rad[2], m_vdAngGearSteerTarget2Rad[3]); fprintf(m_pfileSteerAngTarget, "%f %f %f %f %f \n", m_dNowTime, m_vdAngGearSteerTargetRad[0], m_vdAngGearSteerTargetRad[1], m_vdAngGearSteerTargetRad[2], m_vdAngGearSteerTargetRad[3]); fprintf(m_pfileDriveVelTarget, "%f %f %f %f %f \n", m_dNowTime, m_vdVelGearDriveTargetRadS[0], m_vdVelGearDriveTargetRadS[1], m_vdVelGearDriveTargetRadS[2], m_vdVelGearDriveTargetRadS[3]);*/ } // Set actual values of wheels (steer/drive velocity/position) (Istwerte) void UndercarriageCtrlGeom::SetActualWheelValues(std::vector<double> vdVelGearDriveRadS, std::vector<double> vdVelGearSteerRadS, std::vector<double> vdDltAngGearDriveRad, std::vector<double> vdAngGearSteerRad) { //LOG_OUT("Set Wheel Position to Controller"); m_vdVelGearDriveRadS = vdVelGearDriveRadS; m_vdVelGearSteerRadS = vdVelGearSteerRadS; m_vdDltAngGearDriveRad = vdDltAngGearDriveRad; m_vdAngGearSteerRad = vdAngGearSteerRad; // calc exact Wheel Positions (taking into account lever arm) CalcExWheelPos(); // Peform calculation of direct kinematics (approx.) based on corrected Wheel Positions CalcDirect(); } // Get result of inverse kinematics (without controller) void UndercarriageCtrlGeom::GetSteerDriveSetValues(std::vector<double> & vdVelGearDriveRadS, std::vector<double> & vdAngGearSteerRad) { //LOG_OUT("Calculate Inverse for given Velocity Command"); CalcInverse(); vdVelGearDriveRadS = m_vdVelGearDriveTarget1RadS; vdAngGearSteerRad = m_vdAngGearSteerTarget1Rad; } // Get set point values for the Wheels (including controller) from UndercarriangeCtrl void UndercarriageCtrlGeom::GetNewCtrlStateSteerDriveSetValues(std::vector<double> & vdVelGearDriveRadS, std::vector<double> & vdVelGearSteerRadS, std::vector<double> & vdAngGearSteerRad, double & dVelLongMMS, double & dVelLatMMS, double & dRotRobRadS, double & dRotVelRadS) { if(m_bEMStopActive == false) { //Calculate next step CalcControlStep(); } vdVelGearDriveRadS = m_vdVelGearDriveCmdRadS; vdVelGearSteerRadS = m_vdVelGearSteerCmdRadS; vdAngGearSteerRad = m_vdAngGearSteerCmdRad; dVelLongMMS = m_dCmdVelLongMMS; dVelLatMMS = m_dCmdVelLatMMS; dRotRobRadS = m_dCmdRotRobRadS; dRotVelRadS = m_dCmdRotVelRadS; /*// Logging for debugging // get current time m_RawTime.SetNow(); m_dNowTime = m_RawTime - m_StartTime; // Log out resulting joint-commands fprintf(m_pfileSteerAngCmd, "%f %f %f %f %f \n", m_dNowTime, m_vdAngGearSteerCmdRad[0], m_vdAngGearSteerCmdRad[1], m_vdAngGearSteerCmdRad[2], m_vdAngGearSteerCmdRad[3]); fprintf(m_pfileSteerVelCmd, "%f %f %f %f %f \n", m_dNowTime, m_vdVelGearSteerCmdRadS[0], m_vdVelGearSteerCmdRadS[1], m_vdVelGearSteerCmdRadS[2], m_vdVelGearSteerCmdRadS[3]); fprintf(m_pfileDriveVelCmd, "%f %f %f %f %f \n", m_dNowTime, m_vdVelGearDriveCmdRadS[0], m_vdVelGearDriveCmdRadS[1], m_vdVelGearDriveCmdRadS[2], m_vdVelGearDriveCmdRadS[3]);*/ } // Get result of direct kinematics void UndercarriageCtrlGeom::GetActualPltfVelocity(double & dDeltaLongMM, double & dDeltaLatMM, double & dDeltaRotRobRad, double & dDeltaRotVelRad, double & dVelLongMMS, double & dVelLatMMS, double & dRotRobRadS, double & dRotVelRadS) { dVelLongMMS = m_dVelLongMMS; dVelLatMMS = m_dVelLatMMS; dRotRobRadS = m_dRotRobRadS; dRotVelRadS = m_dRotVelRadS; // calculate travelled distance and angle (from velocity) for output // ToDo: make sure this corresponds to cycle-freqnecy of calling node // --> specify via config file dDeltaLongMM = dVelLongMMS * m_UnderCarriagePrms.dCmdRateS; dDeltaLatMM = dVelLatMMS * m_UnderCarriagePrms.dCmdRateS; dDeltaRotRobRad = dRotRobRadS * m_UnderCarriagePrms.dCmdRateS; dDeltaRotVelRad = dRotVelRadS * m_UnderCarriagePrms.dCmdRateS; } // calculate inverse kinematics void UndercarriageCtrlGeom::CalcInverse(void) { // help variable to store velocities of the steering axis in mm/s double dtempAxVelXRobMMS, dtempAxVelYRobMMS; // check if zero movement commanded -> keep orientation of wheels, set wheel velocity to zero if((m_dCmdVelLongMMS == 0) && (m_dCmdVelLatMMS == 0) && (m_dCmdRotRobRadS == 0) && (m_dCmdRotVelRadS == 0)) { for(int i = 0; i<4; i++) { m_vdAngGearSteerTarget1Rad[i] = m_vdAngGearSteerRad[i]; m_vdVelGearDriveTarget1RadS[i] = 0.0; m_vdAngGearSteerTarget2Rad[i] = m_vdAngGearSteerRad[i]; m_vdVelGearDriveTarget2RadS[i] = 0.0; } return; } // calculate sets of possible Steering Angle // Drive-Velocity combinations for (int i = 0; i<4; i++) { // calculate velocity and direction of single wheel motion // Translational Portion dtempAxVelXRobMMS = m_dCmdVelLongMMS; dtempAxVelYRobMMS = m_dCmdVelLatMMS; // Rotational Portion dtempAxVelXRobMMS += m_dCmdRotRobRadS * m_vdExWheelDistMM[i] * -sin(m_vdExWheelAngRad[i]); dtempAxVelYRobMMS += m_dCmdRotRobRadS * m_vdExWheelDistMM[i] * cos(m_vdExWheelAngRad[i]); // calculate resulting steering angle // Wheel has to move in direction of resulting velocity vector of steering axis m_vdAngGearSteerTarget1Rad[i] = MathSup::atan4quad(dtempAxVelYRobMMS, dtempAxVelXRobMMS); // calculate corresponding angle in opposite direction (+180 degree) m_vdAngGearSteerTarget2Rad[i] = m_vdAngGearSteerTarget1Rad[i] + MathSup::PI; MathSup::normalizePi(m_vdAngGearSteerTarget2Rad[i]); // calculate absolute value of rotational rate of driving wheels in rad/s m_vdVelGearDriveTarget1RadS[i] = sqrt( (dtempAxVelXRobMMS * dtempAxVelXRobMMS) + (dtempAxVelYRobMMS * dtempAxVelYRobMMS) ) / (double)m_UnderCarriagePrms.iRadiusWheelMM; // now adapt to direction (forward/backward) of wheel m_vdVelGearDriveTarget2RadS[i] = - m_vdVelGearDriveTarget1RadS[i]; } } // calculate direct kinematics void UndercarriageCtrlGeom::CalcDirect(void) { // declare auxilliary variables double dtempVelXRobMMS; // Robot-Velocity in x-Direction (longitudinal) in mm/s (in Robot-Coordinateframe) double dtempVelYRobMMS; // Robot-Velocity in y-Direction (lateral) in mm/s (in Robot-Coordinateframe) double dtempRotRobRADPS; // Robot-Rotation-Rate in rad/s (in Robot-Coordinateframe) double dtempDiffXMM; // Difference in X-Coordinate of two wheels in mm double dtempDiffYMM; // Difference in Y-Coordinate of two wheels in mm double dtempRelPhiWheelsRAD; // Angle between axis of two wheels w.r.t the X-Axis of the Robot-Coordinate-System in rad double dtempRelDistWheelsMM; // distance of two wheels in mm double dtempRelPhiWheel1RAD; // Steering Angle of (im math. pos. direction) first Wheel w.r.t. the linking axis of the two wheels double dtempRelPhiWheel2RAD; // Steering Angle of (im math. pos. direction) first Wheel w.r.t. the linking axis of the two wheels std::vector<double> vdtempVelWheelMMS(4); // Wheel-Velocities (all Wheels) in mm/s // initial values dtempVelXRobMMS = 0; // Robot-Velocity in x-Direction (longitudinal) in mm/s (in Robot-Coordinateframe) dtempVelYRobMMS = 0; // Robot-Velocity in y-Direction (lateral) in mm/s (in Robot-Coordinateframe) dtempRotRobRADPS = 0; // calculate corrected wheel velocities for(int i = 0; i<4; i++) { // calc effective Driving-Velocity vdtempVelWheelMMS[i] = m_UnderCarriagePrms.iRadiusWheelMM * (m_vdVelGearDriveRadS[i] - m_UnderCarriagePrms.vdFactorVel[i]* m_vdVelGearSteerRadS[i]); } // calculate rotational rate of robot and current "virtual" axis between all wheels for(int i = 0; i<3; i++) { // calc Parameters (Dist,Phi) of virtual linking axis of the two considered wheels dtempDiffXMM = m_vdExWheelXPosMM[i+1] - m_vdExWheelXPosMM[i]; dtempDiffYMM = m_vdExWheelYPosMM[i+1] - m_vdExWheelYPosMM[i]; dtempRelDistWheelsMM = sqrt( dtempDiffXMM*dtempDiffXMM + dtempDiffYMM*dtempDiffYMM ); dtempRelPhiWheelsRAD = MathSup::atan4quad( dtempDiffYMM, dtempDiffXMM ); // transform velocity of wheels into relative coordinate frame of linking axes -> subtract angles dtempRelPhiWheel1RAD = m_vdAngGearSteerRad[i] - dtempRelPhiWheelsRAD; dtempRelPhiWheel2RAD = m_vdAngGearSteerRad[i+1] - dtempRelPhiWheelsRAD; dtempRotRobRADPS += (vdtempVelWheelMMS[i+1] * sin(dtempRelPhiWheel2RAD) - vdtempVelWheelMMS[i] * sin(dtempRelPhiWheel1RAD))/dtempRelDistWheelsMM; } // calculate last missing axis (between wheel 4 and 1) // calc. Parameters (Dist,Phi) of virtual linking axis of the two considered wheels dtempDiffXMM = m_vdExWheelXPosMM[0] - m_vdExWheelXPosMM[3]; dtempDiffYMM = m_vdExWheelYPosMM[0] - m_vdExWheelYPosMM[3]; dtempRelDistWheelsMM = sqrt( dtempDiffXMM*dtempDiffXMM + dtempDiffYMM*dtempDiffYMM ); dtempRelPhiWheelsRAD = MathSup::atan4quad( dtempDiffYMM, dtempDiffXMM ); // transform velocity of wheels into relative coordinate frame of linking axes -> subtract angles dtempRelPhiWheel1RAD = m_vdAngGearSteerRad[3] - dtempRelPhiWheelsRAD; dtempRelPhiWheel2RAD = m_vdAngGearSteerRad[0] - dtempRelPhiWheelsRAD; // close calculation of robots rotational velocity dtempRotRobRADPS += (vdtempVelWheelMMS[0]*sin(dtempRelPhiWheel2RAD) - vdtempVelWheelMMS[3]*sin(dtempRelPhiWheel1RAD))/dtempRelDistWheelsMM; // calculate linear velocity of robot for(int i = 0; i<4; i++) { dtempVelXRobMMS += vdtempVelWheelMMS[i]*cos(m_vdAngGearSteerRad[i]); dtempVelYRobMMS += vdtempVelWheelMMS[i]*sin(m_vdAngGearSteerRad[i]); } // assign rotational velocities for output m_dRotRobRadS = dtempRotRobRADPS/4; m_dRotVelRadS = 0; // currently not used to represent 3rd degree of freedom -> set to zero // assign linear velocity of robot for output m_dVelLongMMS = dtempVelXRobMMS/4; m_dVelLatMMS = dtempVelYRobMMS/4; } // calculate Exact Wheel Position in robot coordinates void UndercarriageCtrlGeom::CalcExWheelPos(void) { // calculate wheel position and velocity for(int i = 0; i<4; i++) { // calculate current geometry of robot (exact wheel position, taking into account steering offset of wheels) m_vdExWheelXPosMM[i] = m_vdWheelXPosMM[i] + m_UnderCarriagePrms.iDistSteerAxisToDriveWheelMM * sin(m_vdAngGearSteerRad[i]); m_vdExWheelYPosMM[i] = m_vdWheelYPosMM[i] - m_UnderCarriagePrms.iDistSteerAxisToDriveWheelMM * cos(m_vdAngGearSteerRad[i]); // calculate distance from platform center to wheel center m_vdExWheelDistMM[i] = sqrt( (m_vdExWheelXPosMM[i] * m_vdExWheelXPosMM[i]) + (m_vdExWheelYPosMM[i] * m_vdExWheelYPosMM[i]) ); // calculate direction of rotational vector m_vdExWheelAngRad[i] = MathSup::atan4quad( m_vdExWheelYPosMM[i], m_vdExWheelXPosMM[i]); } } // perform one discrete Control Step (controls steering angle) void UndercarriageCtrlGeom::CalcControlStep(void) { // check if zero movement commanded -> keep orientation of wheels, set steer velocity to zero if ((m_dCmdVelLongMMS == 0) && (m_dCmdVelLatMMS == 0) && (m_dCmdRotRobRadS == 0) && (m_dCmdRotVelRadS == 0)) { m_vdVelGearDriveCmdRadS.assign(4,0.0); // set velocity for drives to zero m_vdVelGearSteerCmdRadS.assign(4,0.0); // set velocity for steers to zero // set internal states of controller to zero for(int i=0; i<4; i++) { m_vdCtrlVal[i][0] = 0.0; m_vdCtrlVal[i][1] = 0.0; } return; } // declare auxilliary variables double dCurrentPosWheelRAD; double dDeltaPhi, dVelCmd; double dForceDamp, dForceProp, dAccCmd, dVelCmdInt; // PI- and Impedance-Ctrl for (int i=0; i<4; i++) { // provisorial --> skip interpolation and always take Target m_vdVelGearDriveCmdRadS[i] = m_vdVelGearDriveTargetRadS[i]; m_vdAngGearSteerCmdRad[i] = m_vdAngGearSteerTargetRad[i]; // provisorial --> skip interpolation and always take Target1 //m_vdVelGearDriveCmdRadS[i] = m_vdVelGearDriveTarget1RadS[i]; //m_vdAngGearSteerCmdRad[i] = m_vdAngGearSteerTarget1Rad[i]; /*m_vdAngGearSteerIntpRad[i] += m_vdDeltaAngIntpRad[i]; MathSup::normalizePi(m_vdAngGearSteerIntpRad[i]); m_vdVelGearDriveIntpRadS[i] += m_vdDeltaDriveIntpRadS[i]; m_vdVelGearDriveCmdRadS[i] = m_vdVelGearDriveIntpRadS[i]; m_vdAngGearSteerCmdRad[i] = m_vdAngGearSteerIntpRad[i];*/ } for (int i = 0; i<4; i++) { // Normalize Actual Wheel Position before calculation dCurrentPosWheelRAD = m_vdAngGearSteerRad[i]; MathSup::normalizePi(dCurrentPosWheelRAD); dDeltaPhi = m_vdAngGearSteerCmdRad[i] - dCurrentPosWheelRAD; MathSup::normalizePi(dDeltaPhi); // Impedance-Ctrl // Calculate resulting desired forces, velocities // double dForceDamp, dForceProp, dAccCmd, dVelCmdInt; dForceDamp = - m_dDamp * m_vdCtrlVal[i][1]; dForceProp = m_dSpring * dDeltaPhi; dAccCmd = (dForceDamp + dForceProp) / m_dVirtM; if (dAccCmd > m_dDDPhiMax) { dAccCmd = m_dDDPhiMax; } else if (dAccCmd < -m_dDDPhiMax) { dAccCmd = -m_dDDPhiMax; } dVelCmdInt = m_vdCtrlVal[i][1] + m_UnderCarriagePrms.dCmdRateS * dAccCmd; if (dVelCmdInt > m_dDPhiMax) { dVelCmdInt = m_dDPhiMax; } else if (dVelCmdInt < -m_dDPhiMax) { dVelCmdInt = -m_dDPhiMax; } // Store internal ctrlr-states m_vdCtrlVal[i][0] = dDeltaPhi; m_vdCtrlVal[i][1] = dVelCmdInt; // set outputs m_vdVelGearSteerCmdRadS[i] = dVelCmdInt; // Check if Steeringvelocity overgo maximum allowed rates. if(fabs(m_vdVelGearSteerCmdRadS[i]) > m_UnderCarriagePrms.dMaxSteerRateRadpS) { if (m_vdVelGearSteerCmdRadS[i] > 0) m_vdVelGearSteerCmdRadS[i] = m_UnderCarriagePrms.dMaxSteerRateRadpS; else m_vdVelGearSteerCmdRadS[i] = -m_UnderCarriagePrms.dMaxSteerRateRadpS; } } // Correct Driving-Wheel-Velocity, because of coupling and axis-offset for (int i = 0; i<4; i++) { m_vdVelGearDriveCmdRadS[i] += m_vdVelGearSteerCmdRadS[i] * m_UnderCarriagePrms.vdFactorVel[i]; } } // operator overloading void UndercarriageCtrlGeom::operator=(const UndercarriageCtrlGeom & GeomCtrl) { // Actual Values for PltfMovement (calculated from Actual Wheelspeeds) m_dVelLongMMS = GeomCtrl.m_dVelLongMMS; m_dVelLatMMS = GeomCtrl.m_dVelLatMMS; m_dRotRobRadS = GeomCtrl.m_dRotRobRadS; m_dRotVelRadS = GeomCtrl.m_dRotVelRadS; // Actual Wheelspeed (read from Motor-Ctrls) m_vdVelGearDriveRadS = GeomCtrl.m_vdVelGearDriveRadS; m_vdVelGearSteerRadS = GeomCtrl.m_vdVelGearSteerRadS; m_vdDltAngGearDriveRad = GeomCtrl.m_vdDltAngGearDriveRad; m_vdAngGearSteerRad = GeomCtrl.m_vdAngGearSteerRad; // Desired Pltf-Movement (set from PltfHwItf) m_dCmdVelLongMMS = GeomCtrl.m_dCmdVelLongMMS; m_dCmdVelLatMMS = GeomCtrl.m_dCmdVelLatMMS; m_dCmdRotRobRadS = GeomCtrl.m_dCmdRotRobRadS; m_dCmdRotVelRadS = GeomCtrl.m_dCmdRotVelRadS; // Desired Wheelspeeds (calculated from desired ICM-configuration) m_vdVelGearDriveCmdRadS = GeomCtrl.m_vdVelGearDriveCmdRadS; m_vdVelGearSteerCmdRadS = GeomCtrl.m_vdVelGearSteerCmdRadS; m_vdAngGearSteerCmdRad = GeomCtrl.m_vdAngGearSteerCmdRad; // Target Wheelspeed and -angle (calculated from desired Pltf-Movement with Inverse without controle!) // alternativ 1 for steering angle m_vdAngGearSteerTarget1Rad = GeomCtrl.m_vdAngGearSteerTarget1Rad; m_vdVelGearDriveTarget1RadS = GeomCtrl.m_vdVelGearDriveTarget1RadS; // alternativ 2 for steering angle (+/- PI) m_vdAngGearSteerTarget2Rad = GeomCtrl.m_vdAngGearSteerTarget2Rad; m_vdVelGearDriveTarget2RadS = GeomCtrl.m_vdVelGearDriveTarget2RadS; // Position of the Wheels' Steering Axis' m_vdWheelXPosMM = GeomCtrl.m_vdWheelXPosMM; m_vdWheelYPosMM = GeomCtrl.m_vdWheelYPosMM; m_vdWheelDistMM = GeomCtrl.m_vdWheelDistMM; m_vdWheelAngRad = GeomCtrl.m_vdWheelAngRad; // Exact Position of the Wheels' itself m_vdExWheelXPosMM = GeomCtrl.m_vdExWheelXPosMM; m_vdExWheelYPosMM = GeomCtrl.m_vdExWheelYPosMM; m_vdExWheelDistMM = GeomCtrl.m_vdExWheelDistMM; m_vdExWheelAngRad = GeomCtrl.m_vdExWheelAngRad; // Prms m_UnderCarriagePrms = GeomCtrl.m_UnderCarriagePrms; // Position Controller Steer Wheels // Impedance-Ctrlr m_dSpring = GeomCtrl.m_dSpring; m_dDamp = GeomCtrl.m_dDamp; m_dVirtM = GeomCtrl.m_dDPhiMax; m_dDPhiMax = GeomCtrl.m_dDPhiMax; m_dDDPhiMax = GeomCtrl.m_dDDPhiMax; // Storage for internal controller states m_vdCtrlVal = GeomCtrl.m_vdCtrlVal; } // set EM Flag and stop ctrlr if active void UndercarriageCtrlGeom::setEMStopActive(bool bEMStopActive) { m_bEMStopActive = bEMStopActive; // if emergency stop reset ctrlr to zero if(m_bEMStopActive) { // Steermodules for(int i=0; i<4; i++) { for(int j=0; j< 2; j++) { m_vdCtrlVal[i][j] = 0.0; } } // Outputs for(int i=0; i<4; i++) { m_vdVelGearDriveCmdRadS[i] = 0.0; m_vdVelGearSteerCmdRadS[i] = 0.0; } } }
[ "cpc@okeanos.(none)", "[email protected]", "cob@cob-laptop.(none)", "cpc@COB3-Navigation.(none)" ]
[ [ [ 1, 10 ], [ 12, 56 ], [ 58, 58 ], [ 61, 61 ], [ 67, 73 ], [ 77, 95 ], [ 98, 109 ], [ 112, 117 ], [ 136, 140 ], [ 146, 146 ], [ 149, 149 ], [ 153, 161 ], [ 163, 176 ], [ 178, 191 ], [ 198, 202 ], [ 204, 235 ], [ 238, 258 ], [ 293, 299 ], [ 302, 303 ], [ 305, 312 ], [ 315, 316 ], [ 333, 380 ], [ 391, 401 ], [ 405, 422 ], [ 424, 424 ], [ 426, 555 ], [ 564, 572 ], [ 583, 586 ], [ 590, 730 ] ], [ [ 11, 11 ] ], [ [ 57, 57 ], [ 59, 60 ], [ 62, 66 ], [ 162, 162 ], [ 177, 177 ], [ 203, 203 ] ], [ [ 74, 76 ], [ 96, 97 ], [ 110, 111 ], [ 118, 135 ], [ 141, 145 ], [ 147, 148 ], [ 150, 152 ], [ 192, 197 ], [ 236, 237 ], [ 259, 292 ], [ 300, 301 ], [ 304, 304 ], [ 313, 314 ], [ 317, 332 ], [ 381, 390 ], [ 402, 404 ], [ 423, 423 ], [ 425, 425 ], [ 556, 563 ], [ 573, 582 ], [ 587, 589 ] ] ]
548ffec94b9d25dbf824aada7936129dcaea6c05
1741474383f0b3bc3518d7935a904f7903f40506
/A7/Number.cpp
78819cdc449a26342d6082f7909188f9a89def4f
[]
no_license
osecki/drexelgroupwork
739df86f361e00528a6b03032985288d64b464aa
7c3bde253a50cab42c22d286c80cad72348b4fcf
refs/heads/master
2020-05-31T02:25:57.734312
2009-06-03T18:34:59
2009-06-03T18:34:59
32,121,248
0
0
null
null
null
null
UTF-8
C++
false
false
1,666
cpp
#include "Number.h" #include <map> #include "Program.h" #include <sstream> #include <vector> #include <iostream> #define CONSTANT "C" using namespace std; Number::Number(int value) { value_ = value; } string Number::getConstant(map<int, string> &constantValues, int value) { map<int, string>::iterator location = constantValues.find(value); if ( location!=constantValues.end() ) { return constantValues[value]; } else { stringstream outConst; outConst << value; string newConstant = CONSTANT + outConst.str(); // increment the counter for the next constant Program::constantCounter++; // add this into the constant table constantValues[value] = newConstant; return newConstant; } } string Number::translate(map<int, string> &constantValues, map<string, SymbolDetails> &symbolTable, vector<string> &ralProgram, map<string, Proc*> &FT) const { ralProgram.push_back("; + number"); // Look into constant table for the Number. If it is there get value, otherwise create new Number and add to symbol table string newConstant = getConstant(constantValues, value_); // create new temporary variable then Store the new ident there string newTemp; stringstream outTemp; outTemp << Program::temporaryVarCounter; newTemp = "T" + outTemp.str(); Program::temporaryVarCounter++; SymbolDetails newSymbolTemp(-1, "Temporary", -1); symbolTable[newTemp] = newSymbolTemp; // Load the dynamic memory location ralProgram.push_back("LDA " + newConstant); // Save the constant there ralProgram.push_back("STO " + newTemp); ralProgram.push_back("; - number"); return newTemp; }
[ "jordan.osecki@c6e0ff0a-2120-11de-a108-cd2f117ce590", "geoff.oxholm@c6e0ff0a-2120-11de-a108-cd2f117ce590" ]
[ [ [ 1, 14 ], [ 17, 17 ], [ 20, 21 ], [ 24, 24 ], [ 26, 26 ], [ 29, 29 ], [ 37, 41 ], [ 43, 43 ], [ 45, 48 ], [ 50, 50 ], [ 56, 58 ] ], [ [ 15, 16 ], [ 18, 19 ], [ 22, 23 ], [ 25, 25 ], [ 27, 28 ], [ 30, 36 ], [ 42, 42 ], [ 44, 44 ], [ 49, 49 ], [ 51, 55 ] ] ]
b7acbafc27aa4d2fb90b59d63af72f1d702d55be
d76a67033e3abf492ff2f22d38fb80de804c4269
/src/sdlkeyboard/mod_sdlkeyboard.cpp
c0d8cd3df526a7ddd37e2502040b0e62b4d864fe
[ "Zlib" ]
permissive
truthwzl/lov8
869a6be317b7d963600f2f88edaefdf9b5996f2d
579163941593bae481212148041e0db78270c21d
refs/heads/master
2021-01-10T01:58:59.103256
2009-12-16T16:00:09
2009-12-16T16:00:09
36,340,451
0
0
null
null
null
null
UTF-8
C++
false
false
62,168
cpp
// SWIGFUSION ^.^ // Lua struct lua_State; // Forward declarations of fused methods: namespace love_sdlkeyboard { } /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.35 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus template<typename T> class SwigValueWrapper { T *tt; public: SwigValueWrapper() : tt(0) { } SwigValueWrapper(const SwigValueWrapper<T>& rhs) : tt(new T(*rhs.tt)) { } SwigValueWrapper(const T& t) : tt(new T(t)) { } ~SwigValueWrapper() { delete tt; } SwigValueWrapper& operator=(const T& t) { delete tt; tt = new T(t); return *this; } operator T&() const { return *tt; } T *operator&() { return tt; } private: SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs); }; template <typename T> T SwigValueInit() { return T(); } #endif /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic CAPI SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the swig runtime code. In 99.9% of the cases, swig just needs to declare them as 'static'. But only do this if is strictly necessary, ie, if you have problems with your compiler or so. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The swig conversion methods, as ConvertPtr, return and integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old swig versions, you usually write code as: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit as: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } that seems to be the same, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that requires also to SWIG_ConvertPtr to return new result values, as int SWIG_ConvertPtr(obj, ptr,...) { if (<obj is ok>) { if (<need new object>) { *ptr = <ptr to new allocated object>; return SWIG_NEWOBJ; } else { *ptr = <ptr to old object>; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the swig errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class<int>" == "Class<int >", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCompare(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* think of this as a c++ template<> or a scheme macro */ #define SWIG_TypeCheck_Template(comparison, ty) \ if (ty) { \ swig_cast_info *iter = ty->cast; \ while (iter) { \ if (comparison) { \ if (iter == ty->cast) return iter; \ /* Move iter to the top of the linked list */ \ iter->prev->next = iter->next; \ if (iter->next) \ iter->next->prev = iter->prev; \ iter->next = ty->cast; \ iter->prev = 0; \ if (ty->cast) ty->cast->prev = iter; \ ty->cast = iter; \ return iter; \ } \ iter = iter->next; \ } \ } \ return 0 /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); } /* Same as previous function, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { SWIG_TypeCheck_Template(iter->type == from, into); } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * luarun.swg * * This file contains the runtime support for Lua modules * and includes code for managing global variables and pointer * type checking. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif #include "lua.h" #include "lauxlib.h" #include <stdlib.h> /* for malloc */ #include <assert.h> /* for a few sanity tests */ /* ----------------------------------------------------------------------------- * global swig types * ----------------------------------------------------------------------------- */ /* Constant table */ #define SWIG_LUA_INT 1 #define SWIG_LUA_FLOAT 2 #define SWIG_LUA_STRING 3 #define SWIG_LUA_POINTER 4 #define SWIG_LUA_BINARY 5 #define SWIG_LUA_CHAR 6 /* Structure for variable linking table */ typedef struct { const char *name; lua_CFunction get; lua_CFunction set; } swig_lua_var_info; /* Constant information structure */ typedef struct { int type; char *name; long lvalue; double dvalue; void *pvalue; swig_type_info **ptype; } swig_lua_const_info; typedef struct { const char *name; lua_CFunction method; } swig_lua_method; typedef struct { const char *name; lua_CFunction getmethod; lua_CFunction setmethod; } swig_lua_attribute; typedef struct swig_lua_class { const char *name; swig_type_info **type; lua_CFunction constructor; void (*destructor)(void *); swig_lua_method *methods; swig_lua_attribute *attributes; struct swig_lua_class **bases; const char **base_names; } swig_lua_class; /* this is the struct for wrappering all pointers in SwigLua */ typedef struct { swig_type_info *type; int own; /* 1 if owned & must be destroyed */ void *ptr; } swig_lua_userdata; /* this is the struct for wrapping arbitary packed binary data (currently it is only used for member function pointers) the data ordering is similar to swig_lua_userdata, but it is currently not possible to tell the two structures apart within Swig, other than by looking at the type */ typedef struct { swig_type_info *type; int own; /* 1 if owned & must be destroyed */ char data[1]; /* arbitary amount of data */ } swig_lua_rawdata; /* Common SWIG API */ #define SWIG_NewPointerObj(L, ptr, type, owner) SWIG_Lua_NewPointerObj(L, (void *)ptr, type, owner) #define SWIG_ConvertPtr(L,idx, ptr, type, flags) SWIG_Lua_ConvertPtr(L,idx,ptr,type,flags) #define SWIG_MustGetPtr(L,idx, type,flags, argnum,fnname) SWIG_Lua_MustGetPtr(L,idx, type,flags, argnum,fnname) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(L, idx, ptr, sz, ty) SWIG_Lua_ConvertPacked(L, idx, ptr, sz, ty) #define SWIG_NewMemberObj(L, ptr, sz, type) SWIG_Lua_NewPackedObj(L, ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Lua_GetModule((lua_State*)(clientdata)) #define SWIG_SetModule(clientdata, pointer) SWIG_Lua_SetModule((lua_State*) (clientdata), pointer) #define SWIG_MODULE_CLIENTDATA_TYPE lua_State* /* Contract support */ #define SWIG_contract_assert(expr, msg) \ if (!(expr)) { lua_pushstring(L, (char *) msg); goto fail; } else /* helper #defines */ #define SWIG_fail {goto fail;} #define SWIG_fail_arg(func_name,argnum,type) \ {lua_pushfstring(L,"Error in %s (arg %d), expected '%s' got '%s'",\ func_name,argnum,type,SWIG_Lua_typename(L,argnum));\ goto fail;} #define SWIG_fail_ptr(func_name,argnum,type) \ SWIG_fail_arg(func_name,argnum,(type && type->str)?type->str:"void*") #define SWIG_check_num_args(func_name,a,b) \ if (lua_gettop(L)<a || lua_gettop(L)>b) \ {lua_pushfstring(L,"Error in %s expected %d..%d args, got %d",func_name,a,b,lua_gettop(L));\ goto fail;} #define SWIG_Lua_get_table(L,n) \ (lua_pushstring(L, n), lua_rawget(L,-2)) #define SWIG_Lua_add_function(L,n,f) \ (lua_pushstring(L, n), \ lua_pushcfunction(L, f), \ lua_rawset(L,-3)) /* special helper for allowing 'nil' for usertypes */ #define SWIG_isptrtype(L,I) (lua_isuserdata(L,I) || lua_isnil(L,I)) #ifdef __cplusplus /* Special helper for member function pointers it gets the address, casts it, then dereferences it */ //#define SWIG_mem_fn_as_voidptr(a) (*((char**)&(a))) #endif /* storing/access of swig_module_info */ SWIGRUNTIME swig_module_info * SWIG_Lua_GetModule(lua_State* L) { swig_module_info *ret = 0; lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); lua_rawget(L,LUA_REGISTRYINDEX); if (lua_islightuserdata(L,-1)) ret=(swig_module_info*)lua_touserdata(L,-1); lua_pop(L,1); /* tidy */ return ret; } SWIGRUNTIME void SWIG_Lua_SetModule(lua_State* L, swig_module_info *module) { /* add this all into the Lua registry: */ lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); lua_pushlightuserdata(L,(void*)module); lua_rawset(L,LUA_REGISTRYINDEX); } /* ----------------------------------------------------------------------------- * global variable support code: modules * ----------------------------------------------------------------------------- */ /* this function is called when trying to set an immutable. default value is to print an error. This can removed with a compile flag SWIGLUA_IGNORE_SET_IMMUTABLE */ SWIGINTERN int SWIG_Lua_set_immutable(lua_State* L) { /* there should be 1 param passed in: the new value */ #ifndef SWIGLUA_IGNORE_SET_IMMUTABLE lua_pop(L,1); /* remove it */ lua_pushstring(L,"This variable is immutable"); lua_error(L); #endif return 0; /* should not return anything */ } /* the module.get method used for getting linked data */ SWIGINTERN int SWIG_Lua_module_get(lua_State* L) { /* there should be 2 params passed in (1) table (not the meta table) (2) string name of the attribute printf("SWIG_Lua_module_get %p(%s) '%s'\n", lua_topointer(L,1),lua_typename(L,lua_type(L,1)), lua_tostring(L,2)); */ /* get the metatable */ assert(lua_istable(L,1)); /* just in case */ lua_getmetatable(L,1); /* get the metatable */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".get"); /* get the .get table */ lua_remove(L,3); /* remove metatable */ if (lua_istable(L,-1)) { /* look for the key in the .get table */ lua_pushvalue(L,2); /* key */ lua_rawget(L,-2); lua_remove(L,3); /* remove .get */ if (lua_iscfunction(L,-1)) { /* found it so call the fn & return its value */ lua_call(L,0,1); return 1; } lua_pop(L,1); /* remove the top */ } lua_pop(L,1); /* remove the .get */ lua_pushnil(L); /* return a nil */ return 1; } /* the module.set method used for setting linked data */ SWIGINTERN int SWIG_Lua_module_set(lua_State* L) { /* there should be 3 params passed in (1) table (not the meta table) (2) string name of the attribute (3) any for the new value */ /* get the metatable */ assert(lua_istable(L,1)); /* just in case */ lua_getmetatable(L,1); /* get the metatable */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".set"); /* get the .set table */ lua_remove(L,4); /* remove metatable */ if (lua_istable(L,-1)) { /* look for the key in the .set table */ lua_pushvalue(L,2); /* key */ lua_rawget(L,-2); lua_remove(L,4); /* remove .set */ if (lua_iscfunction(L,-1)) { /* found it so call the fn & return its value */ lua_pushvalue(L,3); /* value */ lua_call(L,1,0); return 0; } } lua_settop(L,3); /* reset back to start */ /* we now have the table, key & new value, so just set directly */ lua_rawset(L,1); /* add direct */ return 0; } /* registering a module in lua */ SWIGINTERN void SWIG_Lua_module_begin(lua_State* L,const char* name) { assert(lua_istable(L,-1)); /* just in case */ lua_pushstring(L,name); lua_newtable(L); /* the table */ /* add meta table */ lua_newtable(L); /* the meta table */ SWIG_Lua_add_function(L,"__index",SWIG_Lua_module_get); SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_module_set); lua_pushstring(L,".get"); lua_newtable(L); /* the .get table */ lua_rawset(L,-3); /* add .get into metatable */ lua_pushstring(L,".set"); lua_newtable(L); /* the .set table */ lua_rawset(L,-3); /* add .set into metatable */ lua_setmetatable(L,-2); /* sets meta table in module */ lua_rawset(L,-3); /* add module into parent */ SWIG_Lua_get_table(L,name); /* get the table back out */ } /* ending the register */ SWIGINTERN void SWIG_Lua_module_end(lua_State* L) { lua_pop(L,1); /* tidy stack (remove module) */ } /* adding a linked variable to the module */ SWIGINTERN void SWIG_Lua_module_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn) { assert(lua_istable(L,-1)); /* just in case */ lua_getmetatable(L,-1); /* get the metatable */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".get"); /* find the .get table */ assert(lua_istable(L,-1)); /* should be a table: */ SWIG_Lua_add_function(L,name,getFn); lua_pop(L,1); /* tidy stack (remove table) */ if (setFn) /* if there is a set fn */ { SWIG_Lua_get_table(L,".set"); /* find the .set table */ assert(lua_istable(L,-1)); /* should be a table: */ SWIG_Lua_add_function(L,name,setFn); lua_pop(L,1); /* tidy stack (remove table) */ } lua_pop(L,1); /* tidy stack (remove meta) */ } /* adding a function module */ SWIGINTERN void SWIG_Lua_module_add_function(lua_State* L,const char* name,lua_CFunction fn) { SWIG_Lua_add_function(L,name,fn); } /* ----------------------------------------------------------------------------- * global variable support code: classes * ----------------------------------------------------------------------------- */ /* the class.get method, performs the lookup of class attributes */ SWIGINTERN int SWIG_Lua_class_get(lua_State* L) { /* there should be 2 params passed in (1) userdata (not the meta table) (2) string name of the attribute */ assert(lua_isuserdata(L,-2)); /* just in case */ lua_getmetatable(L,-2); /* get the meta table */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".get"); /* find the .get table */ assert(lua_istable(L,-1)); /* just in case */ /* look for the key in the .get table */ lua_pushvalue(L,2); /* key */ lua_rawget(L,-2); lua_remove(L,-2); /* stack tidy, remove .get table */ if (lua_iscfunction(L,-1)) { /* found it so call the fn & return its value */ lua_pushvalue(L,1); /* the userdata */ lua_call(L,1,1); /* 1 value in (userdata),1 out (result) */ lua_remove(L,-2); /* stack tidy, remove metatable */ return 1; } lua_pop(L,1); /* remove whatever was there */ /* ok, so try the .fn table */ SWIG_Lua_get_table(L,".fn"); /* find the .get table */ assert(lua_istable(L,-1)); /* just in case */ lua_pushvalue(L,2); /* key */ lua_rawget(L,-2); /* look for the fn */ lua_remove(L,-2); /* stack tidy, remove .fn table */ if (lua_isfunction(L,-1)) /* note: if its a C function or lua function */ { /* found it so return the fn & let lua call it */ lua_remove(L,-2); /* stack tidy, remove metatable */ return 1; } lua_pop(L,1); /* remove whatever was there */ /* NEW: looks for the __getitem() fn this is a user provided get fn */ SWIG_Lua_get_table(L,"__getitem"); /* find the __getitem fn */ if (lua_iscfunction(L,-1)) /* if its there */ { /* found it so call the fn & return its value */ lua_pushvalue(L,1); /* the userdata */ lua_pushvalue(L,2); /* the parameter */ lua_call(L,2,1); /* 2 value in (userdata),1 out (result) */ lua_remove(L,-2); /* stack tidy, remove metatable */ return 1; } return 0; /* sorry not known */ } /* the class.set method, performs the lookup of class attributes */ SWIGINTERN int SWIG_Lua_class_set(lua_State* L) { /* there should be 3 params passed in (1) table (not the meta table) (2) string name of the attribute (3) any for the new value printf("SWIG_Lua_class_set %p(%s) '%s' %p(%s)\n", lua_topointer(L,1),lua_typename(L,lua_type(L,1)), lua_tostring(L,2), lua_topointer(L,3),lua_typename(L,lua_type(L,3)));*/ assert(lua_isuserdata(L,1)); /* just in case */ lua_getmetatable(L,1); /* get the meta table */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".set"); /* find the .set table */ if (lua_istable(L,-1)) { /* look for the key in the .set table */ lua_pushvalue(L,2); /* key */ lua_rawget(L,-2); if (lua_iscfunction(L,-1)) { /* found it so call the fn & return its value */ lua_pushvalue(L,1); /* userdata */ lua_pushvalue(L,3); /* value */ lua_call(L,2,0); return 0; } lua_pop(L,1); /* remove the value */ } lua_pop(L,1); /* remove the value .set table */ /* NEW: looks for the __setitem() fn this is a user provided set fn */ SWIG_Lua_get_table(L,"__setitem"); /* find the fn */ if (lua_iscfunction(L,-1)) /* if its there */ { /* found it so call the fn & return its value */ lua_pushvalue(L,1); /* the userdata */ lua_pushvalue(L,2); /* the parameter */ lua_pushvalue(L,3); /* the value */ lua_call(L,3,0); /* 3 values in ,0 out */ lua_remove(L,-2); /* stack tidy, remove metatable */ return 1; } return 0; } /* the class.destruct method called by the interpreter */ SWIGINTERN int SWIG_Lua_class_destruct(lua_State* L) { /* there should be 1 params passed in (1) userdata (not the meta table) */ swig_lua_userdata* usr; swig_lua_class* clss; assert(lua_isuserdata(L,-1)); /* just in case */ usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ /* if must be destroyed & has a destructor */ if (usr->own) /* if must be destroyed */ { clss=(swig_lua_class*)usr->type->clientdata; /* get the class */ if (clss && clss->destructor) /* there is a destroy fn */ { clss->destructor(usr->ptr); /* bye bye */ } } return 0; } /* gets the swig class registry (or creates it) */ SWIGINTERN void SWIG_Lua_get_class_registry(lua_State* L) { /* add this all into the swig registry: */ lua_pushstring(L,"SWIG"); lua_rawget(L,LUA_REGISTRYINDEX); /* get the registry */ if (!lua_istable(L,-1)) /* not there */ { /* must be first time, so add it */ lua_pop(L,1); /* remove the result */ lua_pushstring(L,"SWIG"); lua_newtable(L); lua_rawset(L,LUA_REGISTRYINDEX); /* then get it */ lua_pushstring(L,"SWIG"); lua_rawget(L,LUA_REGISTRYINDEX); } } /* helper fn to get the classes metatable from the register */ SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State* L,const char* cname) { SWIG_Lua_get_class_registry(L); /* get the registry */ lua_pushstring(L,cname); /* get the name */ lua_rawget(L,-2); /* get it */ lua_remove(L,-2); /* tidy up (remove registry) */ } /* helper add a variable to a registered class */ SWIGINTERN void SWIG_Lua_add_class_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn) { assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_get_table(L,".get"); /* find the .get table */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_add_function(L,name,getFn); lua_pop(L,1); /* tidy stack (remove table) */ if (setFn) { SWIG_Lua_get_table(L,".set"); /* find the .set table */ assert(lua_istable(L,-1)); /* just in case */ SWIG_Lua_add_function(L,name,setFn); lua_pop(L,1); /* tidy stack (remove table) */ } } /* helper to recursively add class details (attributes & operations) */ SWIGINTERN void SWIG_Lua_add_class_details(lua_State* L,swig_lua_class* clss) { int i; /* call all the base classes first: we can then override these later: */ for(i=0;clss->bases[i];i++) { SWIG_Lua_add_class_details(L,clss->bases[i]); } /* add fns */ for(i=0;clss->attributes[i].name;i++){ SWIG_Lua_add_class_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod); } /* add methods to the metatable */ SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ assert(lua_istable(L,-1)); /* just in case */ for(i=0;clss->methods[i].name;i++){ SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].method); } lua_pop(L,1); /* tidy stack (remove table) */ /* add operator overloads these look ANY method which start with "__" and assume they are operator overloads & add them to the metatable (this might mess up is someone defines a method __gc (the destructor)*/ for(i=0;clss->methods[i].name;i++){ if (clss->methods[i].name[0]=='_' && clss->methods[i].name[1]=='_'){ SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].method); } } } /* set up the base classes pointers. Each class structure has a list of pointers to the base class structures. This function fills them. It cannot be done at compile time, as this will not work with hireachies spread over more than one swig file. Therefore it must be done at runtime, querying the SWIG type system. */ SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss) { int i=0; swig_module_info* module=SWIG_GetModule(L); for(i=0;clss->base_names[i];i++) { if (clss->bases[i]==0) /* not found yet */ { /* lookup and cache the base class */ swig_type_info *info = SWIG_TypeQueryModule(module,module,clss->base_names[i]); if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; } } } /* performs the entire class registration process */ SWIGINTERN void SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss) { /* add its constructor to module with the name of the class so you can do MyClass(...) as well as new_MyClass(...) BUT only if a constructor is defined (this overcomes the problem of pure virtual classes without constructors)*/ if (clss->constructor) SWIG_Lua_add_function(L,clss->name,clss->constructor); SWIG_Lua_get_class_registry(L); /* get the registry */ lua_pushstring(L,clss->name); /* get the name */ lua_newtable(L); /* create the metatable */ /* add string of class name called ".type" */ lua_pushstring(L,".type"); lua_pushstring(L,clss->name); lua_rawset(L,-3); /* add a table called ".get" */ lua_pushstring(L,".get"); lua_newtable(L); lua_rawset(L,-3); /* add a table called ".set" */ lua_pushstring(L,".set"); lua_newtable(L); lua_rawset(L,-3); /* add a table called ".fn" */ lua_pushstring(L,".fn"); lua_newtable(L); lua_rawset(L,-3); /* add accessor fns for using the .get,.set&.fn */ SWIG_Lua_add_function(L,"__index",SWIG_Lua_class_get); SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_class_set); SWIG_Lua_add_function(L,"__gc",SWIG_Lua_class_destruct); /* add it */ lua_rawset(L,-3); /* metatable into registry */ lua_pop(L,1); /* tidy stack (remove registry) */ SWIG_Lua_get_class_metatable(L,clss->name); SWIG_Lua_add_class_details(L,clss); /* recursive adding of details (atts & ops) */ lua_pop(L,1); /* tidy stack (remove class metatable) */ } /* ----------------------------------------------------------------------------- * Class/structure conversion fns * ----------------------------------------------------------------------------- */ /* helper to add metatable to new lua object */ SWIGINTERN void _SWIG_Lua_AddMetatable(lua_State* L,swig_type_info *type) { if (type->clientdata) /* there is clientdata: so add the metatable */ { SWIG_Lua_get_class_metatable(L,((swig_lua_class*)(type->clientdata))->name); if (lua_istable(L,-1)) { lua_setmetatable(L,-2); } else { lua_pop(L,1); } } } /* pushes a new object into the lua stack */ SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type, int own) { swig_lua_userdata* usr; if (!ptr){ lua_pushnil(L); return; } usr=(swig_lua_userdata*)lua_newuserdata(L,sizeof(swig_lua_userdata)); /* get data */ usr->ptr=ptr; /* set the ptr */ usr->type=type; usr->own=own; _SWIG_Lua_AddMetatable(L,type); /* add metatable */ } /* takes a object from the lua stack & converts it into an object of the correct type (if possible) */ SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State* L,int index,void** ptr,swig_type_info *type,int flags) { swig_lua_userdata* usr; swig_cast_info *cast; if (lua_isnil(L,index)){*ptr=0; return SWIG_OK;} /* special case: lua nil => NULL pointer */ usr=(swig_lua_userdata*)lua_touserdata(L,index); /* get data */ if (usr) { if (flags & SWIG_POINTER_DISOWN) /* must disown the object */ { usr->own=0; } if (!type) /* special cast void*, no casting fn */ { *ptr=usr->ptr; return SWIG_OK; /* ok */ } cast=SWIG_TypeCheckStruct(usr->type,type); /* performs normal type checking */ if (cast) { int newmemory = 0; *ptr=SWIG_TypeCast(cast,usr->ptr,&newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ return SWIG_OK; /* ok */ } } return SWIG_ERROR; /* error */ } SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State* L,int index,swig_type_info *type,int flags, int argnum,const char* func_name){ void* result; if (!SWIG_IsOK(SWIG_ConvertPtr(L,index,&result,type,flags))){ lua_pushfstring(L,"Error in %s, expected a %s at argument number %d\n", func_name,(type && type->str)?type->str:"void*",argnum); lua_error(L); } return result; } /* pushes a packed userdata. user for member fn pointers only */ SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State* L,void* ptr,size_t size,swig_type_info *type) { swig_lua_rawdata* raw; assert(ptr); /* not acceptable to pass in a NULL value */ raw=(swig_lua_rawdata*)lua_newuserdata(L,sizeof(swig_lua_rawdata)-1+size); /* alloc data */ raw->type=type; raw->own=0; memcpy(raw->data,ptr,size); /* copy the data */ _SWIG_Lua_AddMetatable(L,type); /* add metatable */ } /* converts a packed userdata. user for member fn pointers only */ SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State* L,int index,void* ptr,size_t size,swig_type_info *type) { swig_lua_rawdata* raw; raw=(swig_lua_rawdata*)lua_touserdata(L,index); /* get data */ if (!raw) return SWIG_ERROR; /* error */ if (type==0 || type==raw->type) /* void* or identical type */ { memcpy(ptr,raw->data,size); /* copy it */ return SWIG_OK; /* ok */ } return SWIG_ERROR; /* error */ } /* a function to get the typestring of a piece of data */ SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) { swig_lua_userdata* usr; if (lua_isuserdata(L,tp)) { usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ if (usr && usr->type && usr->type->str) return usr->type->str; return "userdata (unknown type)"; } return lua_typename(L,lua_type(L,tp)); } /* lua callable function to get the userdata's type */ SWIGRUNTIME int SWIG_Lua_type(lua_State* L) { lua_pushstring(L,SWIG_Lua_typename(L,1)); return 1; } /* lua callable function to compare userdata's value the issue is that two userdata may point to the same thing but to lua, they are different objects */ SWIGRUNTIME int SWIG_Lua_equal(lua_State* L) { int result; swig_lua_userdata *usr1,*usr2; if (!lua_isuserdata(L,1) || !lua_isuserdata(L,2)) /* just in case */ return 0; /* nil reply */ usr1=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ usr2=(swig_lua_userdata*)lua_touserdata(L,2); /* get data */ /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ result=(usr1->ptr==usr2->ptr); lua_pushboolean(L,result); return 1; } /* ----------------------------------------------------------------------------- * global variable support code: class/struct typemap functions * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]) { int i; for (i = 0; constants[i].type; i++) { switch(constants[i].type) { case SWIG_LUA_INT: lua_pushstring(L,constants[i].name); lua_pushnumber(L,(lua_Number)constants[i].lvalue); lua_rawset(L,-3); break; case SWIG_LUA_FLOAT: lua_pushstring(L,constants[i].name); lua_pushnumber(L,(lua_Number)constants[i].dvalue); lua_rawset(L,-3); break; case SWIG_LUA_CHAR: lua_pushstring(L,constants[i].name); lua_pushfstring(L,"%c",(char)constants[i].lvalue); lua_rawset(L,-3); break; case SWIG_LUA_STRING: lua_pushstring(L,constants[i].name); lua_pushstring(L,(char *) constants[i].pvalue); lua_rawset(L,-3); break; case SWIG_LUA_POINTER: lua_pushstring(L,constants[i].name); SWIG_NewPointerObj(L,constants[i].pvalue, *(constants[i]).ptype,0); lua_rawset(L,-3); break; case SWIG_LUA_BINARY: lua_pushstring(L,constants[i].name); SWIG_NewMemberObj(L,constants[i].pvalue,constants[i].lvalue,*(constants[i]).ptype); lua_rawset(L,-3); break; default: break; } } } /* ----------------------------------------------------------------------------- * executing lua code from within the wrapper * ----------------------------------------------------------------------------- */ #ifndef SWIG_DOSTRING_FAIL /* Allows redefining of error function */ #define SWIG_DOSTRING_FAIL(S) fprintf(stderr,"%s\n",S) #endif /* Executes a C string in Lua a really simple way of calling lua from C Unfortunately lua keeps changing its API's, so we need a conditional compile In lua 5.0.X its lua_dostring() In lua 5.1.X its luaL_dostring() */ SWIGINTERN int SWIG_Lua_dostring(lua_State *L, const char* str) { int ok,top; if (str==0 || str[0]==0) return 0; /* nothing to do */ top=lua_gettop(L); /* save stack */ #if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501)) ok=luaL_dostring(L,str); /* looks like this is lua 5.1.X or later, good */ #else ok=lua_dostring(L,str); /* might be lua 5.0.x, using lua_dostring */ #endif if (ok!=0) { SWIG_DOSTRING_FAIL(lua_tostring(L,-1)); } lua_settop(L,top); /* restore the stack */ return ok; } #ifdef __cplusplus } #endif /* ------------------------------ end luarun.swg ------------------------------ */ /* -------- TYPES TABLE (BEGIN) -------- */ static swig_type_info *swig_types[1]; static swig_module_info swig_module = {swig_types, 0, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #define SWIG_name "mod_sdlkeyboard" #define SWIG_init luaopen_mod_sdlkeyboard #define SWIG_init_user luaopen_mod_sdlkeyboard_user #define SWIG_LUACODE luaopen_mod_sdlkeyboard_luacode namespace swig { typedef struct{} LANGUAGE_OBJ; } #include "love_sdlkeyboard.h" #ifdef __cplusplus extern "C" { #endif static int _wrap_isDown(lua_State* L) { int SWIG_arg = -1; int arg1 ; bool result; SWIG_check_num_args("love_sdlkeyboard::isDown",1,1) if(!lua_isnumber(L,1)) SWIG_fail_arg("love_sdlkeyboard::isDown",1,"int"); arg1 = (int)lua_tonumber(L, 1); result = (bool)love_sdlkeyboard::isDown(arg1); SWIG_arg=0; lua_pushboolean(L,(int)(result==true)); SWIG_arg++; return SWIG_arg; if(0) SWIG_fail; fail: lua_error(L); return SWIG_arg; } #ifdef __cplusplus } #endif static const struct luaL_reg swig_commands[] = { { "isDown", _wrap_isDown}, {0,0} }; static swig_lua_var_info swig_variables[] = { {0,0,0} }; static swig_lua_const_info swig_constants[] = { {0,0,0,0,0,0} }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info *swig_type_initial[] = { NULL }; static swig_cast_info *swig_cast_initial[] = { NULL }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; clientdata = clientdata; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpeters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif /* Forward declaration of where the user's %init{} gets inserted */ void SWIG_init_user(lua_State* L ); #ifdef __cplusplus extern "C" { #endif /* this is the initialization function added at the very end of the code the function is always called SWIG_init, but an eariler #define will rename it */ SWIGEXPORT int SWIG_init(lua_State* L) { int i; /* start with global table */ lua_pushvalue(L,LUA_GLOBALSINDEX); /* SWIG's internal initalisation */ SWIG_InitializeModule((void*)L); SWIG_PropagateClientData(); /* add a global fn */ SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type); SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_equal); /* begin the module (its a table with the same name as the module) */ SWIG_Lua_module_begin(L,SWIG_name); /* add commands/functions */ for (i = 0; swig_commands[i].name; i++){ SWIG_Lua_module_add_function(L,swig_commands[i].name,swig_commands[i].func); } /* add variables */ for (i = 0; swig_variables[i].name; i++){ SWIG_Lua_module_add_variable(L,swig_variables[i].name,swig_variables[i].get,swig_variables[i].set); } /* set up base class pointers (the hierachy) */ for (i = 0; swig_types[i]; i++){ if (swig_types[i]->clientdata){ SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata)); } } /* additional registration structs & classes in lua */ for (i = 0; swig_types[i]; i++){ if (swig_types[i]->clientdata){ SWIG_Lua_class_register(L,(swig_lua_class*)(swig_types[i]->clientdata)); } } /* constants */ SWIG_Lua_InstallConstants(L,swig_constants); /* invoke user-specific initialization */ SWIG_init_user(L); /* end module */ lua_pop(L,1); /* tidy stack (remove module table)*/ lua_pop(L,1); /* tidy stack (remove global table)*/ return 1; } #ifdef __cplusplus } #endif const char* SWIG_LUACODE= "\n" "love.keyboard = mod_sdlkeyboard"; void SWIG_init_user(lua_State* L) { /* exec Lua code if applicable */ SWIG_Lua_dostring(L,SWIG_LUACODE); }
[ "m4rvin2005@8b5f54a0-8722-11de-9e21-49812d2d8162" ]
[ [ [ 1, 1879 ] ] ]
595453b115bb95939c4c05105065e7f6e7e16b38
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-12-22/pcbnew/pcbplot.cpp
04d7543d46014ca520029e573975bca5cd8cc0d1
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
17,212
cpp
/***********************/ /* fichier pcbplot.cpp */ /***********************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "plot_common.h" #include "pcbnew.h" #include "pcbplot.h" #include "worksheet.h" #include "id.h" #include "protos.h" #define PLOT_DEFAULT_MARGE 300 // mils /* variables locale : */ long s_SelectedLayers = CUIVRE_LAYER | CMP_LAYER | SILKSCREEN_LAYER_CMP | SILKSCREEN_LAYER_CU; /* Routines Locales */ enum id_plotps { ID_CLOSE_PLOT = 8020, ID_DRILL_SHAPE_OPT, ID_SCALE_OPT, ID_ROTATE_OPT, ID_MIROR_OPT, ID_EXEC_PLOT, ID_PLOT_MODE_OPT, ID_MASKVIA_OPT, ID_PLOT_CENTRE_OPT, ID_SEL_PLOT_FORMAT, ID_SEL_GERBER_FORMAT, ID_SAVE_OPT_PLOT, ID_PRINT_REF, ID_PRINT_VALUE, ID_PRINT_MODULE_TEXTS, ID_FORCE_PRINT_INVISIBLE_TEXT, ID_PRINT_PAD_ON_SILKSCREEN, ID_FORCE_PRINT_PAD, ID_CREATE_DRILL_FILE }; /*******************************/ /* Dialog box for plot control */ /*******************************/ class WinEDA_PlotFrame: public wxDialog { public: WinEDA_BasePcbFrame * m_Parent; wxButton * m_MergePlotButton; wxCheckBox * m_BoxSelecLayer[32]; wxRadioBox * m_PlotFormatOpt; wxRadioBox * m_Drill_Shape_Opt; wxRadioBox * m_Scale_Opt; wxRadioBox * m_PlotModeOpt; wxCheckBox * m_PlotMirorOpt; wxCheckBox * m_PlotNoViaOnMaskOpt; wxCheckBox * m_HPGL_PlotCenter_Opt; wxCheckBox * m_Plot_Sheet_Ref; wxCheckBox * m_Plot_Invisible_Text; wxCheckBox * m_Plot_Text_Value; wxCheckBox * m_Plot_Text_Ref; wxCheckBox * m_Plot_Text_Div; wxCheckBox * m_Plot_Pads_on_Silkscreen; wxCheckBox * m_Force_Plot_Pads; WinEDA_ValueCtrl * m_GerbSpotSizeMinOpt; WinEDA_ValueCtrl * m_LinesWidth; WinEDA_ValueCtrl * m_HPGLPenSizeOpt; WinEDA_ValueCtrl * m_HPGLPenSpeedOpt; WinEDA_ValueCtrl * m_HPGLPenOverlayOpt; WinEDA_DFloatValueCtrl * m_FineAdjustXscaleOpt, * m_FineAdjustYscaleOpt; double m_XScaleAdjust, m_YScaleAdjust; int m_PlotFormat; public: WinEDA_PlotFrame(WinEDA_BasePcbFrame * parent); private: void Plot(wxCommandEvent & event); void OnQuit(wxCommandEvent & event); void SetCommands(wxCommandEvent & event); void SaveOptPlot(wxCommandEvent & event); void CreateDrillFile(wxCommandEvent & event); DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(WinEDA_PlotFrame, wxDialog) EVT_BUTTON(ID_CLOSE_PLOT, WinEDA_PlotFrame::OnQuit) EVT_BUTTON(ID_EXEC_PLOT, WinEDA_PlotFrame::Plot) EVT_BUTTON(ID_SAVE_OPT_PLOT, WinEDA_PlotFrame::SaveOptPlot) EVT_BUTTON(ID_CREATE_DRILL_FILE, WinEDA_PlotFrame::CreateDrillFile) EVT_RADIOBOX(ID_SEL_PLOT_FORMAT, WinEDA_PlotFrame::SetCommands) END_EVENT_TABLE() #define UNITS_MILS 1000 #define H_SIZE 640 #define V_SIZE 430 WinEDA_PlotFrame::WinEDA_PlotFrame(WinEDA_BasePcbFrame * parent): wxDialog(parent, -1, _("Plot"), wxPoint(-1,-1), wxSize(H_SIZE, V_SIZE), wxDEFAULT_DIALOG_STYLE) { wxPoint pos; wxButton * Button; int ii, jj, bottom = V_SIZE; #define DELTA_Y 16 m_Parent = parent; SetFont(*g_DialogFont); Centre(); m_PlotFormat = format_plot; m_Plot_Sheet_Ref = NULL; pos.x = 360; pos.y = 5; wxString fmtmsg[4] = { wxT("HPGL"), wxT("GERBER"), wxT("Postscript"), wxT("Postscript A4") }; m_PlotFormatOpt = new wxRadioBox(this, ID_SEL_PLOT_FORMAT, _("Plot Format"), pos, wxSize(-1,-1), 4, fmtmsg, 1, wxRA_SPECIFY_COLS); switch ( m_PlotFormat ) { case PLOT_FORMAT_HPGL: m_PlotFormatOpt->SetSelection(0); break; case PLOT_FORMAT_POST: m_PlotFormatOpt->SetSelection(2); break; case PLOT_FORMAT_GERBER: m_PlotFormatOpt->SetSelection(1); break; case PLOT_FORMAT_POST_A4: m_PlotFormatOpt->SetSelection(3); break; } /* Creation des menus d'option du format GERBER */ m_PlotFormatOpt->GetSize(&ii, &jj); pos.y += jj + 10; m_GerbSpotSizeMinOpt = new WinEDA_ValueCtrl(this, _("Spot min"), spot_mini, UnitMetric, pos, UNITS_MILS); /* Creation des menus d'option du format HPGL */ pos.y += m_GerbSpotSizeMinOpt->GetDimension().y + 8; m_HPGLPenSizeOpt = new WinEDA_ValueCtrl(this, _("Pen Size"), g_HPGL_Pen_Diam, UnitMetric, pos, UNITS_MILS); pos.y += m_HPGLPenSizeOpt->GetDimension().y + 8; /* unites standards = cm pour vitesse plume en HPLG */ m_HPGLPenSpeedOpt = new WinEDA_ValueCtrl(this, _("Pen Speed (cm/s)"), g_HPGL_Pen_Speed, CENTIMETRE, pos, 1); m_HPGLPenSpeedOpt->SetToolTip(_("Set pen speed in cm/s")); pos.y += m_HPGLPenSpeedOpt->GetDimension().y + 8; m_HPGLPenOverlayOpt = new WinEDA_ValueCtrl(this, _("Pen Ovr"), g_HPGL_Pen_Recouvrement, UnitMetric, pos, UNITS_MILS); m_HPGLPenOverlayOpt->SetToolTip(_("Set plot overlay for filling")); pos.y += m_HPGLPenOverlayOpt->GetDimension().y + 8; m_LinesWidth = new WinEDA_ValueCtrl(this, _("Lines Width"), g_PlotLine_Width, UnitMetric, pos, PCB_INTERNAL_UNIT); m_LinesWidth->SetToolTip(_("Set width for lines in Line plot mode")); pos.y += m_LinesWidth->GetDimension().y + 8; bottom = MAX (bottom, pos.y); /* Creation des boutons de commande */ pos.x = 475; pos.y = 5; Button = new wxButton(this, ID_EXEC_PLOT, _("Plot"), pos); Button->SetForegroundColour(*wxRED); pos.y += Button->GetSize().y + 5; Button = new wxButton(this, ID_CLOSE_PLOT, _("Cancel"), pos); Button->SetForegroundColour(*wxBLUE); pos.y += Button->GetSize().y + 5; Button = new wxButton(this, ID_SAVE_OPT_PLOT, _("Save options"), pos); Button->SetForegroundColour(wxColour(0,80,0) ); pos.y += Button->GetSize().y + 5; Button = new wxButton(this, ID_CREATE_DRILL_FILE, _("Create Drill File"), pos); Button->SetForegroundColour(wxColour(0,80,80) ); // Create scale adjust option m_XScaleAdjust = m_YScaleAdjust = 1.0; if ( m_Parent->m_Parent->m_EDA_Config ) { m_Parent->m_Parent->m_EDA_Config->Read(wxT("PlotXFineScaleAdj"), &m_XScaleAdjust); m_Parent->m_Parent->m_EDA_Config->Read(wxT("PlotYFineScaleAdj"), &m_YScaleAdjust); } pos.y += Button->GetSize().y + 15; m_FineAdjustXscaleOpt = new WinEDA_DFloatValueCtrl(this, _("X Scale Adjust"), m_XScaleAdjust, pos); m_FineAdjustXscaleOpt->SetToolTip(_("Set X scale adjust for exact scale plotting")); pos.y += m_FineAdjustXscaleOpt->GetDimension().y + 5; m_FineAdjustYscaleOpt = new WinEDA_DFloatValueCtrl(this, _("Y Scale Adjust"), m_YScaleAdjust, pos); m_FineAdjustYscaleOpt->SetToolTip(_("Set Y scale adjust for exact scale plotting")); /* Creation de la liste des layers */ pos.x = 5; jj = pos.y = 5; int mask = 1; for ( ii = 0; ii < NB_LAYERS; ii++, mask <<= 1 ) { if ( ii == 16 ) { pos.x += 90; jj = pos.y; pos.y = 5; } m_BoxSelecLayer[ii] = new wxCheckBox(this, -1, ReturnPcbLayerName(ii), pos); if ( mask & s_SelectedLayers) m_BoxSelecLayer[ii]->SetValue(TRUE); pos.y += 16; } // Option d'impression du cartouche: pos.x = 5; pos.y = jj + 10; if ( m_Parent->m_Print_Sheet_Ref ) { m_Plot_Sheet_Ref = new wxCheckBox(this, ID_PRINT_REF, _("Print Sheet Ref"), pos); m_Plot_Sheet_Ref->SetValue(Plot_Sheet_Ref); pos.y += DELTA_Y + 2; } else Plot_Sheet_Ref = FALSE; // Option d'impression des pads sur toutes les couches m_Plot_Pads_on_Silkscreen = new wxCheckBox(this, ID_PRINT_PAD_ON_SILKSCREEN, _("Print Pads on Silkscreen"), pos); m_Plot_Pads_on_Silkscreen->SetValue(PlotPadsOnSilkLayer); m_Plot_Pads_on_Silkscreen->SetToolTip( _("Enable/disable print/plot pads on Silkscreen layers") ); pos.y += DELTA_Y; m_Force_Plot_Pads = new wxCheckBox(this, ID_FORCE_PRINT_PAD, _("Always Print Pads"), pos); m_Force_Plot_Pads->SetValue(Plot_Pads_All_Layers); m_Force_Plot_Pads->SetToolTip(_("Force print/plot pads on ALL layers") ); // Options d'impression des textes modules pos.y += DELTA_Y; m_Plot_Text_Value = new wxCheckBox(this, ID_PRINT_VALUE, _("Print Module Value"), pos); m_Plot_Text_Value->SetValue(Sel_Texte_Valeur); m_Plot_Text_Value->SetToolTip( _("Enable/disable print/plot module value on Silkscreen layers") ); pos.y += DELTA_Y; m_Plot_Text_Ref = new wxCheckBox(this, ID_PRINT_REF, _("Print Module Reference"), pos); m_Plot_Text_Ref->SetValue(Sel_Texte_Reference); m_Plot_Text_Ref->SetToolTip( _("Enable/disable print/plot module reference on Silkscreen layers") ); pos.y += DELTA_Y; m_Plot_Text_Div = new wxCheckBox(this, ID_PRINT_MODULE_TEXTS, _("Print other module texts"), pos); m_Plot_Text_Div->SetValue(Sel_Texte_Divers); m_Plot_Text_Div->SetToolTip( _("Enable/disable print/plot module field texts on Silkscreen layers") ); pos.y += DELTA_Y; m_Plot_Invisible_Text = new wxCheckBox(this, ID_FORCE_PRINT_INVISIBLE_TEXT, _("Force Print Invisible Texts"), pos); m_Plot_Invisible_Text->SetValue(Sel_Texte_Invisible); m_Plot_Invisible_Text->SetToolTip( _("Force print/plot module invisible texts on Silkscreen layers") ); pos.x = 230; pos.y = 5; wxString drillmsg[3] = { _("No Drill mark"), _("Small mark"), _("Real Drill") }; m_Drill_Shape_Opt = new wxRadioBox(this, ID_DRILL_SHAPE_OPT, _("Pads Drill Opt"), pos, wxSize(-1,-1), 3, drillmsg, 1, wxRA_SPECIFY_COLS); m_Drill_Shape_Opt->SetSelection(g_DrillShapeOpt); m_Drill_Shape_Opt->GetSize(&ii, &jj); pos.y += 15 + jj; wxString scalemsg[5] = { _("Auto scale"), _("Scale 1"), _("Scale 1.5"), _("Scale 2"), _("Scale 3") }; m_Scale_Opt = new wxRadioBox(this, ID_SCALE_OPT, _("Scale Opt"), pos, wxSize(-1,-1), 5, scalemsg, 1, wxRA_SPECIFY_COLS); m_Scale_Opt->SetSelection(g_PlotScaleOpt); m_Scale_Opt->GetSize(&ii, &jj); pos.y += jj + 15; wxString list_opt3[3] = {_("Line"), _("Filled"), _("Sketch") }; m_PlotModeOpt = new wxRadioBox(this, ID_PLOT_MODE_OPT, _("Plot mode"), pos, wxDefaultSize, 3, list_opt3, 1); m_PlotModeOpt->SetSelection(Plot_Mode); m_PlotModeOpt->GetSize(&ii, &jj); pos.y += jj + 15; m_PlotMirorOpt = new wxCheckBox(this, ID_MIROR_OPT, _("Plot Mirror"), pos); m_PlotMirorOpt->SetValue(Plot_Set_MIROIR); pos.y += 17; m_PlotNoViaOnMaskOpt = new wxCheckBox(this, ID_MASKVIA_OPT, _("Vias on Mask"), pos); m_PlotNoViaOnMaskOpt->SetValue(g_DrawViaOnMaskLayer); m_PlotNoViaOnMaskOpt->SetToolTip( _("Print/plot vias on mask layers. They are in this case not protected") ); pos.y += 17; m_HPGL_PlotCenter_Opt = new wxCheckBox(this, ID_PLOT_CENTRE_OPT, _("Org = Centre"), pos); m_HPGL_PlotCenter_Opt->SetValue(HPGL_Org_Centre); m_HPGL_PlotCenter_Opt->SetToolTip(_("Draw origin ( 0,0 )in on sheet center") ); pos.y += 20; if ( bottom < pos.y ) bottom = pos.y; SetClientSize(wxSize(H_SIZE, bottom) ); // Mise a jour des activations des menus: wxCommandEvent event; SetCommands(event); } /***************************************************************/ void WinEDA_PlotFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) /***************************************************************/ { Close(true); // true is to force the frame to close } /*********************************************************/ void WinEDA_PlotFrame::CreateDrillFile(wxCommandEvent & event) /*********************************************************/ /* Create the board drill file used with gerber documents */ { ((WinEDA_PcbFrame * )m_Parent)->InstallDrillFrame(event); } /*********************************************************/ void WinEDA_PlotFrame::SetCommands(wxCommandEvent & event) /*********************************************************/ /* active ou désactive les différents menus d'option selon le standard choisi */ { int format; int format_list[] = {PLOT_FORMAT_HPGL, PLOT_FORMAT_GERBER, PLOT_FORMAT_POST, PLOT_FORMAT_POST_A4 }; format = format_list[m_PlotFormatOpt->GetSelection()]; switch ( format ) { case PLOT_FORMAT_POST_A4: case PLOT_FORMAT_POST: m_Drill_Shape_Opt->Enable(TRUE); m_PlotModeOpt->Enable(TRUE); m_PlotMirorOpt->Enable(TRUE); m_GerbSpotSizeMinOpt->Enable(FALSE); m_LinesWidth->Enable(TRUE); m_HPGLPenSizeOpt->Enable(FALSE); m_HPGLPenSpeedOpt->Enable(FALSE); m_HPGLPenOverlayOpt->Enable(FALSE); m_HPGL_PlotCenter_Opt->Enable(FALSE); m_Plot_Sheet_Ref->Enable(TRUE); m_Scale_Opt->Enable(TRUE); m_FineAdjustXscaleOpt->Enable(TRUE); m_FineAdjustYscaleOpt->Enable(TRUE); m_PlotFormat = PLOT_FORMAT_POST; if ( format == PLOT_FORMAT_POST_A4 ) g_ForcePlotPS_On_A4 = TRUE; else g_ForcePlotPS_On_A4 = FALSE; break; case PLOT_FORMAT_GERBER: m_Drill_Shape_Opt->Enable(FALSE); m_PlotModeOpt->Enable(FALSE); m_PlotMirorOpt->Enable(FALSE); m_GerbSpotSizeMinOpt->Enable(TRUE); m_LinesWidth->Enable(TRUE); m_HPGLPenSizeOpt->Enable(FALSE); m_HPGLPenSpeedOpt->Enable(FALSE); m_HPGLPenOverlayOpt->Enable(FALSE); m_HPGL_PlotCenter_Opt->Enable(FALSE); m_Plot_Sheet_Ref->Enable(FALSE); m_Scale_Opt->Enable(FALSE); m_FineAdjustXscaleOpt->Enable(FALSE); m_FineAdjustYscaleOpt->Enable(FALSE); m_PlotFormat = PLOT_FORMAT_GERBER; break; case PLOT_FORMAT_HPGL: m_PlotMirorOpt->Enable(TRUE); m_Drill_Shape_Opt->Enable(FALSE); m_PlotModeOpt->Enable(TRUE); m_GerbSpotSizeMinOpt->Enable(FALSE); m_LinesWidth->Enable(FALSE); m_HPGLPenSizeOpt->Enable(TRUE); m_HPGLPenSpeedOpt->Enable(TRUE); m_HPGLPenOverlayOpt->Enable(TRUE); m_HPGL_PlotCenter_Opt->Enable(TRUE); m_Plot_Sheet_Ref->Enable(TRUE); m_Scale_Opt->Enable(TRUE); m_FineAdjustXscaleOpt->Enable(FALSE); m_FineAdjustYscaleOpt->Enable(FALSE); m_PlotFormat = PLOT_FORMAT_HPGL; break; } format_plot = m_PlotFormat; } /*********************************************************/ void WinEDA_PlotFrame::SaveOptPlot(wxCommandEvent & event) /*********************************************************/ { if ( m_Plot_Sheet_Ref ) Plot_Sheet_Ref = m_Plot_Sheet_Ref->GetValue(); PlotPadsOnSilkLayer = m_Plot_Pads_on_Silkscreen->GetValue(); Plot_Pads_All_Layers = m_Force_Plot_Pads->GetValue(); Sel_Texte_Valeur = m_Plot_Text_Value->GetValue(); Sel_Texte_Reference = m_Plot_Text_Ref->GetValue(); Sel_Texte_Divers = m_Plot_Text_Div->GetValue(); Sel_Texte_Invisible = m_Plot_Invisible_Text->GetValue(); g_PlotScaleOpt = m_Scale_Opt->GetSelection(); g_DrillShapeOpt = m_Drill_Shape_Opt->GetSelection(); Plot_Set_MIROIR = m_PlotMirorOpt->GetValue(); if ( Plot_Set_MIROIR ) g_PlotOrient = PLOT_MIROIR; else g_PlotOrient = 0; Plot_Mode = m_PlotModeOpt->GetSelection(); g_DrawViaOnMaskLayer = m_PlotNoViaOnMaskOpt->GetValue(); spot_mini = m_GerbSpotSizeMinOpt->GetValue(); g_HPGL_Pen_Diam = m_HPGLPenSizeOpt->GetValue(); g_HPGL_Pen_Speed = m_HPGLPenSpeedOpt->GetValue(); g_HPGL_Pen_Recouvrement = m_HPGLPenOverlayOpt->GetValue(); HPGL_Org_Centre = m_HPGL_PlotCenter_Opt->GetValue(); g_PlotLine_Width = m_LinesWidth->GetValue(); m_XScaleAdjust = m_FineAdjustXscaleOpt->GetValue(); m_YScaleAdjust = m_FineAdjustYscaleOpt->GetValue(); if ( m_Parent->m_Parent->m_EDA_Config ) { m_Parent->m_Parent->m_EDA_Config->Write(wxT("PlotXFineScaleAdj"), m_XScaleAdjust); m_Parent->m_Parent->m_EDA_Config->Write(wxT("PlotYFineScaleAdj"), m_YScaleAdjust); } } /***************************************************/ void WinEDA_PlotFrame::Plot(wxCommandEvent & event) /***************************************************/ { int layer_to_plot; wxString FullFileName, BaseFileName; wxString ext; SaveOptPlot(event); switch ( g_PlotScaleOpt ) { default: Scale_X = Scale_Y = 1; break; case 2: Scale_X = Scale_Y = 1.5; break; case 3: Scale_X = Scale_Y = 2; break; case 4: Scale_X = Scale_Y = 3; break; } Scale_X *= m_XScaleAdjust; Scale_Y *= m_YScaleAdjust; BaseFileName = m_Parent->GetScreen()->m_FileName; ChangeFileNameExt( BaseFileName, wxT("-") ); switch ( m_PlotFormat) { case PLOT_FORMAT_POST: ext = wxT(".ps"); break; case PLOT_FORMAT_GERBER: ext = wxT(".pho"); break; case PLOT_FORMAT_HPGL: ext = wxT(".plt"); break; } int mask = 1; s_SelectedLayers = 0; for ( layer_to_plot = 0; layer_to_plot < 29; layer_to_plot++, mask <<= 1 ) { if ( m_BoxSelecLayer[layer_to_plot]->GetValue() ) { s_SelectedLayers |= mask; /* Calcul du nom du fichier */ FullFileName = BaseFileName +ReturnPcbLayerName(layer_to_plot, TRUE) + ext; switch ( m_PlotFormat) { case PLOT_FORMAT_POST: m_Parent->Genere_PS(FullFileName, layer_to_plot); break; case PLOT_FORMAT_GERBER: m_Parent->Genere_GERBER(FullFileName, layer_to_plot); break; case PLOT_FORMAT_HPGL: m_Parent->Genere_HPGL(FullFileName, layer_to_plot); break; } } } Close(TRUE); } /**************************************************************/ void WinEDA_BasePcbFrame::ToPlotter(wxCommandEvent& event) /***************************************************************/ { WinEDA_PlotFrame * frame = new WinEDA_PlotFrame(this); frame->ShowModal(); frame->Destroy(); }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 549 ] ] ]
95a361b9b6e05909d54aad55f88f1cc5f9ce1ea6
3920e5fc5cbc2512701a3d2f52e072fd50debb83
/Source/Common/itkManagedImageToPathFilter.cxx
56aceda7c904cc1c7da7b45a7006c8a88aa4956a
[ "MIT" ]
permissive
amirsalah/manageditk
4063a37d7370dcbcd08bfe9d24d22015d226ceaf
1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761
refs/heads/master
2016-08-12T05:38:03.377086
2010-08-02T08:17:32
2010-08-02T08:17:32
52,595,294
0
0
null
null
null
null
UTF-8
C++
false
false
3,913
cxx
/*============================================================================= NOTE: THIS FILE IS A HANDMADE WRAPPER FOR THE ManagedITK PROJECT. Project: ManagedITK Program: Insight Segmentation & Registration Toolkit Module: itkManagedImageToPathFilter.cxx Language: C++/CLI Author: Dan Mueller Date: $Date: 2008-06-21 09:20:09 +0200 (Sat, 21 Jun 2008) $ Revision: $Revision: 18 $ Portions of this code are covered under the ITK and VTK copyright. See http://www.itk.org/HTML/Copyright.htm for details. See http://www.vtk.org/copyright.php for details. Copyright (c) 2007-2008 Daniel Mueller Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================*/ #pragma once #pragma warning( disable : 4635 ) // Disable warnings about XML doc comments #ifndef __itkManagedImageToPathFilter_cxx #define __itkManagedImageToPathFilter_cxx // Include some useful ManagedITK files #include "itkManagedDataObject.cxx" #include "itkManagedPathSource.cxx" // Use some managed namespaces #using <mscorlib.dll> #using <System.dll> using namespace System; using namespace System::IO; using namespace System::Reflection; using namespace System::Diagnostics; using namespace System::Collections::Generic; namespace itk { ///<summary> ///This class is a managed replacement for itk::ImageToPathFilter. ///</summary> ///<remarks> ///ImageToPathFilter is the base class for all process objects that output ///path data and require image data as input. Specifically, this class ///defines the SetInput() method for defining the input to a filter. ///</remarks> public ref class itkImageToPathFilter abstract : itkPathSource { protected: ///<summary>Default constructor.</summary> ///<param name="name">A string representing the name of the ProcessObject.</param> itkImageToPathFilter( String^ name ) : itkPathSource( name ) { } public: ///<summary>Set the first input of the filter object.</summary> ///<param name="input">The input as an itkDataObject.</param> virtual void SetInput(itkDataObject^ input) = 0; ///<summary>Set the specified input of the filter object.</summary> ///<param name="input">The input as an itkDataObject.</param> virtual void SetInput(unsigned int index, itkDataObject^ input) = 0; ///<summary>Set the specified input of the filter object.</summary> ///<param name="itkDataObjectPtr">The input as an IntPtr.</param> virtual void SetInput( unsigned int index, IntPtr itkDataObjectPtr ) = 0; ///<summary>Set the first input of the filter object.</summary> ///<param name="itkDataObjectPtr">The input as an IntPtr.</param> virtual void SetInput( IntPtr itkDataObjectPtr ) = 0; }; // end ref class } // end namespace itk #endif
[ "dan.muel@a4e08166-d753-0410-af4e-431cb8890a25" ]
[ [ [ 1, 100 ] ] ]
00e0dd13739f3f630a2d41e372e55aac786d6e4a
971b000b9e6c4bf91d28f3723923a678520f5bcf
/fop_miniscribus.1.0.0/src/floating_box/floatdiagram.h
8d7a41f2688e394c408a55907d3a1e7acfd81031
[]
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
5,026
h
#ifndef FLOATDIAGRAM_H #define FLOATDIAGRAM_H #include <iostream> #include <stdio.h> #include <iostream> #include <QtCore> #include <QDebug> #include <QCoreApplication> #include <QObject> #include <math.h> #include <QGraphicsScene> #include <QtGui> #include <QApplication> #include "graphicsscene.h" #include <QWidget> #include <QBrush> #include <QPixmap> #include <QColor> #include <QPalette> #include <QGraphicsTextItem> #include <QMenu> #include "wymsingtxt.h" #include <QMessageBox> #include "main.h" class FloatDiagram : public QGraphicsTextItem { Q_OBJECT public: typedef enum { M_SHOW = 50, M_VIEW, /* 51 */ M_HOVER, /* 52 */ M_EDITOR, /* 53 */ M_ADV_EDITOR, /* 54 */ M_WRITTELN, /* 55 */ M_MOVE_NORD, /* 56 */ M_MOVE_SUD, /* 57 */ M_MOVE_WEST, /* 58 */ M_MOVE_OWEST, /* 59 */ M_MOVE_ALL, /* 60 */ M_LOCK, /* 61 */ M_UNLOCK, /* 62 */ M_UNKNOW /* 63 */ } T_MODE; FloatDiagram( int idx , QMenu *Diss , QGraphicsItem *parent, QGraphicsScene *scene ); FloatDiagram *clone() const; inline int Getid() { return id; } inline void SetDimension( qreal w , qreal h ) { wi = w; hi = h; LayerHightChecks(); setTextWidth ( wi - 2 ); ensureVisible(boundingRect(),2, 2); } inline void SetINTarget( QStringList t ) { TargetInternalLink = t; } inline void PaintStausLayer( bool statut ) { PaintLockStaus = statut; update(); } void SetDomeWrite( QDomDocument docwritteln ) { doc = docwritteln; } inline void SetModus( T_MODE e ) { modus = e; update(); } inline T_MODE GetModus() { return modus; } inline void SetupRoq( int degres ) { BoxRotate = degres; } inline int GetDegree() { return BoxRotate; } inline void SetBGColor( QColor qc ) { BGColor = qc; AlphaColor = qc.alpha(); update(); } inline QColor GetColor() { return BGColor; } inline void SetBorder( QColor qc , qreal spess ) { MarginColor = qc; BorderDicks = spess; } inline void SetResource( TypImageContainer block ) { ImageContainer.clear(); ImageContainer = block; } inline TypImageContainer GetResource() { return ImageContainer; } inline QRectF Prect() const { QRectF orealrect( pos().x(), pos().y(), wi, hi ); return orealrect; } inline void setSelected ( bool selected ) { IsSelectActive = selected; QGraphicsItem::setSelected(selected); QGraphicsTextItem::setSelected(selected); } inline bool isSelected() { return IsSelectActive; } QRectF boundingRect() const; QDomElement GetBaseLayerElement( QDomDocument docwritteln ); /* prepare to save layer element writteln attribute */ qreal zValue() const ; void setZValue( qreal zindex ); int DocumentHighgtActual(); QString toDivHtml( QFileInfo f ); protected: void ImageFindertoHtml( QDomElement e , const QString imagepath ); /* export html */ QString SaveHtmlImage( const QString urlimage , const QString path ); /* export html */ QVimedit *d; bool IsSelectActive; QTransform ActualMatrixe( int r ); void RestoreMoveAction(); void LayerHightChecks(); void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); void keyPressEvent ( QKeyEvent * event ); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void paint(QPainter *painter,const QStyleOptionGraphicsItem *option,QWidget *widget); int wi; int hi; qreal ZIndex; int BoxRotate; int OLD_BoxRotate; T_MODE modus; QColor ground; int id; bool PaintLockStaus; QMenu *PMenu; QPointF dragPosition; QTextDocument *tdoc; QTextCursor tcur; QAction *Aundo, *Aredo, *Aselall, *Asetmyfont, *Abgcolor, *AMacolor, *Apaste, *Acopy; QClipboard *baseram; QColor BGColor; QColor MarginColor; int AlphaColor; qreal BorderDicks; WymsingTxt *editTXT; TypImageContainer ImageContainer; QDomDocument doc; QString DefaultMessage; QGraphicsItem *itpararent; QGraphicsScene *scenes; QStringList TargetInternalLink; signals: void Rebuild(); public slots: void Tcopy(); void Tpaste(); void TselectAll(); void SetNewBGColor(); void FlyFonts(); void SetMarginColor(); void EditAdvanceModus(); void SPTransForm( int rot ); void PaintAllFonts( QFont f ); void InValues( QRectF mbox ,qreal margin ,QColor bg , QColor margincolor , QTextDocument * d , TypImageContainer block ); }; #endif // FLOATDIAGRAM_H
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 197 ] ] ]
57384a63061739291165319effd5b0acb1cb673c
4dd44d686f1b96f8e6edae3769369a89013f6bc1
/ocass/console/ocac_proc.cpp
0745fca53441c1a595b2f74dc95068511ad1b932
[]
no_license
bactq/ocass
e1975533a69adbd1b4d1f9fd1bd88647039fff82
116565ea7c554b11b0a696f185d3a6376e0161dc
refs/heads/master
2021-01-10T14:04:02.179429
2007-07-14T16:03:23
2007-07-14T16:03:23
45,017,357
0
0
null
null
null
null
UTF-8
C++
false
false
2,816
cpp
/* * OCASS - Microsoft Office Communicator Assistant * (http://code.google.com/p/ocass/) * * Copyright (C) 2007 Le Xiongjia * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Le Xiongjia ([email protected] [email protected]) * */ #include "libocc.h" #include "liboca.h" #include "ca_getopt.h" #include "ca_misc.h" #include "ca_cfg.h" #include "ocac_proc.h" #include "ocac_misc.h" CAErrno CAC_PDataInit(OCACProc *pProc) { CAErrno caErr; caErr = CA_GetModPath(NULL, pProc->szProcWrkPath, sizeof(pProc->szProcWrkPath) / sizeof(pProc->szProcWrkPath[0])); if (CA_ERR_SUCCESS != caErr) { return caErr; } caErr = CA_CfgGetFName(pProc->szProcWrkPath, pProc->szProcCfgFName, sizeof(pProc->szProcCfgFName) / sizeof(pProc->szProcCfgFName[0])); if (CA_ERR_SUCCESS != caErr) { return caErr; } pProc->procType = OCAC_PROC_TYPE_WORKER; return CA_ERR_SUCCESS; } CAErrno CAC_PStartup(int nArgc, char **pArgv, OCACProc *pProc) { CAGetoptDatum datumGetOpt = {0}; CAErrno caErr; char *pszOptArg; char cOpt; caErr = CAC_PDataInit(pProc); if (CA_ERR_SUCCESS != caErr) { return caErr; } caErr = CA_Startup(); if (CA_ERR_SUCCESS != caErr) { return caErr; } CA_RTSetLog(NULL, OCAC_LogShow); CA_InitGetOpt(nArgc, pArgv, &datumGetOpt); for (;;) { caErr = CA_GetOpt(&datumGetOpt, "hH?Kk", &cOpt, &pszOptArg); if (CA_ERR_SUCCESS != caErr) { break; } switch (cOpt) { case '?': case 'h': case 'H': pProc->procType = OCAC_PROC_TYPE_USAGE; break; case 'K': case 'k': pProc->procType = OCAC_PROC_TYPE_KILLER; break; default: break; } } if (CA_ERR_EOF != caErr) { pProc->procType = OCAC_PROC_TYPE_USAGE; } return CA_ERR_SUCCESS; } CAErrno CAC_PCleanup(OCACProc *pProc) { CA_Cleanup(); return CA_ERR_SUCCESS; }
[ "lexiongjia@4b591cd5-a833-0410-8603-c1928dc92378" ]
[ [ [ 1, 112 ] ] ]
f9a8bddfdb702c5a8903e86be158f775bf855c46
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/openredalert/src/game/AiCommand.cpp
193c27102d6aea28d1fff94f923ad13b0fc13ff1
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
969
cpp
// AiCommand.cpp // 1.0 // This file is part of OpenRedAlert. // // OpenRedAlert 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 of the License. // // OpenRedAlert 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 OpenRedAlert. If not, see <http://www.gnu.org/licenses/>. #include "AiCommand.h" int AiCommand::getId() { return id; } void AiCommand::setId(int id) { this->id = id; } int AiCommand::getWaypoint() { return waypoint; } void AiCommand::setWaypoint(int waypoint) { this->waypoint = waypoint; }
[ [ [ 1, 34 ] ] ]
48740abe87dcf8d806eb634f9659b68c8916b9a4
cd787383f4b4ffad1c6a1d45899ed16a8d12a18a
/CDeleteAction.h
755376e608aa11598dadd095a5ac1cbfad8ba9ae
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
brianly/hobocopy
f6d6277203422d0a757459bafa4856e47dab118d
0450f1551a4df300829723048db0924b69ec7d96
refs/heads/master
2020-12-25T13:08:22.457084
2011-01-22T00:55:01
2011-01-22T00:55:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,561
h
/* Copyright (c) 2006 Wangdera Corporation ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "Utilities.h" #include "OutputWriter.h" class CDeleteAction : public CDirectoryAction { private: LPCTSTR _target; public: CDeleteAction::CDeleteAction(LPCTSTR target) { _target = target; } void VisitDirectoryFinal(LPCTSTR path) { CString fullPath; Utilities::CombinePath(_target, path, fullPath); Utilities::FixLongFilenames(fullPath); BOOL bWorked = ::RemoveDirectory(fullPath); if (!bWorked) { DWORD error = ::GetLastError(); CString errorMessage; Utilities::FormatErrorMessage(error, errorMessage); CString message; message.AppendFormat(TEXT("Error %s calling RemoveDirectory on %s"), errorMessage, fullPath); throw new CHoboCopyException(message); } else { CString message; message.AppendFormat(TEXT("Deleted directory %s"), fullPath); OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL); } } void VisitDirectoryInitial(LPCTSTR path) { // Do nothing } virtual void VisitFile(LPCTSTR path) { CString fullPath; Utilities::CombinePath(_target, path, fullPath); Utilities::FixLongFilenames(fullPath); BOOL bWorked = ::DeleteFile(fullPath); if (!bWorked) { DWORD error = ::GetLastError(); // Maybe it's read-only if (error == 5) { CString message; message.AppendFormat(TEXT("Permission denied when deleting file %s. Resetting read-only bit and retrying."), fullPath); OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_IF_VERBOSE); DWORD attributes = ::GetFileAttributes(fullPath); if (attributes == INVALID_FILE_ATTRIBUTES) { CString message; message.AppendFormat(TEXT("Failed to retrieve attributes for file %s."), fullPath); throw new CHoboCopyException(message); } attributes &= ~FILE_ATTRIBUTE_READONLY; bWorked = ::SetFileAttributes(fullPath, attributes); if (!bWorked) { CString message; message.AppendFormat(TEXT("Failed to clear read-only bit on %s"), fullPath); throw new CHoboCopyException(message); } bWorked = ::DeleteFile(fullPath); if (!bWorked) { error = ::GetLastError(); } } if (!bWorked) { CString errorMessage; Utilities::FormatErrorMessage(error, errorMessage); CString message; message.AppendFormat(TEXT("Error %s calling DeleteFile on %s"), errorMessage, path); throw new CHoboCopyException(message); } } if (bWorked) { CString message; message.AppendFormat(TEXT("Successfully deleted file %s."), fullPath); OutputWriter::WriteLine(message); } } };
[ [ [ 1, 137 ] ] ]
6a2d924e6e94dc5f448245b9cbaacd70ad26f652
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Visualize/Shape/hkDisplayCone.h
a6b0e6bbde73da334281e5984c74b6708e6e1191
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
2,433
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_VISUALIZE_SHAPE_CONE_H #define HK_VISUALIZE_SHAPE_CONE_H #include <Common/Visualize/Shape/hkDisplayGeometry.h> class hkDisplayCone : public hkDisplayGeometry { public: hkDisplayCone(const hkReal coneAngle, const hkReal coneHeight, const int numSegments, const hkVector4& coneAxis, const hkVector4& startPos); hkDisplayCone(); void setParameters(const hkReal coneAngle, const hkReal coneHeight, const int numSegments, const hkVector4& coneAxis, const hkVector4& startPos); virtual void buildGeometry(); virtual void getWireframeGeometry( hkArrayBase<hkVector4>& lines, hkMemoryAllocator& a ); // get apex of cone in WS hkVector4 getPosition(); // get axis of cone in WS hkVector4 getAxis(); // get height along axis hkReal getHeight(); // get angle of cone hkReal getAngle(); // get number of segments int getNumSegments(); protected: hkVector4 m_startPos; hkVector4 m_coneAxis; int m_numSegments; hkReal m_coneAngle; hkReal m_coneHeight; void generateConeVertices(hkArray<hkVector4>& conePoints); }; #endif // HK_VISUALIZE_SHAPE_CONE_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 83 ] ] ]
294616501491aecac582ed3458096ee66864363c
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/internal/ReaderMgr.hpp
24c7d2e45805d18a988a1d610d3007aab12afb12
[]
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
15,293
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: ReaderMgr.hpp 191054 2005-06-17 02:56:35Z jberry $ */ #if !defined(READERMGR_HPP) #define READERMGR_HPP #include <xercesc/internal/XMLReader.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/RefStackOf.hpp> #include <xercesc/sax/Locator.hpp> #include <xercesc/framework/XMLBuffer.hpp> XERCES_CPP_NAMESPACE_BEGIN class XMLEntityDecl; class XMLEntityHandler; class XMLDocumentHandler; class XMLScanner; // --------------------------------------------------------------------------- // This class is used by the scanner. The scanner must deal with expansion // of entities, some of which are totally different files (external parsed // entities.) It does so by pushing readers onto a stack. The top reader is // the one it wants to read out of, but that one must be popped when it is // empty. To keep that logic from being all over the place, the scanner // talks to the reader manager, which handles the stack and popping off // used up readers. // --------------------------------------------------------------------------- class XMLPARSER_EXPORT ReaderMgr : public XMemory , public Locator { public : // ----------------------------------------------------------------------- // Class specific types // ----------------------------------------------------------------------- struct LastExtEntityInfo : public XMemory { const XMLCh* systemId; const XMLCh* publicId; XMLSSize_t lineNumber; XMLSSize_t colNumber; }; // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- ReaderMgr(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); ~ReaderMgr(); // ----------------------------------------------------------------------- // Convenience scanning methods // // This are all convenience methods that work in terms of the core // character spooling methods. // ----------------------------------------------------------------------- bool atEOF() const; bool getName(XMLBuffer& toFill); bool getQName(XMLBuffer& toFill, int* colonPosition); bool getNameToken(XMLBuffer& toFill); XMLCh getNextChar(); bool getNextCharIfNot(const XMLCh chNotToGet, XMLCh& chGotten); void movePlainContentChars(XMLBuffer &dest); void getSpaces(XMLBuffer& toFill); void getUpToCharOrWS(XMLBuffer& toFill, const XMLCh toCheck); bool isEmpty() const; bool lookingAtChar(const XMLCh toCheck); bool lookingAtSpace(); XMLCh peekNextChar(); bool skipIfQuote(XMLCh& chGotten); void skipPastChar(const XMLCh toSkip); bool skipPastSpaces(bool inDecl = false); void skipToChar(const XMLCh toSkipTo); bool skippedChar(const XMLCh toSkip); bool skippedSpace(); bool skippedString(const XMLCh* const toSkip); void skipQuotedString(const XMLCh quoteCh); XMLCh skipUntilIn(const XMLCh* const listToSkip); XMLCh skipUntilInOrWS(const XMLCh* const listToSkip); bool peekString(const XMLCh* const toPeek); // ----------------------------------------------------------------------- // Control methods // ----------------------------------------------------------------------- void cleanStackBackTo(const unsigned int readerNum); XMLReader* createReader ( const InputSource& src , const bool xmlDecl , const XMLReader::RefFrom refFrom , const XMLReader::Types type , const XMLReader::Sources source , const bool calcSrsOfs = true ); XMLReader* createReader ( const XMLCh* const sysId , const XMLCh* const pubId , const bool xmlDecl , const XMLReader::RefFrom refFrom , const XMLReader::Types type , const XMLReader::Sources source , InputSource*& srcToFill , const bool calcSrcOfs = true , const bool disableDefaultEntityResolution = false ); XMLReader* createReader ( const XMLCh* const baseURI , const XMLCh* const sysId , const XMLCh* const pubId , const bool xmlDecl , const XMLReader::RefFrom refFrom , const XMLReader::Types type , const XMLReader::Sources source , InputSource*& srcToFill , const bool calcSrcOfs = true , const bool disableDefaultEntityResolution = false ); XMLReader* createIntEntReader ( const XMLCh* const sysId , const XMLReader::RefFrom refFrom , const XMLReader::Types type , const XMLCh* const dataBuf , const unsigned int dataLen , const bool copyBuf , const bool calcSrcOfs = true ); bool isScanningPERefOutOfLiteral() const; bool pushReader ( XMLReader* const reader , XMLEntityDecl* const entity ); void reset(); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- const XMLCh* getCurrentEncodingStr() const; const XMLEntityDecl* getCurrentEntity() const; XMLEntityDecl* getCurrentEntity(); const XMLReader* getCurrentReader() const; XMLReader* getCurrentReader(); unsigned int getCurrentReaderNum() const; unsigned int getReaderDepth() const; void getLastExtEntityInfo(LastExtEntityInfo& lastInfo) const; unsigned int getSrcOffset() const; bool getThrowEOE() const; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- void setEntityHandler(XMLEntityHandler* const newHandler); void setThrowEOE(const bool newValue); void setXMLVersion(const XMLReader::XMLVersion version); void setStandardUriConformant(const bool newValue); // ----------------------------------------------------------------------- // Implement the SAX Locator interface // ----------------------------------------------------------------------- virtual const XMLCh* getPublicId() const; virtual const XMLCh* getSystemId() const; virtual XMLSSize_t getLineNumber() const; virtual XMLSSize_t getColumnNumber() const; private : // ----------------------------------------------------------------------- // Private helper methods // ----------------------------------------------------------------------- const XMLReader* getLastExtEntity(const XMLEntityDecl*& itsEntity) const; bool popReader(); // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- ReaderMgr(const ReaderMgr&); ReaderMgr& operator=(const ReaderMgr&); // ----------------------------------------------------------------------- // Private data members // // fCurEntity // This is the current top of stack entity. We pull it off the stack // and store it here for efficiency. // // fCurReader // This is the current top of stack reader. We pull it off the // stack and store it here for efficiency. // // fEntityHandler // This is the installed entity handler. Its installed via the // scanner but he passes it on to us since we need it the most, in // process of creating external entity readers. // // fEntityStack // We need to keep up with which of the pushed readers are pushed // entity values that are being spooled. This is done to avoid the // problem of recursive definitions. This stack consists of refs to // EntityDecl objects for the pushed entities. // // fNextReaderNum // This is the reader serial number value. Each new reader that is // created from this reader is given a successive number. This lets // us catch things like partial markup errors and such. // // fReaderStack // This is the stack of reader references. We own all the readers // and destroy them when they are used up. // // fThrowEOE // This flag controls whether we throw an exception when we hit an // end of entity. The scanner doesn't really need to know about ends // of entities in the int/ext subsets, so it will turn this flag off // until it gets into the content usually. // // fXMLVersion // Enum to indicate if each Reader should be created as XML 1.1 or // XML 1.0 conformant // // fStandardUriConformant // This flag controls whether we force conformant URI // ----------------------------------------------------------------------- XMLEntityDecl* fCurEntity; XMLReader* fCurReader; XMLEntityHandler* fEntityHandler; RefStackOf<XMLEntityDecl>* fEntityStack; unsigned int fNextReaderNum; RefStackOf<XMLReader>* fReaderStack; bool fThrowEOE; XMLReader::XMLVersion fXMLVersion; bool fStandardUriConformant; MemoryManager* fMemoryManager; }; // --------------------------------------------------------------------------- // ReaderMgr: Inlined methods // // NOTE: We cannot put these in alphabetical and type order as we usually // do because some of the compilers we have to support are too stupid to // understand out of order inlines! // --------------------------------------------------------------------------- inline unsigned int ReaderMgr::getCurrentReaderNum() const { return fCurReader->getReaderNum(); } inline const XMLReader* ReaderMgr::getCurrentReader() const { return fCurReader; } inline XMLReader* ReaderMgr::getCurrentReader() { return fCurReader; } inline bool ReaderMgr::getName(XMLBuffer& toFill) { toFill.reset(); return fCurReader->getName(toFill, false); } inline bool ReaderMgr::getQName(XMLBuffer& toFill, int *colonPosition) { toFill.reset(); return fCurReader->getQName(toFill, colonPosition); } inline bool ReaderMgr::getNameToken(XMLBuffer& toFill) { toFill.reset(); return fCurReader->getName(toFill, true); } inline bool ReaderMgr::getNextCharIfNot(const XMLCh chNotToGet, XMLCh& chGotten) { return fCurReader->getNextCharIfNot(chNotToGet, chGotten); } inline void ReaderMgr::movePlainContentChars(XMLBuffer &dest) { fCurReader->movePlainContentChars(dest); } inline bool ReaderMgr::getThrowEOE() const { return fThrowEOE; } inline unsigned int ReaderMgr::getSrcOffset() const { return fCurReader? fCurReader->getSrcOffset() : 0; } inline bool ReaderMgr::lookingAtChar(const XMLCh chToCheck) { return (chToCheck == peekNextChar()); } inline bool ReaderMgr::lookingAtSpace() { XMLCh c = peekNextChar(); return fCurReader->isWhitespace(c); } inline void ReaderMgr::setThrowEOE(const bool newValue) { fThrowEOE = newValue; } inline void ReaderMgr::setStandardUriConformant(const bool newValue) { fStandardUriConformant = newValue; } inline bool ReaderMgr::skippedString(const XMLCh* const toSkip) { return fCurReader->skippedString(toSkip); } inline void ReaderMgr::skipToChar(const XMLCh toSkipTo) { XMLCh nextCh = 0; do { // Get chars until we find the one to skip nextCh = getNextChar(); } // Break out at end of input or the char to skip while((nextCh != toSkipTo) && nextCh!=0); } inline void ReaderMgr::skipPastChar(const XMLCh toSkipPast) { XMLCh nextCh = 0; do { // Get chars until we find the one to skip nextCh = getNextChar(); } while((nextCh != toSkipPast) && nextCh!=0); } inline bool ReaderMgr::peekString(const XMLCh* const toPeek) { return fCurReader->peekString(toPeek); } inline void ReaderMgr::setEntityHandler(XMLEntityHandler* const newHandler) { fEntityHandler = newHandler; } inline void ReaderMgr::setXMLVersion(const XMLReader::XMLVersion version) { fXMLVersion = version; fCurReader->setXMLVersion(version); } // // This is a simple class to temporarily change the 'throw at end of entity' // flag of the reader manager. There are some places where we need to // turn this on and off on a scoped basis. // class XMLPARSER_EXPORT ThrowEOEJanitor { public : // ----------------------------------------------------------------------- // Constructors and destructor // ----------------------------------------------------------------------- ThrowEOEJanitor(ReaderMgr* mgrTarget, const bool newValue) : fOld(mgrTarget->getThrowEOE()) , fMgr(mgrTarget) { mgrTarget->setThrowEOE(newValue); } ~ThrowEOEJanitor() { fMgr->setThrowEOE(fOld); }; private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- ThrowEOEJanitor(const ThrowEOEJanitor&); ThrowEOEJanitor& operator=(const ThrowEOEJanitor&); // ----------------------------------------------------------------------- // Private data members // // fOld // The previous value of the flag, which we replaced during ctor, // and will replace during dtor. // // fMgr // A pointer to the reader manager we are going to set/reset the // flag on. // ----------------------------------------------------------------------- bool fOld; ReaderMgr* fMgr; }; XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 435 ] ] ]
54853be04f1516246b3051e55a70414107a334d6
0b66a94448cb545504692eafa3a32f435cdf92fa
/branches/kyr/cbear.berlios.de/windows/com/pointer_base.test.cpp
ab38aab0690af913a1910fe2db1d841dde01d52e
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
58
cpp
#include <cbear.berlios.de/windows/com/pointer_base.hpp>
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 1 ] ] ]
96e6fc60567d78399ffab5e493f97b41a86ee3c8
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Client/Dimensions/IceSpray.h
9d02371efa9dd16cb1d2cb5fb7fbb523e83fefcf
[]
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
389
h
#pragma once #include "basicshot.h" class IceSpray : public BasicShot { public: IceSpray(void); ~IceSpray(void); bool Update(PlayerCharacter* pSkillOwner, float fDeltaTime); protected: int GetRange() { return m_iMinRange + m_iSkillRank /m_iRangeMod; } float m_fArcMod; int m_iRangeMod; int m_iMinRange; int m_iMinResist; int m_iResistMod; };
[ "bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 21 ] ] ]
1dcd8d4c096a09ae24842d21e3d9ac333e659fac
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/circusc.h
ca3fb40f8df7b5211a890ce0ebe6f5db159e565d
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
h
/************************************************************************* Circus Charlie *************************************************************************/ class circusc_state : public driver_device { public: circusc_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT8 * m_videoram; UINT8 * m_colorram; UINT8 * m_spriteram; UINT8 * m_spriteram_2; UINT8 * m_spritebank; UINT8 * m_scroll; size_t m_spriteram_size; /* video-related */ tilemap_t *m_bg_tilemap; /* sound-related */ UINT8 m_sn_latch; /* devices */ cpu_device *m_audiocpu; device_t *m_sn1; device_t *m_sn2; device_t *m_dac; device_t *m_discrete; }; /*----------- defined in video/circusc.c -----------*/ WRITE8_HANDLER( circusc_videoram_w ); WRITE8_HANDLER( circusc_colorram_w ); VIDEO_START( circusc ); WRITE8_HANDLER( circusc_flipscreen_w ); PALETTE_INIT( circusc ); SCREEN_UPDATE( circusc );
[ "Mike@localhost" ]
[ [ [ 1, 45 ] ] ]
92928afb3b60670de4f0034d9ac3f3c7df9541f5
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkQtChartSeriesSelection.h
e5bbd13dddcb51002cf21dea64b914fe9c44b846
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,424
h
/*========================================================================= Program: Visualization Toolkit Module: vtkQtChartSeriesSelection.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ /// \file vtkQtChartSeriesSelection.h /// \date March 14, 2008 #ifndef _vtkQtChartSeriesSelection_h #define _vtkQtChartSeriesSelection_h #include "vtkQtChartExport.h" #include <QMap> // needed for return type #include "vtkQtChartIndexRangeList.h" // needed for return type. class vtkQtChartSeriesSelectionInternal; /// \class vtkQtChartSeriesSelection /// \brief /// The vtkQtChartSeriesSelection class is used for series and point /// selection. class VTKQTCHART_EXPORT vtkQtChartSeriesSelection { public: enum SelectionType { NoSelection = 0, ///< No selection is made. SeriesSelection, ///< The selection contains series indexes. PointSelection ///< The selection contains point indexes. }; public: vtkQtChartSeriesSelection(); vtkQtChartSeriesSelection(const vtkQtChartSeriesSelection &other); ~vtkQtChartSeriesSelection(); vtkQtChartSeriesSelection &operator=(const vtkQtChartSeriesSelection &other); /// \brief /// Gets whether or not the selection is empty. /// \return /// True if the selection is empty. bool isEmpty() const; /// \brief /// Gets the selection type. /// \return /// The selection type. SelectionType getType() const; /// Clears the selection lists. bool clear(); /// \name Series Selection Methods //@{ /// \brief /// Gets the list of selected series ranges. /// \return /// A reference to the list of selected series ranges. const vtkQtChartIndexRangeList &getSeries() const; /// \brief /// Sets the list of selected series ranges. /// \param series The new list of selected series ranges. /// \return /// True if the selection was modified. bool setSeries(const vtkQtChartIndexRangeList &series); /// \brief /// Sets the list of selected series ranges. /// \param first The first series index in the range. /// \param last The last series index in the range. /// \return /// True if the selection was modified. bool setSeries(int first, int last); /// \brief /// Adds the list of series ranges to the selection. /// \param series The list of selected series ranges to add. /// \return /// True if the selection was modified. bool addSeries(const vtkQtChartIndexRangeList &series); /// \brief /// Adds the series index range to the selection. /// \param first The first series index in the range. /// \param last The last series index in the range. /// \return /// True if the selection was modified. bool addSeries(int first, int last); /// \brief /// Subtracts the list of series ranges from the selection. /// \param series The list of selected series ranges to subtract. /// \return /// True if the selection was modified. bool subtractSeries(const vtkQtChartIndexRangeList &series); /// \brief /// Subtracts the series index range from the selection. /// \param first The first series index in the range. /// \param last The last series index in the range. /// \return /// True if the selection was modified. bool subtractSeries(int first, int last); /// \brief /// Selects unique series from the given list and the selection. /// \param series The list of series ranges. /// \return /// True if the selection was modified. bool xorSeries(const vtkQtChartIndexRangeList &series); /// \brief /// Selects unique series from the given range and the selection. /// \param first The first series index in the range. /// \param last The last series index in the range. /// \return /// True if the selection was modified. bool xorSeries(int first, int last); /// \brief /// Trims the selected series to the given bounds. /// \param minimum The minimum series index. /// \param maximum The maximum series index. void limitSeries(int minimum, int maximum); /// \brief /// Adds the offset to all the series greater than or equal to /// the given series. /// \param first The starting series index. /// \param offset The offset to add to the indexes. /// \return /// True if the selection was modified. bool offsetSeries(int first, int offset); //@} /// \name Point Selection Methods //@{ /// \brief /// Gets the list of selected point ranges. /// \return /// A reference to the list of selected point ranges. const QMap<int, vtkQtChartIndexRangeList> &getPoints() const; /// \brief /// Sets the list of selected point ranges. /// \param points The new list of selected point ranges. /// \return /// True if the selection was modified. bool setPoints(const QMap<int, vtkQtChartIndexRangeList> &points); /// \brief /// Sets the list of selected point ranges. /// \param series The series index. /// \param indexes The list of point ranges. /// \return /// True if the selection was modified. bool setPoints(int series, const vtkQtChartIndexRangeList &indexes); /// \brief /// Adds the list of point ranges to the selection. /// \param points The list of selected point ranges to add. /// \return /// True if the selection was modified. bool addPoints(const QMap<int, vtkQtChartIndexRangeList> &points); /// \brief /// Adds the list of point ranges to the selection. /// \param series The series index. /// \param indexes The list of point ranges. /// \return /// True if the selection was modified. bool addPoints(int series, const vtkQtChartIndexRangeList &indexes); /// \brief /// Subtracts the list of point ranges from the selection. /// \param points The list of selected point ranges to subtract. /// \return /// True if the selection was modified. bool subtractPoints(const QMap<int, vtkQtChartIndexRangeList> &points); /// \brief /// Subtracts the list of point ranges from the selection. /// \param series The series index. /// \param indexes The list of point ranges. /// \return /// True if the selection was modified. bool subtractPoints(int series, const vtkQtChartIndexRangeList &indexes); /// \brief /// Subtracts all the selected points in the given series from /// the selection. /// \param first The first series in the range. /// \param last The last series in the range. /// \return /// True if the selection was modified. bool subtractPoints(int first, int last); /// \brief /// Selects unique points from the given list and the selection. /// \param points The list of point ranges. /// \return /// True if the selection was modified. bool xorPoints(const QMap<int, vtkQtChartIndexRangeList> &points); /// \brief /// Selects unique points from the given list and the selection. /// \param series The series index. /// \param indexes The list of point ranges. /// \return /// True if the selection was modified. bool xorPoints(int series, const vtkQtChartIndexRangeList &indexes); /// \brief /// Trims the selected point indexes for the given series. /// \param series The series index. /// \param minimum The minimum point index. /// \param maximum The maximum point index. void limitPoints(int series, int minimum, int maximum); //@} private: vtkQtChartSeriesSelectionInternal *Internal; ///< Stores the selection lists. }; #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 243 ] ] ]
a909e57961da132c02d3e957b1eb0c3e0c71e59b
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/RTTS/TS_ModelLib/GlobalPartitionSeperator.h
520d73270e8763a588fe2a96e505396bb55663cf
[]
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
1,479
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #ifndef __GlobalPartitionSeperator_H #define __GlobalPartitionSeperator_H #ifndef __MD_HEADERS_H #include "md_headers.h" #endif #include "seperator.h" //--------------------------------------------------------------------------- class CSeperator_GlobalPartition : public CSeperator { public: // Constructor CSeperator_GlobalPartition(); // Data Entry Field Method void BuildDataFields(MDataDefn &DB); // Seperator Method Execution void EvalProducts(MStream &Feed , MStream &Product1, MStream &Product2, MStream &Product3, bool bTwoDecks, bool bInit); protected: // Seperates the specified Feed stream into 2 products based on the // Efficiency Curve void Seperate(CArray <double, double&> &in_Eu, double in_WaterSplitToUS, MStream &in_Feed, MStream &out_ProductA , MStream &out_ProductB); // Partition selection list MDDValueLst *m_DDPSDPartition; // Selected Partition to for Display long m_lPartitionSel; // Array of partitions CArray <CPartition, CPartition&> m_CTopPartition; CArray <CPartition, CPartition&> m_CBottomPartition; // Water Splits double m_dTopWaterSplitToUS; double m_dBottomWaterSplitToUS; }; #endif
[ [ [ 1, 57 ] ] ]
ca42872d50f1bf62a3b16a2b4bcf9ed13bc583de
221e3e713891c951e674605eddd656f3a4ce34df
/core/Example/HelloWorld.cpp
0eb1a13bd16a5a6fde64011502d5181edb485b23
[ "MIT" ]
permissive
zacx-z/oneu-engine
da083f817e625c9e84691df38349eab41d356b76
d47a5522c55089a1e6d7109cebf1c9dbb6860b7d
refs/heads/master
2021-05-28T12:39:03.782147
2011-10-18T12:33:45
2011-10-18T12:33:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,166
cpp
#include <OUE/Game.h> #include <OUE/Video.h> #include <OUE/Sprite.h> #include <OUE/Scene.h> #include <OUE/Control.h> #pragma comment(lib, "OUE.lib") #pragma comment(lib, "Base.lib") using namespace OneU; class BeginScene : public IScene { ISprite* s; public: BeginScene(){ image_t a = GetVideo().loadImage(L"picture.png"); s = Sprite_create(a); getRenderScene()->addChild(s); s->setCenterX(0.5f); s->setCenterY(0.5f); } void update(){ if(s){ s->setRotation(s->getRotation() + 1.0f); s->setScaleX(s->getScaleX() + 0.01f); if(GetControl().keyIsDown(OIK_RIGHT)) s->setX(s->getX() + 10.0f); if(GetControl().keyIsDown(OIK_LEFT)) s->setX(s->getX() - 10.0f); if(GetControl().keyIsDown(OIK_UP)) s->setY(s->getY() - 10.0f); if(GetControl().keyIsDown(OIK_DOWN)) s->setY(s->getY() + 10.0f); } } }; extern "C" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, ::LPSTR lpCmdLine, int nShowCmd){ Game_build(Game_create); IGame* game = GetGame(); game->init(L"example", 800, 600, true); game->replaceScene(ONEU_NEW(BeginScene)); return game->run(); }
[ "[email protected]@d30a3831-f586-b1a3-add9-2db6dc386f9c" ]
[ [ [ 1, 49 ] ] ]
5f82a30102bf65a91e51c6e0b29edc6b95183233
cf538d1073bb1b9a2449e9e1996f58e74f09fe4b
/fwk4gps 2011/fwk4gps 2011/Coordinator.cpp
c789e499473da25e2ef3aa04f85dfc2fae760e69
[]
no_license
ScottDowne/Mesocricetus
5067527dd20c7327591f086e9d0947b03e0818e4
c5360965eda35ec9bb7384717714c232bbd7048f
refs/heads/master
2016-09-10T22:35:44.128648
2011-12-15T19:12:39
2011-12-15T19:12:39
2,526,188
0
1
null
null
null
null
UTF-8
C++
false
false
15,280
cpp
/* Coordinator Implementation - Model Branch * * Coordinator.cpp * fwk4gps version 2.0 * gam666/dps901 * October 4 2011 * copyright (c) 2011 Chris Szalwinski * distributed under TPL - see ../Licenses.txt */ #include "iContext.h" // for the Context Interface #include "iUtilities.h" // for error() #include "Coordinator.h" // for the Coordinator class definition #include "Object.h" // for Object::isCoordinatedBy #include "Texture.h" // for Texture::isCoordinatedBy #include "Light.h" // for Light::isCoordinatedBy #include "Camera.h" // for Camera::isCoordinatedBy #include "Sound.h" // for Sound::isCoordinatedBy #include "Graphic.h" // for Graphic::isCoordinatedBy #include "Text.h" // for Text::isCoordinatedBy #include "ModelSettings.h" // for coordinator macros #include "MathDefinitions.h" // for frustum //-------------------------------- Coordinator -------------------------------------- // // The Coordinator object manages the objects, textures, lights, sounds, vertex // lists, and cameras in the model // // CreateCoordinator creates the Coordinator Object // iCoordinator* CreateCoordinator(iContext* c) { return new Coordinator(c); } // constructor initializes the object and texture pointers, the reference // time and attaches the Coordinator class to the Object and Texture classes // Coordinator::Coordinator(iContext* c) : context(c) { // manages the objects, textures, lights, cameras, sounds Object::isCoordinatedBy(this); Texture::isCoordinatedBy(this); Light::isCoordinatedBy(this); Camera::isCoordinatedBy(this); Sound::isCoordinatedBy(this); Graphic::isCoordinatedBy(this); Text::isCoordinatedBy(this); // coordinator timers lastCameraToggle = 0; lastHUDToggle = 0; lastUpdate = 0; lastReset = 0; framecount = 0; fps = 0; // current camera current = 0; // volume and frequency settings freq = DEFAULT_FREQUENCY; maxVolume = context->get(GF_AU_MXVL); minVolume = context->get(GF_AU_MNVL); incVolume = STEP_VOLUME; curVolume = context->get(GF_AU_CVOL); lastVolumeChange = 0; // HUD size and position on = true; hudPosX = HUD_X; hudPosY = HUD_Y; validate(); } // validate keeps the HUD within the client area // void Coordinator::validate() { if (hudPosX < TL_MIN) hudPosX = TL_MIN; else if (hudPosX + HUD_W > TL_MAX) hudPosX = TL_MAX - HUD_W; if (hudPosY < TL_MIN) hudPosY = TL_MIN; else if (hudPosY + HUD_H > TL_MAX) hudPosY = TL_MAX - HUD_H; } // add adds a pointer to Object *o to the coordinator // bool Coordinator::add(const iObject* o) { unsigned i; bool rc = false; for (i = 0; i < object.size() && !rc; i++) if (!object[i]) { object[i] = (iObject*)o; rc = true; } if (!rc) object.push_back((iObject*)o); return true; } // add adds a pointer to iTexture *t to the coordinator // bool Coordinator::add(const iTexture* t) { unsigned i; bool rc = false; for (i = 0; i < texture.size() && !rc; i++) if (!texture[i]) { texture[i] = (iTexture*)t; rc = true; } if (!rc) texture.push_back((iTexture*)t); return true; } // add adds a pointer to Light *l to the coordinator // bool Coordinator::add(const iLight* l) { unsigned i; bool rc = false; for (i = 0; i < light.size() && !rc; i++) if (!light[i]) { light[i] = (iLight*)l; rc = true; } if (!rc) light.push_back((iLight*)l); return true; } // add adds a pointer to Camera *c to the coordinator // bool Coordinator::add(const iCamera* c) { unsigned i; bool rc = false; for (i = 0; i < camera.size() && !rc; i++) if (!camera[i]) { camera[i] = (iCamera*)c; rc = true; } if (!rc) camera.push_back((iCamera*)c); return true; } // add adds a pointer to Sound *s to the coordinator // bool Coordinator::add(const iSound* s) { unsigned i; bool rc = false; for (i = 0; i < sound.size() && !rc; i++) if (!sound[i]) { sound[i] = (iSound*)s; rc = true; } if (!rc) sound.push_back((iSound*)s); return true; } // add adds a pointer to graphic *v to the coordinator // bool Coordinator::add(const iGraphic* g) { unsigned i; bool rc = false; for (i = 0; i < graphic.size() && !rc; i++) if (!graphic[i]) { graphic[i] = (iGraphic*)g; rc = true; } if (!rc) graphic.push_back((iGraphic*)g); return true; } // add adds a pointer to Text *t to the coordinator // bool Coordinator::add(const iText* t) { unsigned i; bool rc = false; for (i = 0; i < text.size() && !rc; i++) if (!text[i]) { text[i] = (iText*)t; rc = true; } if (!rc) text.push_back((iText*)t); return true; } // reset resets the coordinator timers // void Coordinator::reset(int now) { framecount = 0; fps = 0; lastReset = now; lastUpdate = now; lastCameraToggle = now; lastHUDToggle = now; } // attenuate attenuates the volume of the ambient sounds by factor * // incVolume - positive factor increases the volume, negative factor // decreases the volume // void Coordinator::attenuate(int factor) { curVolume = curVolume + (factor * incVolume); if (curVolume > maxVolume) curVolume = maxVolume; else if (curVolume < minVolume) curVolume = minVolume; context->set(GF_AU_CVOL, curVolume); } // update updates the Light, Camera, and Sound objects // void Coordinator::update(int now) { int delta = now - lastUpdate; // update the framecount/frame rate if (now - lastReset <= UNITS_PER_SEC) framecount++; else { // recalculate the frame rate fps = (framecount * UNITS_PER_SEC) / (now - lastReset); framecount = 0; lastReset = now; } // toggle and update the current camera if (context->pressed(CAMERA_SELECT) && now - lastCameraToggle > KEY_LATENCY) { lastCameraToggle = now; current++; if (current == camera.size()) current = 0; } if (camera[current]) camera[current]->update(delta); // toggle and update the sounds // update the volume and the frequency long dz = 0; int iy = context->get(GF_CT_POSY); if (iy) dz = (long)(iy * CTR_DISPLACEMENT_FACTOR); if (now - lastVolumeChange > KEY_LATENCY) { if (context->pressed(AUD_VOLUME_DEC)) attenuate(-(now - lastVolumeChange)); if (context->pressed(AUD_VOLUME_INC)) attenuate(now - lastVolumeChange); lastVolumeChange = now; // drop frequency if AUD_SLOW_DOWN if (context->pressed(AUD_SLOW_DOWN)) { int newfreq = freq - STEP_FREQUENCY; freq = newfreq < MIN_FREQUENCY ? MIN_FREQUENCY : newfreq; context->set(GF_AU_FREQ, freq); } // increase frequency if AUD_SPEED_UP else if (context->pressed(AUD_SPEED_UP)) { int newfreq = freq + STEP_FREQUENCY; freq = newfreq < MAX_FREQUENCY ? MAX_FREQUENCY : newfreq; context->set(GF_AU_FREQ, freq); } } // toggle and update the sound sources for (unsigned i = 0; i < sound.size(); i++) if (sound[i]) sound[i]->update(); // toggle and update the light sources for (unsigned i = 0; i < light.size(); i++) if (light[i]) light[i]->update(); // toggle and update the heads up display if (context->pressed(HUD_DISPLAY) && now - lastHUDToggle > KEY_LATENCY) { lastHUDToggle = now; on = !on; } // update the HUD only if it is on if (on) { // translate the HUD int dx = 0, dy = 0; if (context->pressed(HUD_RIGHT)) dx += delta; if (context->pressed(HUD_LEFT)) dx -= delta; if (context->pressed(HUD_UP)) dy -= delta; if (context->pressed(HUD_DOWN)) dy += delta; hudPosX += dx * HUD_SPEED; hudPosY += dy * HUD_SPEED; validate(); } // update the reference time lastUpdate = now; } // render draws the coordinator elements for the specified Category // void Coordinator::render(Category category) { Frustum frustum(::view(context->get(GF_CA_POSN), context->get(GF_CA_POSN) + context->get(GF_CA_HEAD), context->get(GF_CA_UP)), ::projection(context->get(GF_FR_FOV), context->get(GF_FR_ASP), context->get(GF_FR_NEAR), context->get(GF_FR_FAR))); switch (category) { case ALL_OBJECTS: // draw all objects for (unsigned i = 0; i < object.size(); i++) { if (object[i]) object[i]->draw(); } break; case SOUND: for (unsigned i = 0; i < sound.size(); i++) if (sound[i]) sound[i]->implement(lastUpdate); break; case TRANSLUCENT_OBJECT: case OPAQUE_OBJECT: for (unsigned i = 0; i < object.size(); i++) { if (object[i] && object[i]->belongsTo(category) && frustum.sphereInside(object[i]->position(), object[i]->getRadius())) { object[i]->draw(); } } break; default: for (unsigned i = 0; i < object.size(); i++) { if (object[i] && object[i]->belongsTo(category)) object[i]->draw(); } } } // suspend suspends the textures, lights, sounds, primitive sets, and text // items in the coordinator // void Coordinator::suspend() const { for (unsigned i = 0; i < texture.size(); i++) if (texture[i]) texture[i]->suspend(); for (unsigned i = 0; i < light.size(); i++) if (light[i]) light[i]->suspend(); for (unsigned i = 0; i < sound.size(); i++) if (sound[i]) sound[i]->suspend(); for (unsigned i = 0; i < graphic.size(); i++) if (graphic[i]) graphic[i]->suspend(); for (unsigned i = 0; i < text.size(); i++) if (text[i]) text[i]->suspend(); } // restore restores each light, sound, and text item and initializes // the coordinator timers // void Coordinator::restore(int now) { for (unsigned i = 0; i < light.size(); i++) if (light[i]) light[i]->restore(now); for (unsigned i = 0; i < sound.size(); i++) { if (sound[i]) sound[i]->restore(now); } for (unsigned i = 0; i < text.size(); i++) if (text[i]) text[i]->restore(); framecount = 0; lastReset = now; lastUpdate = now; lastCameraToggle = now; lastHUDToggle = now; } // release releases the textures, vertex lists, and text items in the // coordinator // void Coordinator::release() const { for (unsigned i = 0; i < texture.size(); i++) if (texture[i]) texture[i]->release(); for (unsigned i = 0; i < graphic.size(); i++) if (graphic[i]) graphic[i]->release(); for (unsigned i = 0; i < text.size(); i++) if (text[i]) text[i]->release(); } // remove removes the pointer to iObject *o from the coordinator // bool Coordinator::remove(const iObject* o) { bool rc = false; for (unsigned i = 0; i < object.size(); i++) if (object[i] == o) { object[i] = 0; rc = true; } while (object.size() && !object[object.size() - 1]) object.pop_back(); return rc; } // remove removes the pointer to iTexture *t from the coordinator // bool Coordinator::remove(const iTexture* t) { bool rc = false; for (unsigned i = 0; i < texture.size(); i++) if (texture[i] == t) { texture[i] = 0; rc = true; } while (texture.size() && !texture[texture.size() - 1]) texture.pop_back(); return rc; } // remove removes the pointer to iLight *l from the coordinator // bool Coordinator::remove(const iLight* l) { bool rc = false; for (unsigned i = 0; i < light.size(); i++) if (light[i] == l) { light[i] = 0; rc = true; } while (light.size() && !light[light.size() - 1]) light.pop_back(); return rc; } // remove removes the pointer to iCamera *l from the coordinator // bool Coordinator::remove(const iCamera* c) { bool rc = false; for (unsigned i = 0; i < camera.size(); i++) if (camera[i] == c) { camera[i] = 0; rc = true; } while (camera.size() && !camera[camera.size() - 1]) camera.pop_back(); return rc; } // remove removes the pointer to iSound *s from the coordinator // bool Coordinator::remove(const iSound* s) { bool rc = false; for (unsigned i = 0; i < sound.size(); i++) if (sound[i] == s) { sound[i] = 0; rc = true; } while (sound.size() && !sound[sound.size() - 1]) sound.pop_back(); return rc; } // remove removes the pointer to iGraphic *v from the coordinator // bool Coordinator::remove(const iGraphic* g) { bool rc = false; for (unsigned i = 0; i < graphic.size(); i++) if (graphic[i] == g) { graphic[i] = 0; rc = true; } while (graphic.size() && !graphic[graphic.size() - 1]) graphic.pop_back(); return rc; } // remove removes the pointer to iText *t from the coordinator // bool Coordinator::remove(const iText* t) { bool rc = false; for (unsigned i = 0; i < text.size(); i++) if (text[i] == t) { text[i] = 0; rc = true; } while (text.size() && !text[text.size() - 1]) text.pop_back(); return rc; } // destructor deletes all of the coordinator elements // Coordinator::~Coordinator() { for (unsigned i = 0; i < object.size(); i++) if (object[i]) object[i]->Delete(); for (unsigned i = 0; i < texture.size(); i++) if (texture[i]) texture[i]->Delete(); for (unsigned i = 0; i < light.size(); i++) if (light[i]) light[i]->Delete(); for (unsigned i = 0; i < camera.size(); i++) if (camera[i]) camera[i]->Delete(); for (unsigned i = 0; i < sound.size(); i++) if (sound[i]) sound[i]->Delete(); for (unsigned i = 0; i < graphic.size(); i++) if (graphic[i]) graphic[i]->Delete(); for (unsigned i = 0; i < text.size(); i++) if (text[i]) text[i]->Delete(); }
[ [ [ 1, 576 ] ] ]
ad2084fbc61a2cffedabcbec2e548c7abebbf9f3
e19b72560f44dd99124b49f8437d04e7408c26ac
/VL Feat - Sift/class_descripteur.h
05ed3331b2139f68a21554647cf45e35b31da1d6
[]
no_license
jbfiot/rangers
d5a588da14e188e0f605758e93c6aaf4616cf4f3
15b88a73e39708e68c6224f9809cd2966f9dbe26
refs/heads/master
2021-01-17T05:25:35.494251
2009-03-20T10:09:26
2009-03-20T10:09:26
38,111,954
0
0
null
null
null
null
UTF-8
C++
false
false
771
h
extern "C" { #include "sift.h" } #pragma once #ifndef _CLASS_DESCRIPTEUR #define _CLASS_DESCRIPTEUR #include <vector> using namespace std; class rangers_descripteur { public: //constructeur par default rangers_descripteur(); //Destructeur ~rangers_descripteur(){}; //constructeur rangers_descripteur(double _R_orientation,vl_sift_pix _R_descripteur[128],VlSiftKeypoint _R_keypoint); // Get orientation double rangers_getorientation(); //Get Keypoints; VlSiftKeypoint rangers_getkeypoint(); //Get descripteur vl_sift_pix * rangers_getdescripteur(); private: double R_orientation; vl_sift_pix R_descripteur[128]; VlSiftKeypoint R_keypoint; }; typedef vector<rangers_descripteur> tableau_descripteur; #endif
[ [ [ 1, 41 ] ] ]
0d8849716c2dab0b7b29490d56d701fb7061df9b
5d35825d03fbfe9885316ec7d757b7bcb8a6a975
/src/EditBox.cpp
180d2e20fad53abda0ba07a1fd1e8f869b6479ad
[]
no_license
jjzhang166/3D-Landscape-linux
ce887d290b72ebcc23386782dd30bdd198db93ef
4f87eab887750e3dc5edcb524b9e1ad99977bd94
refs/heads/master
2023-03-15T05:24:40.303445
2010-03-25T00:23:43
2010-03-25T00:23:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,891
cpp
#include "EditBox.h" EditBox::EditBox(int x, int y, int width, int height, int layout, QString title) { this->x = x; this->y = y; this->width = width; this->height = height; this->layout = layout; this->spacing = 5; this->title = title; this->title_size = (int)(this->height * 0.2); this->titleTextR.setX(this->x + this->spacing); this->titleTextR.setY(this->y + this->spacing); this->titleTextR.setWidth(this->width - this->spacing*2); this->titleTextR.setHeight(this->title_size - this->spacing*2); } //items QList should be populated beforehand void EditBox::initialize() { int currX = this->x + this->spacing; int currY = this->y + this->spacing + this->title_size; int itemHeight = 0; int itemWidth = 0; int itemSpacing = 0; if(!layout) { //itemHeight = (this->height - this->title_size - this->spacing - // (this->items.size() * this->spacing)) / this->items.size(); itemHeight = (this->height - this->title_size - this->spacing - (this->items.size() * this->spacing)) / this->items.size(); //currX += (this->width/2) - (itemSize/2); if(this->items.size() > 1) itemSpacing = (this->height - this->title_size - this->spacing*2 - (itemHeight * this->items.size())) / (this->items.size() - 1); else itemSpacing = this->spacing; } else { //itemWidth = (this->width - this->spacing - // (this->items.size() * this->spacing)) / this->items.size(); itemWidth = (this->width - this->spacing - (this->items.size() * this->spacing)) / this->items.size(); if(this->items.size() > 1) itemSpacing = (this->width - this->spacing*2 - (itemWidth * this->items.size())) / (this->items.size() - 1); else itemSpacing = this->spacing; //currY += (this->height/2) - (itemSize/2) + this->title_size; } for(int i = 0; i < this->items.size(); i++) { if(layout) { this->items[i]->width = itemWidth; this->items[i]->height = this->height - this->spacing*2; this->items[i]->x = currX; this->items[i]->y = currY; currX += this->items[i]->width + itemSpacing; } else { this->items[i]->height = itemHeight; this->items[i]->width = this->width - this->spacing*2; this->items[i]->x = currX; this->items[i]->y = currY; currY += this->items[i]->height + itemSpacing; } this->items[i]->calculateInnerPositions(); } } void EditBox::render(QPainter *painter) { QBrush brush(QColor(255, 255, 255, 200)); painter->setBrush(brush); painter->setPen(QPen(QColor(0, 0, 0, 200))); painter->drawRoundedRect(this->x, this->y, this->width, this->height, 5, 5); QFont titleFont("Arial"); titleFont.setPixelSize(this->titleTextR.height()); QFontMetrics fm(titleFont); int textWidthInPixels = fm.width(this->title); if ( textWidthInPixels > (this->titleTextR.width())) { titleFont.setStretch ((100 * this->titleTextR.width()) / textWidthInPixels) ; } painter->setFont(titleFont); painter->drawText(this->titleTextR, Qt::AlignCenter, this->title); for(int i = 0; i < this->items.size(); i++) { this->items[i]->render(painter); } } void EditBox::resize(int x, int y, int width, int height) { this->x = x; this->y = y; this->width = width; this->height = height; this->title_size = (int)(this->height * 0.2); this->titleTextR.setX(this->x + this->spacing); this->titleTextR.setY(this->y + this->spacing); this->titleTextR.setWidth(this->width - this->spacing*2); this->titleTextR.setHeight(this->title_size - this->spacing*2); this->initialize(); } void EditBox::processKeyEvent(QKeyEvent *e) { for(int i = 0; i < this->items.size(); i++) { if(this->items[i]->hasFocus) { this->items[i]->processKeyEvent(e); break; } } } void EditBox::processMouseEvent(QMouseEvent *e) { for(int i = 0; i < this->items.size(); i++) { if(this->items[i]->isInside(e->x(), e->y())) { this->items[i]->hasFocus = true; } else { this->items[i]->hasFocus = false; } } } EditBox::~EditBox() { for(int i = 0; i < this->items.size(); i++) { delete this->items[i]; } }
[ [ [ 1, 175 ] ] ]
db736ee316e6c120404771533e8e02916070e0f8
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-network/src/jingxian/networks/ThreadDNSResolver.h
5d4987a25f89e405ebcf41500ffc129f93fc9ff9
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
956
h
#ifndef _ThreadDNSResolver_H_ #define _ThreadDNSResolver_H_ #include "jingxian/config.h" #if !defined (JINGXIAN_LACKS_PRAGMA_ONCE) # pragma once #endif /* JINGXIAN_LACKS_PRAGMA_ONCE */ // Include files # include "jingxian/string/string.h" # include "jingxian/IDNSResolver.h" # include "jingxian/IReactorCore.h" _jingxian_begin class ThreadDNSResolver : public IDNSResolver { public: ThreadDNSResolver(); void initialize(IReactorCore* core); virtual ~ThreadDNSResolver(void); virtual void ResolveHostByName(const tchar* name , const tchar* port , void* context , ResolveComplete callback , ResolveError onError , int timeout); private: IReactorCore* core_; }; _jingxian_end #endif //_ThreadDNSResolver_H_
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 40 ] ] ]
b0420f7d5f9e6e8ace47ddf7cee6488180510113
3c24ee15aa8c09dea6f44cd7b2ff5b9502613ef5
/stdafx.h
0ae97f4e003cd700fc2964542926dae9fa3d78a0
[]
no_license
liyuan-rey/AniToolbox
b91be78362e6eabf5bdd496f9c302c64074630c4
a07325539f02401b78fd73a0c72653b7bfdbe799
refs/heads/master
2021-09-01T20:19:25.729965
2009-05-12T06:45:25
2009-05-12T06:45:25
114,905,807
0
0
null
null
null
null
GB18030
C++
false
false
1,926
h
// stdafx.h : 标准系统包含文件的包含文件, // 或是常用但不常更改的项目特定的包含文件 // #pragma once #ifndef STRICT #define STRICT #endif // 如果您必须使用下列所指定的平台之前的平台,则修改下面的定义。 // 有关不同平台的相应值的最新信息,请参考 MSDN。 #ifndef WINVER // 允许使用特定于 Windows 95 和 Windows NT 4 或更高版本的功能。 #define WINVER 0x0400 // 将此更改为针对于 Windows 98 和 Windows 2000 或更高版本的合适的值。 #endif #ifndef _WIN32_WINNT // 允许使用特定于 Windows NT 4 或更高版本的功能。 #define _WIN32_WINNT 0x0400 // 将此更改为针对于 Windows 2000 或更高版本的合适的值。 #endif #ifndef _WIN32_WINDOWS // 允许使用特定于 Windows 98 或更高版本的功能。 #define _WIN32_WINDOWS 0x0410 // 将此更改为针对于 Windows Me 或更高版本的合适的值。 #endif #ifndef _WIN32_IE // 允许使用特定于 IE 4.0 或更高版本的功能。 #define _WIN32_IE 0x0400 // 将此更改为针对于 IE 5.0 或更高版本的合适的值。 #endif #define _ATL_APARTMENT_THREADED #define _ATL_NO_AUTOMATIC_NAMESPACE #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // 某些 CString 构造函数将为显式的 // 关闭 ATL 对某些常被安全忽略的常见警告消息的隐藏 #define _ATL_ALL_WARNINGS #include "resource.h" #include <atlbase.h> #include <atlapp.h> using namespace ATL; #include <comdef.h> #include <atlcom.h> #include <atlwin.h> #include <atlframe.h> #include <atlctrls.h> #include <atldlgs.h> #include <atlddx.h> #include <atlstr.h> #include <strsafe.h> #include <atlconv.h> #include <shlobj.h> #include <atlcoll.h> #include <atlpath.h> #include <atltypes.h> typedef CAtlList<CString> CAtlStringList; #include "AniToolboxModule.h"
[ [ [ 1, 67 ] ] ]
f9d6f4ad0b471df458089d1e85099a030875c1b3
0271b1f1070ef9bbbff89a14e925cd5f26e53a49
/580 Final/Project/Plug-In/VoronoiTmp/VoronoiTmp/VoronoiTmp/vsPerform.cpp
d0606309885072cb860c46eeca371a2f7e55b66c
[]
no_license
satychary/voronoi-shattering-csci-580-final-project
e8ff142089a835bc85164ee4be2a26e9ffdc42e2
4d5d454288ce7d93f52b0ad8e3ea84c19adf697a
refs/heads/master
2020-05-18T00:49:01.443211
2011-12-01T11:34:41
2011-12-01T11:34:41
33,340,435
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
//======================================================= // File: vsPerform.cpp // // Authors: //========================================================= #include "voronoiShatter.h" // Description: // // Arguments: // // Return Value; void VoronoiShatter::perform(){ return; }
[ "[email protected]@4f6fa130-d070-310d-0fd1-0289c6893db4" ]
[ [ [ 1, 16 ] ] ]
a06502cd01d2c653d65387814e52aad1e37fcb34
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SAMPLES/DSHOWFILTERS/mpeg4ip_mp4v2/include/atoms.h
fc0ae187ba415879dd0e595952a134b902d83b5b
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
7,798
h
/* * 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 MPEG4IP. * * The Initial Developer of the Original Code is Cisco Systems Inc. * Portions created by Cisco Systems Inc. are * Copyright (C) Cisco Systems Inc. 2001 - 2005. All Rights Reserved. * * 3GPP features implementation is based on 3GPP's TS26.234-v5.60, * and was contributed by Ximpo Group Ltd. * * Portions created by Ximpo Group Ltd. are * Copyright (C) Ximpo Group Ltd. 2003, 2004. All Rights Reserved. * * Contributor(s): * Dave Mackie [email protected] * Ximpo Group Ltd. [email protected] * Bill May [email protected] */ #ifndef __MP4_ATOMS_INCLUDED__ #define __MP4_ATOMS_INCLUDED__ // declare all the atom subclasses // i.e. spare us atom_xxxx.h for all the atoms // // The majority of atoms just need their own constructor declared // Some atoms have a few special needs // A small minority of atoms need lots of special handling class MP4RootAtom : public MP4Atom { public: MP4RootAtom(); void BeginWrite(bool use64 = false); void Write(); void FinishWrite(bool use64 = false); void BeginOptimalWrite(); void FinishOptimalWrite(); protected: u_int32_t GetLastMdatIndex(); void WriteAtomType(const char* type, bool onlyOne); }; /*********************************************************************** * Common atom classes - standard for anything that just contains atoms * and non-maleable properties, treftype and url ***********************************************************************/ class MP4StandardAtom : public MP4Atom { public: MP4StandardAtom(const char *name); }; class MP4TrefTypeAtom : public MP4Atom { public: MP4TrefTypeAtom(const char* type); void Read(); }; class MP4UrlAtom : public MP4Atom { public: MP4UrlAtom(const char *type="url "); void Read(); void Write(); }; /*********************************************************************** * Sound and Video atoms - use the generic atoms when possible * (MP4SoundAtom and MP4VideoAtom) ***********************************************************************/ class MP4SoundAtom : public MP4Atom { public: MP4SoundAtom(const char *atomid); void Generate(); void Read(); protected: void AddProperties(u_int8_t version); }; class MP4VideoAtom : public MP4Atom { public: MP4VideoAtom(const char *atomid); void Generate(); }; class MP4AmrAtom : public MP4Atom { public: MP4AmrAtom(const char *type); void Generate(); }; // H.264 atoms class MP4Avc1Atom : public MP4Atom { public: MP4Avc1Atom(); void Generate(); }; class MP4AvcCAtom : public MP4Atom { public: MP4AvcCAtom(); void Generate(); }; class MP4D263Atom : public MP4Atom { public: MP4D263Atom(); void Generate(); void Write(); }; class MP4DamrAtom : public MP4Atom { public: MP4DamrAtom(); void Generate(); }; class MP4EncaAtom : public MP4Atom { public: MP4EncaAtom(); void Generate(); }; class MP4EncvAtom : public MP4Atom { public: MP4EncvAtom(); void Generate(); }; class MP4Mp4aAtom : public MP4Atom { public: MP4Mp4aAtom(); void Generate(); }; class MP4Mp4sAtom : public MP4Atom { public: MP4Mp4sAtom(); void Generate(); }; class MP4Mp4vAtom : public MP4Atom { public: MP4Mp4vAtom(); void Generate(); }; class MP4S263Atom : public MP4Atom { public: MP4S263Atom(); void Generate(); }; /************************************************************************ * Specialized Atoms ************************************************************************/ class MP4DataAtom : public MP4Atom { public: MP4DataAtom(); void Read(); }; class MP4DrefAtom : public MP4Atom { public: MP4DrefAtom(); void Read(); }; class MP4ElstAtom : public MP4Atom { public: MP4ElstAtom(); void Generate(); void Read(); protected: void AddProperties(u_int8_t version); }; class MP4FreeAtom : public MP4Atom { public: MP4FreeAtom(); void Read(); void Write(); }; class MP4FtypAtom : public MP4Atom { public: MP4FtypAtom(); void Generate(); void Read(); }; class MP4HdlrAtom : public MP4Atom { public: MP4HdlrAtom(); void Read(); }; class MP4HinfAtom : public MP4Atom { public: MP4HinfAtom(); void Generate(); }; class MP4HntiAtom : public MP4Atom { public: MP4HntiAtom(); void Read(); }; class MP4MdatAtom : public MP4Atom { public: MP4MdatAtom(); void Read(); void Write(); }; class MP4MdhdAtom : public MP4Atom { public: MP4MdhdAtom(); void Generate(); void Read(); protected: void AddProperties(u_int8_t version); }; class MP4Meta1Atom : public MP4Atom { public: MP4Meta1Atom(const char *name); void Read(); }; class MP4Meta2Atom : public MP4Atom { public: MP4Meta2Atom(const char *name); void Read(); }; class MP4MvhdAtom : public MP4Atom { public: MP4MvhdAtom(); void Generate(); void Read(); protected: void AddProperties(u_int8_t version); }; class MP4OhdrAtom : public MP4Atom { public: MP4OhdrAtom(); ~MP4OhdrAtom(); void Read(); }; class MP4RtpAtom : public MP4Atom { public: MP4RtpAtom(); void Generate(); void Read(); void Write(); protected: void AddPropertiesStsdType(); void AddPropertiesHntiType(); void GenerateStsdType(); void GenerateHntiType(); void ReadStsdType(); void ReadHntiType(); void WriteHntiType(); }; class MP4SdpAtom : public MP4Atom { public: MP4SdpAtom(); void Read(); void Write(); }; class MP4SmiAtom : public MP4Atom { public: MP4SmiAtom(void); void Read(); }; class MP4StblAtom : public MP4Atom { public: MP4StblAtom(); void Generate(); }; class MP4StdpAtom : public MP4Atom { public: MP4StdpAtom(); void Read(); }; class MP4StscAtom : public MP4Atom { public: MP4StscAtom(); void Read(); }; class MP4StsdAtom : public MP4Atom { public: MP4StsdAtom(); void Read(); }; class MP4StszAtom : public MP4Atom { public: MP4StszAtom(); void Read(); void Write(); }; class MP4TfhdAtom : public MP4Atom { public: MP4TfhdAtom(); void Read(); protected: void AddProperties(u_int32_t flags); }; class MP4TkhdAtom : public MP4Atom { public: MP4TkhdAtom(); void Generate(); void Read(); protected: void AddProperties(u_int8_t version); }; class MP4TrunAtom : public MP4Atom { public: MP4TrunAtom(); void Read(); protected: void AddProperties(u_int32_t flags); }; class MP4UdtaAtom : public MP4Atom { public: MP4UdtaAtom(); void Read(); }; class MP4UrnAtom : public MP4Atom { public: MP4UrnAtom(); void Read(); }; class MP4VmhdAtom : public MP4Atom { public: MP4VmhdAtom(); void Generate(); }; class MP4HrefAtom : public MP4Atom { public: MP4HrefAtom(); void Generate(void); }; #endif /* __MP4_ATOMS_INCLUDED__ */
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 383 ] ] ]
2dd95e3b24f242988c96a34a9cb7b3ee16382805
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/graph/test/make_maximal_planar_test.cpp
fdd4b7e1dc95b7e7abda20d36d852797a0263953
[ "Artistic-2.0", "LicenseRef-scancode-public-domain", "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,644
cpp
//======================================================================= // Copyright 2007 Aaron Windsor // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <boost/graph/adjacency_list.hpp> #include <boost/graph/properties.hpp> #include <boost/graph/make_maximal_planar.hpp> #include <boost/graph/boyer_myrvold_planar_test.hpp> #include <boost/property_map/property_map.hpp> #include <boost/property_map/vector_property_map.hpp> #include <boost/test/minimal.hpp> using namespace boost; template <typename Graph> void reset_edge_index(Graph& g) { typename property_map<Graph, edge_index_t>::type index = get(edge_index, g); typename graph_traits<Graph>::edge_iterator ei, ei_end; typename graph_traits<Graph>::edges_size_type cnt = 0; for(tie(ei,ei_end) = edges(g); ei != ei_end; ++ei) put(index, *ei, cnt++); } template <typename Graph> void make_cycle(Graph& g, int size) { typedef typename graph_traits<Graph>::vertex_descriptor vertex_t; vertex_t first_vertex = add_vertex(g); vertex_t prev_vertex = first_vertex; for(int i = 1; i < size; ++i) { vertex_t curr_vertex = add_vertex(g); add_edge(curr_vertex, prev_vertex, g); prev_vertex = curr_vertex; } add_edge(first_vertex, prev_vertex, g); } struct UpdateVertexIndex { template <typename Graph> void update(Graph& g) { typename property_map<Graph, vertex_index_t>::type index = get(vertex_index, g); typename graph_traits<Graph>::vertex_iterator vi, vi_end; typename graph_traits<Graph>::vertices_size_type cnt = 0; for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi) put(index, *vi, cnt++); } }; struct NoVertexIndexUpdater { template <typename Graph> void update(Graph& g) {} }; template <typename Graph, typename VertexIndexUpdater> void test_cycle(VertexIndexUpdater vertex_index_updater, int size) { Graph g; make_cycle(g, size); vertex_index_updater.update(g); reset_edge_index(g); typedef std::vector< typename graph_traits<Graph>::edge_descriptor > edge_vector_t; typedef std::vector< edge_vector_t > embedding_storage_t; typedef iterator_property_map < typename embedding_storage_t::iterator, typename property_map<Graph, vertex_index_t>::type > embedding_t; embedding_storage_t embedding_storage(num_vertices(g)); embedding_t embedding(embedding_storage.begin(), get(vertex_index, g)); typename graph_traits<Graph>::vertex_iterator vi, vi_end; for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi) std::copy(out_edges(*vi,g).first, out_edges(*vi,g).second, std::back_inserter(embedding[*vi])); BOOST_CHECK(boyer_myrvold_planarity_test(g)); make_maximal_planar(g, embedding); reset_edge_index(g); // A graph is maximal planar exactly when it's both // planar and has 3 * num_vertices(g) - 6 edges. BOOST_CHECK(num_edges(g) == 3 * num_vertices(g) - 6); BOOST_CHECK(boyer_myrvold_planarity_test(g)); } int test_main(int, char* []) { typedef adjacency_list <vecS, vecS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > VVgraph_t; typedef adjacency_list <vecS, listS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > VLgraph_t; typedef adjacency_list <listS, vecS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > LVgraph_t; typedef adjacency_list <listS, listS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > LLgraph_t; typedef adjacency_list <setS, setS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > SSgraph_t; test_cycle<VVgraph_t>(NoVertexIndexUpdater(), 10); test_cycle<VVgraph_t>(NoVertexIndexUpdater(), 50); test_cycle<VLgraph_t>(UpdateVertexIndex(), 3); test_cycle<VLgraph_t>(UpdateVertexIndex(), 30); test_cycle<LVgraph_t>(NoVertexIndexUpdater(), 15); test_cycle<LVgraph_t>(NoVertexIndexUpdater(), 45); test_cycle<LLgraph_t>(UpdateVertexIndex(), 8); test_cycle<LLgraph_t>(UpdateVertexIndex(), 19); test_cycle<SSgraph_t>(UpdateVertexIndex(), 13); test_cycle<SSgraph_t>(UpdateVertexIndex(), 20); return 0; }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 173 ] ] ]
f602042884d9d748f6d66de9d18e334dbf16f95e
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/CERTIFIER/inputinternaladdrdlg.h
712f99b10780bdcc0bc8f806271b9c8c4e7447b6
[]
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
UTF-8
C++
false
false
1,370
h
#if !defined(AFX_INPUTINTERNALADDRDLG_H__5FA28345_63E9_4288_83B3_A1CA217C17C8__INCLUDED_) #define AFX_INPUTINTERNALADDRDLG_H__5FA28345_63E9_4288_83B3_A1CA217C17C8__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // inputinternaladdrdlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CInputInternalAddrDlg dialog class CInputInternalAddrDlg : public CDialog { // Construction public: CInputInternalAddrDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CInputInternalAddrDlg) enum { IDD = IDD_DIALOG_INTERNAL_IP }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CInputInternalAddrDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CInputInternalAddrDlg) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_INPUTINTERNALADDRDLG_H__5FA28345_63E9_4288_83B3_A1CA217C17C8__INCLUDED_)
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 46 ] ] ]
8b39557cbc9ce8b3fa00f59c42e9d7326340c77a
a02276848c2bea89526819874c016ff17fc36104
/Mth/Helper.h
6256e483938b25a7563e461ab6548cf724b30a80
[]
no_license
AnupGupta/geometrywarsreloaded
ec85ddc07ffd687d5d53c1c9abd4138f7ffcc141
f6a615c05423c66433e8a85d3497e8386b618d0d
refs/heads/master
2016-09-01T11:12:37.197796
2008-06-04T14:17:44
2008-06-04T14:17:44
44,064,867
0
0
null
null
null
null
UTF-8
C++
false
false
968
h
/********************************************** * Namespace: mth * Classes: Helper * Desc: Various helper functions and constants * Author: Vaios Kalpias-Ilias (C) 2008-2009 ***********************************************/ #ifndef HELPER_H #define HELPER_H #include <stdlib.h> #include "Vector.h" namespace mth { const float M_PI = 3.14159265358979323846f; const float M_PI_2 = 6.28318530717958647692f; const float TO_DEG = 57.2957795f; const float TO_RAD = 0.0174532925f; const float INFINITY = 999999999999999999999.0f; class Helper { public: // limits an angle between minV and maxV static float ClampAngle(float radians, float minV, float maxV) ; // returns random number between -1 and 1 static float RandomBinomial(); // returns a float as a vector2 static Vector2 AsVector(float value); private: Helper(); ~Helper(); }; } #endif // end of namespace mth
[ "vkalpias@ff6a4cd7-4e4d-0410-b3e6-9b514b4d81ca" ]
[ [ [ 1, 47 ] ] ]
db1d9904cdd891389e8320821848d17ddc3522b4
6a1a184ceb7be1f73c490fcbaf8fba7a64cab1ff
/Source/TestFluidic/TestScene3D.cpp
d93e9abd6b9e465c5131e8e05574f382e47e1390
[ "MIT" ]
permissive
alexsaen/fluidic
c8aa913ce03e8d3d9bc8091a31aa96a7d1e5b4ad
bf7eb0f3e9ca4e15f53623020c7f0313315f4e49
refs/heads/master
2020-12-24T15:14:17.261742
2010-04-06T13:10:54
2010-04-06T13:10:54
32,979,664
1
0
null
null
null
null
UTF-8
C++
false
false
9,033
cpp
/* Copyright (c) 2010 Steven Leigh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "TestScene3D.h" #include <iostream> #include <GL/glut.h> using namespace std; using namespace Fluidic; using namespace TestFluidic; TestScene3D::TestScene3D() : moving(false), injectZPos(0.5f) { fluid = new Fluid3D(CG_PROGRAM_DIR); options = Fluid3D::DefaultOptions(); fluid->Init(options); fluid->SetColorDensities(1, 0, -1); obj = new TestObject(options.Size/2, Vector::Zero(), 1); fluid->AttachPoller(obj); //initialise the camera camera.x = 0; camera.y = 0.865; camera.z = 2; camera.yaw = 180; camera.pitch = -30; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, options.RenderResolution.x/options.RenderResolution.y, 0.01, 400.0); glMatrixMode (GL_MODELVIEW); //set up all the depth test and etc. glShadeModel(GL_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); //light information glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 }; GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat light_position[] = { 0.0, 0.0, 10.0, 0.0 }; glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glDepthMask(GL_TRUE); glClearColor(0.0, 0.0, 0.0, 0.0) ; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); } TestScene3D::~TestScene3D() { cgDestroyContext(cgContext); glDisable(GL_BLEND); glDisable(GL_COLOR_MATERIAL); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); } void TestScene3D::Interact() { TestScene::Interact(); if (moving) { //update yaw depending on how much the mouse has moved //in the 'x' direction. keep it between 0 and 360 degrees. camera.yaw -= mouseState.dx/10; if (camera.yaw >= 360) camera.yaw -= 360; if (camera.yaw < 0)camera.yaw += 360; mouseState.dx=0; //update pitch depending on how much the mouse has moved //in the 'x' direction. keep it between 0 and 360 degrees. camera.pitch -= mouseState.dy/10; if (camera.pitch > 60) camera.pitch=60; if (camera.pitch < -60) camera.pitch = -60; mouseState.dy=0; //move mouse back to center of screen, and reset theMouse variable to suit mouseState.x = options.RenderResolution.xi()/2; mouseState.y = options.RenderResolution.yi()/2; mouseState.dx = 0; mouseState.dy = 0; glutWarpPointer(mouseState.x,mouseState.y); } else { float xPos = (float)mouseState.x / options.RenderResolution.x; float yPos = (float)mouseState.y / options.RenderResolution.y; Vector position(xPos, yPos, injectZPos); position = position * options.Size; float dx = options.Size.x * (float)mouseState.dx / options.RenderResolution.x; float dy = -options.Size.y * (float)mouseState.dy / options.RenderResolution.y; Vector d(dx, dy); bool lmb = ((mouseState.buttons & MB_LEFT) == MB_LEFT); bool mmb = ((mouseState.buttons & MB_MIDDLE) == MB_MIDDLE); bool rmb = ((mouseState.buttons & MB_RIGHT) == MB_RIGHT); bool ctrl = (mouseState.modifiers & GLUT_ACTIVE_CTRL) == GLUT_ACTIVE_CTRL; bool shift = (mouseState.modifiers & GLUT_ACTIVE_SHIFT) == GLUT_ACTIVE_SHIFT; bool noMods = !ctrl && !shift; float size = options.Size.Length(); if (lmb || rmb || mmb) { //dye injection if (lmb && noMods) fluid->Inject(position, 1, 0, 0, 0.05f * size, false); //red if (rmb && noMods) fluid->Inject(position, 0, 1, 0, 0.05f * size, false); //green if (mmb && noMods) fluid->Inject(position, 0, 0, 1, 0.05f * size, false); //blue //fluid perturbation if (lmb && ctrl) fluid->Perturb(position, d*5, 0.025f*size); //normal if (rmb && ctrl) fluid->Perturb(position, d, 0.025*size); //slow if (mmb && ctrl) fluid->Perturb(position, d*20, 0.025*size); //fast // arbitrary boundaries if (lmb && shift) fluid->AddArbitraryBoundary(position, 0.05*size); if (mmb && shift) fluid->AddArbitraryBoundary(position, 0.1*size); if (rmb && shift) fluid->AddArbitraryBoundary(position, 0.2*size); } } } void TestScene3D::HandleKeyboard(unsigned char key, bool down) { TestScene::HandleKeyboard(key, down); switch(key) { case ' ': // toggle mode if (down) { moving = !moving; if (moving) glutSetCursor(GLUT_CURSOR_NONE); else glutSetCursor(GLUT_CURSOR_FULL_CROSSHAIR); } break; case 'a': //strafe left camera.vx = down ? -3 : 0; break; case 'd': //strafe right camera.vx = down ? 3 : 0; break; case 'w': //forward camera.vz = down ? 3 : 0; break; case 's': //back camera.vz = down ? -3 : 0; break; } } void TestScene3D::HandleKeyboardSpecial(int key) { TestScene::HandleKeyboardSpecial(key); if (key == GLUT_KEY_UP) { injectZPos += 0.1; } else if (key == GLUT_KEY_DOWN) { injectZPos -= 0.1; } else if (key == GLUT_KEY_F1) { cout << endl; cout << "Space: Toggle moving/injecting" << endl; cout << " w: Move Forward" << endl; cout << " a: Move Back" << endl; cout << " s: Strafe Left" << endl; cout << " d: Strafe Right" << endl; cout << endl; cout << " Up: Move injection point up" << endl; cout << " Down: Move injection point down" << endl; } } void TestScene3D::Update(float time) { TestScene::Update(time); fluid->Update(time); obj->Update(time); if (moving) { //move the camera forward in the directino we're moving (if we are moving) camera.z += camera.vz * cos(degToRad(camera.yaw))*time; camera.x += camera.vz * sin(degToRad(camera.yaw))*time; camera.y += camera.vz * sin(degToRad(camera.pitch))*time; //move the camera left or right (if we're moving) camera.z += camera.vx * sin(degToRad(camera.yaw))*time; camera.x -= camera.vx * cos(degToRad(camera.yaw))*time; } } void TestScene3D::Display() { glPushMatrix(); glTranslatef(options.Size.x*0.1, options.Size.y*0.4, 0); glScalef(options.Size.x*0.8, options.Size.y*0.2, 0); DrawFluidText(); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); //set up the camera gluLookAt(camera.x, camera.y, camera.z, //position camera.x + sin(degToRad(camera.yaw)), camera.y + sin(degToRad(camera.pitch)),camera.z + cos(degToRad(camera.pitch))*cos(degToRad(camera.yaw)), //direction 0,cos(degToRad(camera.pitch)),0); //roll //draw a sphere glColor3f(0.3, 0.0, 0.3); glTranslatef(0, 0, -3); glutSolidSphere(1, 16, 16); glTranslatef(0, 0, 3); //draw wire cube around fluid glDisable(GL_BLEND); glPushMatrix(); glColor4f(1.0, 1.0, 1.0, 0.0); glTranslatef(-options.Size.x/2, -options.Size.y/2, -options.Size.z/2); glScalef(options.Size.x, options.Size.y, options.Size.z); glTranslatef(0.5,0.5,0.5); glutWireCube(1); glPopMatrix(); glEnable(GL_BLEND); // draw the ball glColor3f(1, 1, 1); glPushMatrix(); glTranslatef(-0.5, -0.5, -0.5); const Vector &objPosition = obj->GetPosition(); glTranslatef(objPosition.x, objPosition.y, objPosition.z); glutSolidSphere(options.Size.Length()/80, 16, 16); glPopMatrix(); //draw the fluid, blending it in with current scene fluid->Render(); glPopMatrix(); } void TestScene3D::Resize(int w, int h) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, options.RenderResolution.x/options.RenderResolution.y, 0.01, 400.0); glMatrixMode (GL_MODELVIEW); TestScene::Resize(w, h); }
[ "xwipeoutx@6c3c8482-2914-11df-ad47-1d73243ccc9f" ]
[ [ [ 1, 301 ] ] ]
9ef2947c00b1affce4ad3a6c538599d1833aceb4
9eb49222299e0e92722b38959272c0489d20fab7
/CopyPathContextMenu.h
2979d53ff7bbd793de166dc260c8411e73c40278
[]
no_license
kerolldev/copypathx
f86a4bc7f89dff294e012a951bcdba0faa52c437
8d76ab1704014fe4e800e69da46ca9bb27971270
refs/heads/master
2021-01-10T19:58:53.262997
2011-10-28T02:35:32
2011-10-28T02:35:32
2,509,231
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,725
h
// CopyPathContextMenu.h : CCopyPathContextMenu の宣言 // [***]VC7.0 IContextMenuのエラーはPlatform SDKのインクルードディレクトリの優先順位を上げる #pragma once #include "resource.h" // メイン シンボル #include <shlguid.h> #include <shlobj.h> #include <comdef.h> #include <list> #include <string> #include <fstream> #include "resource.h" #include "global.h" #include "option.h" #define ID_COPY_PATH 0 #define ID_MENU_1 1 #define ID_MENU_2 2 #define ID_MENU_3 4 #define ID_MENU_4 8 #define ID_MENU_5 16 #define ID_MENU_6 32 #define ID_MENU_7 64 #define ID_MENU_8 128 #define ID_MENU_SEPARATOR 9999 #define TOPCMD_MAX 1 // ICopyPathContextMenu [ object, uuid("D96F8104-CE33-4DA1-BA9E-E38A9F815CAF"), dual, helpstring("ICopyPathContextMenu インターフェイス"), pointer_default(unique) ] __interface ICopyPathContextMenu : IDispatch { }; // CCopyPathContextMenu [ coclass, threading(apartment), vi_progid("CopyPathX.CopyPathContextMenu"), progid("CopyPathX.CopyPathContextMenu.1"), version(1.0), uuid("BE21F5FB-D683-43B1-959B-DB6A83B218CB"), helpstring("CopyPathContextMenu Class") ] class ATL_NO_VTABLE CCopyPathContextMenu : // public ICopyPathContextMenu, // public IContextMenu3, public IContextMenu, public IShellExtInit { public: CCopyPathContextMenu() { m_hbmpCopy = ::LoadBitmap(_AtlBaseModule.GetModuleInstance(), MAKEINTRESOURCE(IDB_COPY)); m_pOption = new COption(_AtlBaseModule.GetModuleInstance()); m_cids = 0; } ~CCopyPathContextMenu() { if(m_hbmpCopy) { ::DeleteObject(m_hbmpCopy); } if(m_pOption) { delete m_pOption; } } /* void writeLog(_TCHAR * msg) { // ファイルを開く std::ofstream fout( "c:/copypathx.log", std::ios::app ); //追記モードで開く // 開けなかった場合は終了 if( fout.fail() ) { return ; } // 出力 fout << msg << std::endl ; // ファイルを閉じる fout.close(); } */ // IContextMenu interface STDMETHOD(QueryContextMenu)(HMENU hmenu, UINT indexMenu, UINT idCmdFirst, UINT idCmdLast, UINT uFlags); STDMETHOD(InvokeCommand)(LPCMINVOKECOMMANDINFO lpici); #if defined(_M_X64) STDMETHOD(GetCommandString)(UINT_PTR idCmd, UINT uType, UINT *pwReserved, LPSTR pszName, UINT cchMax); #else STDMETHOD(GetCommandString)(UINT idCmd, UINT uType, UINT *pwReserved, LPSTR pszName, UINT cchMax); #endif // IContextMenu2 interface //STDMETHOD(HandleMenuMsg)(UINT uMsg, WPARAM wParam, LPARAM lParam); // IContextMenu3 interface //STDMETHOD(HandleMenuMsg2)(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* plResult); // IShellExtInit interface STDMETHOD(Initialize)(LPCITEMIDLIST pidlFolder, LPDATAOBJECT lpdobj, HKEY hkeyProgID); //DECLARE_REGISTRY_RESOURCEID(IDR_COPYPATHX) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CCopyPathContextMenu) //COM_INTERFACE_ENTRY(IContextMenu3) //COM_INTERFACE_ENTRY(IContextMenu2) COM_INTERFACE_ENTRY(IContextMenu) COM_INTERFACE_ENTRY(IShellExtInit) END_COM_MAP() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } private: bool IsDirectryAdd(); int GetOption(_TCHAR * pKeyName, int idef); bool IsPlatformWin32NT(); int GetCtrlStyle(); bool IsMenuIcon(); HRESULT ValidateCommand(UINT_PTR idCmd); private: typedef std::basic_string<_TCHAR> string; std::list<string> m_listFileNames; HBITMAP m_hbmpCopy; COption * m_pOption; UINT m_cids; //void MakePath(LPPATHSETTING lpPathSetting, _TCHAR * pPath, _TCHAR * pTemp); };
[ [ [ 1, 155 ] ] ]
f7177cbd31e284e350e62985fd176077aaf6e30c
b1093f654e78210a00e6ca561c1a8f8f108f543e
/include/Nodemaster.h
06b401d63966fec127b2d539a73167bab6940fa7
[]
no_license
childhood/libAiml
bc82b7cd8859aa6fe0a7a3c42ffe4591438ae329
7954dc347463bcb4ab0070af87b9cbd421b08acc
refs/heads/master
2021-01-18T10:07:02.407246
2010-09-20T04:40:34
2010-09-20T04:40:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
817
h
/** * Nodemaster - The real nodemapper ;-) * * @author Jonathan Roewen */ #ifndef NODEMASTER_H #define NODEMASTER_H #include <map> #include <vector> #include <string> using namespace std; #include "Template.h" class NodeWalker; class Nodemaster { public: Nodemaster() { templates = NULL; } ~Nodemaster() { } Nodemaster *getChild(const string &); void addChild(const string &, Nodemaster *); string getTemplate(bool reload = true); Template *getActualTemplate(); void addTemplate(Template *t); bool hasTemplate(); private: map<char *, Nodemaster *> children; // vector<Template> templates; Template *templates; // Template *templates; // unsigned int lastIndex; friend class NodeWalker; }; typedef map<char *, Nodemaster *> childrenMap; #endif
[ [ [ 1, 44 ] ] ]
870289807510c0f3552723466d51d2b3992f80fe
1fb34766bfe39d7ce1315ad309e938e9f9b5700e
/stdafx.cpp
d0d232c835abc0dc56d80f44788c2a61ab7d94ef
[]
no_license
sebinthomas/Ahab
bc5f5680b4a844f3030ef004a2e5bb91b266d016
ab86e3d826d69fa3a011ccee664f6f0330dd764c
refs/heads/master
2021-01-20T01:57:20.915658
2010-12-27T16:29:14
2010-12-27T16:29:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
// stdafx.cpp : source file that includes just the standard includes // ahab.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ [ [ 1, 8 ] ] ]
f792e1424cb9d279e904223db689fadfe9f1a947
5dc6c87a7e6459ef8e832774faa4b5ae4363da99
/vis_avs/r_videodelay.cpp
9e67a775ff5836fbef2281516a9a2d673745cce6
[]
no_license
aidinabedi/avs4unity
407603d2fc44bc8b075b54cd0a808250582ee077
9b6327db1d092218e96d8907bd14d68b741dcc4d
refs/heads/master
2021-01-20T15:27:32.449282
2010-12-24T03:28:09
2010-12-24T03:28:09
90,773,183
5
2
null
null
null
null
UTF-8
C++
false
false
10,934
cpp
/* LICENSE ------- Copyright 2005 Nullsoft, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nullsoft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" // video delay // copyright tom holden, 2002 // mail: [email protected] #include <windows.h> #include "resource.h" #include "r_defs.h" #ifndef LASER #define MOD_NAME "Trans / Video Delay" #define C_DELAY C_VideoDelayClass class C_DELAY : public C_RBASE { protected: public: // standard ape members C_DELAY(); virtual ~C_DELAY(); virtual int render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h); virtual HWND conf(HINSTANCE hInstance, HWND hwndParent); virtual char *get_desc(); virtual void load_config(unsigned char *data, int len); virtual int save_config(unsigned char *data); // saved members bool enabled; bool usebeats; unsigned int delay; // unsaved members LPVOID buffer; LPVOID inoutpos; unsigned long buffersize; unsigned long virtualbuffersize; unsigned long oldvirtualbuffersize; unsigned long framessincebeat; unsigned long framedelay; unsigned long framemem; unsigned long oldframemem; }; // global configuration dialog pointer static C_DELAY *g_Delay; // global DLL instance pointer static HINSTANCE g_hDllInstance; // configuration screen static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam,LPARAM lParam) { char value[16]; int val; unsigned int objectcode, objectmessage; HWND hwndEdit; switch (uMsg) { case WM_INITDIALOG: //init CheckDlgButton(hwndDlg,IDC_CHECK1,g_Delay->enabled); CheckDlgButton(hwndDlg,IDC_RADIO1,g_Delay->usebeats); CheckDlgButton(hwndDlg,IDC_RADIO2,!g_Delay->usebeats); hwndEdit = GetDlgItem(hwndDlg,IDC_EDIT1); _itoa(g_Delay->delay,value,10); SetWindowText(hwndEdit,value); return 1; case WM_COMMAND: objectcode = LOWORD(wParam); objectmessage = HIWORD(wParam); // see if enable checkbox is checked if (objectcode == IDC_CHECK1) { g_Delay->enabled = IsDlgButtonChecked(hwndDlg,IDC_CHECK1)==1; return 0; } // see if beats radiobox is checked if (objectcode == IDC_RADIO1) { if(IsDlgButtonChecked(hwndDlg,IDC_RADIO1)==1) { g_Delay->usebeats = true; CheckDlgButton(hwndDlg,IDC_RADIO2,BST_UNCHECKED); g_Delay->framedelay = 0; g_Delay->framessincebeat = 0; hwndEdit = GetDlgItem(hwndDlg,IDC_EDIT1); //new if (g_Delay->delay>16) { //new g_Delay->delay = 16; //new SetWindowText(hwndEdit,"16"); //new } //new } else g_Delay->usebeats = false; return 0; } // see if frames radiobox is checked if (objectcode == IDC_RADIO2) { if(IsDlgButtonChecked(hwndDlg,IDC_RADIO2)==1) { g_Delay->usebeats = false; CheckDlgButton(hwndDlg,IDC_RADIO1,BST_UNCHECKED); g_Delay->framedelay = g_Delay->delay; } else g_Delay->usebeats = true; return 0; } //get and put data from the delay box if (objectcode == IDC_EDIT1) { hwndEdit = GetDlgItem(hwndDlg,IDC_EDIT1); if (objectmessage == EN_CHANGE) { GetWindowText(hwndEdit,value,16); val = atoi(value); if (g_Delay->usebeats) {if (val > 16) val = 16;} //new else {if (val > 200) val = 200;} //new g_Delay->delay = val; g_Delay->framedelay = g_Delay->usebeats?0:g_Delay->delay; } else if (objectmessage == EN_KILLFOCUS) { _itoa(g_Delay->delay,value,10); SetWindowText(hwndEdit,value); } return 0; } } return 0; } // set up default configuration C_DELAY::C_DELAY() { // enable enabled = true; usebeats = false; delay = 10; framedelay = 10; framessincebeat = 0; buffersize = 1; virtualbuffersize = 1; oldvirtualbuffersize = 1; buffer = VirtualAlloc(NULL,buffersize,MEM_COMMIT,PAGE_READWRITE); inoutpos = buffer; } // virtual destructor C_DELAY::~C_DELAY() { VirtualFree(buffer,buffersize,MEM_DECOMMIT); } // RENDER FUNCTION: // render should return 0 if it only used framebuffer, or 1 if the new output data is in fbout // w and h are the-width and height of the screen, in pixels. // isBeat is 1 if a beat has been detected. // visdata is in the format of [spectrum:0,wave:1][channel][band]. int C_DELAY::render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h) { if (isBeat&0x80000000) return 0; framemem = w*h*4; if (usebeats) { if (isBeat) { framedelay = framessincebeat*delay; //changed if (framedelay > 400) framedelay = 400; //new framessincebeat = 0; } framessincebeat++; } if (enabled && framedelay!=0) { virtualbuffersize = framedelay*framemem; if (framemem == oldframemem) { if (virtualbuffersize != oldvirtualbuffersize) { if (virtualbuffersize > oldvirtualbuffersize) { if (virtualbuffersize > buffersize) { // allocate new memory if (!VirtualFree(buffer,buffersize,MEM_DECOMMIT)) return 0; if (usebeats) { buffersize = 2*virtualbuffersize; if (buffersize > framemem*400) buffersize = framemem*400; //new buffer = VirtualAlloc(NULL,buffersize,MEM_COMMIT,PAGE_READWRITE); if (buffer == NULL) { buffersize = virtualbuffersize; buffer = VirtualAlloc(NULL,buffersize,MEM_COMMIT,PAGE_READWRITE); } } else { buffersize = virtualbuffersize; buffer = VirtualAlloc(NULL,buffersize,MEM_COMMIT,PAGE_READWRITE); } inoutpos = buffer; if (buffer == NULL) { framedelay = 0; framessincebeat = 0; return 0; } } else { unsigned long size = (((unsigned long)buffer)+oldvirtualbuffersize) - ((unsigned long)inoutpos); unsigned long l = ((unsigned long)buffer)+virtualbuffersize; unsigned long d = l - size; MoveMemory((LPVOID)d, inoutpos, size); for (l = (unsigned long)inoutpos; l < d; l += framemem) CopyMemory((LPVOID)l,(LPVOID)d,framemem); } } else { // virtualbuffersize < oldvirtualbuffersize unsigned long presegsize = ((unsigned long)inoutpos)-((unsigned long)buffer)+framemem; if (presegsize > virtualbuffersize) { MoveMemory(buffer,(LPVOID)(((unsigned long)buffer)+presegsize-virtualbuffersize),virtualbuffersize); inoutpos = (LPVOID)(((unsigned long)buffer)+virtualbuffersize-framemem); } else if (presegsize < virtualbuffersize) MoveMemory((LPVOID)(((unsigned long)inoutpos)+framemem),(LPVOID)(((unsigned long)buffer)+oldvirtualbuffersize+presegsize-virtualbuffersize),virtualbuffersize-presegsize); } oldvirtualbuffersize = virtualbuffersize; } } else { // allocate new memory if (!VirtualFree(buffer,buffersize,MEM_DECOMMIT)) return 0; if (usebeats) { buffersize = 2*virtualbuffersize; buffer = VirtualAlloc(NULL,buffersize,MEM_COMMIT,PAGE_READWRITE); if (buffer == NULL) { buffersize = virtualbuffersize; buffer = VirtualAlloc(NULL,buffersize,MEM_COMMIT,PAGE_READWRITE); } } else { buffersize = virtualbuffersize; buffer = VirtualAlloc(NULL,buffersize,MEM_COMMIT,PAGE_READWRITE); } inoutpos = buffer; if (buffer == NULL) { framedelay = 0; framessincebeat = 0; return 0; } oldvirtualbuffersize = virtualbuffersize; } oldframemem = framemem; CopyMemory(fbout,inoutpos,framemem); CopyMemory(inoutpos,framebuffer,framemem); inoutpos = (LPVOID)(((unsigned long)inoutpos)+framemem); if ((unsigned long)inoutpos>=((unsigned long)buffer)+virtualbuffersize) inoutpos = buffer; return 1; } else return 0; } HWND C_DELAY::conf(HINSTANCE hInstance, HWND hwndParent) // return NULL if no config dialog possible { g_Delay = this; return CreateDialog(hInstance,MAKEINTRESOURCE(IDD_CFG_VIDEODELAY),hwndParent,g_DlgProc); } char *C_DELAY::get_desc(void) { return MOD_NAME; } // load_/save_config are called when saving and loading presets (.avs files) #define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24)) void C_DELAY::load_config(unsigned char *data, int len) // read configuration of max length "len" from data. { int pos=0; // always ensure there is data to be loaded if (len-pos >= 4) { // load activation toggle enabled=(GET_INT()==1); pos+=4; } if (len-pos >= 4) { // load beats toggle usebeats=(GET_INT()==1); pos+=4; } if (len-pos >= 4) { // load delay delay=GET_INT(); if (usebeats) {if (delay > 16) delay = 16;} //new else {if (delay > 200) delay = 200;} //new pos+=4; } } // write configuration to data, return length. config data should not exceed 64k. #define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255 int C_DELAY::save_config(unsigned char *data) { int pos=0; PUT_INT((int)enabled); pos+=4; PUT_INT((int)usebeats); pos+=4; PUT_INT((unsigned int)delay); pos+=4; return pos; } // export stuff C_RBASE *R_VideoDelay(char *desc) // creates a new effect object if desc is NULL, otherwise fills in desc with description { if (desc) { strcpy(desc,MOD_NAME); return NULL; } return (C_RBASE *) new C_DELAY(); } #endif
[ [ [ 1, 362 ] ] ]
2cf7afe15f66fc3e6cb928656c118efc5c726a9a
77aa13a51685597585abf89b5ad30f9ef4011bde
/dep/src/boost/boost/fusion/adapted/array/detail/is_view_impl.hpp
355f67fcffa4d146fb263479f1abd395aec461f9
[ "BSL-1.0" ]
permissive
Zic/Xeon-MMORPG-Emulator
2f195d04bfd0988a9165a52b7a3756c04b3f146c
4473a22e6dd4ec3c9b867d60915841731869a050
refs/heads/master
2021-01-01T16:19:35.213330
2009-05-13T18:12:36
2009-05-14T03:10:17
200,849
8
10
null
null
null
null
UTF-8
C++
false
false
903
hpp
/*============================================================================= Copyright (c) 2001-2006 Joel de Guzman Copyright (c) 2005-2006 Dan Marsden 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) ==============================================================================*/ #if !defined(BOOST_FUSION_IS_VIEW_IMPL_27042006_2221) #define BOOST_FUSION_IS_VIEW_IMPL_27042006_2221 #include <boost/mpl/bool.hpp> namespace boost { namespace fusion { struct array_tag; namespace extension { template<typename Tag> struct is_view_impl; template<> struct is_view_impl<array_tag> { template<typename T> struct apply : mpl::false_ {}; }; } }} #endif
[ "pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88" ]
[ [ [ 1, 32 ] ] ]
0411c8f1a2a561354fcbefca149e7f1a011729c2
294d277502d9d0d2ca1f3535d3517d7d21a9141a
/midas_timer.cpp
fd6361eb6f739266c789d00d846b58aa18d72c95
[]
no_license
grigory/midas-landmarks
57b818646ebfe7c0022eb3ad9546052ed53bc550
3a8c4148968077b87b7aab50860ff07d7f43aa7c
refs/heads/master
2021-01-20T22:31:26.157819
2010-08-10T21:21:22
2010-08-10T21:21:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,017
cpp
// (c) Microsoft Corporation. All rights reserved. /************************************* * * MIDASTimer (used for time measured) * *************************************/ #include "midas_timer.h" #define INFINITE_TIME 10e100 /******************** * Generic functions ********************/ MIDASTimer::MIDASTimer (bool s) { base_time = 0.0; max_time = 0.0; if (s) Start(); else running = false; } MIDASTimer::MIDASTimer (double maxtime) { base_time = 0.0; SetMaxTime(maxtime); Start(); } double MIDASTimer::GetTime() { if (running) return (GetElapsedTime() + base_time); else return base_time; } double MIDASTimer::Start() { double current = GetTime(); base_time = 0.0; StartTiming(); running = true; return current; } void MIDASTimer::SetMaxTime (double mt) {max_time = mt;} double MIDASTimer::GetMaxTime () {return max_time;} bool MIDASTimer::IsTimeExpired () { if (GetMaxTime() == 0) return false; bool time_expired = (GetTime() >= GetMaxTime()); return time_expired; } double MIDASTimer::GetTimeToExpire () { //may be negative! if (GetMaxTime() == 0) return INFINITE_TIME; else return (GetMaxTime() - GetTime()); } void MIDASTimer::SetBaseTime (double bt) {base_time = bt;} double MIDASTimer::Reset() { double current = GetTime(); running = false; base_time = 0.0; return current; } double MIDASTimer::Pause() { base_time = GetTime(); running = false; return base_time; } double MIDASTimer::Resume() { if (running) return GetTime(); else { running = true; StartTiming(); return base_time; } } //------------- // MIDAS_CLOCK //------------- void MIDASTimer::StartTiming() {start_time = GetUserTime();} double MIDASTimer::GetElapsedTime() { return (GetUserTime() - start_time); } double MIDASTimer::GetUserTime() { double msecs = (double) clock() / CLOCKS_PER_SEC; if (msecs > 0) return msecs; else return 0.0; //sometimes msecs is -0.000 (go figure...) }
[ [ [ 1, 95 ] ] ]
27fbdf958e62ac4e4e941586fb061e387ef0eee5
55196303f36aa20da255031a8f115b6af83e7d11
/include/bikini/base/random.inl
ed0dabe4d8b163b6befc62ab9223b2c53b86075a
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
934
inl
/*---------------------------------------------------------------------------------------------*//* Binary Kinematics 3 - C++ Game Programming Library Copyright (C) 2008-2010 Viktor Reutskyy [email protected] *//*---------------------------------------------------------------------------------------------*/ #pragma once // random inline random::random(uint _seed) : seed(_seed) {} inline uint random::get() { seed = seed * 1103515245 + 12345; return uint(seed / 65536) & max; } inline uint random::get(uint _max) { return get() % (_max + 1); } inline sint random::get(sint _min, sint _max) { if(_max < _min) swap(_min, _max); return _min + get(uint(_max - _min)); } inline real random::get(real _max) { return bk::max(real(0), real(get()) * _max / real(max)); } inline real random::get(real _min, real _max) { if(_max < _min) swap(_min, _max); return _min + get(_max - _min); }
[ "[email protected]", "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 3 ], [ 6, 31 ] ], [ [ 4, 5 ] ] ]
476cfefafb68d4a616da2c64875b719679501dbd
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/inl/QxDao/QxDao_Exist.inl
0e5e05f0f2a3b5ce0348affcf6be18c8c6a43c8c
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
5,572
inl
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any ** damages arising from the use of this software. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ namespace qx { namespace dao { namespace detail { template <class T> struct QxDao_Exist_Generic { static qx_bool exist(T & t, QSqlDatabase * pDatabase) { qx::dao::detail::QxDao_Helper<T> dao(t, pDatabase, "exist"); if (! dao.isValid()) { return qx_bool(false); } QString sql = dao.builder().exist().getSqlQuery(); if (! dao.getDataId() || sql.isEmpty()) { dao.errEmpty(); return qx_bool(false); } dao.query().prepare(sql); qx::dao::detail::QxSqlQueryHelper_Exist<T>::resolveInput(t, dao.query(), dao.builder()); if (! dao.query().exec()) { dao.errFailed(); return qx_bool(false); } return qx_bool(dao.nextRecord()); } }; template <class T> struct QxDao_Exist_Container { static qx_bool exist(T & t, QSqlDatabase * pDatabase) { if (qx::trait::generic_container<T>::size(t) <= 0) { return qx_bool(false); } qx::dao::detail::QxDao_Helper_Container<T> dao(t, pDatabase, "exist"); if (! dao.isValid()) { return qx_bool(false); } QString sql = dao.builder().exist().getSqlQuery(); if (sql.isEmpty()) { dao.errEmpty(); return qx_bool(false); } dao.query().prepare(sql); for (typename T::iterator it = t.begin(); it != t.end(); ++it) { if (! existItem((* it), dao)) { return qx_bool(false); } } return qx_bool(true); } private: template <typename U> static inline bool existItem(U & item, qx::dao::detail::QxDao_Helper_Container<T> & dao) { return existItem_Helper<U, boost::is_pointer<U>::value || qx::trait::is_smart_ptr<U>::value>::exist(item, dao); } template <typename U, bool bIsPointer /* = true */> struct existItem_Helper { static inline bool exist(U & item, qx::dao::detail::QxDao_Helper_Container<T> & dao) { return (item ? qx::dao::detail::QxDao_Exist_Container<T>::existItem((* item), dao) : false); } }; template <typename U1, typename U2> struct existItem_Helper<std::pair<U1, U2>, false> { static inline bool exist(std::pair<U1, U2> & item, qx::dao::detail::QxDao_Helper_Container<T> & dao) { return qx::dao::detail::QxDao_Exist_Container<T>::existItem(item.second, dao); } }; template <typename U1, typename U2> struct existItem_Helper<const std::pair<U1, U2>, false> { static inline bool exist(const std::pair<U1, U2> & item, qx::dao::detail::QxDao_Helper_Container<T> & dao) { return qx::dao::detail::QxDao_Exist_Container<T>::existItem(item.second, dao); } }; template <typename U1, typename U2> struct existItem_Helper<QPair<U1, U2>, false> { static inline bool exist(QPair<U1, U2> & item, qx::dao::detail::QxDao_Helper_Container<T> & dao) { return qx::dao::detail::QxDao_Exist_Container<T>::existItem(item.second, dao); } }; template <typename U1, typename U2> struct existItem_Helper<const QPair<U1, U2>, false> { static inline bool exist(const QPair<U1, U2> & item, qx::dao::detail::QxDao_Helper_Container<T> & dao) { return qx::dao::detail::QxDao_Exist_Container<T>::existItem(item.second, dao); } }; template <typename U> struct existItem_Helper<U, false> { static bool exist(U & item, qx::dao::detail::QxDao_Helper_Container<T> & dao) { qx::dao::detail::QxSqlQueryHelper_Exist<U>::resolveInput(item, dao.query(), dao.builder()); if (! dao.query().exec()) { dao.errFailed(); return false; } return dao.nextRecord(); } }; }; template <class T> struct QxDao_Exist_Ptr { static inline qx_bool exist(T & t, QSqlDatabase * pDatabase) { qAssert(t != NULL); return (t ? qx::dao::exist((* t), pDatabase) : qx_bool(false)); } }; template <class T> struct QxDao_Exist { static inline qx_bool exist(T & t, QSqlDatabase * pDatabase) { typedef typename boost::mpl::if_c< boost::is_pointer<T>::value, qx::dao::detail::QxDao_Exist_Ptr<T>, qx::dao::detail::QxDao_Exist_Generic<T> >::type type_dao_1; typedef typename boost::mpl::if_c< qx::trait::is_smart_ptr<T>::value, qx::dao::detail::QxDao_Exist_Ptr<T>, type_dao_1 >::type type_dao_2; typedef typename boost::mpl::if_c< qx::trait::is_container<T>::value, qx::dao::detail::QxDao_Exist_Container<T>, type_dao_2 >::type type_dao_3; return type_dao_3::exist(t, pDatabase); } }; } // namespace detail } // namespace dao } // namespace qx
[ [ [ 1, 150 ] ] ]
346bc51105a27086cc3b2ae712ea4bacf0093755
61352a7371397524fe7dcfab838de40d502c3c9a
/client/Headers/View/Windows/MsgWindow.h
088c9bcfc0375e04220b4a86d4c1078cbc76a72b
[]
no_license
ustronieteam/emmanuelle
fec6b6ccfa1a9a6029d8c3bb5ee2b9134fccd004
68d639091a781795d2e8ce95c3806ce6ae9f36f6
refs/heads/master
2021-01-21T13:04:29.965061
2009-01-28T04:07:01
2009-01-28T04:07:01
32,144,524
2
0
null
null
null
null
UTF-8
C++
false
false
2,236
h
#ifndef _MSGWINDOW_H_ #define _MSGWINDOW_H_ #include <list> #include "Window.h" // Opjcie konfiguracyjne. #define MSG_MAX_MSG_LEN 100 #define MSG_MAX_SEE_MSG 10 // Informacje #define MSG_INF_NO_MSG "Brak wiadomosci." #define MSG_INF_SND_MSG "Wysylanie wiadomosci..." #define MSG_INF_SND_FIL "Wysylanie pliku..." #define MSG_INF_SHOW_L "^^ Pokazywane sa ostatnie wiadomosci." #define MSG_INF_SHOW_A "^^ Pokazywane sa wszystkie wiadomosci." #define MSG_INF_FILE_SND1 " Plik '" #define MSG_INF_FILE_SND2 "' zostal pomyslnie wyslany." #define MSG_INF_FILE_SNDR "[emmanuelle]" // Bledy #define MSG_ER_SND_MSG "!@# Nie mozna bylo wyslac wiadomosci!" #define MSG_ER_SND_FIL "!@# Nie znaleziono pliku!" #define MSG_ER_FILE_SND2 " nie mogl byc wyslany." /// /// MsgWindow /// @brief Okienko wysylania i odbierania wiadomosci. /// @author Wojciech Grzeskowiak /// @date 2009.01.11 /// class MsgWindow : public Window { private: /// /// Nazwa uzytkownika z ktorym odbywa sie rozmowa. /// std::string _contactName; /// /// Rozmowa. /// std::list<MYMESSAGE> * _talk; /// /// Mutex na rozmowe. /// boost::mutex * _mxTalk; /// /// Mutex na renderowanie. /// boost::mutex _mxRender; /// /// Bufor do pobranie jednej wiadomosci. /// char _singleMsg[MSG_MAX_MSG_LEN]; /// /// Typ wyswietlania. /// bool _showLast; /// /// Obiekt logowania. /// log4cxx::LoggerPtr _logger; public: /// /// Konstruktor. /// @param[in] controller Kontroler. /// MsgWindow(Controller * controller, const std::string & name); /// /// Renderowanie okienka. /// @param[in] o Strumien do ktorego renderujemy obraz. /// virtual void Render(std::ostream & o); /// /// Komenda przekazana do okna. /// @param[in] cmd Komenda. /// virtual void Command(std::string & cmd); /// /// Ustawia rozmowe. /// @param[in] talk Wskaznik na rozmowe. /// void SetTalk(std::list<MYMESSAGE> * talk); /// /// Ustawia mutex na rozmowe. /// @param[in] mxTalk Wskaznik na mutex do rozmowy. /// void SetMutexTalk(boost::mutex * mxTalk); }; #endif /* _MSGWINDOW_H_ */
[ "w.grzeskowiak@c118a9a8-d993-11dd-9042-6d746b85d38b" ]
[ [ [ 1, 103 ] ] ]
33d0883873e978ca1120e59ea3852745bc8553b9
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_appsharing/src/DebugWin.cpp
3bc2eb687b24db349e5fcf7bf79f8548a784e33c
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
3,096
cpp
#include "DebugWin.h" #include "tchar.h" #define LISTID 0x0001 // Creates a pop-up window LRESULT g_DebugWindowProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { long ret; CREATESTRUCT *pCS; RECT rc; DebugWin *pThis = (DebugWin *)GetWindowLong( hWnd, GWL_USERDATA ); switch( message ) { case WM_CREATE: pCS = (CREATESTRUCT *)lParam; SetWindowLong( hWnd, GWL_USERDATA, (LONG)(pCS->lpCreateParams) ); pThis = (DebugWin *)pCS->lpCreateParams; GetClientRect( hWnd, &rc ); pThis->m_hList = CreateWindow( _T("LISTBOX"), NULL, WS_VISIBLE | WS_CHILD| WS_VSCROLL | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT, 0, 0, rc.right - rc.left, rc.bottom - rc.top, hWnd, (HMENU)LISTID, pThis->m_hInstance, NULL ); ShowWindow( pThis->m_hList, SW_SHOW ); SendMessage( pThis->m_hList, WM_SETFONT, (WPARAM)GetStockObject( SYSTEM_FIXED_FONT ), TRUE ); ret = 0; break; case WM_SIZE: SetWindowPos( pThis->m_hList, hWnd, 0, 0, LOWORD( lParam ), HIWORD( lParam ), SWP_NOMOVE | SWP_NOZORDER | SWP_SHOWWINDOW ); ret = 0; break; case WM_DESTROY: pThis->m_hWnd = NULL; ret = 0; break; default: ret = ::DefWindowProc( hWnd, message, wParam, lParam ); } return ret; } DebugWin::DebugWin( HINSTANCE hInstance ) { WNDCLASS wndclass; m_hWnd = NULL; m_hList = NULL; m_hInstance = hInstance; if( !GetClassInfo( hInstance, _T("CxDebugWin"), &wndclass) ) { m_wndclass.style = CS_HREDRAW | CS_VREDRAW; m_wndclass.lpfnWndProc = (WNDPROC)g_DebugWindowProc; m_wndclass.cbClsExtra = 0; m_wndclass.cbWndExtra = 0; m_wndclass.hInstance = m_hInstance; m_wndclass.hIcon = NULL; m_wndclass.hCursor = LoadCursor( NULL, IDC_ARROW ); m_wndclass.hbrBackground = GetSysColorBrush( COLOR_WINDOW ); m_wndclass.lpszMenuName = NULL; m_wndclass.lpszClassName = _T("CxDebugWin"); RegisterClass( &m_wndclass ); } } DebugWin::~DebugWin( void ) { } bool DebugWin::Create( void ) { m_hWnd = CreateWindow( _T("CxDebugWin"), _T("CxDebugWin"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, GetDesktopWindow( ), NULL, m_hInstance, (LPVOID)this ); ShowWindow( m_hWnd, SW_SHOW ); return m_hWnd != NULL; } bool DebugWin::Destroy( void ) { return DestroyWindow( m_hWnd ) != 0; } bool DebugWin::AddString( char *pStr ) { long index; if( !m_hWnd ) return false; index = SendMessage( m_hList, LB_ADDSTRING, 0, (LPARAM) pStr ); SendMessage( m_hList, LB_SETCURSEL, index, (LPARAM) 0 ); return true; }
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 109 ] ] ]
f862e60f0e6cefe7c1f32538b86e5d752c8730a8
d609fb08e21c8583e5ad1453df04a70573fdd531
/trunk/GirlDiary/HScrollTip.cpp
cf47953c0f3b1a597ac0e2bdf05430cd24a3f0d9
[]
no_license
svn2github/openxp
d68b991301eaddb7582b8a5efd30bc40e87f2ac3
56db08136bcf6be6c4f199f4ac2a0850cd9c7327
refs/heads/master
2021-01-19T10:29:42.455818
2011-09-17T10:27:15
2011-09-17T10:27:15
21,675,919
0
1
null
null
null
null
GB18030
C++
false
false
1,805
cpp
#include "stdafx.h" #include "HScrollTip.h" #define IDM_SCORLL 1121 static int g_nPaintX=0; IMPLEMENT_DYNAMIC(HScrollTip, CWnd) HScrollTip::HScrollTip() { m_strScroll = "月光洗去的只是往日的容颜,留下的却是心灵的春天!"; m_fontText.CreateFont(12,8,0,0,FW_NORMAL,FALSE,FALSE,FALSE,ANSI_CHARSET,3,2,1,2,_T("宋体")); } HScrollTip::~HScrollTip() { } BEGIN_MESSAGE_MAP(HScrollTip, CWnd) ON_WM_TIMER() ON_WM_CREATE() ON_WM_PAINT() ON_WM_ERASEBKGND() END_MESSAGE_MAP() //定时器 void HScrollTip::OnTimer(UINT_PTR nIDEvent) { g_nPaintX--; if (g_nPaintX < -1*(m_strScroll.GetLength()*8)) { CRect rcClient; GetClientRect(&rcClient); g_nPaintX = rcClient.Width(); } Invalidate(); CWnd::OnTimer(nIDEvent); } //创建 int HScrollTip::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; CString m_strEXE = GetExeModulePath(AfxGetInstanceHandle()); TCHAR szBackImage[260] = {0}; ::GetPrivateProfileString("default","tip",_T("不存在关键字"),szBackImage,sizeof(szBackImage),m_strEXE+"config.ini"); m_strScroll.Format("%s",szBackImage); if (m_strScroll == "不存在关键字") m_strScroll = "月光洗去的只是往日的容颜,留下的却是心灵的春天!"; SetTimer(IDM_SCORLL,50,NULL); return 0; } //绘制 void HScrollTip::OnPaint() { CPaintDC dc(this); CRect rcClient; GetClientRect(&rcClient); HMemDC memDC(&dc,rcClient); memDC->SetTextColor(RGB(128,128,0)); CFont *pOldFont = memDC->SelectObject(&m_fontText); memDC->DrawText(m_strScroll,CRect(g_nPaintX,0,rcClient.Width(),rcClient.Height()),DT_LEFT); memDC->SelectObject(pOldFont); } //擦除背景 BOOL HScrollTip::OnEraseBkgnd(CDC* pDC) { return TRUE; }
[ "[email protected]@f92b348d-55a1-4afa-8193-148a6675784b" ]
[ [ [ 1, 73 ] ] ]
5e798cefe1e752a44e887fe7147435c928e16a20
111599781f886c42099cb9f4ccadff397cab51e8
/AddressBar.cpp
7f08356eac611724af120c2a900a4fe3b8ae4fff
[]
no_license
victorliu/ColumnViewBrowser
6fd5f02cc37b4834aec59c736d3b9006ba3fc183
a37b8bcf272c125041492b681bdb280f051fa478
refs/heads/master
2020-05-29T17:30:33.683440
2011-02-05T10:45:03
2011-02-05T10:45:03
528,279
2
0
null
null
null
null
UTF-8
C++
false
false
249
cpp
#include "StdAfx.h" #include "AddressBar.h" int AddressBar::OnCreate(LPCREATESTRUCT lpCreateStruct){ LoadToolBar(IDR_ADDRESSBAR_TOOLBAR); m_comboAddress.Create(*this, rcDefault); SetButtonInfo(1, IDW_ADDRESS_COMBO, TBBS_SEPARATOR, 100); }
[ [ [ 1, 8 ] ] ]
2842b58fbe5fbe761cc00bda1dd3c0664b883b3e
b6e0e894be10de33532969a67b9e278753d392f9
/logindialog.h
75b43bd13c9fb9b2813c6810adc5715811932c66
[]
no_license
faellsa/teachersmanagement
4f9ef70ec91b1237d45cd2b7c71afdd2bc183e0e
15f79a11eadac2e6c811fe27fbf727faa27d32c3
refs/heads/master
2020-05-16T19:01:29.339150
2011-05-21T09:46:30
2011-05-21T09:46:30
32,401,290
0
0
null
null
null
null
UTF-8
C++
false
false
545
h
#ifndef LOGINDIALOG_H #define LOGINDIALOG_H #include <QDialog> #include <mainwindow.h> #include "datacenter.h" namespace Ui { class LoginDialog; } class LoginDialog : public QDialog { Q_OBJECT public: explicit LoginDialog(QWidget *parent = 0); ~LoginDialog(); private: Ui::LoginDialog *ui; void setupSignals(); MainWindow *m_MainWindow; DataCenter *m_DataCenter; AccountManage* m_accountManage; private slots: void onLoginButton(); void onExitButton(); }; #endif // LOGINDIALOG_H
[ "lefthand0702@69ecbcbb-dc20-fe55-c2b8-cdc3f9c2dbdb" ]
[ [ [ 1, 32 ] ] ]
8b247777b15a70719e5982c32b479bfd1b3c4a3f
5dc6c87a7e6459ef8e832774faa4b5ae4363da99
/vis_avs/Recorder.h
c2a47ea81c4037d4f49ddb9716a8c64fcb7a35d7
[]
no_license
aidinabedi/avs4unity
407603d2fc44bc8b075b54cd0a808250582ee077
9b6327db1d092218e96d8907bd14d68b741dcc4d
refs/heads/master
2021-01-20T15:27:32.449282
2010-12-24T03:28:09
2010-12-24T03:28:09
90,773,183
5
2
null
null
null
null
UTF-8
C++
false
false
1,734
h
// Recorder.h: interface for the CRecorder class. // ////////////////////////////////////////////////////////////////////// #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <windows.h> #include <mmsystem.h> #pragma comment(lib,"winmm.lib") typedef struct _PCMFORMAT { WORD wBitsPerSample;//no.of bits per sample for Recording WORD wChannels;//no.of channels for Recording DWORD dwSampleRate;//Sampling rate for Recording }PCMFORMAT, *LPPCMFORMAT; struct WAVECLASS { HWAVE hWave; void* lpData; }; #define MAXNUMOFBUFFER 16 typedef BOOL (*ProcessBuffer)(void* lpData, LPWAVEHDR pwh); class Recorder { public: Recorder(int nBufferLength=2048); Recorder(PCMFORMAT pcm,int nBufferLength=2048); Recorder(WORD wBitsPerSample,WORD wChannels,DWORD dwSampleRate,int nBufferLength=2048); virtual ~Recorder(); void Open(DWORD dwCallBack=NULL,DWORD dwCallbackType=CALLBACK_FUNCTION,MCIDEVICEID wMCIDeviceID=WAVE_MAPPER); void Close(); void Start(); void Stop(); void ReuseHeader(LPWAVEHDR pwh); void SetFormat(LPPCMFORMAT lpPcmFormat); void SetFormat(WORD wBitsPerSample,WORD wChannels,DWORD dwSampleRate); BOOL IsRecording(); BOOL IsDeviceOpen(); DWORD GetPosition(); BOOL Pause(); BOOL Continue(); BOOL IsFormatSupported(WAVEFORMATEX wfEx, UINT nDev=WAVE_MAPPER); LPWAVEHDR m_lpWaveHdr; protected: WAVECLASS m_waveClass; GLOBALHANDLE m_hWaveInHdr[MAXNUMOFBUFFER]; LPWAVEHDR m_lpWaveInHdr[MAXNUMOFBUFFER]; GLOBALHANDLE m_hInBuffer[MAXNUMOFBUFFER]; LPBYTE m_lpInBuffer [MAXNUMOFBUFFER]; PCMFORMAT m_PcmFormat; WAVEFORMATEX m_WaveFormat; HWAVEIN m_hWaveIn; BOOL m_bRecording; BOOL m_bDeviceOpen; DWORD m_dwBufferSize; };
[ [ [ 1, 63 ] ] ]
83bbb385f6ae688e42f6e419cb7792c0f6d339e9
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment4/stack.hpp
8fd78f27580d8035b74ef4c26f6cb7d368c79dee
[]
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
1,258
hpp
////////////////////////////////////////////////////////////////////// /// @file stack.hpp /// @author James Anderson CS 153 Section A /// @brief Template implemintation file for /// the stack class for assignment 4 ////////////////////////////////////////////////////////////////////// template <class generic> Stack<generic>::Stack () { } template <class generic> Stack<generic>::Stack (Stack & s) : SList<generic> (s) { } template <class generic> Stack<generic>::~Stack () { } template <class generic> Stack<generic> & Stack<generic>:: operator= (const Stack & s) { return *this; } template <class generic> void Stack<generic>::push (generic x) { SList<generic>::push_front (x); } template <class generic> void Stack<generic>::pop () { SList<generic>::pop_front (); } template <class generic> void Stack<generic>::clear () { SList<generic>::clear (); } template <class generic> generic & Stack<generic>::top () { return SList<generic>::front (); } template <class generic> unsigned int Stack<generic>::size () const { return SList<generic>::size (); } template <class generic> bool Stack<generic>::empty () const { return SList<generic>::empty (); }
[ [ [ 1, 65 ] ] ]
11f546fbc447de944ef40806c9f867b3c23b0ff8
5e9454e71c57778f2471f2cb7549121cd711f4f9
/QAnts/GeneratedFiles/Debug/moc_AntWidget.cpp
ce2fdb6f710ccf8077d1de0cfee5261c3973434a
[]
no_license
ImTheNo/Ants
37bca3dbc618f77721731102d80dc38e9f17d110
2790be0e41733af2df5923d9446f876e94d3fba1
refs/heads/master
2021-01-23T02:53:51.899578
2011-05-19T23:32:36
2011-05-19T23:32:36
1,772,968
0
0
null
null
null
null
UTF-8
C++
false
false
2,515
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'AntWidget.hpp' ** ** Created: Wed 4. May 11:55:52 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../AntWidget.hpp" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'AntWidget.hpp' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_AntWidget[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: signature, parameters, type, tag, flags 11, 10, 10, 10, 0x05, 0 // eod }; static const char qt_meta_stringdata_AntWidget[] = { "AntWidget\0\0antViewChanged()\0" }; const QMetaObject AntWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_AntWidget, qt_meta_data_AntWidget, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &AntWidget::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *AntWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *AntWidget::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_AntWidget)) return static_cast<void*>(const_cast< AntWidget*>(this)); return QWidget::qt_metacast(_clname); } int AntWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: antViewChanged(); break; default: ; } _id -= 1; } return _id; } // SIGNAL 0 void AntWidget::antViewChanged() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } QT_END_MOC_NAMESPACE
[ [ [ 1, 85 ] ] ]
b2816194b4c317b993b3cdbc1c6998a9af7fe141
f13f46fbe8535a7573d0f399449c230a35cd2014
/JelloMan/Sprite.cpp
c3fafd79784a04e495609969f45e40c697c2422d
[]
no_license
fangsunjian/jello-man
354f1c86edc2af55045d8d2bcb58d9cf9b26c68a
148170a4834a77a9e1549ad3bb746cb03470df8f
refs/heads/master
2020-12-24T16:42:11.511756
2011-06-14T10:16:51
2011-06-14T10:16:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
883
cpp
#include "Sprite.h" #include "Blox2D.h" /* CONSTRUCTOR - DESTRUCTOR */ Sprite::Sprite(Image* imgSpriteSheet, int nrAnimSteps) : m_imgSpriteSheet(imgSpriteSheet), m_AnimSteps(nrAnimSteps), m_SpriteSize(SizeF(0,0)) { m_SpriteSize.width = m_imgSpriteSheet->GetDimensions().width / m_AnimSteps; m_SpriteSize.height = m_imgSpriteSheet->GetDimensions().height; } Sprite::~Sprite() { } /* GENERAL */ void Sprite::Draw(float x, float y, int animStep) const { D2D1_RECT_F area; area.left = x + (m_SpriteSize.width * animStep); area.top = y; area.right = x + m_SpriteSize.width + (m_SpriteSize.width * animStep); area.bottom = y + m_SpriteSize.height; BX2D->DrawImage(m_imgSpriteSheet, x, y, area, false); } /* GETTERS */ Size2D Sprite::GetSpriteSheetDimensions() const { return m_imgSpriteSheet->GetDimensions(); }
[ [ [ 1, 34 ] ] ]
a329dd6ca4dd2d38d54c5ab6623c2d03f422c313
694894e5fd2a4600a2bd3fd04d4f36d9dddf252d
/AccordsCalculator/AccordsCalculator/main.cpp
d7619094f659c037bfc64b1bb229f8027fc0d5f6
[]
no_license
dodikk/Akkords-Calculator
a419b7e775f46b254c738b67850587d118880e98
67fb819040f41fb26c249596fe7a26ff5e791982
refs/heads/master
2021-01-01T05:34:37.538194
2010-01-31T14:11:35
2010-01-31T14:11:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
576
cpp
#include "stdafx.h" using namespace Wt; using namespace WebUi; WApplication *CreateApplication(const WEnvironment& env) { return new AccordsCalculatorApp(env); } int main(int argc, char **argv) { try { return WRun(argc, argv, &CreateApplication); } catch(const std::exception& ex) { std::cout << "std::exception caught" << std::endl; std::cout << ex.what() << std::endl; return 2; } catch (...) { std::cout << "Unknown error occured" << std::endl; return 1; } }
[ [ [ 1, 35 ] ] ]
1d4ceb4f089e316e7aa320e9d5df32f8d3812663
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Approximation/Wm4ApprLineFit2.h
e8815c45cdb0bda908beebf311401269916ab0eb
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
1,266
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4APPRLINEFIT2_H #define WM4APPRLINEFIT2_H #include "Wm4FoundationLIB.h" #include "Wm4Line2.h" namespace Wm4 { // Least-squares fit of a line to (x,f(x)) data by using distance // measurements in the y-direction. The resulting line is represented by // y = A*x + B. The return value is 'false' if the 2x2 coefficient matrix // in the linear system that defines A and B is (nearly) singular. In this // case, A and B are returned as MAX_REAL. template <class Real> WM4_FOUNDATION_ITEM bool HeightLineFit2 (int iQuantity, const Vector2<Real>* akPoint, Real& rfA, Real& rfB); // Least-squares fit of a line to (x,y,z) data by using distance measurements // orthogonal to the proposed line. template <class Real> WM4_FOUNDATION_ITEM Line2<Real> OrthogonalLineFit2 (int iQuantity, const Vector2<Real>* akPoint); } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 36 ] ] ]
23e26e42de7f8c7111e9f75340b577e094ee54bf
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/Transcoders/Uniconv390/XML88591Transcoder390.hpp
51d28e277c93fff878484eda8eec484335398bc8
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
3,539
hpp
/* * Copyright 2004,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: XML88591Transcoder390.hpp,v $ * Revision 1.3 2004/09/08 13:56:46 peiyongz * Apache License Version 2.0 * * Revision 1.2 2004/04/22 22:46:46 neilg * not all 390 processors support the new transcoding instructions; this patch makes Xerces work there as well. Thanks to Steve Dulin * * Revision 1.1 2004/02/06 15:02:11 cargilld * Intrinsic transcoding support for 390. * */ #ifndef XML88591TRANSCODER390_HPP #define XML88591TRANSCODER390_HPP #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/TransService.hpp> XERCES_CPP_NAMESPACE_BEGIN // // This class provides an implementation of the XMLTranscoder interface // for a simple 8859-1 transcoder. The parser does some encodings // intrinsically without depending upon external transcoding services. // To make everything more orthagonal, we implement these internal // transcoders using the same transcoder abstraction as the pluggable // transcoding services do. // class XMLUTIL_EXPORT XML88591Transcoder390 : public XMLTranscoder { public : // ----------------------------------------------------------------------- // Public constructors and destructor // ----------------------------------------------------------------------- XML88591Transcoder390 ( const XMLCh* const encodingName , const unsigned int blockSize , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); virtual ~XML88591Transcoder390(); // ----------------------------------------------------------------------- // Implementation of the XMLTranscoder interface // ----------------------------------------------------------------------- virtual unsigned int transcodeFrom ( const XMLByte* const srcData , const unsigned int srcCount , XMLCh* const toFill , const unsigned int maxChars , unsigned int& bytesEaten , unsigned char* const charSizes ); virtual unsigned int transcodeTo ( const XMLCh* const srcData , const unsigned int srcCount , XMLByte* const toFill , const unsigned int maxBytes , unsigned int& charsEaten , const UnRepOpts options ); virtual bool canTranscodeTo ( const unsigned int toCheck ) const; private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- XML88591Transcoder390(const XML88591Transcoder390&); XML88591Transcoder390& operator=(const XML88591Transcoder390&); }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 101 ] ] ]
d974bd17ca211e03b06809b6bee80cd0b51a84c7
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/FlwLib/SparseSlv/Indirect/src/qsort_type.cc
17fe47331177b1b4783c75d74baaf77373dbf1c7
[]
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
12,532
cc
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* ******** *** SparseLib++ */ /* ******* ** *** *** *** */ /* ***** *** ******** ******** */ /* ***** *** ******** ******** R. Pozo */ /* ** ******* *** ** *** *** K. Remington */ /* ******** ******** A. Lumsdaine */ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* */ /* */ /* SparseLib++ : Sparse Matrix Library */ /* */ /* National Institute of Standards and Technology */ /* University of Notre Dame */ /* Authors: R. Pozo, K. Remington, A. Lumsdaine */ /* */ /* NOTICE */ /* */ /* Permission to use, copy, modify, and distribute this software and */ /* its documentation for any purpose and without fee is hereby granted */ /* provided that the above notice appear in all copies and supporting */ /* documentation. */ /* */ /* Neither the Institutions (National Institute of Standards and Technology, */ /* University of Notre Dame) nor the Authors make any representations about */ /* the suitability of this software for any purpose. This software is */ /* provided ``as is'' without expressed or implied warranty. */ /* */ /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ // An adaptation of Schmidt's new quicksort (taken from GNU emacs) // for MV++ // by Andrew Lumsdaine #include "qsort_TYPE.h" #ifdef sparc #include <alloca.h> #endif // Invoke the < comparison function #define CMP(A,B) ((A) < (B)) // swap two items // static inline void SWAP_TYPE(TYPE &A, TYPE &B) { TYPE tmp = A; A = B; B = tmp; } static inline void swap_int(int &a, int &b) { int tmp=a; a=b; b=tmp; } // This should be replaced by a standard ANSI macro. #define BYTES_PER_WORD 8 /* The next 4 #defines implement a very fast in-line stack abstraction. */ #define STACK_SIZE (BYTES_PER_WORD * sizeof (long)) #define PUSH(LOW,HIGH) do {top->lo = LOW;top++->hi = HIGH;} while (0) #define POP(LOW,HIGH) do {LOW = (--top)->lo;HIGH = top->hi;} while (0) #define STACK_NOT_EMPTY (stack < top) /* Discontinue quicksort algorithm when partition gets below this size. This particular magic number was chosen to work best on a Sun 4/260. */ #define MAX_THRESH 4 /* Stack node declarations used to store unfulfilled partition obligations. */ typedef struct { int lo; int hi; } stack_node; /* Order size using quicksort. This implementation incorporates four optimizations discussed in Sedgewick: 1. Non-recursive, using an explicit stack of pointer that store the next array partition to sort. To save time, this maximum amount of space required to store an array of MAX_INT is allocated on the stack. Assuming a 32-bit integer, this needs only 32 * sizeof (stack_node) == 136 bits. Pretty cheap, actually. 2. Chose the pivot element using a median-of-three decision tree. This reduces the probability of selecting a bad pivot value and eliminates certain extraneous comparisons. 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving insertion sort to order the MAX_THRESH items within each partition. This is a big win, since insertion sort is faster for small, mostly sorted array segments. 4. The larger of the two sub-partitions is always pushed onto the stack first, with the algorithm then concentrating on the smaller partition. This *guarantees* no more than log (n) stack size is needed (actually O(1) in this case)! */ int QSort(VECTOR_TYPE& v, int base_ptr, int total_elems) { TYPE pivot_buffer; if (total_elems > MAX_THRESH) { int lo = base_ptr; int hi = lo + total_elems - 1; stack_node stack[STACK_SIZE]; /* Largest size needed for 32-bit int!!! */ stack_node *top = stack + 1; while (STACK_NOT_EMPTY) { int left_ptr; int right_ptr; { { /* Select median value from among LO, MID, and HI. Rearrange LO and HI so the three values are sorted. This lowers the probability of picking a pathological pivot value and skips a comparison for both the LEFT_PTR and RIGHT_PTR. */ int mid = lo + (hi - lo) / 2; if (CMP (v[mid], v[lo])) SWAP_TYPE(v[mid], v[lo]); if (CMP (v[hi], v[mid])) SWAP_TYPE(v[hi], v[mid]); else goto jump_over; if (CMP (v[mid], v[lo])) SWAP_TYPE(v[mid], v[lo]); jump_over: pivot_buffer = v[mid]; } left_ptr = lo + 1; right_ptr = hi - 1; /* Here's the famous ``collapse the walls'' section of quicksort. Gotta like those tight inner loops! They are the main reason that this algorithm runs much faster than others. */ do { while (CMP (v[left_ptr], pivot_buffer)) left_ptr++; while (CMP (pivot_buffer, v[right_ptr])) right_ptr--; if (left_ptr < right_ptr) { SWAP_TYPE(v[left_ptr], v[right_ptr]); left_ptr++; right_ptr--; } else if (left_ptr == right_ptr) { left_ptr ++; right_ptr --; break; } } while (left_ptr <= right_ptr); } /* Set up pointers for next iteration. First determine whether left and right partitions are below the threshold size. If so, ignore one or both. Otherwise, push the larger partition's bounds on the stack and continue sorting the smaller one. */ if ((right_ptr - lo) <= MAX_THRESH) { if ((hi - left_ptr) <= MAX_THRESH) POP (lo, hi); else lo = left_ptr; } else if ((hi - left_ptr) <= MAX_THRESH) hi = right_ptr; else if ((right_ptr - lo) > (hi - left_ptr)) { PUSH (lo, right_ptr); lo = left_ptr; } else { PUSH (left_ptr, hi); hi = right_ptr; } } } /* Once the BASE_PTR array is partially sorted by quicksort the rest is completely sorted using insertion sort, since this is efficient for partitions below MAX_THRESH size. BASE_PTR points to the beginning of the array to sort, and END_PTR points at the very last element in the array (*not* one beyond it!). */ #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) { int end_ptr = base_ptr + total_elems - 1; int run_ptr; int tmp_ptr = base_ptr; int thresh = MIN (end_ptr, base_ptr + MAX_THRESH); for (run_ptr = tmp_ptr + 1; run_ptr <= thresh; run_ptr++) if (CMP (v[run_ptr], v[tmp_ptr])) tmp_ptr = run_ptr; if (tmp_ptr != base_ptr) SWAP_TYPE(v[tmp_ptr], v[base_ptr]); for (run_ptr = base_ptr + 1; (tmp_ptr = run_ptr += 1) <= end_ptr;) { while (CMP (v[run_ptr], v[tmp_ptr -= 1])) ; if ((tmp_ptr += 1) != run_ptr) { int trav; for (trav = run_ptr + 1; --trav >= run_ptr;) { TYPE c; c = v[trav]; int hi, lo; for (hi = lo = trav; (lo -= 1) >= tmp_ptr; hi = lo) v[hi] = v[lo]; v[hi] = c; } } } } return 1; } int QSort(VECTOR_int & v, VECTOR_TYPE& x, int base_ptr, int total_elems) { int pivot_buffer; TYPE pixot_buffer; if (total_elems > MAX_THRESH) { int lo = base_ptr; int hi = lo + total_elems - 1; stack_node stack[STACK_SIZE]; /* Largest size needed for 32-bit int!!! */ stack_node *top = stack + 1; while (STACK_NOT_EMPTY) { int left_ptr; int right_ptr; { { /* Select median value from among LO, MID, and HI. Rearrange LO and HI so the three values are sorted. This lowers the probability of picking a pathological pivot value and skips a comparison for both the LEFT_PTR and RIGHT_PTR. */ int mid = lo + (hi - lo) / 2; if (CMP (v[mid], v[lo])) { swap_int (v[mid], v[lo]); SWAP_TYPE (x[mid], x[lo]); } if (CMP (v[hi], v[mid])) { swap_int (v[hi], v[mid]); SWAP_TYPE (x[hi], x[mid]); } else goto jump_over; if (CMP (v[mid], v[lo])) { swap_int(v[mid], v[lo]); SWAP_TYPE (x[mid], x[lo]); } jump_over: pivot_buffer = v[mid]; pixot_buffer = x[mid]; } left_ptr = lo + 1; right_ptr = hi - 1; /* Here's the famous ``collapse the walls'' section of quicksort. Gotta like those tight inner loops! They are the main reason that this algorithm runs much faster than others. */ do { while (CMP (v[left_ptr], pivot_buffer)) left_ptr++; while (CMP (pivot_buffer, v[right_ptr])) right_ptr--; if (left_ptr < right_ptr) { swap_int (v[left_ptr], v[right_ptr]); SWAP_TYPE (x[left_ptr], x[right_ptr]); left_ptr++; right_ptr--; } else if (left_ptr == right_ptr) { left_ptr ++; right_ptr --; break; } } while (left_ptr <= right_ptr); } /* Set up pointers for next iteration. First determine whether left and right partitions are below the threshold size. If so, ignore one or both. Otherwise, push the larger partition's bounds on the stack and continue sorting the smaller one. */ if ((right_ptr - lo) <= MAX_THRESH) { if ((hi - left_ptr) <= MAX_THRESH) POP (lo, hi); else lo = left_ptr; } else if ((hi - left_ptr) <= MAX_THRESH) hi = right_ptr; else if ((right_ptr - lo) > (hi - left_ptr)) { PUSH (lo, right_ptr); lo = left_ptr; } else { PUSH (left_ptr, hi); hi = right_ptr; } } } /* Once the BASE_PTR array is partially sorted by quicksort the rest is completely sorted using insertion sort, since this is efficient for partitions below MAX_THRESH size. BASE_PTR points to the beginning of the array to sort, and END_PTR points at the very last element in the array (*not* one beyond it!). */ #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) { int end_ptr = base_ptr + total_elems - 1; int run_ptr; int tmp_ptr = base_ptr; int thresh = MIN (end_ptr, base_ptr + MAX_THRESH); for (run_ptr = tmp_ptr + 1; run_ptr <= thresh; run_ptr++) if (CMP (v[run_ptr], v[tmp_ptr])) tmp_ptr = run_ptr; if (tmp_ptr != base_ptr) { swap_int(v[tmp_ptr], v[base_ptr]); SWAP_TYPE (x[tmp_ptr], x[base_ptr]); } for (run_ptr = base_ptr + 1; (tmp_ptr = run_ptr += 1) <= end_ptr;) { while (CMP (v[run_ptr], v[tmp_ptr -= 1])) ; if ((tmp_ptr += 1) != run_ptr) { int trav; for (trav = run_ptr + 1; --trav >= run_ptr;) { int c; TYPE d; c = v[trav]; d = x[trav]; int hi, lo; for (hi = lo = trav; (lo -= 1) >= tmp_ptr; hi = lo) { v[hi] = v[lo]; x[hi] = x[lo]; } v[hi] = c; x[hi] = d; } } } } return 1; }
[ [ [ 1, 380 ] ] ]
8baa3c305b7a1a31c0c700c28a7311450ba26cbf
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/microtcl/tclObj.cc
303e7a283a0d9065b30fb7895a646a6f350bcd34
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
69,818
cc
/* * tclObj.c -- * * This file contains Tcl object-related procedures that are used by * many Tcl commands. * * Copyright (c) 1995-1997 Sun Microsystems, Inc. * Copyright (c) 1999 by Scriptics Corporation. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * */ #include "microtcl/tclInt.h" #include "microtcl/tclPort.h" /* * Table of all object types. */ static Tcl_HashTable typeTable; static int typeTableInitialized = 0; /* 0 means not yet initialized. */ TCL_DECLARE_MUTEX(tableMutex) /* * Head of the list of free Tcl_Obj structs we maintain. */ Tcl_Obj *tclFreeObjList = NULL; /* * The object allocator is single threaded. This mutex is referenced * by the TclNewObj macro, however, so must be visible. */ #ifdef TCL_THREADS Tcl_Mutex tclObjMutex; #endif /* * Pointer to a heap-allocated string of length zero that the Tcl core uses * as the value of an empty string representation for an object. This value * is shared by all new objects allocated by Tcl_NewObj. */ static char emptyString; char *tclEmptyStringRep = &emptyString; /* * The number of Tcl objects ever allocated (by Tcl_NewObj) and freed * (by TclFreeObj). */ #ifdef TCL_COMPILE_STATS long ObjsAlloced = 0; long ObjsFreed = 0; long ObjsShared[TCL_MAX_SHARED_OBJ_STATS] = { 0, 0, 0, 0, 0 }; #endif /* TCL_COMPILE_STATS */ /* * Prototypes for procedures defined later in this file: */ static int SetBooleanFromAny _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Obj *objPtr)); static int SetDoubleFromAny _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Obj *objPtr)); static int SetIntFromAny _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Obj *objPtr)); static void UpdateStringOfBoolean _ANSI_ARGS_((Tcl_Obj *objPtr)); static void UpdateStringOfDouble _ANSI_ARGS_((Tcl_Obj *objPtr)); static void UpdateStringOfInt _ANSI_ARGS_((Tcl_Obj *objPtr)); /* * Prototypes for the array hash key methods. */ static Tcl_HashEntry * AllocObjEntry _ANSI_ARGS_(( Tcl_HashTable *tablePtr, VOID *keyPtr)); static int CompareObjKeys _ANSI_ARGS_(( VOID *keyPtr, Tcl_HashEntry *hPtr)); static void FreeObjEntry _ANSI_ARGS_(( Tcl_HashEntry *hPtr)); static unsigned int HashObjKey _ANSI_ARGS_(( Tcl_HashTable *tablePtr, VOID *keyPtr)); /* * The structures below defines the Tcl object types defined in this file by * means of procedures that can be invoked by generic object code. See also * tclStringObj.c, tclListObj.c, tclByteCode.c for other type manager * implementations. */ Tcl_ObjType tclBooleanType = { "boolean", /* name */ (Tcl_FreeInternalRepProc *) NULL, /* freeIntRepProc */ (Tcl_DupInternalRepProc *) NULL, /* dupIntRepProc */ UpdateStringOfBoolean, /* updateStringProc */ SetBooleanFromAny /* setFromAnyProc */ }; Tcl_ObjType tclDoubleType = { "double", /* name */ (Tcl_FreeInternalRepProc *) NULL, /* freeIntRepProc */ (Tcl_DupInternalRepProc *) NULL, /* dupIntRepProc */ UpdateStringOfDouble, /* updateStringProc */ SetDoubleFromAny /* setFromAnyProc */ }; Tcl_ObjType tclIntType = { "int", /* name */ (Tcl_FreeInternalRepProc *) NULL, /* freeIntRepProc */ (Tcl_DupInternalRepProc *) NULL, /* dupIntRepProc */ UpdateStringOfInt, /* updateStringProc */ SetIntFromAny /* setFromAnyProc */ }; /* * The structure below defines the Tcl obj hash key type. */ Tcl_HashKeyType tclObjHashKeyType = { TCL_HASH_KEY_TYPE_VERSION, /* version */ 0, /* flags */ HashObjKey, /* hashKeyProc */ CompareObjKeys, /* compareKeysProc */ AllocObjEntry, /* allocEntryProc */ FreeObjEntry /* freeEntryProc */ }; /* *------------------------------------------------------------------------- * * TclInitObjectSubsystem -- * * This procedure is invoked to perform once-only initialization of * the type table. It also registers the object types defined in * this file. * * Results: * None. * * Side effects: * Initializes the table of defined object types "typeTable" with * builtin object types defined in this file. * *------------------------------------------------------------------------- */ void TclInitObjSubsystem() { Tcl_MutexLock(&tableMutex); typeTableInitialized = 1; Tcl_InitHashTable(&typeTable, TCL_STRING_KEYS); Tcl_MutexUnlock(&tableMutex); Tcl_RegisterObjType(&tclBooleanType); Tcl_RegisterObjType(&tclByteArrayType); Tcl_RegisterObjType(&tclDoubleType); Tcl_RegisterObjType(&tclIntType); Tcl_RegisterObjType(&tclStringType); Tcl_RegisterObjType(&tclListType); Tcl_RegisterObjType(&tclByteCodeType); Tcl_RegisterObjType(&tclProcBodyType); #ifdef TCL_COMPILE_STATS Tcl_MutexLock(&tclObjMutex); ObjsAlloced = 0; ObjsFreed = 0; { int i; for (i = 0; i < TCL_MAX_SHARED_OBJ_STATS; i++) { ObjsShared[i] = 0; } } Tcl_MutexUnlock(&tclObjMutex); #endif } /* *---------------------------------------------------------------------- * * TclFinalizeCompExecEnv -- * * This procedure is called by Tcl_Finalize to clean up the Tcl * compilation and execution environment so it can later be properly * reinitialized. * * Results: * None. * * Side effects: * Cleans up the compilation and execution environment * *---------------------------------------------------------------------- */ void TclFinalizeCompExecEnv() { Tcl_MutexLock(&tableMutex); if (typeTableInitialized) { Tcl_DeleteHashTable(&typeTable); typeTableInitialized = 0; } Tcl_MutexUnlock(&tableMutex); Tcl_MutexLock(&tclObjMutex); tclFreeObjList = NULL; Tcl_MutexUnlock(&tclObjMutex); TclFinalizeCompilation(); TclFinalizeExecution(); } /* *-------------------------------------------------------------- * * Tcl_RegisterObjType -- * * This procedure is called to register a new Tcl object type * in the table of all object types supported by Tcl. * * Results: * None. * * Side effects: * The type is registered in the Tcl type table. If there was already * a type with the same name as in typePtr, it is replaced with the * new type. * *-------------------------------------------------------------- */ void Tcl_RegisterObjType(typePtr) Tcl_ObjType *typePtr; /* Information about object type; * storage must be statically * allocated (must live forever). */ { register Tcl_HashEntry *hPtr; int new; /* * If there's already an object type with the given name, remove it. */ Tcl_MutexLock(&tableMutex); hPtr = Tcl_FindHashEntry(&typeTable, typePtr->name); if (hPtr != (Tcl_HashEntry *) NULL) { Tcl_DeleteHashEntry(hPtr); } /* * Now insert the new object type. */ hPtr = Tcl_CreateHashEntry(&typeTable, typePtr->name, &new); if (new) { Tcl_SetHashValue(hPtr, typePtr); } Tcl_MutexUnlock(&tableMutex); } /* *---------------------------------------------------------------------- * * Tcl_AppendAllObjTypes -- * * This procedure appends onto the argument object the name of each * object type as a list element. This includes the builtin object * types (e.g. int, list) as well as those added using * Tcl_NewObj. These names can be used, for example, with * Tcl_GetObjType to get pointers to the corresponding Tcl_ObjType * structures. * * Results: * The return value is normally TCL_OK; in this case the object * referenced by objPtr has each type name appended to it. If an * error occurs, TCL_ERROR is returned and the interpreter's result * holds an error message. * * Side effects: * If necessary, the object referenced by objPtr is converted into * a list object. * *---------------------------------------------------------------------- */ int Tcl_AppendAllObjTypes(interp, objPtr) Tcl_Interp *interp; /* Interpreter used for error reporting. */ Tcl_Obj *objPtr; /* Points to the Tcl object onto which the * name of each registered type is appended * as a list element. */ { register Tcl_HashEntry *hPtr; Tcl_HashSearch search; Tcl_ObjType *typePtr; int result; /* * This code assumes that types names do not contain embedded NULLs. */ Tcl_MutexLock(&tableMutex); for (hPtr = Tcl_FirstHashEntry(&typeTable, &search); hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { typePtr = (Tcl_ObjType *) Tcl_GetHashValue(hPtr); result = Tcl_ListObjAppendElement(interp, objPtr, Tcl_NewStringObj(typePtr->name, -1)); if (result == TCL_ERROR) { Tcl_MutexUnlock(&tableMutex); return result; } } Tcl_MutexUnlock(&tableMutex); return TCL_OK; } /* *---------------------------------------------------------------------- * * Tcl_GetObjType -- * * This procedure looks up an object type by name. * * Results: * If an object type with name matching "typeName" is found, a pointer * to its Tcl_ObjType structure is returned; otherwise, NULL is * returned. * * Side effects: * None. * *---------------------------------------------------------------------- */ Tcl_ObjType * Tcl_GetObjType(typeName) char *typeName; /* Name of Tcl object type to look up. */ { register Tcl_HashEntry *hPtr; Tcl_ObjType *typePtr; Tcl_MutexLock(&tableMutex); hPtr = Tcl_FindHashEntry(&typeTable, typeName); if (hPtr != (Tcl_HashEntry *) NULL) { typePtr = (Tcl_ObjType *) Tcl_GetHashValue(hPtr); Tcl_MutexUnlock(&tableMutex); return typePtr; } Tcl_MutexUnlock(&tableMutex); return NULL; } /* *---------------------------------------------------------------------- * * Tcl_ConvertToType -- * * Convert the Tcl object "objPtr" to have type "typePtr" if possible. * * Results: * The return value is TCL_OK on success and TCL_ERROR on failure. If * TCL_ERROR is returned, then the interpreter's result contains an * error message unless "interp" is NULL. Passing a NULL "interp" * allows this procedure to be used as a test whether the conversion * could be done (and in fact was done). * * Side effects: * Any internal representation for the old type is freed. * *---------------------------------------------------------------------- */ int Tcl_ConvertToType(interp, objPtr, typePtr) Tcl_Interp *interp; /* Used for error reporting if not NULL. */ Tcl_Obj *objPtr; /* The object to convert. */ Tcl_ObjType *typePtr; /* The target type. */ { if (objPtr->typePtr == typePtr) { return TCL_OK; } /* * Use the target type's Tcl_SetFromAnyProc to set "objPtr"s internal * form as appropriate for the target type. This frees the old internal * representation. */ return typePtr->setFromAnyProc(interp, objPtr); } /* *---------------------------------------------------------------------- * * Tcl_NewObj -- * * This procedure is normally called when not debugging: i.e., when * TCL_MEM_DEBUG is not defined. It creates new Tcl objects that denote * the empty string. These objects have a NULL object type and NULL * string representation byte pointer. Type managers call this routine * to allocate new objects that they further initialize. * * When TCL_MEM_DEBUG is defined, this procedure just returns the * result of calling the debugging version Tcl_DbNewObj. * * Results: * The result is a newly allocated object that represents the empty * string. The new object's typePtr is set NULL and its ref count * is set to 0. * * Side effects: * If compiling with TCL_COMPILE_STATS, this procedure increments * the global count of allocated objects (ObjsAlloced). * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG #undef Tcl_NewObj Tcl_Obj * Tcl_NewObj() { return Tcl_DbNewObj("unknown", 0); } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_NewObj() { register Tcl_Obj *objPtr; /* * Allocate the object using the list of free Tcl_Obj structs * we maintain. */ Tcl_MutexLock(&tclObjMutex); if (tclFreeObjList == NULL) { TclAllocateFreeObjects(); } objPtr = tclFreeObjList; tclFreeObjList = (Tcl_Obj *) tclFreeObjList->internalRep.otherValuePtr; objPtr->refCount = 0; objPtr->bytes = tclEmptyStringRep; objPtr->length = 0; objPtr->typePtr = NULL; #ifdef TCL_COMPILE_STATS ObjsAlloced++; #endif /* TCL_COMPILE_STATS */ Tcl_MutexUnlock(&tclObjMutex); return objPtr; } #endif /* TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * Tcl_DbNewObj -- * * This procedure is normally called when debugging: i.e., when * TCL_MEM_DEBUG is defined. It creates new Tcl objects that denote the * empty string. It is the same as the Tcl_NewObj procedure above * except that it calls Tcl_DbCkalloc directly with the file name and * line number from its caller. This simplifies debugging since then * the checkmem command will report the correct file name and line * number when reporting objects that haven't been freed. * * When TCL_MEM_DEBUG is not defined, this procedure just returns the * result of calling Tcl_NewObj. * * Results: * The result is a newly allocated that represents the empty string. * The new object's typePtr is set NULL and its ref count is set to 0. * * Side effects: * If compiling with TCL_COMPILE_STATS, this procedure increments * the global count of allocated objects (ObjsAlloced). * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG Tcl_Obj * Tcl_DbNewObj(file, line) register char *file; /* The name of the source file calling this * procedure; used for debugging. */ register int line; /* Line number in the source file; used * for debugging. */ { register Tcl_Obj *objPtr; /* * If debugging Tcl's memory usage, allocate the object using ckalloc. * Otherwise, allocate it using the list of free Tcl_Obj structs we * maintain. */ objPtr = (Tcl_Obj *) Tcl_DbCkalloc(sizeof(Tcl_Obj), file, line); objPtr->refCount = 0; objPtr->bytes = tclEmptyStringRep; objPtr->length = 0; objPtr->typePtr = NULL; #ifdef TCL_COMPILE_STATS Tcl_MutexLock(&tclObjMutex); ObjsAlloced++; Tcl_MutexUnlock(&tclObjMutex); #endif /* TCL_COMPILE_STATS */ return objPtr; } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_DbNewObj(file, line) char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { return Tcl_NewObj(); } #endif /* TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * TclAllocateFreeObjects -- * * Procedure to allocate a number of free Tcl_Objs. This is done using * a single ckalloc to reduce the overhead for Tcl_Obj allocation. * * Assumes mutex is held. * * Results: * None. * * Side effects: * tclFreeObjList, the head of the list of free Tcl_Objs, is set to the * first of a number of free Tcl_Obj's linked together by their * internalRep.otherValuePtrs. * *---------------------------------------------------------------------- */ #define OBJS_TO_ALLOC_EACH_TIME 100 void TclAllocateFreeObjects() { Tcl_Obj tmp[2]; size_t objSizePlusPadding = /* NB: this assumes byte addressing. */ ((int)(&(tmp[1])) - (int)(&(tmp[0]))); size_t bytesToAlloc = (OBJS_TO_ALLOC_EACH_TIME * objSizePlusPadding); char *basePtr; register Tcl_Obj *prevPtr, *objPtr; register int i; basePtr = (char *) ckalloc(bytesToAlloc); memset(basePtr, 0, bytesToAlloc); prevPtr = NULL; objPtr = (Tcl_Obj *) basePtr; for (i = 0; i < OBJS_TO_ALLOC_EACH_TIME; i++) { objPtr->internalRep.otherValuePtr = (VOID *) prevPtr; prevPtr = objPtr; objPtr = (Tcl_Obj *) (((char *)objPtr) + objSizePlusPadding); } tclFreeObjList = prevPtr; } #undef OBJS_TO_ALLOC_EACH_TIME /* *---------------------------------------------------------------------- * * TclFreeObj -- * * This procedure frees the memory associated with the argument * object. It is called by the tcl.h macro Tcl_DecrRefCount when an * object's ref count is zero. It is only "public" since it must * be callable by that macro wherever the macro is used. It should not * be directly called by clients. * * Results: * None. * * Side effects: * Deallocates the storage for the object's Tcl_Obj structure * after deallocating the string representation and calling the * type-specific Tcl_FreeInternalRepProc to deallocate the object's * internal representation. If compiling with TCL_COMPILE_STATS, * this procedure increments the global count of freed objects * (ObjsFreed). * *---------------------------------------------------------------------- */ void TclFreeObj(objPtr) register Tcl_Obj *objPtr; /* The object to be freed. */ { register Tcl_ObjType *typePtr = objPtr->typePtr; #ifdef TCL_MEM_DEBUG if ((objPtr)->refCount < -1) { panic("Reference count for %lx was negative", objPtr); } #endif /* TCL_MEM_DEBUG */ if ((typePtr != NULL) && (typePtr->freeIntRepProc != NULL)) { typePtr->freeIntRepProc(objPtr); } Tcl_InvalidateStringRep(objPtr); /* * If debugging Tcl's memory usage, deallocate the object using ckfree. * Otherwise, deallocate it by adding it onto the list of free * Tcl_Obj structs we maintain. */ Tcl_MutexLock(&tclObjMutex); #ifdef TCL_MEM_DEBUG ckfree((char *) objPtr); #else objPtr->internalRep.otherValuePtr = (VOID *) tclFreeObjList; tclFreeObjList = objPtr; #endif /* TCL_MEM_DEBUG */ #ifdef TCL_COMPILE_STATS ObjsFreed++; #endif /* TCL_COMPILE_STATS */ Tcl_MutexUnlock(&tclObjMutex); } /* *---------------------------------------------------------------------- * * Tcl_DuplicateObj -- * * Create and return a new object that is a duplicate of the argument * object. * * Results: * The return value is a pointer to a newly created Tcl_Obj. This * object has reference count 0 and the same type, if any, as the * source object objPtr. Also: * 1) If the source object has a valid string rep, we copy it; * otherwise, the duplicate's string rep is set NULL to mark * it invalid. * 2) If the source object has an internal representation (i.e. its * typePtr is non-NULL), the new object's internal rep is set to * a copy; otherwise the new internal rep is marked invalid. * * Side effects: * What constitutes "copying" the internal representation depends on * the type. For example, if the argument object is a list, * the element objects it points to will not actually be copied but * will be shared with the duplicate list. That is, the ref counts of * the element objects will be incremented. * *---------------------------------------------------------------------- */ Tcl_Obj * Tcl_DuplicateObj(objPtr) register Tcl_Obj *objPtr; /* The object to duplicate. */ { register Tcl_ObjType *typePtr = objPtr->typePtr; register Tcl_Obj *dupPtr; TclNewObj(dupPtr); if (objPtr->bytes == NULL) { dupPtr->bytes = NULL; } else if (objPtr->bytes != tclEmptyStringRep) { TclInitStringRep(dupPtr, objPtr->bytes, objPtr->length); } if (typePtr != NULL) { if (typePtr->dupIntRepProc == NULL) { dupPtr->internalRep = objPtr->internalRep; dupPtr->typePtr = typePtr; } else { (*typePtr->dupIntRepProc)(objPtr, dupPtr); } } return dupPtr; } /* *---------------------------------------------------------------------- * * Tcl_GetString -- * * Returns the string representation byte array pointer for an object. * * Results: * Returns a pointer to the string representation of objPtr. The byte * array referenced by the returned pointer must not be modified by the * caller. Furthermore, the caller must copy the bytes if they need to * retain them since the object's string rep can change as a result of * other operations. * * Side effects: * May call the object's updateStringProc to update the string * representation from the internal representation. * *---------------------------------------------------------------------- */ char * Tcl_GetString(objPtr) register Tcl_Obj *objPtr; /* Object whose string rep byte pointer * should be returned. */ { if (objPtr->bytes != NULL) { return objPtr->bytes; } if (objPtr->typePtr->updateStringProc == NULL) { panic("UpdateStringProc should not be invoked for type %s", objPtr->typePtr->name); } (*objPtr->typePtr->updateStringProc)(objPtr); return objPtr->bytes; } /* *---------------------------------------------------------------------- * * Tcl_GetStringFromObj -- * * Returns the string representation's byte array pointer and length * for an object. * * Results: * Returns a pointer to the string representation of objPtr. If * lengthPtr isn't NULL, the length of the string representation is * stored at *lengthPtr. The byte array referenced by the returned * pointer must not be modified by the caller. Furthermore, the * caller must copy the bytes if they need to retain them since the * object's string rep can change as a result of other operations. * * Side effects: * May call the object's updateStringProc to update the string * representation from the internal representation. * *---------------------------------------------------------------------- */ char * Tcl_GetStringFromObj(objPtr, lengthPtr) register Tcl_Obj *objPtr; /* Object whose string rep byte pointer * should be returned. */ register int *lengthPtr; /* If non-NULL, the location where the * string rep's byte array length should be * stored. If NULL, no length is stored. */ { if (objPtr->bytes != NULL) { if (lengthPtr != NULL) { *lengthPtr = objPtr->length; } return objPtr->bytes; } if (objPtr->typePtr->updateStringProc == NULL) { panic("UpdateStringProc should not be invoked for type %s", objPtr->typePtr->name); } (*objPtr->typePtr->updateStringProc)(objPtr); if (lengthPtr != NULL) { *lengthPtr = objPtr->length; } return objPtr->bytes; } /* *---------------------------------------------------------------------- * * Tcl_InvalidateStringRep -- * * This procedure is called to invalidate an object's string * representation. * * Results: * None. * * Side effects: * Deallocates the storage for any old string representation, then * sets the string representation NULL to mark it invalid. * *---------------------------------------------------------------------- */ void Tcl_InvalidateStringRep(objPtr) register Tcl_Obj *objPtr; /* Object whose string rep byte pointer * should be freed. */ { if (objPtr->bytes != NULL) { if (objPtr->bytes != tclEmptyStringRep) { ckfree((char *) objPtr->bytes); } objPtr->bytes = NULL; } } /* *---------------------------------------------------------------------- * * Tcl_NewBooleanObj -- * * This procedure is normally called when not debugging: i.e., when * TCL_MEM_DEBUG is not defined. It creates a new boolean object and * initializes it from the argument boolean value. A nonzero * "boolValue" is coerced to 1. * * When TCL_MEM_DEBUG is defined, this procedure just returns the * result of calling the debugging version Tcl_DbNewBooleanObj. * * Results: * The newly created object is returned. This object will have an * invalid string representation. The returned object has ref count 0. * * Side effects: * None. * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG #undef Tcl_NewBooleanObj Tcl_Obj * Tcl_NewBooleanObj(boolValue) register int boolValue; /* Boolean used to initialize new object. */ { return Tcl_DbNewBooleanObj(boolValue, "unknown", 0); } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_NewBooleanObj(boolValue) register int boolValue; /* Boolean used to initialize new object. */ { register Tcl_Obj *objPtr; TclNewObj(objPtr); objPtr->bytes = NULL; objPtr->internalRep.longValue = (boolValue? 1 : 0); objPtr->typePtr = &tclBooleanType; return objPtr; } #endif /* TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * Tcl_DbNewBooleanObj -- * * This procedure is normally called when debugging: i.e., when * TCL_MEM_DEBUG is defined. It creates new boolean objects. It is the * same as the Tcl_NewBooleanObj procedure above except that it calls * Tcl_DbCkalloc directly with the file name and line number from its * caller. This simplifies debugging since then the checkmem command * will report the correct file name and line number when reporting * objects that haven't been freed. * * When TCL_MEM_DEBUG is not defined, this procedure just returns the * result of calling Tcl_NewBooleanObj. * * Results: * The newly created object is returned. This object will have an * invalid string representation. The returned object has ref count 0. * * Side effects: * None. * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG Tcl_Obj * Tcl_DbNewBooleanObj(boolValue, file, line) register int boolValue; /* Boolean used to initialize new object. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { register Tcl_Obj *objPtr; TclDbNewObj(objPtr, file, line); objPtr->bytes = NULL; objPtr->internalRep.longValue = (boolValue? 1 : 0); objPtr->typePtr = &tclBooleanType; return objPtr; } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_DbNewBooleanObj(boolValue, file, line) register int boolValue; /* Boolean used to initialize new object. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { return Tcl_NewBooleanObj(boolValue); } #endif /* TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * Tcl_SetBooleanObj -- * * Modify an object to be a boolean object and to have the specified * boolean value. A nonzero "boolValue" is coerced to 1. * * Results: * None. * * Side effects: * The object's old string rep, if any, is freed. Also, any old * internal rep is freed. * *---------------------------------------------------------------------- */ void Tcl_SetBooleanObj(objPtr, boolValue) register Tcl_Obj *objPtr; /* Object whose internal rep to init. */ register int boolValue; /* Boolean used to set object's value. */ { register Tcl_ObjType *oldTypePtr = objPtr->typePtr; if (Tcl_IsShared(objPtr)) { panic("Tcl_SetBooleanObj called with shared object"); } if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) { oldTypePtr->freeIntRepProc(objPtr); } objPtr->internalRep.longValue = (boolValue? 1 : 0); objPtr->typePtr = &tclBooleanType; Tcl_InvalidateStringRep(objPtr); } /* *---------------------------------------------------------------------- * * Tcl_GetBooleanFromObj -- * * Attempt to return a boolean from the Tcl object "objPtr". If the * object is not already a boolean, an attempt will be made to convert * it to one. * * Results: * The return value is a standard Tcl object result. If an error occurs * during conversion, an error message is left in the interpreter's * result unless "interp" is NULL. * * Side effects: * If the object is not already a boolean, the conversion will free * any old internal representation. * *---------------------------------------------------------------------- */ int Tcl_GetBooleanFromObj(interp, objPtr, boolPtr) Tcl_Interp *interp; /* Used for error reporting if not NULL. */ register Tcl_Obj *objPtr; /* The object from which to get boolean. */ register int *boolPtr; /* Place to store resulting boolean. */ { register int result; result = SetBooleanFromAny(interp, objPtr); if (result == TCL_OK) { *boolPtr = (int) objPtr->internalRep.longValue; } return result; } /* *---------------------------------------------------------------------- * * SetBooleanFromAny -- * * Attempt to generate a boolean internal form for the Tcl object * "objPtr". * * Results: * The return value is a standard Tcl result. If an error occurs during * conversion, an error message is left in the interpreter's result * unless "interp" is NULL. * * Side effects: * If no error occurs, an integer 1 or 0 is stored as "objPtr"s * internal representation and the type of "objPtr" is set to boolean. * *---------------------------------------------------------------------- */ static int SetBooleanFromAny(interp, objPtr) Tcl_Interp *interp; /* Used for error reporting if not NULL. */ register Tcl_Obj *objPtr; /* The object to convert. */ { Tcl_ObjType *oldTypePtr = objPtr->typePtr; char *string, *end; register char c; char lowerCase[10]; int newBool, length; register int i; double dbl; /* * Get the string representation. Make it up-to-date if necessary. */ string = Tcl_GetStringFromObj(objPtr, &length); /* * Copy the string converting its characters to lower case. */ for (i = 0; (i < 9) && (i < length); i++) { c = string[i]; /* * Weed out international characters so we can safely operate * on single bytes. */ if (c & 0x80) { goto badBoolean; } if (Tcl_UniCharIsUpper(UCHAR(c))) { c = (char) Tcl_UniCharToLower(UCHAR(c)); } lowerCase[i] = c; } lowerCase[i] = 0; /* * Parse the string as a boolean. We use an implementation here that * doesn't report errors in interp if interp is NULL. */ c = lowerCase[0]; if ((c == '0') && (lowerCase[1] == '\0')) { newBool = 0; } else if ((c == '1') && (lowerCase[1] == '\0')) { newBool = 1; } else if ((c == 'y') && (strncmp(lowerCase, "yes", (size_t) length) == 0)) { newBool = 1; } else if ((c == 'n') && (strncmp(lowerCase, "no", (size_t) length) == 0)) { newBool = 0; } else if ((c == 't') && (strncmp(lowerCase, "true", (size_t) length) == 0)) { newBool = 1; } else if ((c == 'f') && (strncmp(lowerCase, "false", (size_t) length) == 0)) { newBool = 0; } else if ((c == 'o') && (length >= 2)) { if (strncmp(lowerCase, "on", (size_t) length) == 0) { newBool = 1; } else if (strncmp(lowerCase, "off", (size_t) length) == 0) { newBool = 0; } else { goto badBoolean; } } else { /* * Still might be a string containing the characters representing an * int or double that wasn't handled above. This would be a string * like "27" or "1.0" that is non-zero and not "1". Such a string * whould result in the boolean value true. We try converting to * double. If that succeeds and the resulting double is non-zero, we * have a "true". Note that numbers can't have embedded NULLs. */ dbl = strtod(string, &end); if (end == string) { goto badBoolean; } /* * Make sure the string has no garbage after the end of the double. */ while ((end < (string+length)) && isspace(UCHAR(*end))) { /* INTL: ISO only */ end++; } if (end != (string+length)) { goto badBoolean; } newBool = (dbl != 0.0); } /* * Free the old internalRep before setting the new one. We do this as * late as possible to allow the conversion code, in particular * Tcl_GetStringFromObj, to use that old internalRep. */ if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) { oldTypePtr->freeIntRepProc(objPtr); } objPtr->internalRep.longValue = newBool; objPtr->typePtr = &tclBooleanType; return TCL_OK; badBoolean: if (interp != NULL) { /* * Must copy string before resetting the result in case a caller * is trying to convert the interpreter's result to a boolean. */ char buf[100]; sprintf(buf, "expected boolean value but got \"%.50s\"", string); Tcl_ResetResult(interp); Tcl_AppendToObj(Tcl_GetObjResult(interp), buf, -1); } return TCL_ERROR; } /* *---------------------------------------------------------------------- * * UpdateStringOfBoolean -- * * Update the string representation for a boolean object. * Note: This procedure does not free an existing old string rep * so storage will be lost if this has not already been done. * * Results: * None. * * Side effects: * The object's string is set to a valid string that results from * the boolean-to-string conversion. * *---------------------------------------------------------------------- */ static void UpdateStringOfBoolean(objPtr) register Tcl_Obj *objPtr; /* Int object whose string rep to update. */ { char *s = ckalloc((unsigned) 2); s[0] = (char) (objPtr->internalRep.longValue? '1' : '0'); s[1] = '\0'; objPtr->bytes = s; objPtr->length = 1; } /* *---------------------------------------------------------------------- * * Tcl_NewDoubleObj -- * * This procedure is normally called when not debugging: i.e., when * TCL_MEM_DEBUG is not defined. It creates a new double object and * initializes it from the argument double value. * * When TCL_MEM_DEBUG is defined, this procedure just returns the * result of calling the debugging version Tcl_DbNewDoubleObj. * * Results: * The newly created object is returned. This object will have an * invalid string representation. The returned object has ref count 0. * * Side effects: * None. * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG #undef Tcl_NewDoubleObj Tcl_Obj * Tcl_NewDoubleObj(dblValue) register double dblValue; /* Double used to initialize the object. */ { return Tcl_DbNewDoubleObj(dblValue, "unknown", 0); } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_NewDoubleObj(dblValue) register double dblValue; /* Double used to initialize the object. */ { register Tcl_Obj *objPtr; TclNewObj(objPtr); objPtr->bytes = NULL; objPtr->internalRep.doubleValue = dblValue; objPtr->typePtr = &tclDoubleType; return objPtr; } #endif /* if TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * Tcl_DbNewDoubleObj -- * * This procedure is normally called when debugging: i.e., when * TCL_MEM_DEBUG is defined. It creates new double objects. It is the * same as the Tcl_NewDoubleObj procedure above except that it calls * Tcl_DbCkalloc directly with the file name and line number from its * caller. This simplifies debugging since then the checkmem command * will report the correct file name and line number when reporting * objects that haven't been freed. * * When TCL_MEM_DEBUG is not defined, this procedure just returns the * result of calling Tcl_NewDoubleObj. * * Results: * The newly created object is returned. This object will have an * invalid string representation. The returned object has ref count 0. * * Side effects: * None. * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG Tcl_Obj * Tcl_DbNewDoubleObj(dblValue, file, line) register double dblValue; /* Double used to initialize the object. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { register Tcl_Obj *objPtr; TclDbNewObj(objPtr, file, line); objPtr->bytes = NULL; objPtr->internalRep.doubleValue = dblValue; objPtr->typePtr = &tclDoubleType; return objPtr; } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_DbNewDoubleObj(dblValue, file, line) register double dblValue; /* Double used to initialize the object. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { return Tcl_NewDoubleObj(dblValue); } #endif /* TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * Tcl_SetDoubleObj -- * * Modify an object to be a double object and to have the specified * double value. * * Results: * None. * * Side effects: * The object's old string rep, if any, is freed. Also, any old * internal rep is freed. * *---------------------------------------------------------------------- */ void Tcl_SetDoubleObj(objPtr, dblValue) register Tcl_Obj *objPtr; /* Object whose internal rep to init. */ register double dblValue; /* Double used to set the object's value. */ { register Tcl_ObjType *oldTypePtr = objPtr->typePtr; if (Tcl_IsShared(objPtr)) { panic("Tcl_SetDoubleObj called with shared object"); } if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) { oldTypePtr->freeIntRepProc(objPtr); } objPtr->internalRep.doubleValue = dblValue; objPtr->typePtr = &tclDoubleType; Tcl_InvalidateStringRep(objPtr); } /* *---------------------------------------------------------------------- * * Tcl_GetDoubleFromObj -- * * Attempt to return a double from the Tcl object "objPtr". If the * object is not already a double, an attempt will be made to convert * it to one. * * Results: * The return value is a standard Tcl object result. If an error occurs * during conversion, an error message is left in the interpreter's * result unless "interp" is NULL. * * Side effects: * If the object is not already a double, the conversion will free * any old internal representation. * *---------------------------------------------------------------------- */ int Tcl_GetDoubleFromObj(interp, objPtr, dblPtr) Tcl_Interp *interp; /* Used for error reporting if not NULL. */ register Tcl_Obj *objPtr; /* The object from which to get a double. */ register double *dblPtr; /* Place to store resulting double. */ { register int result; if (objPtr->typePtr == &tclDoubleType) { *dblPtr = objPtr->internalRep.doubleValue; return TCL_OK; } result = SetDoubleFromAny(interp, objPtr); if (result == TCL_OK) { *dblPtr = objPtr->internalRep.doubleValue; } return result; } /* *---------------------------------------------------------------------- * * SetDoubleFromAny -- * * Attempt to generate an double-precision floating point internal form * for the Tcl object "objPtr". * * Results: * The return value is a standard Tcl object result. If an error occurs * during conversion, an error message is left in the interpreter's * result unless "interp" is NULL. * * Side effects: * If no error occurs, a double is stored as "objPtr"s internal * representation. * *---------------------------------------------------------------------- */ static int SetDoubleFromAny(interp, objPtr) Tcl_Interp *interp; /* Used for error reporting if not NULL. */ register Tcl_Obj *objPtr; /* The object to convert. */ { Tcl_ObjType *oldTypePtr = objPtr->typePtr; char *string, *end; double newDouble; int length; /* * Get the string representation. Make it up-to-date if necessary. */ string = Tcl_GetStringFromObj(objPtr, &length); /* * Now parse "objPtr"s string as an double. Numbers can't have embedded * NULLs. We use an implementation here that doesn't report errors in * interp if interp is NULL. */ errno = 0; newDouble = strtod(string, &end); if (end == string) { badDouble: if (interp != NULL) { /* * Must copy string before resetting the result in case a caller * is trying to convert the interpreter's result to an int. */ char buf[100]; sprintf(buf, "expected floating-point number but got \"%.50s\"", string); Tcl_ResetResult(interp); Tcl_AppendToObj(Tcl_GetObjResult(interp), buf, -1); } return TCL_ERROR; } if (errno != 0) { if (interp != NULL) { TclExprFloatError(interp, newDouble); } return TCL_ERROR; } /* * Make sure that the string has no garbage after the end of the double. */ while ((end < (string+length)) && isspace(UCHAR(*end))) { /* INTL: ISO space. */ end++; } if (end != (string+length)) { goto badDouble; } /* * The conversion to double succeeded. Free the old internalRep before * setting the new one. We do this as late as possible to allow the * conversion code, in particular Tcl_GetStringFromObj, to use that old * internalRep. */ if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) { oldTypePtr->freeIntRepProc(objPtr); } objPtr->internalRep.doubleValue = newDouble; objPtr->typePtr = &tclDoubleType; return TCL_OK; } /* *---------------------------------------------------------------------- * * UpdateStringOfDouble -- * * Update the string representation for a double-precision floating * point object. This must obey the current tcl_precision value for * double-to-string conversions. Note: This procedure does not free an * existing old string rep so storage will be lost if this has not * already been done. * * Results: * None. * * Side effects: * The object's string is set to a valid string that results from * the double-to-string conversion. * *---------------------------------------------------------------------- */ static void UpdateStringOfDouble(objPtr) register Tcl_Obj *objPtr; /* Double obj with string rep to update. */ { char buffer[TCL_DOUBLE_SPACE]; register int len; Tcl_PrintDouble((Tcl_Interp *) NULL, objPtr->internalRep.doubleValue, buffer); len = strlen(buffer); objPtr->bytes = (char *) ckalloc((unsigned) len + 1); strcpy(objPtr->bytes, buffer); objPtr->length = len; } /* *---------------------------------------------------------------------- * * Tcl_NewIntObj -- * * If a client is compiled with TCL_MEM_DEBUG defined, calls to * Tcl_NewIntObj to create a new integer object end up calling the * debugging procedure Tcl_DbNewLongObj instead. * * Otherwise, if the client is compiled without TCL_MEM_DEBUG defined, * calls to Tcl_NewIntObj result in a call to one of the two * Tcl_NewIntObj implementations below. We provide two implementations * so that the Tcl core can be compiled to do memory debugging of the * core even if a client does not request it for itself. * * Integer and long integer objects share the same "integer" type * implementation. We store all integers as longs and Tcl_GetIntFromObj * checks whether the current value of the long can be represented by * an int. * * Results: * The newly created object is returned. This object will have an * invalid string representation. The returned object has ref count 0. * * Side effects: * None. * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG #undef Tcl_NewIntObj Tcl_Obj * Tcl_NewIntObj(intValue) register int intValue; /* Int used to initialize the new object. */ { return Tcl_DbNewLongObj((long)intValue, "unknown", 0); } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_NewIntObj(intValue) register int intValue; /* Int used to initialize the new object. */ { register Tcl_Obj *objPtr; TclNewObj(objPtr); objPtr->bytes = NULL; objPtr->internalRep.longValue = (long)intValue; objPtr->typePtr = &tclIntType; return objPtr; } #endif /* if TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * Tcl_SetIntObj -- * * Modify an object to be an integer and to have the specified integer * value. * * Results: * None. * * Side effects: * The object's old string rep, if any, is freed. Also, any old * internal rep is freed. * *---------------------------------------------------------------------- */ void Tcl_SetIntObj(objPtr, intValue) register Tcl_Obj *objPtr; /* Object whose internal rep to init. */ register int intValue; /* Integer used to set object's value. */ { register Tcl_ObjType *oldTypePtr = objPtr->typePtr; if (Tcl_IsShared(objPtr)) { panic("Tcl_SetIntObj called with shared object"); } if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) { oldTypePtr->freeIntRepProc(objPtr); } objPtr->internalRep.longValue = (long) intValue; objPtr->typePtr = &tclIntType; Tcl_InvalidateStringRep(objPtr); } /* *---------------------------------------------------------------------- * * Tcl_GetIntFromObj -- * * Attempt to return an int from the Tcl object "objPtr". If the object * is not already an int, an attempt will be made to convert it to one. * * Integer and long integer objects share the same "integer" type * implementation. We store all integers as longs and Tcl_GetIntFromObj * checks whether the current value of the long can be represented by * an int. * * Results: * The return value is a standard Tcl object result. If an error occurs * during conversion or if the long integer held by the object * can not be represented by an int, an error message is left in * the interpreter's result unless "interp" is NULL. * * Side effects: * If the object is not already an int, the conversion will free * any old internal representation. * *---------------------------------------------------------------------- */ int Tcl_GetIntFromObj(interp, objPtr, intPtr) Tcl_Interp *interp; /* Used for error reporting if not NULL. */ register Tcl_Obj *objPtr; /* The object from which to get a int. */ register int *intPtr; /* Place to store resulting int. */ { register long l; int result; if (objPtr->typePtr != &tclIntType) { result = SetIntFromAny(interp, objPtr); if (result != TCL_OK) { return result; } } l = objPtr->internalRep.longValue; if (((long)((int)l)) == l) { *intPtr = (int)objPtr->internalRep.longValue; return TCL_OK; } if (interp != NULL) { Tcl_ResetResult(interp); Tcl_AppendToObj(Tcl_GetObjResult(interp), "integer value too large to represent as non-long integer", -1); } return TCL_ERROR; } /* *---------------------------------------------------------------------- * * SetIntFromAny -- * * Attempt to generate an integer internal form for the Tcl object * "objPtr". * * Results: * The return value is a standard object Tcl result. If an error occurs * during conversion, an error message is left in the interpreter's * result unless "interp" is NULL. * * Side effects: * If no error occurs, an int is stored as "objPtr"s internal * representation. * *---------------------------------------------------------------------- */ static int SetIntFromAny(interp, objPtr) Tcl_Interp *interp; /* Used for error reporting if not NULL. */ register Tcl_Obj *objPtr; /* The object to convert. */ { Tcl_ObjType *oldTypePtr = objPtr->typePtr; char *string, *end; int length; register char *p; long newLong; /* * Get the string representation. Make it up-to-date if necessary. */ string = Tcl_GetStringFromObj(objPtr, &length); /* * Now parse "objPtr"s string as an int. We use an implementation here * that doesn't report errors in interp if interp is NULL. Note: use * strtoul instead of strtol for integer conversions to allow full-size * unsigned numbers, but don't depend on strtoul to handle sign * characters; it won't in some implementations. */ errno = 0; for (p = string; isspace(UCHAR(*p)); p++) { /* INTL: ISO space. */ /* Empty loop body. */ } if (*p == '-') { p++; newLong = -((long)strtoul(p, &end, 0)); } else if (*p == '+') { p++; newLong = strtoul(p, &end, 0); } else { newLong = strtoul(p, &end, 0); } if (end == p) { badInteger: if (interp != NULL) { /* * Must copy string before resetting the result in case a caller * is trying to convert the interpreter's result to an int. */ char buf[100]; sprintf(buf, "expected integer but got \"%.50s\"", string); Tcl_ResetResult(interp); Tcl_AppendToObj(Tcl_GetObjResult(interp), buf, -1); TclCheckBadOctal(interp, string); } return TCL_ERROR; } if (errno == ERANGE) { if (interp != NULL) { char *s = "integer value too large to represent"; Tcl_ResetResult(interp); Tcl_AppendToObj(Tcl_GetObjResult(interp), s, -1); Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW", s, (char *) NULL); } return TCL_ERROR; } /* * Make sure that the string has no garbage after the end of the int. */ while ((end < (string+length)) && isspace(UCHAR(*end))) { /* INTL: ISO space. */ end++; } if (end != (string+length)) { goto badInteger; } /* * The conversion to int succeeded. Free the old internalRep before * setting the new one. We do this as late as possible to allow the * conversion code, in particular Tcl_GetStringFromObj, to use that old * internalRep. */ if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) { oldTypePtr->freeIntRepProc(objPtr); } objPtr->internalRep.longValue = newLong; objPtr->typePtr = &tclIntType; return TCL_OK; } /* *---------------------------------------------------------------------- * * UpdateStringOfInt -- * * Update the string representation for an integer object. * Note: This procedure does not free an existing old string rep * so storage will be lost if this has not already been done. * * Results: * None. * * Side effects: * The object's string is set to a valid string that results from * the int-to-string conversion. * *---------------------------------------------------------------------- */ static void UpdateStringOfInt(objPtr) register Tcl_Obj *objPtr; /* Int object whose string rep to update. */ { char buffer[TCL_INTEGER_SPACE]; register int len; len = TclFormatInt(buffer, objPtr->internalRep.longValue); objPtr->bytes = ckalloc((unsigned) len + 1); strcpy(objPtr->bytes, buffer); objPtr->length = len; } /* *---------------------------------------------------------------------- * * Tcl_NewLongObj -- * * If a client is compiled with TCL_MEM_DEBUG defined, calls to * Tcl_NewLongObj to create a new long integer object end up calling * the debugging procedure Tcl_DbNewLongObj instead. * * Otherwise, if the client is compiled without TCL_MEM_DEBUG defined, * calls to Tcl_NewLongObj result in a call to one of the two * Tcl_NewLongObj implementations below. We provide two implementations * so that the Tcl core can be compiled to do memory debugging of the * core even if a client does not request it for itself. * * Integer and long integer objects share the same "integer" type * implementation. We store all integers as longs and Tcl_GetIntFromObj * checks whether the current value of the long can be represented by * an int. * * Results: * The newly created object is returned. This object will have an * invalid string representation. The returned object has ref count 0. * * Side effects: * None. * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG #undef Tcl_NewLongObj Tcl_Obj * Tcl_NewLongObj(longValue) register long longValue; /* Long integer used to initialize the * new object. */ { return Tcl_DbNewLongObj(longValue, "unknown", 0); } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_NewLongObj(longValue) register long longValue; /* Long integer used to initialize the * new object. */ { register Tcl_Obj *objPtr; TclNewObj(objPtr); objPtr->bytes = NULL; objPtr->internalRep.longValue = longValue; objPtr->typePtr = &tclIntType; return objPtr; } #endif /* if TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * Tcl_DbNewLongObj -- * * If a client is compiled with TCL_MEM_DEBUG defined, calls to * Tcl_NewIntObj and Tcl_NewLongObj to create new integer or * long integer objects end up calling the debugging procedure * Tcl_DbNewLongObj instead. We provide two implementations of * Tcl_DbNewLongObj so that whether the Tcl core is compiled to do * memory debugging of the core is independent of whether a client * requests debugging for itself. * * When the core is compiled with TCL_MEM_DEBUG defined, * Tcl_DbNewLongObj calls Tcl_DbCkalloc directly with the file name and * line number from its caller. This simplifies debugging since then * the checkmem command will report the caller's file name and line * number when reporting objects that haven't been freed. * * Otherwise, when the core is compiled without TCL_MEM_DEBUG defined, * this procedure just returns the result of calling Tcl_NewLongObj. * * Results: * The newly created long integer object is returned. This object * will have an invalid string representation. The returned object has * ref count 0. * * Side effects: * Allocates memory. * *---------------------------------------------------------------------- */ #ifdef TCL_MEM_DEBUG Tcl_Obj * Tcl_DbNewLongObj(longValue, file, line) register long longValue; /* Long integer used to initialize the * new object. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { register Tcl_Obj *objPtr; TclDbNewObj(objPtr, file, line); objPtr->bytes = NULL; objPtr->internalRep.longValue = longValue; objPtr->typePtr = &tclIntType; return objPtr; } #else /* if not TCL_MEM_DEBUG */ Tcl_Obj * Tcl_DbNewLongObj(longValue, file, line) register long longValue; /* Long integer used to initialize the * new object. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { return Tcl_NewLongObj(longValue); } #endif /* TCL_MEM_DEBUG */ /* *---------------------------------------------------------------------- * * Tcl_SetLongObj -- * * Modify an object to be an integer object and to have the specified * long integer value. * * Results: * None. * * Side effects: * The object's old string rep, if any, is freed. Also, any old * internal rep is freed. * *---------------------------------------------------------------------- */ void Tcl_SetLongObj(objPtr, longValue) register Tcl_Obj *objPtr; /* Object whose internal rep to init. */ register long longValue; /* Long integer used to initialize the * object's value. */ { register Tcl_ObjType *oldTypePtr = objPtr->typePtr; if (Tcl_IsShared(objPtr)) { panic("Tcl_SetLongObj called with shared object"); } if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) { oldTypePtr->freeIntRepProc(objPtr); } objPtr->internalRep.longValue = longValue; objPtr->typePtr = &tclIntType; Tcl_InvalidateStringRep(objPtr); } /* *---------------------------------------------------------------------- * * Tcl_GetLongFromObj -- * * Attempt to return an long integer from the Tcl object "objPtr". If * the object is not already an int object, an attempt will be made to * convert it to one. * * Results: * The return value is a standard Tcl object result. If an error occurs * during conversion, an error message is left in the interpreter's * result unless "interp" is NULL. * * Side effects: * If the object is not already an int object, the conversion will free * any old internal representation. * *---------------------------------------------------------------------- */ int Tcl_GetLongFromObj(interp, objPtr, longPtr) Tcl_Interp *interp; /* Used for error reporting if not NULL. */ register Tcl_Obj *objPtr; /* The object from which to get a long. */ register long *longPtr; /* Place to store resulting long. */ { register int result; if (objPtr->typePtr == &tclIntType) { *longPtr = objPtr->internalRep.longValue; return TCL_OK; } result = SetIntFromAny(interp, objPtr); if (result == TCL_OK) { *longPtr = objPtr->internalRep.longValue; } return result; } /* *---------------------------------------------------------------------- * * Tcl_DbIncrRefCount -- * * This procedure is normally called when debugging: i.e., when * TCL_MEM_DEBUG is defined. This checks to see whether or not * the memory has been freed before incrementing the ref count. * * When TCL_MEM_DEBUG is not defined, this procedure just increments * the reference count of the object. * * Results: * None. * * Side effects: * The object's ref count is incremented. * *---------------------------------------------------------------------- */ void Tcl_DbIncrRefCount(objPtr, file, line) register Tcl_Obj *objPtr; /* The object we are registering a * reference to. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { #ifdef TCL_MEM_DEBUG if (objPtr->refCount == 0x61616161) { fprintf(stderr, "file = %s, line = %d\n", file, line); fflush(stderr); panic("Trying to increment refCount of previously disposed object."); } #endif ++(objPtr)->refCount; } /* *---------------------------------------------------------------------- * * Tcl_DbDecrRefCount -- * * This procedure is normally called when debugging: i.e., when * TCL_MEM_DEBUG is defined. This checks to see whether or not * the memory has been freed before decrementing the ref count. * * When TCL_MEM_DEBUG is not defined, this procedure just decrements * the reference count of the object. * * Results: * None. * * Side effects: * The object's ref count is incremented. * *---------------------------------------------------------------------- */ void Tcl_DbDecrRefCount(objPtr, file, line) register Tcl_Obj *objPtr; /* The object we are releasing a reference * to. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { #ifdef TCL_MEM_DEBUG if (objPtr->refCount == 0x61616161) { fprintf(stderr, "file = %s, line = %d\n", file, line); fflush(stderr); panic("Trying to decrement refCount of previously disposed object."); } #endif if (--(objPtr)->refCount <= 0) { TclFreeObj(objPtr); } } /* *---------------------------------------------------------------------- * * Tcl_DbIsShared -- * * This procedure is normally called when debugging: i.e., when * TCL_MEM_DEBUG is defined. It tests whether the object has a ref * count greater than one. * * When TCL_MEM_DEBUG is not defined, this procedure just tests * if the object has a ref count greater than one. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ int Tcl_DbIsShared(objPtr, file, line) register Tcl_Obj *objPtr; /* The object to test for being shared. */ char *file; /* The name of the source file calling this * procedure; used for debugging. */ int line; /* Line number in the source file; used * for debugging. */ { #ifdef TCL_MEM_DEBUG if (objPtr->refCount == 0x61616161) { fprintf(stderr, "file = %s, line = %d\n", file, line); fflush(stderr); panic("Trying to check whether previously disposed object is shared."); } #endif #ifdef TCL_COMPILE_STATS Tcl_MutexLock(&tclObjMutex); if ((objPtr)->refCount <= 1) { ObjsShared[1]++; } else if ((objPtr)->refCount < TCL_MAX_SHARED_OBJ_STATS) { ObjsShared[(objPtr)->refCount]++; } else { ObjsShared[0]++; } Tcl_MutexUnlock(&tclObjMutex); #endif return ((objPtr)->refCount > 1); } /* *---------------------------------------------------------------------- * * Tcl_InitObjHashTable -- * * Given storage for a hash table, set up the fields to prepare * the hash table for use, the keys are Tcl_Obj *. * * Results: * None. * * Side effects: * TablePtr is now ready to be passed to Tcl_FindHashEntry and * Tcl_CreateHashEntry. * *---------------------------------------------------------------------- */ void Tcl_InitObjHashTable(tablePtr) register Tcl_HashTable *tablePtr; /* Pointer to table record, which * is supplied by the caller. */ { Tcl_InitHashTableEx (tablePtr, TCL_CUSTOM_PTR_KEYS, &tclObjHashKeyType); } /* *---------------------------------------------------------------------- * * AllocObjEntry -- * * Allocate space for a Tcl_HashEntry containing the Tcl_Obj * key. * * Results: * The return value is a pointer to the created entry. * * Side effects: * Increments the reference count on the object. * *---------------------------------------------------------------------- */ static Tcl_HashEntry * AllocObjEntry(tablePtr, keyPtr) Tcl_HashTable *tablePtr; /* Hash table. */ VOID *keyPtr; /* Key to store in the hash table entry. */ { Tcl_Obj *objPtr = (Tcl_Obj *) keyPtr; Tcl_HashEntry *hPtr; hPtr = (Tcl_HashEntry *) ckalloc((unsigned) (sizeof(Tcl_HashEntry))); hPtr->key.oneWordValue = (char *) objPtr; Tcl_IncrRefCount (objPtr); return hPtr; } /* *---------------------------------------------------------------------- * * CompareObjKeys -- * * Compares two Tcl_Obj * keys. * * Results: * The return value is 0 if they are different and 1 if they are * the same. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int CompareObjKeys(keyPtr, hPtr) VOID *keyPtr; /* New key to compare. */ Tcl_HashEntry *hPtr; /* Existing key to compare. */ { Tcl_Obj *objPtr1 = (Tcl_Obj *) keyPtr; Tcl_Obj *objPtr2 = (Tcl_Obj *) hPtr->key.oneWordValue; register CONST char *p1, *p2; register int l1, l2; /* * If the object pointers are the same then they match. */ if (objPtr1 == objPtr2) { return 1; } /* * Don't use Tcl_GetStringFromObj as it would prevent l1 and l2 being * in a register. */ p1 = Tcl_GetString (objPtr1); l1 = objPtr1->length; p2 = Tcl_GetString (objPtr2); l2 = objPtr2->length; /* * Only compare if the string representations are of the same length. */ if (l1 == l2) { for (;; p1++, p2++, l1--) { if (*p1 != *p2) { break; } if (l1 == 0) { return 1; } } } return 0; } /* *---------------------------------------------------------------------- * * FreeObjEntry -- * * Frees space for a Tcl_HashEntry containing the Tcl_Obj * key. * * Results: * The return value is a pointer to the created entry. * * Side effects: * Decrements the reference count of the object. * *---------------------------------------------------------------------- */ static void FreeObjEntry(hPtr) Tcl_HashEntry *hPtr; /* Hash entry to free. */ { Tcl_Obj *objPtr = (Tcl_Obj *) hPtr->key.oneWordValue; Tcl_DecrRefCount (objPtr); ckfree ((char *) hPtr); } /* *---------------------------------------------------------------------- * * HashObjKey -- * * Compute a one-word summary of the string representation of the * Tcl_Obj, which can be used to generate a hash index. * * Results: * The return value is a one-word summary of the information in * the string representation of the Tcl_Obj. * * Side effects: * None. * *---------------------------------------------------------------------- */ static unsigned int HashObjKey(tablePtr, keyPtr) Tcl_HashTable *tablePtr; /* Hash table. */ VOID *keyPtr; /* Key from which to compute hash value. */ { Tcl_Obj *objPtr = (Tcl_Obj *) keyPtr; register CONST char *string; register int length; register unsigned int result; register int c; string = Tcl_GetString (objPtr); length = objPtr->length; /* * I tried a zillion different hash functions and asked many other * people for advice. Many people had their own favorite functions, * all different, but no-one had much idea why they were good ones. * I chose the one below (multiply by 9 and add new character) * because of the following reasons: * * 1. Multiplying by 10 is perfect for keys that are decimal strings, * and multiplying by 9 is just about as good. * 2. Times-9 is (shift-left-3) plus (old). This means that each * character's bits hang around in the low-order bits of the * hash value for ever, plus they spread fairly rapidly up to * the high-order bits to fill out the hash value. This seems * works well both for decimal and non-decimal strings. */ result = 0; while (length) { c = *string; string++; length--; if (length == 0) { break; } result += (result<<3) + c; } return result; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 2329 ] ] ]
2f21f9fd9f0fe6f9ba50107b2b5dd37c3f57d1f6
81e051c660949ac0e89d1e9cf286e1ade3eed16a
/quake3ce/code/botlib/be_aas_file.cpp
e3cef113d180afb58d73dfe9a275e50e4c0a0f73
[]
no_license
crioux/q3ce
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
5e724f55940ac43cb25440a65f9e9e12220c9ada
refs/heads/master
2020-06-04T10:29:48.281238
2008-11-16T15:00:38
2008-11-16T15:00:38
32,103,416
5
0
null
null
null
null
UTF-8
C++
false
false
24,898
cpp
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ /***************************************************************************** * name: be_aas_file.c * * desc: AAS file loading/writing * * $Archive: /MissionPack/code/botlib/be_aas_file.c $ * *****************************************************************************/ #include"botlib_pch.h" //#define AASFILEDEBUG //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_SwapAASData(void) { int i, j; //bounding boxes for (i = 0; i < aasworld.numbboxes; i++) { aasworld.bboxes[i].presencetype = LittleLong(aasworld.bboxes[i].presencetype); aasworld.bboxes[i].flags = LittleLong(aasworld.bboxes[i].flags); for (j = 0; j < 3; j++) { aasworld.bboxes[i].mins[j] = LittleFixed_IS_FLOAT_B(aasworld.bboxes[i].mins[j]); aasworld.bboxes[i].maxs[j] = LittleFixed_IS_FLOAT_B(aasworld.bboxes[i].maxs[j]); } //end for } //end for //vertexes for (i = 0; i < aasworld.numvertexes; i++) { for (j = 0; j < 3; j++) aasworld.vertexes[i][j] = LittleFixed_IS_FLOAT_B(aasworld.vertexes[i][j]); } //end for //planes for (i = 0; i < aasworld.numplanes; i++) { for (j = 0; j < 3; j++) aasworld.planes[i].normal[j] = LittleFixed_IS_FLOAT_A(aasworld.planes[i].normal[j]); aasworld.planes[i].dist = LittleFixed_IS_FLOAT_B(aasworld.planes[i].dist); aasworld.planes[i].type = LittleLong(aasworld.planes[i].type); } //end for //edges for (i = 0; i < aasworld.numedges; i++) { aasworld.edges[i].v[0] = LittleLong(aasworld.edges[i].v[0]); aasworld.edges[i].v[1] = LittleLong(aasworld.edges[i].v[1]); } //end for //edgeindex for (i = 0; i < aasworld.edgeindexsize; i++) { aasworld.edgeindex[i] = LittleLong(aasworld.edgeindex[i]); } //end for //faces for (i = 0; i < aasworld.numfaces; i++) { aasworld.faces[i].planenum = LittleLong(aasworld.faces[i].planenum); aasworld.faces[i].faceflags = LittleLong(aasworld.faces[i].faceflags); aasworld.faces[i].numedges = LittleLong(aasworld.faces[i].numedges); aasworld.faces[i].firstedge = LittleLong(aasworld.faces[i].firstedge); aasworld.faces[i].frontarea = LittleLong(aasworld.faces[i].frontarea); aasworld.faces[i].backarea = LittleLong(aasworld.faces[i].backarea); } //end for //face index for (i = 0; i < aasworld.faceindexsize; i++) { aasworld.faceindex[i] = LittleLong(aasworld.faceindex[i]); } //end for //convex areas for (i = 0; i < aasworld.numareas; i++) { aasworld.areas[i].areanum = LittleLong(aasworld.areas[i].areanum); aasworld.areas[i].numfaces = LittleLong(aasworld.areas[i].numfaces); aasworld.areas[i].firstface = LittleLong(aasworld.areas[i].firstface); for (j = 0; j < 3; j++) { aasworld.areas[i].mins[j] = LittleFixed_IS_FLOAT_B(aasworld.areas[i].mins[j]); aasworld.areas[i].maxs[j] = LittleFixed_IS_FLOAT_B(aasworld.areas[i].maxs[j]); aasworld.areas[i].center[j] = LittleFixed_IS_FLOAT_B(aasworld.areas[i].center[j]); } //end for } //end for //area settings for (i = 0; i < aasworld.numareasettings; i++) { aasworld.areasettings[i].contents = LittleLong(aasworld.areasettings[i].contents); aasworld.areasettings[i].areaflags = LittleLong(aasworld.areasettings[i].areaflags); aasworld.areasettings[i].presencetype = LittleLong(aasworld.areasettings[i].presencetype); aasworld.areasettings[i].cluster = LittleLong(aasworld.areasettings[i].cluster); aasworld.areasettings[i].clusterareanum = LittleLong(aasworld.areasettings[i].clusterareanum); aasworld.areasettings[i].numreachableareas = LittleLong(aasworld.areasettings[i].numreachableareas); aasworld.areasettings[i].firstreachablearea = LittleLong(aasworld.areasettings[i].firstreachablearea); } //end for //area reachability for (i = 0; i < aasworld.reachabilitysize; i++) { aasworld.reachability[i].areanum = LittleLong(aasworld.reachability[i].areanum); aasworld.reachability[i].facenum = LittleLong(aasworld.reachability[i].facenum); aasworld.reachability[i].edgenum = LittleLong(aasworld.reachability[i].edgenum); for (j = 0; j < 3; j++) { aasworld.reachability[i].start[j] = LittleFixed_IS_FLOAT_B(aasworld.reachability[i].start[j]); aasworld.reachability[i].end[j] = LittleFixed_IS_FLOAT_B(aasworld.reachability[i].end[j]); } //end for aasworld.reachability[i].traveltype = LittleLong(aasworld.reachability[i].traveltype); aasworld.reachability[i].traveltime = LittleShort(aasworld.reachability[i].traveltime); } //end for //nodes for (i = 0; i < aasworld.numnodes; i++) { aasworld.nodes[i].planenum = LittleLong(aasworld.nodes[i].planenum); aasworld.nodes[i].children[0] = LittleLong(aasworld.nodes[i].children[0]); aasworld.nodes[i].children[1] = LittleLong(aasworld.nodes[i].children[1]); } //end for //cluster portals for (i = 0; i < aasworld.numportals; i++) { aasworld.portals[i].areanum = LittleLong(aasworld.portals[i].areanum); aasworld.portals[i].frontcluster = LittleLong(aasworld.portals[i].frontcluster); aasworld.portals[i].backcluster = LittleLong(aasworld.portals[i].backcluster); aasworld.portals[i].clusterareanum[0] = LittleLong(aasworld.portals[i].clusterareanum[0]); aasworld.portals[i].clusterareanum[1] = LittleLong(aasworld.portals[i].clusterareanum[1]); } //end for //cluster portal index for (i = 0; i < aasworld.portalindexsize; i++) { aasworld.portalindex[i] = LittleLong(aasworld.portalindex[i]); } //end for //cluster for (i = 0; i < aasworld.numclusters; i++) { aasworld.clusters[i].numareas = LittleLong(aasworld.clusters[i].numareas); aasworld.clusters[i].numreachabilityareas = LittleLong(aasworld.clusters[i].numreachabilityareas); aasworld.clusters[i].numportals = LittleLong(aasworld.clusters[i].numportals); aasworld.clusters[i].firstportal = LittleLong(aasworld.clusters[i].firstportal); } //end for } //end of the function AAS_SwapAASData //=========================================================================== // dump the current loaded aas file // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_DumpAASData(void) { aasworld.numbboxes = 0; if (aasworld.bboxes) FreeMemory(aasworld.bboxes); aasworld.bboxes = NULL; aasworld.numvertexes = 0; if (aasworld.vertexes) FreeMemory(aasworld.vertexes); aasworld.vertexes = NULL; aasworld.numplanes = 0; if (aasworld.planes) FreeMemory(aasworld.planes); aasworld.planes = NULL; aasworld.numedges = 0; if (aasworld.edges) FreeMemory(aasworld.edges); aasworld.edges = NULL; aasworld.edgeindexsize = 0; if (aasworld.edgeindex) FreeMemory(aasworld.edgeindex); aasworld.edgeindex = NULL; aasworld.numfaces = 0; if (aasworld.faces) FreeMemory(aasworld.faces); aasworld.faces = NULL; aasworld.faceindexsize = 0; if (aasworld.faceindex) FreeMemory(aasworld.faceindex); aasworld.faceindex = NULL; aasworld.numareas = 0; if (aasworld.areas) FreeMemory(aasworld.areas); aasworld.areas = NULL; aasworld.numareasettings = 0; if (aasworld.areasettings) FreeMemory(aasworld.areasettings); aasworld.areasettings = NULL; aasworld.reachabilitysize = 0; if (aasworld.reachability) FreeMemory(aasworld.reachability); aasworld.reachability = NULL; aasworld.numnodes = 0; if (aasworld.nodes) FreeMemory(aasworld.nodes); aasworld.nodes = NULL; aasworld.numportals = 0; if (aasworld.portals) FreeMemory(aasworld.portals); aasworld.portals = NULL; aasworld.numportals = 0; if (aasworld.portalindex) FreeMemory(aasworld.portalindex); aasworld.portalindex = NULL; aasworld.portalindexsize = 0; if (aasworld.clusters) FreeMemory(aasworld.clusters); aasworld.clusters = NULL; aasworld.numclusters = 0; // aasworld.loaded = qfalse; aasworld.initialized = qfalse; aasworld.savefile = qfalse; } //end of the function AAS_DumpAASData //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== #ifdef AASFILEDEBUG void AAS_FileInfo(void) { int i, n, optimized; botimport.Print(PRT_MESSAGE, "version = %d\n", AASVERSION); botimport.Print(PRT_MESSAGE, "numvertexes = %d\n", aasworld.numvertexes); botimport.Print(PRT_MESSAGE, "numplanes = %d\n", aasworld.numplanes); botimport.Print(PRT_MESSAGE, "numedges = %d\n", aasworld.numedges); botimport.Print(PRT_MESSAGE, "edgeindexsize = %d\n", aasworld.edgeindexsize); botimport.Print(PRT_MESSAGE, "numfaces = %d\n", aasworld.numfaces); botimport.Print(PRT_MESSAGE, "faceindexsize = %d\n", aasworld.faceindexsize); botimport.Print(PRT_MESSAGE, "numareas = %d\n", aasworld.numareas); botimport.Print(PRT_MESSAGE, "numareasettings = %d\n", aasworld.numareasettings); botimport.Print(PRT_MESSAGE, "reachabilitysize = %d\n", aasworld.reachabilitysize); botimport.Print(PRT_MESSAGE, "numnodes = %d\n", aasworld.numnodes); botimport.Print(PRT_MESSAGE, "numportals = %d\n", aasworld.numportals); botimport.Print(PRT_MESSAGE, "portalindexsize = %d\n", aasworld.portalindexsize); botimport.Print(PRT_MESSAGE, "numclusters = %d\n", aasworld.numclusters); // for (n = 0, i = 0; i < aasworld.numareasettings; i++) { if (aasworld.areasettings[i].areaflags & AREA_GROUNDED) n++; } //end for botimport.Print(PRT_MESSAGE, "num grounded areas = %d\n", n); // botimport.Print(PRT_MESSAGE, "planes size %d bytes\n", aasworld.numplanes * sizeof(aas_plane_t)); botimport.Print(PRT_MESSAGE, "areas size %d bytes\n", aasworld.numareas * sizeof(aas_area_t)); botimport.Print(PRT_MESSAGE, "areasettings size %d bytes\n", aasworld.numareasettings * sizeof(aas_areasettings_t)); botimport.Print(PRT_MESSAGE, "nodes size %d bytes\n", aasworld.numnodes * sizeof(aas_node_t)); botimport.Print(PRT_MESSAGE, "reachability size %d bytes\n", aasworld.reachabilitysize * sizeof(aas_reachability_t)); botimport.Print(PRT_MESSAGE, "portals size %d bytes\n", aasworld.numportals * sizeof(aas_portal_t)); botimport.Print(PRT_MESSAGE, "clusters size %d bytes\n", aasworld.numclusters * sizeof(aas_cluster_t)); optimized = aasworld.numplanes * sizeof(aas_plane_t) + aasworld.numareas * sizeof(aas_area_t) + aasworld.numareasettings * sizeof(aas_areasettings_t) + aasworld.numnodes * sizeof(aas_node_t) + aasworld.reachabilitysize * sizeof(aas_reachability_t) + aasworld.numportals * sizeof(aas_portal_t) + aasworld.numclusters * sizeof(aas_cluster_t); botimport.Print(PRT_MESSAGE, "optimzed size %d KB\n", optimized >> 10); } //end of the function AAS_FileInfo #endif //AASFILEDEBUG //=========================================================================== // allocate memory and read a lump of a AAS file // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== char *AAS_LoadAASLump(fileHandle_t fp, int offset, int length, int *lastoffset, int size) { char *buf; // if (!length) { //just alloc a dummy return (char *) GetClearedHunkMemory(size+1); } //end if //seek to the data if (offset != *lastoffset) { botimport.Print(PRT_WARNING, "AAS file not sequentially read\n"); if (botimport.FS_Seek(fp, offset, FS_SEEK_SET)) { AAS_Error("can't seek to aas lump\n"); AAS_DumpAASData(); botimport.FS_FCloseFile(fp); return 0; } //end if } //end if //allocate memory buf = (char *) GetClearedHunkMemory(length+1); //read the data if (length) { botimport.FS_Read(buf, length, fp ); *lastoffset += length; } //end if return buf; } //end of the function AAS_LoadAASLump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_DData(unsigned char *data, int size) { int i; for (i = 0; i < size; i++) { data[i] ^= (unsigned char) i * 119; } //end for } //end of the function AAS_DData //=========================================================================== // load an aas file // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_LoadAASFile(char *filename) { fileHandle_t fp; aas_header_t header; int offset, length, lastoffset; botimport.Print(PRT_MESSAGE, "trying to load %s\n", filename); //dump current loaded aas file AAS_DumpAASData(); //open the file botimport.FS_FOpenFile( filename, &fp, FS_READ ); if (!fp) { AAS_Error("can't open %s\n", filename); return BLERR_CANNOTOPENAASFILE; } //end if //read the header botimport.FS_Read(&header, sizeof(aas_header_t), fp ); lastoffset = sizeof(aas_header_t); //check header identification header.ident = LittleLong(header.ident); if (header.ident != AASID) { AAS_Error("%s is not an AAS file\n", filename); botimport.FS_FCloseFile(fp); return BLERR_WRONGAASFILEID; } //end if //check the version header.version = LittleLong(header.version); // if (header.version != AASVERSION_OLD && header.version != AASVERSION) { AAS_Error("aas file %s is version %i, not %i\n", filename, header.version, AASVERSION); botimport.FS_FCloseFile(fp); return BLERR_WRONGAASFILEVERSION; } //end if // if (header.version == AASVERSION) { AAS_DData((unsigned char *) &header + 8, sizeof(aas_header_t) - 8); } //end if // aasworld.bspchecksum = atoi(LibVarGetString( "sv_mapChecksum")); if (LittleLong(header.bspchecksum) != aasworld.bspchecksum) { AAS_Error("aas file %s is out of date\n", filename); botimport.FS_FCloseFile(fp); return BLERR_WRONGAASFILEVERSION; } //end if //load the lumps: //bounding boxes offset = LittleLong(header.lumps[AASLUMP_BBOXES].fileofs); length = LittleLong(header.lumps[AASLUMP_BBOXES].filelen); aasworld.bboxes = (aas_bbox_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_bbox_t)); aasworld.numbboxes = length / sizeof(aas_bbox_t); if (aasworld.numbboxes && !aasworld.bboxes) return BLERR_CANNOTREADAASLUMP; //vertexes offset = LittleLong(header.lumps[AASLUMP_VERTEXES].fileofs); length = LittleLong(header.lumps[AASLUMP_VERTEXES].filelen); aasworld.vertexes = (aas_vertex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_vertex_t)); aasworld.numvertexes = length / sizeof(aas_vertex_t); if (aasworld.numvertexes && !aasworld.vertexes) return BLERR_CANNOTREADAASLUMP; //planes offset = LittleLong(header.lumps[AASLUMP_PLANES].fileofs); length = LittleLong(header.lumps[AASLUMP_PLANES].filelen); aasworld.planes = (aas_plane_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_plane_t)); aasworld.numplanes = length / sizeof(aas_plane_t); if (aasworld.numplanes && !aasworld.planes) return BLERR_CANNOTREADAASLUMP; //edges offset = LittleLong(header.lumps[AASLUMP_EDGES].fileofs); length = LittleLong(header.lumps[AASLUMP_EDGES].filelen); aasworld.edges = (aas_edge_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_edge_t)); aasworld.numedges = length / sizeof(aas_edge_t); if (aasworld.numedges && !aasworld.edges) return BLERR_CANNOTREADAASLUMP; //edgeindex offset = LittleLong(header.lumps[AASLUMP_EDGEINDEX].fileofs); length = LittleLong(header.lumps[AASLUMP_EDGEINDEX].filelen); aasworld.edgeindex = (aas_edgeindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_edgeindex_t)); aasworld.edgeindexsize = length / sizeof(aas_edgeindex_t); if (aasworld.edgeindexsize && !aasworld.edgeindex) return BLERR_CANNOTREADAASLUMP; //faces offset = LittleLong(header.lumps[AASLUMP_FACES].fileofs); length = LittleLong(header.lumps[AASLUMP_FACES].filelen); aasworld.faces = (aas_face_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_face_t)); aasworld.numfaces = length / sizeof(aas_face_t); if (aasworld.numfaces && !aasworld.faces) return BLERR_CANNOTREADAASLUMP; //faceindex offset = LittleLong(header.lumps[AASLUMP_FACEINDEX].fileofs); length = LittleLong(header.lumps[AASLUMP_FACEINDEX].filelen); aasworld.faceindex = (aas_faceindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_faceindex_t)); aasworld.faceindexsize = length / sizeof(aas_faceindex_t); if (aasworld.faceindexsize && !aasworld.faceindex) return BLERR_CANNOTREADAASLUMP; //convex areas offset = LittleLong(header.lumps[AASLUMP_AREAS].fileofs); length = LittleLong(header.lumps[AASLUMP_AREAS].filelen); aasworld.areas = (aas_area_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_area_t)); aasworld.numareas = length / sizeof(aas_area_t); if (aasworld.numareas && !aasworld.areas) return BLERR_CANNOTREADAASLUMP; //area settings offset = LittleLong(header.lumps[AASLUMP_AREASETTINGS].fileofs); length = LittleLong(header.lumps[AASLUMP_AREASETTINGS].filelen); aasworld.areasettings = (aas_areasettings_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_areasettings_t)); aasworld.numareasettings = length / sizeof(aas_areasettings_t); if (aasworld.numareasettings && !aasworld.areasettings) return BLERR_CANNOTREADAASLUMP; //reachability list offset = LittleLong(header.lumps[AASLUMP_REACHABILITY].fileofs); length = LittleLong(header.lumps[AASLUMP_REACHABILITY].filelen); aasworld.reachability = (aas_reachability_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_reachability_t)); aasworld.reachabilitysize = length / sizeof(aas_reachability_t); if (aasworld.reachabilitysize && !aasworld.reachability) return BLERR_CANNOTREADAASLUMP; //nodes offset = LittleLong(header.lumps[AASLUMP_NODES].fileofs); length = LittleLong(header.lumps[AASLUMP_NODES].filelen); aasworld.nodes = (aas_node_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_node_t)); aasworld.numnodes = length / sizeof(aas_node_t); if (aasworld.numnodes && !aasworld.nodes) return BLERR_CANNOTREADAASLUMP; //cluster portals offset = LittleLong(header.lumps[AASLUMP_PORTALS].fileofs); length = LittleLong(header.lumps[AASLUMP_PORTALS].filelen); aasworld.portals = (aas_portal_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_portal_t)); aasworld.numportals = length / sizeof(aas_portal_t); if (aasworld.numportals && !aasworld.portals) return BLERR_CANNOTREADAASLUMP; //cluster portal index offset = LittleLong(header.lumps[AASLUMP_PORTALINDEX].fileofs); length = LittleLong(header.lumps[AASLUMP_PORTALINDEX].filelen); aasworld.portalindex = (aas_portalindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_portalindex_t)); aasworld.portalindexsize = length / sizeof(aas_portalindex_t); if (aasworld.portalindexsize && !aasworld.portalindex) return BLERR_CANNOTREADAASLUMP; //clusters offset = LittleLong(header.lumps[AASLUMP_CLUSTERS].fileofs); length = LittleLong(header.lumps[AASLUMP_CLUSTERS].filelen); aasworld.clusters = (aas_cluster_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_cluster_t)); aasworld.numclusters = length / sizeof(aas_cluster_t); if (aasworld.numclusters && !aasworld.clusters) return BLERR_CANNOTREADAASLUMP; //swap everything AAS_SwapAASData(); //aas file is loaded aasworld.loaded = qtrue; //close the file botimport.FS_FCloseFile(fp); // #ifdef AASFILEDEBUG AAS_FileInfo(); #endif //AASFILEDEBUG // return BLERR_NOERROR; } //end of the function AAS_LoadAASFile //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== static int AAS_WriteAASLump_offset; int AAS_WriteAASLump(fileHandle_t fp, aas_header_t *h, int lumpnum, void *data, int length) { aas_lump_t *lump; lump = &h->lumps[lumpnum]; lump->fileofs = LittleLong(AAS_WriteAASLump_offset); //LittleLong(ftell(fp)); lump->filelen = LittleLong(length); if (length > 0) { botimport.FS_Write(data, length, fp ); } //end if AAS_WriteAASLump_offset += length; return qtrue; } //end of the function AAS_WriteAASLump //=========================================================================== // aas data is useless after writing to file because it is byte swapped // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== qboolean AAS_WriteAASFile(char *filename) { aas_header_t header; fileHandle_t fp; botimport.Print(PRT_MESSAGE, "writing %s\n", filename); //swap the aas data AAS_SwapAASData(); //initialize the file header Com_Memset(&header, 0, sizeof(aas_header_t)); header.ident = LittleLong(AASID); header.version = LittleLong(AASVERSION); header.bspchecksum = LittleLong(aasworld.bspchecksum); //open a new file botimport.FS_FOpenFile( filename, &fp, FS_WRITE ); if (!fp) { botimport.Print(PRT_ERROR, "error opening %s\n", filename); return qfalse; } //end if //write the header botimport.FS_Write(&header, sizeof(aas_header_t), fp); AAS_WriteAASLump_offset = sizeof(aas_header_t); //add the data lumps to the file if (!AAS_WriteAASLump(fp, &header, AASLUMP_BBOXES, aasworld.bboxes, aasworld.numbboxes * sizeof(aas_bbox_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_VERTEXES, aasworld.vertexes, aasworld.numvertexes * sizeof(aas_vertex_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_PLANES, aasworld.planes, aasworld.numplanes * sizeof(aas_plane_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGES, aasworld.edges, aasworld.numedges * sizeof(aas_edge_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGEINDEX, aasworld.edgeindex, aasworld.edgeindexsize * sizeof(aas_edgeindex_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACES, aasworld.faces, aasworld.numfaces * sizeof(aas_face_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACEINDEX, aasworld.faceindex, aasworld.faceindexsize * sizeof(aas_faceindex_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREAS, aasworld.areas, aasworld.numareas * sizeof(aas_area_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREASETTINGS, aasworld.areasettings, aasworld.numareasettings * sizeof(aas_areasettings_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_REACHABILITY, aasworld.reachability, aasworld.reachabilitysize * sizeof(aas_reachability_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_NODES, aasworld.nodes, aasworld.numnodes * sizeof(aas_node_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALS, aasworld.portals, aasworld.numportals * sizeof(aas_portal_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALINDEX, aasworld.portalindex, aasworld.portalindexsize * sizeof(aas_portalindex_t))) return qfalse; if (!AAS_WriteAASLump(fp, &header, AASLUMP_CLUSTERS, aasworld.clusters, aasworld.numclusters * sizeof(aas_cluster_t))) return qfalse; //rewrite the header with the added lumps botimport.FS_Seek(fp, 0, FS_SEEK_SET); AAS_DData((unsigned char *) &header + 8, sizeof(aas_header_t) - 8); botimport.FS_Write(&header, sizeof(aas_header_t), fp); //close the file botimport.FS_FCloseFile(fp); return qtrue; } //end of the function AAS_WriteAASFile
[ "jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac" ]
[ [ [ 1, 571 ] ] ]
c46cc5e2958e7a9467bf0a4b01ed43d9f85e9ff6
07e88c109af86db6aa3194cbb71c41d449f1a805
/Code/m3sbinarized/robot.cpp
875922d73fe205729bf944dd2ad104b2de905b51
[]
no_license
jbongard/ISCS
2a7fe528140aa24631022807c5af34d7442a122d
a7f7196a2a729564bd033abc13cdf4acb172edfb
refs/heads/master
2016-09-05T08:44:10.630025
2011-08-17T15:31:58
2011-08-17T15:31:58
2,222,304
1
1
null
null
null
null
UTF-8
C++
false
false
17,687
cpp
#include "stdio.h" #ifndef _ROBOT_CPP #define _ROBOT_CPP #include "robot.h" #include "matrix.h" extern int ROBOT_STARFISH; extern int SHAPE_CYLINDER; extern int SHAPE_RECTANGLE; extern double ROBOT_STARFISH_BODY_LENGTH; extern double ROBOT_STARFISH_BODY_WIDTH; extern double ROBOT_STARFISH_BODY_HEIGHT; extern double ROBOT_STARFISH_LEG_RADIUS; extern double ROBOT_STARFISH_LEG_LENGTH; extern double ROBOT_STARFISH_JOINT_RANGE; extern double WORST_FITNESS; ROBOT::ROBOT(ENVIRONMENT *cE, int robotType) { containerEnvironment = cE; if ( robotType == ROBOT_STARFISH ) Create_Starfish(); for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->containerRobot = this; for (int j=0; j<numJoints; j++) if ( joints[j] ) joints[j]->containerRobot = this; hidden = false; physicalized = false; neuralNetwork = NULL; sensorDifferences = 0.0; } ROBOT::ROBOT(ROBOT *other) { containerEnvironment = other->containerEnvironment; Initialize(other); } ROBOT::ROBOT(ENVIRONMENT *cE, ROBOT *other) { containerEnvironment = cE; Initialize(other); } ROBOT::ROBOT(ENVIRONMENT *cE, ifstream *inFile) { containerEnvironment = cE; Initialize(inFile); } ROBOT::~ROBOT(void) { if ( containerEnvironment ) containerEnvironment = NULL; if ( objects ) { for (int i=0; i<numObjects; i++) { if ( objects[i] ) { delete objects[i]; objects[i] = NULL; } } delete[] objects; objects = NULL; } if ( joints ) { for (int j=0; j<numJoints; j++) { if ( joints[j] ) { delete joints[j]; joints[j] = NULL; } } delete[] joints; joints = NULL; } if ( neuralNetwork ) { delete neuralNetwork; neuralNetwork = NULL; } } void ROBOT::Activate(void) { for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Activate(); } void ROBOT::Deactivate(void) { for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Deactivate(); } void ROBOT::Draw(void) { if ( hidden ) return; for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Draw(); } double ROBOT::Fitness_Get(ROBOT *targetRobot) { /* // if ( neuralNetwork->inAFixedAttractor ) // return( WORST_FITNESS ); double fitness = 0.0; double diff = Sensors_Get_Total_Differences(targetRobot); //double diff = Sensors_Get_Largest_Difference(targetRobot); fitness = -diff; // fitness = Sensors_Get_Total(); return( fitness ); */ return( -sensorDifferences ); } int ROBOT::Has_Stopped(void) { if ( !neuralNetwork ) return( true ); return( neuralNetwork->inAFixedAttractor ); } void ROBOT::Hide(void) { hidden = true; for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Hide(); } int ROBOT::In_Simulator(void) { return( physicalized ); } void ROBOT::Label(NEURAL_NETWORK *genome, int environmentIndex) { if ( neuralNetwork ) delete neuralNetwork; neuralNetwork = new NEURAL_NETWORK(genome); } void ROBOT::Make_Incorporeal(void) { for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Make_Incorporeal(); for (int j=0; j<numJoints; j++) if ( joints[j] ) joints[j]->Make_Incorporeal(); physicalized = false; } void ROBOT::Make_Physical(dWorldID world, dSpaceID space) { // Add the robot to the physical simulator. if ( physicalized ) return; physicalized = true; for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Make_Physical(world,space); for (int j=0; j<numJoints; j++) if ( joints[j] ) joints[j]->Make_Physical(world); } int ROBOT::Motors_Number_Of(void) { return( numJoints ); // Assumes all joints are motorized. } void ROBOT::Move(int timeStep) { // The robot is moving itself. // The robot cannot move itself it is not physical. if ( !physicalized ) return; Neural_Network_Set_Sensors(); Neural_Network_Update(timeStep); Actuate_Motors(); Sensors_Touch_Clear(); } void ROBOT::Move(double x, double y, double z) { // The robot is being moved by the user. for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Move(x,y,z); for (int j=0; j<numJoints; j++) if ( joints[j] ) joints[j]->Move(x,y,z); } void ROBOT::Save(ofstream *outFile) { (*outFile) << numObjects << "\n"; for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Save(outFile); (*outFile) << numJoints << "\n"; for (int j=0; j<numJoints; j++) if ( joints[j] ) joints[j]->Save(outFile); } double ROBOT::Sensor_Sum(void) { return( Sensors_Get_Total() ); } void ROBOT::Sensors_Add_Difference(ROBOT *other) { sensorDifferences = sensorDifferences + Sensors_In_Objects_Total_Differences(other); } int ROBOT::Sensors_Number_Of(void) { int numSensors = 0; for (int i=0; i<numObjects; i++) if ( objects[i] ) numSensors = numSensors + objects[i]->Sensors_Number_Of(); for (int j=0; j<numJoints; j++) if ( joints[j] ) numSensors = numSensors + joints[j]->Sensors_Number_Of(); return( numSensors ); } void ROBOT::Sensors_Update(void) { // Light sensors already updated during the // last drawing of the robot. for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Sensors_Update(); // Touch sensors updated by nearCallback function. // Update all of the proprioceptive sensors. for (int j=0; j<numJoints; j++) if ( joints[j] ) joints[j]->Sensors_Update(); } void ROBOT::Sensors_Write(void) { Sensors_In_Objects_Write(); Sensors_In_Joints_Write(); printf("\n"); } void ROBOT::Set_Color(double r, double g, double b) { for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Set_Color(r,g,b); } void ROBOT::Unhide(void) { hidden = false; for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Unhide(); } // --------------------- Private methods ------------------------ void ROBOT::Actuate_Motors(void) { for (int j=0; j<numJoints; j++) { double motorNeuronValue = neuralNetwork->Get_Motor_Neuron_Value(j); if ( joints[j] ) joints[j]->Move(motorNeuronValue); } } void ROBOT::Create_Starfish(void) { Create_Starfish_Objects(); Create_Starfish_Joints(); } void ROBOT::Create_Starfish_Joints(void) { // Four joints connecting each lower and upper leg, and // four joints connecting each leg to the main body. numJoints = 4 + 4; joints = new JOINT * [numJoints]; for (int j=0; j<numJoints; j++) joints[j] = NULL; // Attach the left upper and lower legs. joints[0] = new JOINT(this,1,5, -ROBOT_STARFISH_BODY_LENGTH/2.0 -ROBOT_STARFISH_LEG_LENGTH, 0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 0,1,0, -ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE); // Attach the right upper and lower legs. joints[1] = new JOINT(this,2,6, +ROBOT_STARFISH_BODY_LENGTH/2.0 +ROBOT_STARFISH_LEG_LENGTH, 0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 0,-1,0, -ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE); // Attach the forward upper and lower legs. joints[2] = new JOINT(this,3,7, 0, +ROBOT_STARFISH_BODY_LENGTH/2.0 +ROBOT_STARFISH_LEG_LENGTH, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 1,0,0, -ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE); // Attach the back upper and lower legs. joints[3] = new JOINT(this,4,8, 0, -ROBOT_STARFISH_BODY_LENGTH/2.0 -ROBOT_STARFISH_LEG_LENGTH, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, -1,0,0, -ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE); // Attach main body and the left upper leg. joints[4] = new JOINT(this,0,1, -ROBOT_STARFISH_BODY_LENGTH/2.0, 0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 0,1,0, -ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE); // Attach main body and the right upper leg. joints[5] = new JOINT(this,0,2, +ROBOT_STARFISH_BODY_LENGTH/2.0, 0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 0,-1,0, -ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE); // Attach main body and the forward upper leg. joints[6] = new JOINT(this,0,3, 0, +ROBOT_STARFISH_BODY_LENGTH/2.0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 1,0,0, -ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE); // Attach main body and the back upper leg. joints[7] = new JOINT(this,0,4, 0, -ROBOT_STARFISH_BODY_LENGTH/2.0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, -1,0,0, -ROBOT_STARFISH_JOINT_RANGE,+ROBOT_STARFISH_JOINT_RANGE); for (int j=0;j<numJoints;j++) joints[j]->Sensor_Proprioceptive_Add(); } void ROBOT::Create_Starfish_Objects(void) { // One main body, four upper legs and four lower legs numObjects = 1 + 4 + 4; objects = new OBJECT * [numObjects]; for (int i=0; i<numObjects; i++) objects[i] = NULL; // Main body objects[0] = new OBJECT(SHAPE_RECTANGLE, ROBOT_STARFISH_BODY_LENGTH, ROBOT_STARFISH_BODY_WIDTH, ROBOT_STARFISH_BODY_HEIGHT, 0, 0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 0,0,1); // Left upper leg objects[1] = new OBJECT(SHAPE_CYLINDER, ROBOT_STARFISH_LEG_RADIUS, ROBOT_STARFISH_LEG_LENGTH, -ROBOT_STARFISH_BODY_LENGTH/2.0 -ROBOT_STARFISH_LEG_LENGTH/2.0, 0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, -1,0,0); // Right upper leg objects[2] = new OBJECT(SHAPE_CYLINDER, ROBOT_STARFISH_LEG_RADIUS, ROBOT_STARFISH_LEG_LENGTH, +ROBOT_STARFISH_BODY_LENGTH/2.0 +ROBOT_STARFISH_LEG_LENGTH/2.0, 0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, +1,0,0); // Forward upper leg objects[3] = new OBJECT(SHAPE_CYLINDER, ROBOT_STARFISH_LEG_RADIUS, ROBOT_STARFISH_LEG_LENGTH, 0, +ROBOT_STARFISH_BODY_LENGTH/2.0 +ROBOT_STARFISH_LEG_LENGTH/2.0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 0,+1,0); // Back upper leg objects[4] = new OBJECT(SHAPE_CYLINDER, ROBOT_STARFISH_LEG_RADIUS, ROBOT_STARFISH_LEG_LENGTH, 0, -ROBOT_STARFISH_BODY_LENGTH/2.0 -ROBOT_STARFISH_LEG_LENGTH/2.0, ROBOT_STARFISH_LEG_LENGTH +ROBOT_STARFISH_LEG_RADIUS, 0,-1,0); // Left lower leg objects[5] = new OBJECT(SHAPE_CYLINDER, ROBOT_STARFISH_LEG_RADIUS, ROBOT_STARFISH_LEG_LENGTH, -ROBOT_STARFISH_BODY_LENGTH/2.0 -ROBOT_STARFISH_LEG_LENGTH, 0, ROBOT_STARFISH_LEG_LENGTH/2.0 +ROBOT_STARFISH_LEG_RADIUS, 0,0,+1); // Right lower leg objects[6] = new OBJECT(SHAPE_CYLINDER, ROBOT_STARFISH_LEG_RADIUS, ROBOT_STARFISH_LEG_LENGTH, +ROBOT_STARFISH_BODY_LENGTH/2.0 +ROBOT_STARFISH_LEG_LENGTH, 0, ROBOT_STARFISH_LEG_LENGTH/2.0 +ROBOT_STARFISH_LEG_RADIUS, 0,0,+1); // Forward lower leg objects[7] = new OBJECT(SHAPE_CYLINDER, ROBOT_STARFISH_LEG_RADIUS, ROBOT_STARFISH_LEG_LENGTH, 0, +ROBOT_STARFISH_BODY_LENGTH/2.0 +ROBOT_STARFISH_LEG_LENGTH, ROBOT_STARFISH_LEG_LENGTH/2.0 +ROBOT_STARFISH_LEG_RADIUS, 0,0,+1); // Back lower leg objects[8] = new OBJECT(SHAPE_CYLINDER, ROBOT_STARFISH_LEG_RADIUS, ROBOT_STARFISH_LEG_LENGTH, 0, -ROBOT_STARFISH_BODY_LENGTH/2.0 -ROBOT_STARFISH_LEG_LENGTH, ROBOT_STARFISH_LEG_LENGTH/2.0 +ROBOT_STARFISH_LEG_RADIUS, 0,0,+1); for (int i=0;i<numObjects;i++) objects[i]->Sensor_Light_Add(); objects[5]->Sensor_Touch_Add(); objects[6]->Sensor_Touch_Add(); objects[7]->Sensor_Touch_Add(); objects[8]->Sensor_Touch_Add(); } bool ROBOT::File_Exists(char *fileName) { ifstream ifile(fileName); return ifile; } int ROBOT::File_Index_Next_Available(void) { int fileIndex = 0; char fileName[100]; sprintf(fileName,"SavedFiles/robot%d.dat",fileIndex); while ( File_Exists(fileName) ) { fileIndex++; sprintf(fileName,"SavedFiles/robot%d.dat",fileIndex); } return( fileIndex ); } void ROBOT::Initialize(ifstream *inFile) { (*inFile) >> numObjects; objects = new OBJECT * [numObjects]; for (int i=0; i<numObjects; i++) objects[i] = new OBJECT(this,inFile); (*inFile) >> numJoints; joints = new JOINT * [numJoints]; for (int j=0; j<numJoints; j++) joints[j] = new JOINT(this,inFile); hidden = false; physicalized = false; neuralNetwork = NULL; sensorDifferences = 0.0; } void ROBOT::Initialize(ROBOT *other) { numObjects = other->numObjects; objects = new OBJECT * [numObjects]; for (int i=0; i<numObjects; i++) objects[i] = new OBJECT(this,other->objects[i]); numJoints = other->numJoints; joints = new JOINT * [numJoints]; for (int j=0; j<numJoints; j++) joints[j] = new JOINT(this,other->joints[j]); hidden = false; physicalized = false; if ( other->neuralNetwork ) neuralNetwork = new NEURAL_NETWORK(other->neuralNetwork); else neuralNetwork = NULL; sensorDifferences = 0.0; } void ROBOT::Neural_Network_Set_Sensors(void) { int sensorIndex = 0; double sensorValue = 0.0; for (int i=0; i<numObjects; i++) if ( objects[i] ) { if ( objects[i]->lightSensor ) { sensorValue = objects[i]->lightSensor->Get_Value(); neuralNetwork->Sensor_Set(sensorIndex,sensorValue); sensorIndex++; } if ( objects[i]->touchSensor ) { sensorValue = objects[i]->touchSensor->Get_Value(); //sensorValue = 0.0; neuralNetwork->Sensor_Set(sensorIndex,sensorValue); sensorIndex++; } } for (int j=0; j<numJoints; j++) if ( joints[j] ) { if ( joints[j]->proprioceptiveSensor ) { sensorValue = joints[j]->proprioceptiveSensor->Get_Value(); //sensorValue = 0.0; neuralNetwork->Sensor_Set(sensorIndex,sensorValue); sensorIndex++; } } // neuralNetwork->sensorValues->Print(); } void ROBOT::Neural_Network_Update(int timeStep) { if ( !neuralNetwork ) return; neuralNetwork->Update(timeStep); } void ROBOT::Sensors_Touch_Print(void) { for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Sensor_Touch_Print(); printf("\n"); } double ROBOT::Sensors_Get_Largest_Difference(ROBOT *other) { double largestDifferenceInJoints = Sensors_In_Joints_Largest_Difference(other); double largestDifferenceInObjects = Sensors_In_Objects_Largest_Difference(other); if ( largestDifferenceInJoints > largestDifferenceInObjects ) return( largestDifferenceInJoints ); else return( largestDifferenceInObjects ); } double ROBOT::Sensors_Get_Total_Differences(ROBOT *other) { // return( Sensors_In_Joints_Total_Differences(other) + // Sensors_In_Objects_Total_Differences(other) ); return( Sensors_In_Objects_Total_Differences(other) ); } double ROBOT::Sensors_Get_Total(void) { double sum = 0.0; for (int i=0; i<numObjects; i++) if ( objects[i] ) if ( objects[i]->lightSensor ) { sum = sum + objects[i]->lightSensor->Get_Value(); } return( sum ); } double ROBOT::Sensors_In_Joints_Largest_Difference(ROBOT *other) { double diff = -1000.0; for (int j=0; j<numJoints; j++) if ( joints[j] ) if ( joints[j]->proprioceptiveSensor ) { /* PROP_SENSOR *otherSensor = other->joints[j]->proprioceptiveSensor; if ( otherSensor ) { double currDiff = joints[j]->proprioceptiveSensor-> Difference(otherSensor); if ( currDiff > diff ) diff = currDiff; otherSensor = NULL; } */ } return( diff ); } double ROBOT::Sensors_In_Joints_Total_Differences(ROBOT *other) { double diff = 0.0; double num = 1.0; for (int j=0; j<numJoints; j++) if ( joints[j] && joints[j]->proprioceptiveSensor && other->joints[j] && other->joints[j]->proprioceptiveSensor ) { double myVal = joints[j]->proprioceptiveSensor->Get_Value(); double otherVal = other->joints[j]->proprioceptiveSensor->Get_Value();; diff = diff + fabs(myVal - otherVal); num++; } return( diff/num ); } void ROBOT::Sensors_In_Joints_Write(void) { for (int j=0; j<numJoints; j++) if ( joints[j] ) if ( joints[j]->proprioceptiveSensor ) joints[j]->proprioceptiveSensor->Write(); } double ROBOT::Sensors_In_Objects_Largest_Difference(ROBOT *other) { double diff = -1000.0; for (int i=0; i<numObjects; i++) if ( objects[i] ) { if ( objects[i]->lightSensor ) { LIGHT_SENSOR *otherSensor = other->objects[i]->lightSensor; if ( otherSensor ) { double currDiff = objects[i]->lightSensor-> Difference(otherSensor); if ( currDiff > diff ) diff = currDiff; otherSensor = NULL; } } /* if ( objects[i]->touchSensor ) { TOUCH_SENSOR *otherSensor = other->objects[i]->touchSensor; if ( otherSensor ) { double currDiff = objects[i]->touchSensor-> Difference(otherSensor); if ( currDiff > diff ) diff = currDiff; otherSensor = NULL; } } */ } return( diff ); } double ROBOT::Sensors_In_Objects_Total_Differences(ROBOT *other) { double diff = 0.0; double num = 1.0; for (int i=0; i<numObjects; i++) if ( objects[i] && objects[i]->lightSensor && other->objects[i] && other->objects[i]->lightSensor ) { double myVal = objects[i]->lightSensor->Get_Value(); double otherVal = other->objects[i]->lightSensor->Get_Value(); diff = diff + fabs(myVal - otherVal); num++; } return( diff/num ); } void ROBOT::Sensors_In_Objects_Write(void) { for (int i=0; i<numObjects; i++) if ( objects[i] ) if ( objects[i]->lightSensor ) objects[i]->lightSensor->Write(); } void ROBOT::Sensors_Touch_Clear(void) { for (int i=0; i<numObjects; i++) if ( objects[i] ) objects[i]->Sensor_Touch_Clear(); } #endif
[ [ [ 1, 924 ] ] ]
3d5ef37114ab72ed21e5d3825786c65f77ed621e
9a10a9d7886ce0ba9e85a0ed092e6eb6bafb2780
/src/kolobok/Help.cpp
2bbff0b9a64d8f9ce1bb02e5cf7e431efa747a02
[ "BSD-3-Clause" ]
permissive
leok7v/kolobok
ccc51bbeef67739978d8465d328b4f93b4d7e833
30278ac53285912587db078e28205ea33a85143f
refs/heads/master
2020-06-04T08:37:01.952623
2010-01-07T06:23:38
2010-01-07T06:23:38
32,692,395
0
0
null
null
null
null
UTF-8
C++
false
false
1,569
cpp
#include "resource.h" #include "Help.h" #include "Application.h" #include "Controls.h" #include "Skin.h" static int CALLBACK helpDlgProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp); Help Help::help; static void helpAbout() { if (Help::help.dlgAbout != null) return; Help::help.dlgAbout = Controls::createDialog(IDD_MB, helpDlgProc); assert(Help::help.dlgAbout != null); SetDlgItemText(Help::help.dlgAbout, IDC_VERSION, main.getVersion()); } void Help::eventReceived(const Message& m) { if (ustrcmp(m.id, L"commandHelpAbout") == 0) helpAbout(); else if (ustrcmp(m.id, L"updateCommandsState") == 0) { HashMap& map = *(HashMap*)dynamic_cast<const HashMap*>(m.param); map.put(L"commandHelpAbout", dlgAbout == null); map.put(L"commandButtonOK", dlgAbout != null); } else if (ustrcmp(m.id, L"commandButtonOK") == 0 && dlgAbout != null) { PostMessage(dlgAbout, WM_COMMAND, IDOK, 0); } } int CALLBACK helpDlgProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { switch (msg) { case WM_INITDIALOG: { SetProp(hwnd, L"dialog", (void*)true); SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED); SetLayeredWindowAttributes(hwnd, 0, (255 * 90) / 100, LWA_ALPHA); return true; } case WM_DESTROY: { Help::help.dlgAbout = null; EnableWindow(getApplicationMainWindow(), true); break; } } return false; }
[ "leo.kuznetsov@e731d3c6-f9ae-11de-973d-3ba8dba7af4f" ]
[ [ [ 1, 47 ] ] ]
29603863e507475e02e36d247788904d79776d3d
a1fc2d997221a801e11b57c5d7d28dbd2f462978
/gravsim420/ARCgenePool.h
f604cdce0b6d63e01826eeac065884d2c37a4563
[]
no_license
misterbowtie/gravsim420
daf2a262de88db4f8bb520bb9fae2f6aa01932a5
f5532aa3c8fd64a7f85881e698f1025058dee189
refs/heads/master
2021-01-19T06:19:56.460262
2006-12-03T23:40:24
2006-12-03T23:40:24
32,546,587
0
0
null
null
null
null
UTF-8
C++
false
false
1,867
h
// ARCgenePool.h #include <time.h> #include <algorithm> #include <iostream> #include "ARCgenes.h" using namespace std; float SURVIVAL_RATE = .50f; int geneCompare(const void * a, const void * b) { if(*(genes*)a<*(genes*)b) return -1; return 1; } class genePool { public: genePool(int poolSize, double *variables[], int geneSize) { srand((unsigned int) time(0)); max=poolSize; size=geneSize; var = variables; genes original; double* par = new double[size]; for(int i=0; i<size; i++) par[i]=*var[i]; original.init(size,par); gs = new genes[max]; gs[0].make(original,original); for(int i=1; i<max; i++) gs[i].make(gs[i-1],original); delete[] par; index=0; } ~genePool() {} void nextTest() { index++; if(index==max) { repopulate(); index=0; } for(int i=0;i<size; i++) { *(var[i]) = gs[index].get(i); } } void setBest() { for(int i=0;i<size; i++) { *(var[i]) = best.get(i); } } void printBest() { best.print(); } void score(double geneFit) { gs[index].setFit(geneFit); } void print() { cout<<"\n----------------"; for(int i=0; i<max; i++) { gs[i].print();} } private: void repopulate(); int max; //# of genes int size; //# of nums in genes int index; genes *gs; genes best; double** var; }; void genePool::repopulate() { qsort(gs,max,sizeof(genes),geneCompare); //(gs, gs+max); cout<<"\n AFTER SORT"; print(); int mother, father; genes* oldgs = gs; gs = new genes[max]; for(int i=0; i<max; i++) { father= i*SURVIVAL_RATE; mother= randf()*randf()*max*SURVIVAL_RATE; gs[i].make(oldgs[father],oldgs[mother]); } if(best.getFit()<oldgs[0].getFit()) best = oldgs[0]; delete[] oldgs; }
[ "aaron.canary@b131a309-ab20-0410-8173-7914f2e55ca6", "wmluckett@b131a309-ab20-0410-8173-7914f2e55ca6" ]
[ [ [ 1, 62 ], [ 70, 125 ] ], [ [ 63, 69 ] ] ]
3313299392cacdf163e39a38999c14dd002a73fc
faacd0003e0c749daea18398b064e16363ea8340
/3rdparty/phonon/effect.h
fb54e3e6dfc81a04f3c4507cd27e4f6449ed191d
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
3,857
h
/* This file is part of the KDE project Copyright (C) 2005-2007 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Trolltech ASA (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. 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, see <http://www.gnu.org/licenses/>. */ #ifndef PHONON_EFFECT_H #define PHONON_EFFECT_H #include "phonondefs.h" #include <QtCore/QObject> #include "objectdescription.h" #include "medianode.h" QT_BEGIN_HEADER QT_BEGIN_NAMESPACE #ifndef QT_NO_PHONON_EFFECT class QString; template<class T> class QList; namespace Phonon { class EffectParameter; class EffectPrivate; /** \class Effect effect.h Phonon/Effect * \short Effects that can be inserted into a Path. * An effect is a special object which can perform * transformations on the specified path. Examples may include simple * modifiers such as fading or pitch shifting, or more complex mathematical * transformations. * * In order to use an effect, insert it into the path as follows: * \code * Path path = Phonon::createPath(...); * Effect *effect = new Effect(this); * path.insertEffect(effect); * \endcode * * The effect will immediately begin applying it's transformations on * the path. To stop it, remove the Effect from the path. * * \ingroup PhononEffects * \author Matthias Kretz <[email protected]> */ class PHONON_EXPORT Effect : public QObject, public MediaNode { Q_OBJECT K_DECLARE_PRIVATE(Effect) public: ~Effect(); //X enum Type { //X AudioEffect, //X VideoEffect //X }; /** * QObject constructor. * * \param description An EffectDescription object to determine the * type of effect. See BackendCapabilities::availableAudioEffects(). * \param parent QObject parent */ explicit Effect(const EffectDescription &description, QObject *parent = 0); //X Type type() const; /** * Returns the description of this effect. This is the same type as was * passed to the constructor. */ EffectDescription description() const; /** * Returns a list of parameters that this effect provides to control * its behaviour. * * \see EffectParameter * \see EffectWidget */ QList<EffectParameter> parameters() const; QVariant parameterValue(const EffectParameter&) const; void setParameterValue(const EffectParameter&, const QVariant &value); protected: Effect(EffectPrivate &dd, QObject *parent); }; } //namespace Phonon #endif // QT_NO_EFFECT QT_END_NAMESPACE QT_END_HEADER // vim: sw=4 ts=4 tw=80 #endif // PHONON_EFFECT_H
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 119 ] ] ]
3f947b5d860838fbb6912b7e675d22aa96bafdea
ccc3e2995bc64d09b9e88fea8c1c7e2029a60ed8
/SO/Trabalhos/Trabalho 2/tmp_src/31529/versao4 conditional variables/SesError.cpp
5fedf79f1076ef9eecbee923667a77e2026b1952
[]
no_license
masterzdran/semestre5
e559e93017f5e40c29e9f28466ae1c5822fe336e
148d65349073f8ae2f510b5659b94ddf47adc2c7
refs/heads/master
2021-01-25T10:05:42.513229
2011-02-20T17:46:14
2011-02-20T17:46:14
35,061,115
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,789
cpp
/** * Implementação do módulo de tratamento de erros */ #include "SesError.h" #include "stdafx.h" const int MAX_CH_ERROR_TITLE = 64; // Dimensão max. do titulo em caracters //const int ERROR_TITLE = 64; const int MAX_CH_ERROR_MESSAGE = 256; // Dimensão max. da mensagem de erro em caracters //---------------------------------------------------------------------------- // Função privada auxiliar que bloqueia o programa até o utilizador // primir uma tecla. // Em ambiente Unix deve premir ENTER // void terminar() { fputs("\nPrima uma tecla para terminar ", stderr); _getch(); } // terminar //---------------------------------------------------------------------------- // Função privada que sabe mostrar um erro // void DisplayError(int errorn, const TCHAR * fmtStr, va_list args) { LPVOID errorBuf; TCHAR msgBuffer[MAX_CH_ERROR_MESSAGE]; TCHAR title[MAX_CH_ERROR_TITLE] = TEXT(""); TCHAR * progName; if ( GetConsoleTitle(title, MAX_CH_ERROR_TITLE) ) { progName = _tcsrchr(title, '\\'); if ( progName != NULL ) { if ( progName[ _tcslen(progName)-1 ] == '"') progName[ _tcslen(progName)-1 ] = '\0'; //_stprintf(title, TEXT("Error on %s"), ++progName); StringCchPrintf(title, MAX_CH_ERROR_TITLE, TEXT("Error on %s"), ++progName); } } DWORD res = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorn, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Linguagem por omissão do sistema (LPTSTR) &errorBuf, 0, NULL ); //_vstprintf( msgBuffer, fmtStr, args ); StringCchVPrintf(msgBuffer, MAX_CH_ERROR_MESSAGE, fmtStr, args ); //_stprintf( msgBuffer + _tcsclen(msgBuffer), TEXT(": (%d) %s"), errorn, (res ? errorBuf : "") ); size_t dimMsg = _tcsclen(msgBuffer); StringCchPrintf(msgBuffer + dimMsg, MAX_CH_ERROR_MESSAGE - dimMsg, TEXT(": (%d) %s"), errorn, (res ? errorBuf : TEXT("")) ); MessageBox( NULL, (LPCTSTR)msgBuffer, title, MB_OK | MB_ICONERROR | MB_SETFOREGROUND); // Libertar memória referenciada por lpMsgBuf alocada pela função FormatMessage LocalFree( errorBuf ); } // DisplayError //---------------------------------------------------------------------------- // Função privada que sabe mostrar um erro da aplicação // void DisplayErrorApp(const TCHAR * fmtStr, va_list args) { TCHAR msgBuffer[MAX_CH_ERROR_MESSAGE]; TCHAR title[MAX_CH_ERROR_TITLE] = TEXT(""); TCHAR * progName; if ( GetConsoleTitle(title, MAX_CH_ERROR_TITLE) ) { progName = _tcsrchr(title, '\\'); if ( progName!=NULL ) { if ( progName[ _tcsclen(progName)-1 ]=='"' ) progName[ _tcsclen(progName)-1 ] = '\0'; //_stprintf(title, TEXT("Error on %s"), ++progName); StringCchPrintf(title, MAX_CH_ERROR_TITLE, TEXT("Error on %s"), ++progName); } } //_vstprintf( msgBuffer, fmtStr, args ); StringCchVPrintf(msgBuffer, MAX_CH_ERROR_MESSAGE, fmtStr, args ); MessageBox( NULL, (LPCTSTR)msgBuffer, title, MB_OK | MB_ICONERROR | MB_SETFOREGROUND); } // DisplayErrorApp //---------------------------------------------------------------------------- // Erro de sistema // void ReportErrorSystem( const TCHAR *fmtStr, ... ) { va_list args; int error = GetLastError(); va_start( args, fmtStr ); DisplayError( error, fmtStr, args ); va_end( args ); } // ReportErrorSystem //---------------------------------------------------------------------------- // Erro de sistema com terminação do programa // void FatalErrorSystem( const TCHAR *fmtStr, ... ) { va_list args; int error = GetLastError(); va_start( args, fmtStr ); DisplayError( error, fmtStr, args ); va_end( args ); terminar(); exit( 1 ); } // ErrorSystem //---------------------------------------------------------------------------- // Erro da aplicação // void ReportErrorUser( const TCHAR *fmtStr, ... ) { va_list args; va_start( args, fmtStr ); DisplayErrorApp(fmtStr, args ); va_end( args ); } // ReportErrorSystem //---------------------------------------------------------------------------- // Erro da aplicação com terminação do programa // void FatalErrorUser( const TCHAR *fmtStr, ... ) { va_list args; va_start( args, fmtStr ); DisplayErrorApp(fmtStr, args ); va_end( args ); terminar(); exit( 1 ); } // FatalErrorSystem
[ "the.whinner@b139f23c-5e1e-54d6-eab5-85b03e268133" ]
[ [ [ 1, 168 ] ] ]
74fee11cce41a1fa65ad5a3448cb7f50bec6e9c8
27bde5e083cf5a32f75de64421ba541b3a23dd29
/source/Timer.cpp
99463aa000d93674c92e4235127ecaafc472c571
[]
no_license
jbsheblak/fatal-inflation
229fc6111039aff4fd00bb1609964cf37e4303af
5d6c0a99e8c4791336cf529ed8ce63911a297a23
refs/heads/master
2021-03-12T19:22:31.878561
2006-10-20T21:48:17
2006-10-20T21:48:17
32,184,096
0
0
null
null
null
null
UTF-8
C++
false
false
3,672
cpp
//--------------------------------------------------- // Name: Game : Timer // Desc: keeps track of time // Author: John Sheblak // Contact: [email protected] //--------------------------------------------------- #include "Timer.h" #include <time.h> namespace Game { //----------------------------------------------------------- // Name: Timer // Desc: constructor //----------------------------------------------------------- Timer::Timer() : mPaused(true) , mStartTime(0) , mAccumPauseTime(0) , mPauseStartTime(0) , mUnpauseTime(0) {} //----------------------------------------------------------- // Name: StartTimer // Desc: unpauses and begins the timer //----------------------------------------------------------- void Timer::StartTimer() { mStartTime = GetCurTime(); mPaused = false; mUnpauseTime = -1.0f; } //----------------------------------------------------------- // Name: StopTimer // Desc: pauses the timer with no intent to resume //----------------------------------------------------------- void Timer::StopTimer() { mPaused = true; mUnpauseTime = -1.0f; }; //----------------------------------------------------------- // Name: PauseTimer // Desc: pauses the timer with intent to resume //----------------------------------------------------------- void Timer::PauseTimer( F32 pauseLength ) { mPaused = true; mPauseStartTime = GetCurTime(); mUnpauseTime = pauseLength == -1.0f ? -1.0f : GetCurTime() + pauseLength; }; //----------------------------------------------------------- // Name: UnpauseTimer // Desc: restarts timer using the accumulated pause time //----------------------------------------------------------- void Timer::UnpauseTimer() { if( mPaused ) { mAccumPauseTime += GetCurTime() - mPauseStartTime; mPaused = false; mUnpauseTime = -1.0f; } } //----------------------------------------------------------- // Name: ResetAndStopTimer // Desc: //----------------------------------------------------------- void Timer::ResetAndStopTimer() { mAccumPauseTime = 0; StopTimer(); } //----------------------------------------------------------- // Name: GetTimeElapsed // Desc: returns the elapased time since starting the timer //----------------------------------------------------------- F32 Timer::GetTimeElapsed() { return GetCurTime() - mStartTime - mAccumPauseTime; } //----------------------------------------------------------- // Name: IsPaused // Desc: returns if the timer is paused or not //----------------------------------------------------------- bool Timer::IsPaused() { return mPaused; } //----------------------------------------------------------- // Name: Tick // Desc: deals with frame by frame needs of timer //----------------------------------------------------------- void Timer::Tick() { if( mPaused && mUnpauseTime != -1.0f ) { if( GetCurTime() > mUnpauseTime ) UnpauseTimer(); } } //----------------------------------------------------------- // Name: GetTimer // Desc: singleton pattern //----------------------------------------------------------- Timer* Timer::GetTimer() { static Timer* timer = new Timer(); return timer; } //----------------------------------------------------------- // Name: GetCurTime // Desc: grabs the time in seconds //----------------------------------------------------------- F32 Timer::GetCurTime() { return (F32)clock() / 1000.0f; } }; //end Game
[ "jbsheblak@5660b91f-811d-0410-8070-91869aa11e15" ]
[ [ [ 1, 132 ] ] ]
03ccf1ada7feaf3b1ed3b52ddceaece57c8c2c8a
e354a51eef332858855eac4c369024a7af5ff804
/threadsync.cpp
1b4355dc4e54161ed64c8da0c1f8e0cc789d8a20
[]
no_license
cjus/msgCourierLite
0f9c1e05b71abf820c55f74a913555eec2267bb4
9efc1d54737ba47620a03686707b31b1eeb61586
refs/heads/master
2020-04-05T22:41:39.141740
2010-09-05T18:43:12
2010-09-05T18:43:12
887,172
1
0
null
null
null
null
UTF-8
C++
false
false
4,695
cpp
/* threadsync.cpp Copyright (C) 2004 Carlos Justiniano threadsync.cpp is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. threadsync.cpp was developed by Carlos Justiniano for use on the ChessBrain Project (http://www.chessbrain.net) and is now 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 threadsync.cpp; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /** @file threadsync.cpp @brief Thread Synchronization objects @author Carlos Justiniano @attention Copyright (C) 2004 Carlos Justiniano, GNU GPL Licence (see source file header) Thread Synchronization objects */ #include <stdio.h> #include <stdlib.h> #include "threadsync.h" #ifdef _PLATFORM_LINUX #include <unistd.h> #include <signal.h> #define MUTEX_ERROR_CHECK 1 #endif //_PLATFORM_LINUX /** * cThreadSync Constructor */ cThreadSync::cThreadSync() { #ifdef _PLATFORM_LINUX #ifdef MUTEX_ERROR_CHECK pthread_mutexattr_init(&m_attr); //pthread_mutexattr_setkind_np(&m_attr, PTHREAD_MUTEX_ERRORCHECK_NP); pthread_mutex_init(&m_lock, &m_attr); #else pthread_mutex_init(&m_lock, NULL); #endif #endif //_PLATFORM_LINUX #ifdef _PLATFORM_WIN32 InitializeCriticalSection(&m_lock); #endif //_PLATFORM_WIN32 } /** * cThreadSync Destructor */ cThreadSync::~cThreadSync() { #ifdef _PLATFORM_LINUX pthread_mutex_destroy(&m_lock); #endif //_PLATFORM_LINUX #ifdef _PLATFORM_WIN32 DeleteCriticalSection(&m_lock); #endif //_PLATFORM_WIN32 } /** * Acquire exclusive access to code block * @return HRC_THREAD_SYNC_OK if lock is acquired * @note Thread blocks if unable to acquire lock */ int cThreadSync::Lock() { int rc = HRC_THREAD_SYNC_OK; #ifdef _PLATFORM_LINUX #ifdef MUTEX_ERROR_CHECK rc = pthread_mutex_lock(&m_lock); //MC_ASSERT(rc != EDEADLK); #else pthread_mutex_lock(&m_lock); #endif #endif //_PLATFORM_LINUX #ifdef _PLATFORM_WIN32 EnterCriticalSection(&m_lock); #endif //_PLATFORM_WIN32 return rc; } /** * Attempts to acquire exclusive access to code block * @return HRC_THREAD_SYNC_OK if lock is acquired or HRC_THREAD_SYNC_BUSY * if another thread already has exclusive access to the code block. */ int cThreadSync::TryLock() { int rc = HRC_THREAD_SYNC_OK; #ifdef _PLATFORM_LINUX #ifdef MUTEX_ERROR_CHECK rc = pthread_mutex_trylock(&m_lock); //MC_ASSERT(rc != EDEADLK); if (rc == EBUSY) return HRC_THREAD_SYNC_BUSY; #else rc = pthread_mutex_trylock(&m_lock); if (rc == EBUSY) return HRC_THREAD_SYNC_BUSY; #endif #endif //_PLATFORM_LINUX #ifdef _PLATFORM_WIN32 rc = (TryEnterCriticalSection(&m_lock)) ? HRC_THREAD_SYNC_OK : HRC_THREAD_SYNC_BUSY; #endif //_PLATFORM_WIN32 return rc; } /** * Release exclusive access to code block * @return HRC_THREAD_SYNC_OK */ int cThreadSync::Unlock() { int rc = HRC_THREAD_SYNC_OK; #ifdef _PLATFORM_LINUX pthread_mutex_unlock(&m_lock); #endif //_PLATFORM_LINUX #ifdef _PLATFORM_WIN32 LeaveCriticalSection(&m_lock); #endif //_PLATFORM_WIN32 return rc; } /** * Automatic lock and unlock on stack frame * @param pThreadSync pointer to a cThreadSync object * @note block if unable to acquire exclusive lock */ cAutoThreadSync::cAutoThreadSync(cThreadSync *pThreadSync) : m_pThreadSync(pThreadSync) { m_pThreadSync->Lock(); } cAutoThreadSync::~cAutoThreadSync() { m_pThreadSync->Unlock(); } /** * Experimental Automatic timed lock and unlock on stack frame * @param pThreadSync pointer to a cThreadSync object * @note make sure to use the GetRetCode() function to determine * whether the lock was successful. */ cAutoTimedThreadSync::cAutoTimedThreadSync(cThreadSync *pThreadSync) : m_pThreadSync(pThreadSync) , m_rc(HRC_THREAD_SYNC_BUSY) { int spin = 10; while (spin--) { if (m_pThreadSync->TryLock() != HRC_THREAD_SYNC_BUSY) { m_rc = HRC_THREAD_SYNC_OK; break; } #ifdef _PLATFORM_LINUX usleep(1000); #endif //_PLATFORM_LINUX #ifdef _PLATFORM_WIN32 Sleep(10); #endif //_PLATFORM_WIN32 } } /** * cAutoTimedThreadSync Destructor */ cAutoTimedThreadSync::~cAutoTimedThreadSync() { m_pThreadSync->Unlock(); }
[ [ [ 1, 186 ] ] ]