blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ccfa3f16d93b8d3ff54f7d461caa86834b9124f5 | 073dfce42b384c9438734daa8ee2b575ff100cc9 | /RCF/src/RCF/CurrentSession.cpp | 2e220b63b414379503b8e6c4456282124284efe8 | [] | no_license | r0ssar00/iTunesSpeechBridge | a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf | 71a27a52e66f90ade339b2b8a7572b53577e2aaf | refs/heads/master | 2020-12-24T17:45:17.838301 | 2009-08-24T22:04:48 | 2009-08-24T22:04:48 | 285,393 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp |
//******************************************************************************
// RCF - Remote Call Framework
// Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved.
// Consult your license for conditions of use.
// Version: 1.1
// Contact: jarl.lindrud <at> gmail.com
//******************************************************************************
#include <RCF/CurrentSession.hpp>
| [
"[email protected]"
] | [
[
[
1,
10
]
]
] |
87085770f167baaa18ab73cd0a014cfea78b34c4 | 6253ab92ce2e85b4db9393aa630bde24655bd9b4 | /Scene Estimator 2/OperationalMessage.h | ce8a86c981c72e666daf6c18b1f51dcc653e6d29 | [] | no_license | Aand1/cornell-urban-challenge | 94fd4df18fd4b6cc6e12d30ed8eed280826d4aed | 779daae8703fe68e7c6256932883de32a309a119 | refs/heads/master | 2021-01-18T11:57:48.267384 | 2008-10-01T06:43:18 | 2008-10-01T06:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,141 | h | #pragma once
#include <string>
//this file provides the methods that will go from the unmanaged C++ code of the scene estimator to the managed publisher
//specifically for the Operational communication
#ifdef __cplusplus_cli
#pragma managed(push,off)
#endif
using namespace std;
struct UnmanagedOperationalMessage
{
double timestamp;
bool isModelValid;
double roadHeading;
double roadCurvature;
double roadHeadingVar;
double roadCurvatureVar;
string centerLaneID;
string leftLaneID;
string rightLaneID;
double centerLaneCenter;
double leftLaneCenter;
double rightLaneCenter;
double centerLaneWidth;
double leftLaneWidth;
double rightLaneWidth;
bool leftLaneExists;
bool rightLaneExists;
bool centerLaneExists;
double centerLaneCenterVar;
double leftLaneCenterVar;
double rightLaneCenterVar;
double centerLaneWidthVar;
double leftLaneWidthVar;
double rightLaneWidthVar;
bool stopLineExists;
double distToStopline;
double distToStoplineVar;
};
#ifdef __cplusplus_cli
#pragma managed(pop)
#endif
| [
"anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5"
] | [
[
[
1,
56
]
]
] |
7d035940b9fcaf7b7aa556af219c3fc4ac559310 | 880e5a47c23523c8e5ba1602144ea1c48c8c8f9a | /enginesrc/renderer/renderer.cpp | 40eb074ebe71f2f5495cf1fd20aa7b0ca040ae90 | [] | no_license | kfazi/Engine | 050cb76826d5bb55595ecdce39df8ffb2d5547f8 | 0cedfb3e1a9a80fd49679142be33e17186322290 | refs/heads/master | 2020-05-20T10:02:29.050190 | 2010-02-11T17:45:42 | 2010-02-11T17:45:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | cpp | #include "../common.hpp"
#include "renderer.hpp"
#include "rendererbuffermanager.hpp"
namespace engine
{
CRenderer::CRenderer()
{
}
CRenderer::~CRenderer()
{
}
}
/* EOF */
| [
"[email protected]"
] | [
[
[
1,
18
]
]
] |
217b4d1623df0db15560fc98909aff2452b3fe16 | 6f796044ae363f9ca58c66423c607e3b59d077c7 | /source/GuiDialogs/GuiDlgGameSelect.h | 88491a9cb602cef3e98be46d1469456d10d6b080 | [] | no_license | Wiimpathy/bluemsx-wii | 3a68d82ac82268a3a1bf1b5ca02115ed5e61290b | fde291e57fe93c0768b375a82fc0b62e645bd967 | refs/heads/master | 2020-05-02T22:46:06.728000 | 2011-10-06T20:57:54 | 2011-10-06T20:57:54 | 178,261,485 | 2 | 0 | null | 2019-03-28T18:32:30 | 2019-03-28T18:32:30 | null | UTF-8 | C++ | false | false | 3,532 | h | /***************************************************************
*
* Copyright (C) 2008-2011 Tim Brugman
*
* This file may be licensed under the terms of of the
* GNU General Public License Version 2 (the ``GPL'').
*
* Software distributed under the License is distributed
* on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the GPL for the specific language
* governing rights and limitations.
*
* You should have received a copy of the GPL along with this
* program. If not, go to http://www.gnu.org/licenses/gpl.html
* or write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
***************************************************************/
#ifndef _GUI_GAME_SELECT_H
#define _GUI_GAME_SELECT_H
#include "../GuiBase/GuiDialog.h"
#include "../GuiBase/GuiEffectFade.h"
#include "../Gui/DirectoryHelper.h"
#include "../Gui/GameList.h"
#define NUM_LIST_ITEMS 12
typedef enum {
GLEDITSEL_NONE,
GLEDITSEL_ADD,
GLEDITSEL_DEL,
GLEDITSEL_UP,
GLEDITSEL_DOWN,
GLEDITSEL_SETTINGS,
GLEDITSEL_SCRSHOT_1,
GLEDITSEL_SCRSHOT_2
} GLEDITSEL;
class GuiElmBackground;
class GuiElmButton;
class GuiElmFrame;
class GuiElmSelectionList;
class GuiDlgGameSelect;
class GuiElmGameSelectControl : public GuiElement
{
public:
GuiElmGameSelectControl(GuiElement *_parent, const char *name);
virtual ~GuiElmGameSelectControl();
// GuiElement interface
virtual bool OnKey(GuiDialog *dlg, BTN key, bool pressed);
private:
GuiDlgGameSelect *parent;
GuiElmFrame *grWinControlsEdit;
GuiElmButton *grButtonAdd;
GuiElmButton *grButtonDel;
GuiElmButton *grButtonUp;
GuiElmButton *grButtonDown;
GuiElmButton *grButtonSettings;
};
class GuiDlgGameSelect : public GuiDialog
{
friend class GuiElmGameSelectControl;
public:
GuiDlgGameSelect(GuiContainer *parent, const char *name, GuiElmBackground *bgr);
virtual ~GuiDlgGameSelect();
// GuiElement interface
virtual bool OnKey(GuiDialog *dlg, BTN key, bool pressed);
// GuiDialog interface
virtual void OnUpdateScreen(void);
bool Load(const char *dir, const char *filename, GameElement *select = NULL);
GameElement *DoModal(void);
protected:
DirectoryHelper directory;
bool update_screenshots;
GuiElmBackground *background;
GuiElmSelectionList *list;
GameList games;
unsigned games_crc;
char *games_filename;
int num_games;
const char **title_list;
GuiSprite *sprScreenShotNormal[2];
GuiSprite *sprScreenShotEdit[2];
float screenshotWidth;
float screenshotHeigth;
int screenshotYpos;
int last_index;
int last_selected;
GLEDITSEL selected_button;
bool editMode;
GuiEffectFade effectDefault;
GuiEffectFade effectRestart;
GuiEffectFade effectScreenshot;
GuiElmFrame *grWinList;
GuiContainer *containerTitleNormal;
GuiContainer *containerTitleEdit;
GuiContainer *containerPlayNormal;
GuiContainer *containerPlayEdit;
GuiElmGameSelectControl elmControl;
GuiElmFrame *grWinTitleNormal;
GuiElmFrame *grWinPlayNormal;
GuiElmFrame *grWinTitleEdit;
GuiElmFrame *grWinPlayEdit;
GuiElmButton *grButtonDelScr1;
GuiElmButton *grButtonDelScr2;
void ShowElements(void);
void SetSelectedGame(int selected);
void UpdateList(void);
};
#endif
| [
"[email protected]",
"timbrug@c2eab908-c631-11dd-927d-974589228060"
] | [
[
[
1,
21
],
[
23,
24
],
[
26,
28
],
[
44,
63
],
[
67,
69
],
[
72,
74
],
[
80,
83
],
[
86,
86
],
[
89,
92
],
[
95,
95
],
[
101,
104
],
[
107,
118
],
[
121,
123
],
[
125,
128
]
],
[
[
22,
22
],
[
25,
25
],
[
29,
43
],
[
64,
66
],
[
70,
71
],
[
75,
79
],
[
84,
85
],
[
87,
88
],
[
93,
94
],
[
96,
100
],
[
105,
106
],
[
119,
120
],
[
124,
124
]
]
] |
6375b77890d1b48551b3d1ba3fd6a930b73b8770 | cd07acbe92f87b59260478f62a6f8d7d1e218ba9 | /src/MorphaResDlg.cpp | 58d25dc1ecc8ed113bb46f62f46f1a0e914c8e79 | [] | no_license | niepp/sperm-x | 3a071783e573d0c4bae67c2a7f0fe9959516060d | e8f578c640347ca186248527acf82262adb5d327 | refs/heads/master | 2021-01-10T06:27:15.004646 | 2011-09-24T03:33:21 | 2011-09-24T03:33:21 | 46,690,957 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 12,042 | cpp | // MorphaResDlg.cpp : implementation file
//
#include "stdafx.h"
#include "sperm.h"
#include "MorphaResDlg.h"
#include "MainFrm.h"
#include "AllFunction.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMorphaResDlg property page
extern _ConnectionPtr theConnection;
IMPLEMENT_DYNCREATE(CMorphaResDlg, CPropertyPage)
CMorphaResDlg::CMorphaResDlg() : CPropertyPage(CMorphaResDlg::IDD)
{
//{{AFX_DATA_INIT(CMorphaResDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
CMorphaResDlg::~CMorphaResDlg()
{
}
void CMorphaResDlg::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMorphaResDlg)
DDX_Control(pDX, IDC_LIST_MORPHADATA, m_wndMorphaDataList);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMorphaResDlg, CPropertyPage)
//{{AFX_MSG_MAP(CMorphaResDlg)
ON_NOTIFY(NM_CLICK, IDC_LIST_MORPHADATA, OnClickListMorphadata)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMorphaResDlg message handlers
BOOL CMorphaResDlg::OnInitDialog()
{
CPropertyPage::OnInitDialog();
CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd();
CMorphaDataRetriveDlg& dlg = *(pMainFrm->m_pWndMorphadlg);
CString strSQLCRMfi("select morpharesult.* into morphafordisplay \
from morpharesult,basicinfo,morphaimage,spermchait,morpharesultratio \
where morpharesult.pdetectno = basicinfo.pdetectno \
and morpharesult.pdetectno = morphaimage.pdetectno \
and morpharesult.pdetectno = spermchait.pdetectno \
and morpharesult.pdetectno = morpharesultratio.pdetectno");
try
{
if(IsTableExist(theConnection, "morphafordisplay") == true)
{
theConnection->Execute((LPCTSTR)"drop table morphafordisplay",NULL,adCmdText);
}
theConnection->Execute((LPCTSTR)strSQLCRMfi,NULL,adCmdText);
CString strGetN("select count(*) from morphafordisplay");
_RecordsetPtr rs=theConnection->Execute((LPCSTR)strGetN,NULL,adCmdText);
dlg.m_dp[0].nCurPage = 1;
dlg.m_dp[0].nTotalRecord=rs->GetCollect((long)0).iVal;
dlg.m_dp[0].nPageRecord = NUMPERPAGE;
dlg.m_dp[0].nTotalPage = dlg.m_dp[0].nTotalRecord / dlg.m_dp[0].nPageRecord +
(dlg.m_dp[0].nTotalRecord % dlg.m_dp[0].nPageRecord!=0);
CString queryinfo;
queryinfo.Format("共查询到%d条记录",dlg.m_dp[0].nTotalRecord);
dlg.SetDlgItemText(IDC_STATIC_QUERY,queryinfo);
if(dlg.m_dp[0].nTotalRecord == 0 )
{
CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd();
pMainFrm->m_pWndMorphadlg->GetDlgItem(IDC_BTN_FIRSTPAGE)->EnableWindow(FALSE);
pMainFrm->m_pWndMorphadlg->GetDlgItem(IDC_BTN_PREPAGE)->EnableWindow(FALSE);
pMainFrm->m_pWndMorphadlg->GetDlgItem(IDC_BTN_NEXTPAGE)->EnableWindow(FALSE);
pMainFrm->m_pWndMorphadlg->GetDlgItem(IDC_BTN_LASTPAGE)->EnableWindow(FALSE);
pMainFrm->m_pWndMorphadlg->GetDlgItem(IDC_PAGENUM)->EnableWindow(FALSE);
return FALSE;
}
int lowRow, upRow;
dlg.GetPageBound(1,lowRow,upRow,dlg.m_dp[0]);
GetRecordSet(rs,lowRow,upRow);
int n=dlg.m_resdlg.m_wndMorphaDataList.SetData(rs);
queryinfo.Format("第 %d / %d 页",dlg.m_dp[0].nCurPage,dlg.m_dp[0].nTotalPage);
dlg.SetDlgItemText(IDC_PAGENUM,queryinfo);
dlg.GetDlgItem(IDC_BTN_FIRSTPAGE)->EnableWindow(dlg.m_dp[dlg.IsInqueryState()].nCurPage != 1);
dlg.GetDlgItem(IDC_BTN_PREPAGE)->EnableWindow(dlg.m_dp[dlg.IsInqueryState()].nCurPage != 1);
dlg.GetDlgItem(IDC_BTN_NEXTPAGE)->EnableWindow(dlg.m_dp[dlg.IsInqueryState()].nCurPage != dlg.m_dp[dlg.IsInqueryState()].nTotalPage);
dlg.GetDlgItem(IDC_BTN_LASTPAGE)->EnableWindow(dlg.m_dp[dlg.IsInqueryState()].nCurPage != dlg.m_dp[dlg.IsInqueryState()].nTotalPage );
}
catch (_com_error& e)
{
MessageBox(e.Description());
return FALSE;
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CMorphaResDlg::GetRecordSet(_RecordsetPtr &rs, int row1, int row2)
{
ASSERT(row1>=0&&row2>=0&&row1<=row2);
CString strSQL;
CString tablename;
if(((CMorphaDataRetriveDlg*)(GetParent()->GetParent()->GetParent()))->IsInqueryState())
tablename = "morphaforinquery";
else
tablename = "morphafordisplay";
if(row1 == 0 )
{
strSQL.Format("select * from (select top %d * from %s) a "
,row2,tablename);
}
else
{
strSQL.Format("select * from (select top %d * from %s) a \
where pdetectno not in(select top %d pdetectno from %s)"
,row2,tablename,row1,tablename);
}
if(rs == NULL)
rs.CreateInstance("adodb.recordset");
rs = theConnection->Execute((LPCSTR)strSQL,NULL,adCmdText);
}
void CMorphaResDlg::OnClickListMorphadata(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
LV_COLUMN lc;
lc.mask = LVCF_TEXT ;
TCHAR pszText[40];
lc.pszText = pszText;
lc.cchTextMax = sizeof(pszText)/sizeof(pszText[0]);
int nCol = 0;
while (m_wndMorphaDataList.GetColumn(nCol,&lc))
{
if(CString(lc.pszText) == TEXT("检测号"))
break;
++nCol;
}
CString str=m_wndMorphaDataList.GetItemText(pNMListView->iItem,nCol);
if(str == "") return;
CString strSQLinfo("select distinct *,basicinfo.pdetectno as 'pDetectno' from basicinfo,spermchait\
where basicinfo.pdetectno=spermchait.pdetectno and \
basicinfo.pdetectno='");
strSQLinfo= strSQLinfo + str + CString("'");
CPropertySheet* pSheet=(CPropertySheet*)GetParent();
CStatic* pStatic=(CStatic*)pSheet->GetParent();
CMorphaDataRetriveDlg* pDlg=(CMorphaDataRetriveDlg*)pStatic->GetParent();
try
{
_variant_t var;
COleDateTime pddt;
_RecordsetPtr rs=theConnection->Execute((LPCTSTR)strSQLinfo,NULL,adCmdText);
var = rs->GetCollect("pDetectno");
pDlg->m_strEditDetectNO = (char*)(_bstr_t)var;
// pDlg->m_strEditDetectNO.TrimLeft();
// pDlg->m_strEditDetectNO.TrimRight();
var = rs->GetCollect("pCaseNO");
pDlg->m_strEditCaseNO = (char*)(_bstr_t)var;
// pDlg->m_strEditCaseNO.TrimLeft();
// pDlg->m_strEditCaseNO.TrimRight();
var = rs->GetCollect("pname");
pDlg->m_strEditName = (char*)(_bstr_t)var;
// pDlg->m_strEditName.TrimLeft();
// pDlg->m_strEditName.TrimRight();
var = rs->GetCollect("pspermvolume");
pDlg->m_strEditSpermVolume = (char*)(_bstr_t)var;
// pDlg->m_strEditSpermVolume.TrimLeft();
// pDlg->m_strEditSpermVolume.TrimRight();
var = rs->GetCollect("page");
pDlg->m_strEditAge = (char*)(_bstr_t)var;
// pDlg->m_strEditAge.TrimLeft();
// pDlg->m_strEditAge.TrimRight();
pddt=rs->GetCollect("pdetectdatetime");
pDlg->m_oledateDetectDate.SetDate(pddt.GetYear(),pddt.GetMonth(),pddt.GetDay());
pDlg->m_oletimeDetectTime.SetTime(pddt.GetHour(),pddt.GetMinute(),pddt.GetSecond());
var = rs->GetCollect("pSampleNO");
pDlg->m_strEditSampleNO = (char*)(_bstr_t)var;
// pDlg->m_strEditSampleNO.TrimLeft();
// pDlg->m_strEditSampleNO.TrimRight();
var = rs->GetCollect("pdilutionratio");
pDlg->m_strEditDilutionRatio = (char*)(_bstr_t)var;
// pDlg->m_strEditDilutionRatio.TrimLeft();
// pDlg->m_strEditDilutionRatio.TrimRight();
var = rs->GetCollect("pShape");
pDlg->m_strEditShape = (char*)(_bstr_t)var;
// pDlg->m_strEditShape.TrimLeft();
// pDlg->m_strEditShape.TrimRight();
pddt=rs->GetCollect("pspermgetdatetime");
pDlg->m_oledateSpermGetDate.SetDate(pddt.GetYear(),pddt.GetMonth(),pddt.GetDay());
pDlg->m_oletimeSpermGetTime.SetTime(pddt.GetHour(),pddt.GetMinute(),pddt.GetSecond());
var = rs->GetCollect("pcolor");
pDlg->m_strEditSpermColor = (char*)(_bstr_t)var;
// pDlg->m_strEditSpermColor.TrimLeft();
// pDlg->m_strEditSpermColor.TrimRight();
var = rs->GetCollect("pcohesion");
pDlg->m_strEditCohension = (char*)(_bstr_t)var;
// pDlg->m_strEditCohension.TrimLeft();
// pDlg->m_strEditCohension.TrimRight();
var = rs->GetCollect("pRoomTempera");
pDlg->m_strEditRoomTempera = (char*)(_bstr_t)var;
// pDlg->m_strEditRoomTempera.TrimLeft();
// pDlg->m_strEditRoomTempera.TrimRight();
var = rs->GetCollect("pdaysofabstinency");
pDlg->m_strEditAbstinency = (char*)(_bstr_t)var;
// pDlg->m_strEditAbstinency.TrimLeft();
// pDlg->m_strEditAbstinency.TrimRight();
var = rs->GetCollect("pliquifystate");
pDlg->m_strEditLiquifyState = (char*)(_bstr_t)var;
// pDlg->m_strEditLiquifyState.TrimLeft();
// pDlg->m_strEditLiquifyState.TrimRight();
var = rs->GetCollect("psmell");
pDlg->m_strEditSmell = (char*)(_bstr_t)var;
// pDlg->m_strEditSmell.TrimLeft();
// pDlg->m_strEditSmell.TrimRight();
var = rs->GetCollect("pthickness");
pDlg->m_strEditThickness = (char*)(_bstr_t)var;
// pDlg->m_strEditThickness.TrimLeft();
// pDlg->m_strEditThickness.TrimRight();
var = rs->GetCollect("pph");
pDlg->m_strEditPH = (char*)(_bstr_t)var;
// pDlg->m_strEditPH.TrimLeft();
// pDlg->m_strEditPH.TrimRight();
var = rs->GetCollect("pspermmethod");
pDlg->m_strEditSpermWay = (char*)(_bstr_t)var;
// pDlg->m_strEditSpermWay.TrimLeft();
// pDlg->m_strEditSpermWay.TrimRight();
var = rs->GetCollect("pliquifytime");
pDlg->m_strEditLiquifyTime = (char*)(_bstr_t)var;
// pDlg->m_strEditLiquifyTime.TrimLeft();
// pDlg->m_strEditLiquifyTime.TrimRight();
pDlg->UpdateData(FALSE);
}
catch (_com_error& e)
{
AfxMessageBox(e.Description());
return;
}
//
str.Format("select * from morphasperminfo where pid like('%s%%')", pDlg->m_strEditDetectNO);
try
{
_RecordsetPtr rs=theConnection->Execute((LPCTSTR)str,NULL,adCmdText);
_variant_t vt;
SingleSpermInfo ssInfo;
pDlg->m_vSpermInfo.clear();
while(!rs->EndOfFile)
{
vt = rs->GetCollect("x");
ssInfo.pos.x = (long)vt;
vt = rs->GetCollect("y");
ssInfo.pos.y = (long)vt;
vt = rs->GetCollect("pid");
CString cs;
cs = (char*)(_bstr_t)vt;
int nl = cs.ReverseFind('_');
nl = cs.GetLength()-nl-1;
cs = cs.Right(nl);
ssInfo.nSpermNO = atol((LPCTSTR)cs);
vt = rs->GetCollect("IsNormal");
ssInfo.bIsNormal = (bool)vt;
vt = rs->GetCollect("m_length");
ssInfo.smPara.m_length = (double)vt;
vt = rs->GetCollect("m_width");
ssInfo.smPara.m_width = (double)vt;
vt = rs->GetCollect("m_area");
ssInfo.smPara.m_area = (double)vt;
vt = rs->GetCollect("m_ellipticity");
ssInfo.smPara.m_ellipticity = (double)vt;
vt = rs->GetCollect("m_perfor_area");
ssInfo.smPara.m_perfor_area = (double)vt;
vt = rs->GetCollect("m_head_area");
ssInfo.smPara.m_head_area = (double)vt;
vt = rs->GetCollect("m_perimeter");
ssInfo.smPara.m_perimeter = (double)vt;
vt = rs->GetCollect("m_head_perfor_area");
ssInfo.smPara.m_head_perfor_area = (double)vt;
vt = rs->GetCollect("m_tail_length");
ssInfo.smPara.m_tail_length = (double)vt;
vt = rs->GetCollect("m_tail_width");
ssInfo.smPara.m_tail_width = (double)vt;
vt = rs->GetCollect("m_tail_angle");
ssInfo.smPara.m_tail_angle = (double)vt;
vt = rs->GetCollect("m_extension");
ssInfo.smPara.m_extension = (double)vt;
vt = rs->GetCollect("m_symmetry");
ssInfo.smPara.m_symmetry = (double)vt;
vt = rs->GetCollect("m_ruga");
ssInfo.smPara.m_ruga = (double)vt;
pDlg->m_vSpermInfo.push_back(ssInfo);
rs->MoveNext();
}
// Update UI button
UINT uSelectedCount = m_wndMorphaDataList.GetSelectedCount();
BOOL enable = uSelectedCount>=1 ? TRUE : FALSE;
CDialog *pdlg = ((CMainFrame*)AfxGetMainWnd())->m_pWndMorphadlg;
::SendMessage(pdlg->GetSafeHwnd(), USER_MSG_SHOW_PRINT_BTN, (WPARAM)enable, 0);
::SendMessage(pdlg->GetSafeHwnd(), USER_MSG_SHOW_MOPHY_DEL_SEL_BTN, (WPARAM)enable, 0);
}
catch (_com_error& e)
{
MessageBox(e.Description());
return;
}
*pResult = 0;
}
| [
"harithchen@e030fd90-5f31-5877-223c-63bd88aa7192"
] | [
[
[
1,
342
]
]
] |
0abcc1467c5b7dcf638034fa17f580141cfd09ac | aa825896cc7c672140405ab51634d00d28fad09b | /zomgatron/DialogManager.h | bfaffbe77f4ffc5f1d5b5d3a6ff40891ea85d72f | [] | 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 | 443 | h | #ifndef __DIALOGMANAGER_H__
#define __DIALOGMANAGER_H__
#define DIALOG_WIDTH 512
#define DIALOG_HEIGHT 512
#define DIALOG_FIRSTX 16
#define DIALOG_FIRSTY 32
#define DIALOG_MAXX 496
#define DIALOG_MAXY 480
#include "Button.h"
#include "Window.h"
#include "Label.h"
class DialogManager{
public:
static Window* MakeMessageWindow(std::string text, Vector2 position);
static void closeWindow(UIBase* caller);
};
#endif
| [
"Kivu.Rako@54144a58-e977-11dd-a550-c997509ed985"
] | [
[
[
1,
22
]
]
] |
cf56618146ab5851ee90210e681717be2510d97c | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEEffects/SETerrainEffect.cpp | baa10d40322c2da31019b060a7cc6155b216035e | [] | 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 | 5,290 | 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 "SEFoundationPCH.h"
#include "SETerrainEffect.h"
using namespace Swing;
SE_IMPLEMENT_RTTI(Swing, SETerrainEffect, SEShaderEffect);
SE_IMPLEMENT_STREAM(SETerrainEffect);
SE_IMPLEMENT_DEFAULT_NAME_ID(SETerrainEffect, SEShaderEffect);
//SE_REGISTER_STREAM(SETerrainEffect);
float SETerrainEffect::ms_afFogColorDensity[4] = {0.0f, 0.0f, 0.0f, 0.0f};
bool SETerrainEffect::ms_bFogColorDensityUCInitialized = false;
//----------------------------------------------------------------------------
SETerrainEffect::SETerrainEffect(const char* acBaseName,
const char* acDetailName, const SEColorRGB& rFogColor, float fFogDensity)
:
SEShaderEffect(1)
{
m_VShader[0] = SE_NEW SEVertexShader(
"BaseMulDetailFogExpSqr.v_BaseMulDetailFogExpSqr");
m_PShader[0] = SE_NEW SEPixelShader(
"BaseMulDetailFogExpSqr.p_BaseMulDetailFogExpSqr");
m_PShader[0]->SetTextureCount(2);
m_PShader[0]->SetImageName(0, acBaseName);
m_PShader[0]->SetImageName(1, acDetailName);
SETexture* pBase = m_PShader[0]->GetTexture(0);
pBase->SetFilterType(SETexture::LINEAR_LINEAR);
pBase->SetWrapType(0, SETexture::REPEAT);
pBase->SetWrapType(1, SETexture::REPEAT);
SETexture* pDetail = m_PShader[0]->GetTexture(1);
pDetail->SetFilterType(SETexture::LINEAR_LINEAR);
SetFogColor(rFogColor);
SetFogDensity(fFogDensity);
}
//----------------------------------------------------------------------------
SETerrainEffect::SETerrainEffect()
{
}
//----------------------------------------------------------------------------
SETerrainEffect::~SETerrainEffect()
{
}
//----------------------------------------------------------------------------
void SETerrainEffect::OnLoadPrograms(int, SEProgram* pVProgram,
SEProgram* pPProgram, SEProgram*)
{
if( !ms_bFogColorDensityUCInitialized )
{
SEUserConstant* pUC = pVProgram->GetUC("FogColorDensity");
if( pUC )
pUC->SetDataSource(ms_afFogColorDensity);
pUC = pPProgram->GetUC("FogColorDensity");
if( pUC )
pUC->SetDataSource(ms_afFogColorDensity);
ms_bFogColorDensityUCInitialized = true;
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// streaming
//----------------------------------------------------------------------------
void SETerrainEffect::Load(SEStream& rStream, SEStream::SELink* pLink)
{
SE_BEGIN_DEBUG_STREAM_LOAD;
SEShaderEffect::Load(rStream, pLink);
rStream.Read(4, ms_afFogColorDensity);
SE_END_DEBUG_STREAM_LOAD(SETerrainEffect);
}
//----------------------------------------------------------------------------
void SETerrainEffect::Link(SEStream& rStream, SEStream::SELink* pLink)
{
SEShaderEffect::Link(rStream, pLink);
}
//----------------------------------------------------------------------------
bool SETerrainEffect::Register(SEStream& rStream) const
{
return SEShaderEffect::Register(rStream);
}
//----------------------------------------------------------------------------
void SETerrainEffect::Save(SEStream& rStream) const
{
SE_BEGIN_DEBUG_STREAM_SAVE;
SEShaderEffect::Save(rStream);
rStream.Write(4, ms_afFogColorDensity);
SE_END_DEBUG_STREAM_SAVE(SETerrainEffect);
}
//----------------------------------------------------------------------------
int SETerrainEffect::GetDiskUsed(const SEStreamVersion& rVersion) const
{
return SEShaderEffect::GetDiskUsed(rVersion) +
4*sizeof(ms_afFogColorDensity[0]);
}
//----------------------------------------------------------------------------
SEStringTree* SETerrainEffect::SaveStrings(const char*)
{
SEStringTree* pTree = SE_NEW SEStringTree;
// strings
pTree->Append(Format(&TYPE, GetName().c_str()));
SEColorRGB tempColor(ms_afFogColorDensity[0], ms_afFogColorDensity[1],
ms_afFogColorDensity[2]);
pTree->Append(Format("fog color =", tempColor));
pTree->Append(Format("fog density =", ms_afFogColorDensity[3]));
// children
pTree->Append(SEShaderEffect::SaveStrings());
return pTree;
}
//----------------------------------------------------------------------------
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
145
]
]
] |
187614b7468b8054f377d0693ceedb6ebc2c7ba7 | 3856c39683bdecc34190b30c6ad7d93f50dce728 | /LastProject/Source/GUIListbox.h | edf16a2e4bcaf3287981c2ab5adf0f880b52d49d | [] | no_license | yoonhada/nlinelast | 7ddcc28f0b60897271e4d869f92368b22a80dd48 | 5df3b6cec296ce09e35ff0ccd166a6937ddb2157 | refs/heads/master | 2021-01-20T09:07:11.577111 | 2011-12-21T22:12:36 | 2011-12-21T22:12:36 | 34,231,967 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,636 | h | #pragma once
#ifndef _GUILISTBOX_H_
#define _GUILISTBOX_H_
#include "GUIBase.h"
#include <list>
class GUIBtnManager;
class GUIScrollbar;
class GUIListbox : public GUIBase
{
private:
VOID Initialize();
VOID Release();
VOID CopyTextureToItem( INT _iNumItem, LPIMAGE2D _pimg2DTexture, LPIMAGE2D _pimg2DItemNormal, LPIMAGE2D _pimg2DItemDown );
VOID CopyTextToItem( INT _iNumItem, LPIMAGE2D _pimg2DText, LPIMAGE2D _pimg2DItemNormal, LPIMAGE2D _pimg2DItemDown );
VOID CopyItemToFront( INT _iNumItem, LPIMAGE2D _pimg2DItem, LPIMAGE2D _pimg2DFront );
public:
GUIListbox( LPDIRECT3DDEVICE9 _pd3dDevice, LPD3DXSPRITE _pSprite ) : GUIBase( _pd3dDevice, _pSprite )
{
this->Initialize();
}
virtual ~GUIListbox()
{
this->Release();
}
enum { LBX_HROZ = 0, LBX_VERT };
typedef struct _ITEM
{
LPIMAGE2D pimg2DNormal;
LPIMAGE2D pimg2DDown;
_ITEM()
{
pimg2DNormal = NULL;
pimg2DDown = NULL;
}
~_ITEM()
{
if( pimg2DNormal != NULL )
delete pimg2DNormal;
if( pimg2DDown != NULL )
delete pimg2DDown;
}
}ITEM, *LPITEM;
typedef std::list< LPITEM > ITEMLIST;
typedef struct _DATA
{
IMAGE3D img3DBackground;
IMAGE2D img2DFront; // 나눈건 뭔가 이유가 있을꺼야...기억은 안나지만
RECT rtRear;
ITEMLIST lstItem;
~_DATA()
{
ITEMLIST::iterator itE;
for( itE = lstItem.begin() ; itE != lstItem.end() ; itE++ )
delete (*itE);
lstItem.clear();
}
}DATA, *LPDATA;
//VOID Create( GUIBase::IMAGEPARAM& _imgFront, GUIBase::IMAGEPARAM& _imgBack );
VOID Create( LPIMAGEPARAM _pimgBack );
VOID Create( FLOAT _fX, FLOAT _fY, FLOAT _fWidth, FLOAT _fHeight, IMAGEPARAM& _imgBackground );
VOID AddItem( LPWSTR _Text, LPWSTR _TextureFileName = NULL );
VOID SetItemGap( INT _iItemGap );
VOID Update( INT _iX, INT _iY );
VOID Render();
VOID OnDown( INT x, INT y );
VOID OnMove( INT x, INT y );
VOID OnUp( INT x, INT y );
VOID SetFont( LPWSTR _pFaceName, INT _iWidth, INT _iHeight, DWORD _dColor );
private:
enum { GLB_BTN_UP = 6000, GLB_BTN_DOWN };
DATA m_Data;
//ITEMLIST m_lstItem;
DWORD m_dStyle; // 가로, 세로 따로 할려고 했는데 아직;;
FLOAT m_iMaxItem;
INT m_iScrollSpeed;
INT m_iItemGap;
FLOAT m_fX, m_fY;
FLOAT m_fWidth, m_fHeight;
GUIBtnManager* m_pGUIBtnManager;
GUIScrollbar* m_pGUIScrollbar;
BOOL m_bActScrollbar;
TCHAR m_aFaceName[ 1024 ];
INT m_iFontX, m_iFontY;
INT m_iFontWidth, m_iFontHeight;
DWORD m_dFontColor;
public:
};
#endif | [
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0"
] | [
[
[
1,
113
]
]
] |
4e3679099926b1fca8f4a559557796393586cf96 | 672d939ad74ccb32afe7ec11b6b99a89c64a6020 | /Graph/FloatLevel/MainFrm.h | b9b1ee5740cd948c21a4f0cb38a7120b3fb73b68 | [] | no_license | cloudlander/legacy | a073013c69e399744de09d649aaac012e17da325 | 89acf51531165a29b35e36f360220eeca3b0c1f6 | refs/heads/master | 2022-04-22T14:55:37.354762 | 2009-04-11T13:51:56 | 2009-04-11T13:51:56 | 256,939,313 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,639 | h | // MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__525F46AA_7EF0_4F44_A30D_9E25ACA15912__INCLUDED_)
#define AFX_MAINFRM_H__525F46AA_7EF0_4F44_A30D_9E25ACA15912__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "ChildView.h"
class CMainFrame : public CFrameWnd
{
public:
CMainFrame();
protected:
DECLARE_DYNAMIC(CMainFrame)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
CChildView m_wndView;
// Generated message map functions
protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSetFocus(CWnd *pOldWnd);
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__525F46AA_7EF0_4F44_A30D_9E25ACA15912__INCLUDED_)
| [
"xmzhang@5428276e-be0b-f542-9301-ee418ed919ad"
] | [
[
[
1,
60
]
]
] |
c185272262d2d7f809bf813c7bd42eead158b1be | b06523245317f59fca3a83e26e0abb22d353b50b | /sikuli-script/src/main/native/finder.h | 5e81acd9078ae35ec8a0056f996cfdf01b3834c0 | [
"MIT"
] | permissive | ck1125/sikuli | 500935e981349824e17aa82cd47214dbe19c51e0 | 978b61e79a589be04c558ae4c1d78479b658774b | refs/heads/master | 2016-09-06T00:19:32.340710 | 2011-06-08T20:37:19 | 2011-06-08T20:37:19 | 1,905,905 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,986 | h | /*
* Copyright 2010-2011, Sikuli.org
* Released under the MIT License.
*
*/
#ifndef _FINDER_H_
#define _FINDER_H_
#include "pyramid-template-matcher.h"
class BaseFinder{
public:
BaseFinder(IplImage* screen_image);
BaseFinder(Mat source);
BaseFinder(const char* source_image_filename);
virtual ~BaseFinder();
void setROI(int x, int y, int w, int h);
int get_screen_height() const { return source.rows;};
int get_screen_width() const {return source.cols;};
void find();
// virtual void find(const char* str, double min_similarity) = 0;
virtual bool hasNext() = 0;
virtual FindResult next() = 0;
protected:
Rect roi;
Mat source;
Mat roiSource;
double min_similarity;
};
class TextFinder : public BaseFinder {
public:
TextFinder(Mat source);
static void train(Mat& trainingImage);
void find(const char* word, double min_similarity);
void find(vector<string> words, double min_similarity);
void find_all(const char* word, double min_similarity);
void find_all(vector<string> words, double min_similarity);
bool hasNext();
FindResult next();
static vector<string> recognize(const Mat& inputImage);
private:
vector<FindResult> matches;
vector<FindResult>::iterator matches_iterator;
void test_find(const Mat& inputImage, const vector<string>& testWords);
};
class TemplateFinder : public BaseFinder{
public:
TemplateFinder(Mat source);
TemplateFinder(IplImage* source);
TemplateFinder(const char* source_image_filename);
~TemplateFinder();
void find(Mat target, double min_similarity);
void find(IplImage* target, double min_similarity);
void find(const char *target_image_filename, double min_similarity);
void find_all(Mat target, double min_similarity);
void find_all(IplImage* target, double min_similarity);
void find_all(const char *target_image_filename, double min_similarity);
bool hasNext();
FindResult next();
private:
void create_matcher(Mat& source, Mat& target, int level, float ratio);
PyramidTemplateMatcher* matcher;
FindResult current_match;
int current_rank;
// buffer matches and return top score
void add_matches_to_buffer(int num_matches_to_add);
float top_score_in_buffer();
vector<FindResult> buffered_matches;
};
class Finder {
public:
Finder(Mat mat);
Finder(IplImage* source);
Finder(const char* source);
~Finder();
void setROI(int x, int y, int w, int h);
void find(IplImage* target, double min_similarity);
void find(const char *target, double min_similarity);
void find_all(IplImage* target, double min_similarity);
void find_all(const char *target, double min_similarity);
bool hasNext();
FindResult next();
private:
Mat _source;
BaseFinder* _finder;
Rect _roi;
};
class FaceFinder : public BaseFinder {
public:
FaceFinder(const char* screen_image_filename);
~FaceFinder();
void find();
bool hasNext();
FindResult next();
private:
CvMemStorage* storage;
static CvHaarClassifierCascade* cascade;
CvSeq* faces;
int face_i;
};
class ChangeFinder : public BaseFinder {
public:
ChangeFinder(const IplImage* screen_image);
ChangeFinder(const Mat screen_image);
ChangeFinder(const char* screen_image_filename);
~ChangeFinder();
void find(IplImage* new_img);
void find(Mat new_img);
void find(const char* new_screen_image_filename);
bool hasNext();
FindResult next();
private:
bool is_identical;
IplImage *prev_img;
CvSeq* c;
CvMemStorage* storage;
};
#endif // _FINDER_H_
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
5
],
[
9,
9
],
[
12,
12
],
[
14,
33
],
[
35,
38
],
[
42,
45
],
[
47,
47
],
[
49,
50
],
[
58,
58
],
[
60,
60
],
[
63,
64
],
[
66,
66
],
[
68,
70
],
[
72,
90
],
[
92,
92
],
[
94,
99
],
[
101,
101
],
[
103,
108
],
[
110,
115
],
[
117,
124
],
[
126,
131
],
[
134,
134
],
[
136,
143
],
[
145,
152
],
[
157,
157
],
[
159,
172
],
[
174,
180
],
[
186,
186
]
],
[
[
6,
8
],
[
10,
11
],
[
13,
13
],
[
34,
34
],
[
52,
55
],
[
71,
71
],
[
91,
91
],
[
132,
133
],
[
135,
135
],
[
144,
144
],
[
153,
156
],
[
158,
158
],
[
173,
173
],
[
181,
181
]
],
[
[
39,
41
],
[
46,
46
],
[
48,
48
],
[
51,
51
],
[
56,
57
],
[
59,
59
],
[
61,
62
],
[
65,
65
],
[
67,
67
],
[
93,
93
],
[
100,
100
],
[
102,
102
],
[
109,
109
],
[
116,
116
],
[
125,
125
],
[
182,
185
]
]
] |
7402a3a28ab6b893ad38ea9720f5be7bc9f0f471 | d37a1d5e50105d82427e8bf3642ba6f3e56e06b8 | /DVR/HaohanITPlayer/public/Common/SysUtils/sonic_crt.cpp | 254e9dbf18be985412aa2d2590c8ad04e4e265a9 | [] | no_license | 080278/dvrmd-filter | 176f4406dbb437fb5e67159b6cdce8c0f48fe0ca | b9461f3bf4a07b4c16e337e9c1d5683193498227 | refs/heads/master | 2016-09-10T21:14:44.669128 | 2011-10-17T09:18:09 | 2011-10-17T09:18:09 | 32,274,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,036 | cpp | ///////////////////////////////////////////////////////////////////////////////
// sonic_crt.cpp
// Copyright (c) 2005, Haohanit. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include "sonic_crt.h"
#include "UnicodeUtilities.h"
#include <cstdio>
#include <ctime>
#ifdef _WIN32
#pragma warning(disable:4996) // disable deprecation warnings
#else
#include "UnicodeUtilities.h"
#endif
char * sonic::asctime_safe(
const tm * tm,
__out_bcount_z(bytes) char * buffer,
size_t bytes)
{
return strlcpy(buffer, asctime(tm), bytes);
}
char * sonic::ctime_safe(
const time_t * time,
__out_bcount_z(bytes) char * buffer,
size_t bytes)
{
return asctime_safe(localtime(time), buffer, bytes); // per the ISO C standard
}
FILE * sonic::fopen(
const char * path,
const char * mode)
{
return ::fopen(path, mode);
}
void sonic::ftime(
timeb * t)
{
#ifdef _WIN32
_ftime(t);
#elif defined(OSXPORT)
// no _timezone and timezone is a function. So do it the
// hardway
time_t rawtime;
struct tm * timeinfo;
struct timeval timeval;
time( &rawtime );
gettimeofday(&timeval, 0);
timeinfo = localtime(&rawtime);
t->time = timeval.tv_sec;
t->millitm = timeval.tv_usec/1000L;
t->timezone = timeinfo->tm_gmtoff;
t->dstflag = timeinfo->tm_isdst;
#else
::ftime(t);
#endif
}
char * sonic::itoa_safe(
SInt64 i,
__out_bcount_z(bytes) char * buffer,
size_t bytes,
int radix)
{
UInt64 ui = i;
if (
radix == 10
&& i < 0)
{
bytes--;
assert(bytes > 1);
*buffer++ = '-';
ui = -i;
};
return uitoa_safe(ui, buffer, bytes, radix);
}
struct tm * sonic::localtime_safe(
const time_t * time,
tm * result)
{
#ifdef _WIN32
*result = *localtime(time);
return result;
#else
return localtime_r(time, result);
#endif
}
struct tm * sonic::gmtime_safe(
const time_t * time,
tm * result)
{
#ifdef _WIN32
*result = *gmtime(time);
return result;
#else
return gmtime_r(time, result);
#endif
}
char * sonic::uitoa_safe(
UInt64 ui,
__out_bcount_z(bytes) char * buffer,
size_t bytes,
int radix)
{
assert(radix >= 2 && radix <= 16);
std::string digits;
if (ui == 0)
digits = "0";
else while (ui != 0)
{
char digit = static_cast<char>(ui % radix);
digit += digit <= 9 ? '0' : 'A' - 10;
digits.insert(0, 1, static_cast<char>(digit));
ui /= radix;
}
return strlcpy(buffer, digits.c_str(), bytes);
}
size_t sonic::snprintf_safe(
__out_bcount_z(bytes) char * buffer,
size_t bytes,
const char * format,
...)
{
va_list args;
va_start(args, format);
size_t r = vsnprintf_safe(buffer, bytes, format, args);
va_end(args);
return r;
}
int sonic::get_daylight()
{
sonic::tzset();
#ifdef _WIN32
#if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__NTBUILD__)
int hours;
_get_daylight(&hours);
return hours;
#else
return _daylight;
#endif
#elif defined(OSXPORT)
// no _timezone and timezone is a function. So do it the
// hardway
time_t rawtime;
struct tm * timeinfo;
time( &rawtime );
timeinfo = localtime(&rawtime);
return timeinfo->tm_isdst;
#else
return daylight;
#endif
}
long sonic::get_timezone()
{
sonic::tzset();
#ifdef _WIN32
#if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__NTBUILD__)
long seconds;
_get_timezone(&seconds);
return seconds;
#else
return _timezone;
#endif
#elif defined (__CYGWIN__)
return _timezone;
#elif defined(macintosh) || defined(OSXPORT)
// no _timezone and timezone is a function. So do it the
// hardway
time_t rawtime;
struct tm * timeinfo;
time( &rawtime );
timeinfo = localtime(&rawtime);
return timeinfo->tm_gmtoff;
#else
return timezone;
#endif
}
void sonic::tzset()
{
static bool is_tzset = false;
if (!is_tzset)
{
#ifdef _WIN32
_tzset();
#else
tzset();
#endif
is_tzset = true;
}
}
size_t sonic::vsnprintf_safe(
__out_bcount_z(bytes) char * buffer,
size_t bytes,
const char * format,
const va_list args)
{
assert(buffer != 0);
assert(bytes > 0);
assert(format != 0);
#ifndef __stm__ // g++ complains, kernel 2.6.11, version 3.4.3 error: invalid operands of types `va_list' and `int' to binary `operator==' isn't it void* ?
assert(args != 0);
#endif
#ifdef _WIN32
int result = _vsnprintf(buffer, bytes, format, args);
#else
int result = vsnprintf(buffer, bytes, format, args);
#endif
if (
result < 0
|| static_cast<size_t>(result) >= bytes)
{
assert(false);
buffer[bytes - 1] = 0;
return bytes - 1;
}
return static_cast<size_t>(result);
}
FILE * sonic::wfopen(
const wchar_t * path,
const wchar_t * mode)
{
#ifdef _WIN32
return _wfopen(path, mode);
#else
return ::fopen(
unicode::to_string(path).c_str(),
unicode::to_string(mode).c_str());
#endif
} | [
"[email protected]@27769579-7047-b306-4d6f-d36f87483bb3"
] | [
[
[
1,
311
]
]
] |
45b4c7a2ec6f7762f82fedc86655bc8e24f223b1 | f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae | /Exercises/Old Solutions/OpenGL4/OpenGL4/controller.h | 8661889edb41bfbe31c468d44747abfb08c11d87 | [] | no_license | giacomof/gameengines2010itu | 8407be66d1aff07866d3574a03804f2f5bcdfab1 | bc664529a429394fe5743d5a76a3d3bf5395546b | refs/heads/master | 2016-09-06T05:02:13.209432 | 2010-12-12T22:18:19 | 2010-12-12T22:18:19 | 35,165,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 830 | h | #pragma once
#include <SDL.h>
#include "entitySpectator.h"
#include "assetManager.h"
class Controller // Singleton
{
public:
static Controller _instance;
static SDL_mutex *mutex_controller;
static entitySpectator *playerObject;
static bool quit;
Controller() { &getInstance(); }
~Controller() { SDL_DestroyMutex( mutex_controller ); }
Controller(const Controller &getInstance());
Controller & operator=(Controller &getInstance());
static Controller &getInstance();
static void setPlayerObject(entitySpectator *player);
static void moveForward(bool shouldMove);
static void moveBackward(bool shouldMove);
static void strafeLeft(bool shouldMove);
static void strafeRight(bool shouldMove);
static void lookDeltaX(float deltaLook);
static void lookDeltaY(float deltaLook);
}; | [
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d",
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d"
] | [
[
[
1,
2
],
[
5,
5
],
[
15,
15
],
[
28,
28
]
],
[
[
3,
4
],
[
6,
14
],
[
16,
27
],
[
29,
29
]
]
] |
79426044ddc9850fc9ed5338a5debfaedb038c74 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/SearchButton.h | 2fefb659b3aaea5546679deaca182a91f367c9f0 | [] | no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,157 | h | #pragma once
// CSearchButton
class CSearchButton : public CButton
{
public:
CSearchButton();
virtual ~CSearchButton();
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct);
//{{AFX_VIRTUAL(CButtonST)
//virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
//}}AFX_VIRTUAL
protected:
virtual void PreSubclassWindow();
void DrawInactive(CDC* pDC, const CRect& rect);
void DrawHover(CDC* pDC,const CRect& rect);
void DrawPressed(CDC* pDC, const CRect& rect);
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
protected:
HICON m_hIcon;
BOOL m_bHover;
BOOL m_bIsPressed;
public:
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
public:
BOOL Create(CWnd* pParentWnd, CRect rect, LPCTSTR lpszCaption = NULL, DWORD dwStyle = WS_CHILD | WS_VISIBLE, UINT nID = 123);
void GetDesireSize(CSize &size);
private:
LRESULT OnMouseLeave(WPARAM wParam, LPARAM lParam);
public:
afx_msg void OnBnClicked();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
// afx_msg void OnPaint();
virtual BOOL PreTranslateMessage(MSG* pMsg);
}; | [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
] | [
[
[
1,
45
]
]
] |
4866c8765cd279f2bbb96c1aa61d0e8e2768ca65 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/2950/2950.cpp | 277b9c80ac7e1faea03e899c97eac34fa248fbc9 | [] | no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 941 | cpp | #include "iostream"
#include "stdio.h"
using namespace std;
int m,n,time;
int num[52][52];
int sum;
int x=-1,y=-1,nx,ny;
int abs(int _x,int _y)
{
if (_x<_y )
return _y-_x;
return _x-_y;
}
void findnext()
{
int max=0;
for (int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
if (num[i][j]>max)
{
max=num[i][j];
nx=i;ny=j;
}
}
}
if (max==0)
{
nx=-1;ny=-1;
}
}
int step()
{
if (x<0)
{
return 1+nx;
}
return abs(x,nx)+abs(y,ny);
}
int main()
{
int cs;
cin>>cs;
while(cs--){
cin>>m>>n>>time;
memset(num,0,sizeof(num));
sum=0;x=-1;y=-1;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
scanf("%d",&num[i][j]);
while(time){
findnext();
if(nx==-1) break;
int nextstep=step()+nx+2;
if(nextstep>time) break;
time-=nextstep-nx-1;
sum+=num[nx][ny];
num[nx][ny]=0;
x=nx;y=ny;
}
cout<<sum<<endl;
}
return 0;
} | [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] | [
[
[
1,
68
]
]
] |
9daacb58ce7703bde4accf28899daef5d5bc3d80 | 611fc0940b78862ca89de79a8bbeab991f5f471a | /src/Teki/KaeruKing.h | 87cf6bb4594ff9803b73bbc2cf828e42834b9395 | [] | no_license | LakeIshikawa/splstage2 | df1d8f59319a4e8d9375b9d3379c3548bc520f44 | b4bf7caadf940773a977edd0de8edc610cd2f736 | refs/heads/master | 2021-01-10T21:16:45.430981 | 2010-01-29T08:57:34 | 2010-01-29T08:57:34 | 37,068,575 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 816 | h | #pragma once
#include "Teki.h"
class KaeruKing : public Teki
{
public:
KaeruKing(int rXPx, int rYPx);
~KaeruKing(void);
void _Move(); // 敵から
TEKI_SETUP;
enum STATUS
{
TAIKI,
JUMP_START,
JUMP
};
private:
// ルーチン
void MapAtHt();
void DieIfGamenGai();
// データ
static int sMapAtHanteiX[4][MAX_TEN]; // 2点: 0- 床 1- 前
static int sMapAtHanteiY[4][MAX_TEN];
// 基本
STATUS mStatus;
// 移動用
float mTaikiTimer;
// 当たり判定用
int mShirabe[4]; // 当たったときに、壁の位置を返す(その軸の座標)
int mAtari[4]; // 当たってるとフラグが立つ
int KAERUKSX;
int KAERUKSY;
float KTAIKI_TIME;
float KJUMPSTART_TIME;
float KJMPSPX;
float KJMPTAKASA;
};
| [
"lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b"
] | [
[
[
1,
50
]
]
] |
dc0fb1df114c942d0d831a49aae16c0b293c3e67 | 6eef3e34d3fe47a10336a53df1a96a591b15cd01 | /ASearch/Main/alkaline.cpp | 04b2077986bb3dd724091264671c8e6114c20a55 | [] | no_license | praveenmunagapati/alkaline | 25013c233a80b07869e0fdbcf9b8dfa7888cc32e | 7cf43b115d3e40ba48854f80aca8d83b67f345ce | refs/heads/master | 2021-05-27T16:44:12.356701 | 2009-10-29T11:23:09 | 2009-10-29T11:23:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25 | cpp | #include "alkaline.hpp"
| [
"[email protected]"
] | [
[
[
1,
1
]
]
] |
a01b6d28e8e5af6763e187686087875009b6ef08 | a1dc22c5f671b7859339aaef69b3461fad583d58 | /src/collisions/CCollisionAABBTree.cpp | e97bb607e88541795fd68dd9760bfcfd35ee6027 | [] | no_license | remis/chai3d | cd694053f55773ca6883a9ea30047e95e70a33e8 | 15323a24b97be73df6f7172bc0b41cc09631c94e | refs/heads/master | 2021-01-18T08:46:44.253084 | 2009-05-11T21:51:22 | 2009-05-11T22:10:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,807 | cpp | //===========================================================================
/*
This file is part of the CHAI 3D visualization and haptics libraries.
Copyright (C) 2003-2004 by CHAI 3D. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License("GPL") version 2
as published by the Free Software Foundation.
For using the CHAI 3D libraries with software that can not be combined
with the GNU GPL, and for taking advantage of the additional benefits
of our support services, please contact CHAI 3D about acquiring a
Professional Edition License.
\author: <http://www.chai3d.org>
\author: Chris Sewell
\version 1.1
\date 01/2004
*/
//===========================================================================
//---------------------------------------------------------------------------
#include "CCollisionAABBTree.h"
//---------------------------------------------------------------------------
#include <stdlib.h>
//! Pointer for creating new AABB tree nodes, declared in CCollisionAABB.cpp.
extern cCollisionAABBInternal* g_nextFreeNode;
//===========================================================================
/*!
Determine whether the two given boxes intersect each other.
\fn bool intersect(const cCollisionAABBBox& a_0, const cCollisionAABBBox& a_1)
\param a_0 First box; may intersect with second box.
\param a_1 Second box; may intersect with first box.
\return Return whether there is any overlap of the two boxes.
*/
//===========================================================================
inline bool intersect(const cCollisionAABBBox& a_0, const cCollisionAABBBox& a_1)
{
// check for overlap along each axis
if (a_0.getLowerX() > a_1.getUpperX()) return false;
if (a_0.getLowerY() > a_1.getUpperY()) return false;
if (a_0.getLowerZ() > a_1.getUpperZ()) return false;
if (a_1.getLowerX() > a_0.getUpperX()) return false;
if (a_1.getLowerY() > a_0.getUpperY()) return false;
if (a_1.getLowerZ() > a_0.getUpperZ()) return false;
// if the boxes are not separated along any axis, a collision has occurred
return true;
}
//===========================================================================
/*!
Render bounding box of leaf node if it is at level a_depth in the tree.
\fn void cCollisionAABBLeaf::render(int a_depth)
\param a_depth Only draw nodes at this depth in the tree.
a_depth < 0 render _up to_ abs(a_depth).
*/
//===========================================================================
void cCollisionAABBLeaf::render(int a_depth)
{
if ( ( (a_depth < 0) && (abs(a_depth) >= m_depth) ) || a_depth == m_depth)
{
if (a_depth < 0)
{
cColorf c(1.0, 0.0, 0.0, 1.0);
glColor4fv(c.pColor());
}
m_bbox.render();
}
}
//===========================================================================
/*!
Create a bounding box to enclose the three vertices of the triangle
belonging to the leaf node.
\fn void cCollisionAABBLeaf::fitBBox()
*/
//===========================================================================
void cCollisionAABBLeaf::fitBBox()
{
// empty box
m_bbox.setEmpty();
// enclose all three vertices of triangle
if (m_triangle != NULL)
{
m_bbox.enclose(m_triangle->getVertex0()->getPos());
m_bbox.enclose(m_triangle->getVertex1()->getPos());
m_bbox.enclose(m_triangle->getVertex2()->getPos());
}
}
//===========================================================================
/*!
Determine whether the given line intersects the triangle belonging to
this leaf node by calling the triangle's collision detection method.
\fn bool cCollisionAABBLeaf::computeCollision(cVector3d& a_segmentPointA,
cVector3d& a_segmentDirection, cCollisionAABBBox &a_lineBox,
cTriangle*& a_colTriangle, cVector3d& a_colPoint, double& a_colSquareDistance)
\param a_segmentPointA Initial point of segment.
\param a_segmentDirection Direction of ray from first to second
segment points (i.e., proxy to goal).
\param a_lineBox A bounding box for the incoming segment, for quick
discarding of collision tests.
\param a_colTriangle Returns pointer to nearest collided triangle.
\param a_colPoint Returns position of nearest collision.
\param a_colSquareDistance Returns distance between ray origin and
collision point.
\return Return true if the line segment intersects the leaf's triangle.
*/
//===========================================================================
bool cCollisionAABBLeaf::computeCollision(cVector3d& a_segmentPointA,
cVector3d& a_segmentDirection,
cCollisionAABBBox &a_lineBox,
cTriangle*& a_colTriangle,
cVector3d& a_colPoint,
double& a_colSquareDistance)
{
// check for a collision between this leaf's triangle and the segment by
// calling the triangle's collision detection method; it will only
// return true if the distance between the segment origin and this
// triangle is less than the current closest intersecting triangle
// (whose distance squared is kept in colSquareDistance)
cGenericObject* colObject;
bool result = m_triangle->computeCollision(a_segmentPointA, a_segmentDirection,
colObject, a_colTriangle,a_colPoint, a_colSquareDistance);
// return result
return (result);
}
//===========================================================================
/*!
Destructor of cCollisionAABBInternal.
\fn cCollisionAABBInternal::~cCollisionAABBInternal()
*/
//===========================================================================
cCollisionAABBInternal::~cCollisionAABBInternal()
{
// Note that we don't delete leaf nodes here; they're stored in one big
// array and can't be deleted individually...
}
//===========================================================================
/*!
Draw the edges of the bounding box for an internal tree node if it is
at depth a_depth in the tree, and call the draw function for its children.
\fn void cCollisionAABBInternal::render(int a_depth)
\param a_depth Only draw nodes at this level in the tree.
a_depth < 0 render _up to_ this level.
*/
//===========================================================================
void cCollisionAABBInternal::render(int a_depth)
{
// render current node
if ( ( (a_depth < 0) && (abs(a_depth) >= m_depth) ) || a_depth == m_depth)
{
if (a_depth < 0)
{
cColorf c(1.0, 0.0, 0.0, 1.0);
glColor4fv(c.pColor());
}
m_bbox.render();
}
// render left sub tree
m_leftSubTree->render(a_depth);
// render right sub tree
m_rightSubTree->render(a_depth);
}
//===========================================================================
/*!
Create an internal AABB tree node.
\fn cCollisionAABBInternal::cCollisionAABBInternal(
unsigned int a_numLeaves, cCollisionAABBLeaf *a_leaves,
unsigned int a_depth)
\param a_numLeaves Number of leaves in subtree rooted at this node.
\param a_leaves Pointer to the location in the array of leafs for the
first leaf under this internal node.
\param a_depth Depth of this node in the collision tree.
\return Return a pointer to a new cCollisionAABBInternal node.
*/
//===========================================================================
cCollisionAABBInternal::cCollisionAABBInternal(unsigned int a_numLeaves,
cCollisionAABBLeaf *a_leaves,
unsigned int a_depth)
{
// set depth of this node and initialize left and right subtree pointers
m_depth = a_depth;
m_leftSubTree = NULL;
m_rightSubTree = NULL;
m_testLineBox = true;
// create a box to enclose all the leafs below this internal node
m_bbox.setEmpty();
for (unsigned int j = 0; j < a_numLeaves; ++j)
{
m_bbox.enclose(a_leaves[j].m_bbox);
}
// move leafs with smaller coordinates (on the longest axis) towards the
// beginning of the array and leaves with larger coordinates towards the
// end of the array
int axis = m_bbox.longestAxis();
unsigned int i = 0;
unsigned int mid = a_numLeaves;
while (i < mid)
{
if (a_leaves[i].m_bbox.getCenter().get(axis) < m_bbox.getCenter().get(axis))
{
++i;
}
else
{
std::swap(a_leaves[i], a_leaves[--mid]);
}
}
// we expect mid, used as the right iterator in the "insertion sort" style
// rearrangement above, to have moved roughly to the middle of the array;
// however, if it never moved left or moved all the way left, set it to
// the middle of the array so that neither the left nor right subtree will
// be empty
if (mid == 0 || mid == a_numLeaves)
{
mid = a_numLeaves / 2;
}
// if the right subtree contains multiple triangles, create new internal node
if (mid >= 2)
{
m_rightSubTree = g_nextFreeNode;
new(g_nextFreeNode++) cCollisionAABBInternal(mid, &a_leaves[0], m_depth + 1);
}
// if there is only one triangle in the right subtree, the right subtree
// pointer should just point to the leaf node
else
{
m_rightSubTree = &a_leaves[0];
if (m_rightSubTree != NULL) m_rightSubTree->m_depth = m_depth + 1;
}
// if the left subtree contains multiple triangles, create new internal node
if (a_numLeaves - mid >= 2)
{
m_leftSubTree = g_nextFreeNode;
new(g_nextFreeNode++) cCollisionAABBInternal(a_numLeaves - mid, &a_leaves[mid], m_depth + 1);
}
// if there is only one triangle in the left subtree, the left subtree
// pointer should just point to the leaf node
else
{
m_leftSubTree = &a_leaves[mid];
if (m_leftSubTree) m_leftSubTree->m_depth = m_depth + 1;
}
}
//===========================================================================
/*!
Determine whether the given ray intersects the bounding box. Based on code
by Andrew Woo from "Graphics Gems", Academic Press, 1990.
\fn bool hitBoundingBox(double a_minB[3], double a_maxB[3],
double a_origin[3], double a_dir[3])
\param a_minB[3] Minimum coordinates (along each axis) of bounding box.
\param a_maxB[3] Maximum coordinates (along each axis) of bounding box.
\param a_origin[3] Origin of the ray.
\param a_dir[3] Direction of the ray.
\return Return true if line segment intersects the bounding box.
*/
//===========================================================================
bool hitBoundingBox(const double a_minB[3], const double a_maxB[3], const double a_origin[3], const double a_dir[3])
{
const int RIGHT = 0;
const int LEFT = 1;
const int MIDDLE = 2;
double coord[3];
char inside = true;
char quadrant[3];
register int i;
int whichPlane;
double maxT[3];
double candidatePlane[3];
// Find candidate planes; this loop can be avoided if
// rays cast all from the eye (assume perspective view)
for (i=0; i<3; i++)
{
if(a_origin[i] < a_minB[i])
{
quadrant[i] = LEFT;
candidatePlane[i] = a_minB[i];
inside = false;
}
else if (a_origin[i] > a_maxB[i])
{
quadrant[i] = RIGHT;
candidatePlane[i] = a_maxB[i];
inside = false;
}
else
{
quadrant[i] = MIDDLE;
}
}
// Ray origin inside bounding box
if (inside)
{
//coord = origin;
return (true);
}
// Calculate T distances to candidate planes
for (i = 0; i < 3; i++)
{
if (quadrant[i] != MIDDLE && a_dir[i] !=0.)
maxT[i] = (candidatePlane[i]-a_origin[i]) / a_dir[i];
else
maxT[i] = -1.;
}
// Get largest of the maxT's for final choice of intersection
whichPlane = 0;
for (i = 1; i < 3; i++)
if (maxT[whichPlane] < maxT[i])
whichPlane = i;
// Check final candidate actually inside box
if (maxT[whichPlane] < 0.) return (false);
for (i = 0; i < 3; i++)
{
if (whichPlane != i)
{
coord[i] = a_origin[i] + maxT[whichPlane] * a_dir[i];
if (coord[i] < a_minB[i] || coord[i] > a_maxB[i])
return (false);
}
else
{
coord[i] = candidatePlane[i];
}
}
// Ray hits box...
return (true);
}
//===========================================================================
/*!
Determine whether the given line intersects the mesh covered by the
AABB Tree rooted at this internal node. If so, return (in the output
parameters) information about the intersected triangle of the mesh closest
to the segment origin.
\fn bool cCollisionAABBInternal::computeCollision(
cVector3d& a_segmentPointA, cVector3d& a_segmentDirection,
cCollisionAABBBox &a_lineBox, cTriangle*& a_colTriangle,
cVector3d& a_colPoint, double& a_colSquareDistance)
\param a_segmentPointA Initial point of segment.
\param a_segmentDirection Direction of ray from first to second
segment points (i.e., proxy to goal).
\param a_lineBox A bounding box for the incoming segment, for quick
discarding of collision tests.
\param a_colTriangle Returns pointer to nearest collided triangle.
\param a_colPoint Returns position of nearest collision.
\param a_colSquareDistance Returns distance between ray origin and
collision point.
\return Return true if line segment intersects a triangle in the subtree.
*/
//===========================================================================
bool cCollisionAABBInternal::computeCollision(cVector3d& a_segmentPointA,
cVector3d& a_segmentDirection,
cCollisionAABBBox &a_lineBox,
cTriangle*& a_colTriangle,
cVector3d& a_colPoint,
double& a_colSquareDistance)
{
// if a line's bounding box does not intersect the node's bounding box,
// there can be no intersection
if (!intersect(m_bbox, a_lineBox))
{
return (false);
}
if (m_testLineBox)
{
// Avoid unnecessary copying by casting straight to double...
//double minB[3];
//double maxB[3];
//double origin[3];
//double dir[3];
//minB[0] = m_bbox.getLowerX(); minB[1] = m_bbox.getLowerY(); minB[2] = m_bbox.getLowerZ();
//maxB[0] = m_bbox.getUpperX(); maxB[1] = m_bbox.getUpperY(); maxB[2] = m_bbox.getUpperZ();
//origin[0] = a_segmentPointA.x; origin[1] = a_segmentPointA.y; origin[2] = a_segmentPointA.z;
//dir[0] = a_segmentDirection.x; dir[1] = a_segmentDirection.y; dir[2] = a_segmentDirection.z;
//if (!hitBoundingBox(minB, maxB, origin, dir))
if (!hitBoundingBox(
(const double*)(&m_bbox.m_min),
(const double*)(&m_bbox.m_max),
(const double*)(&a_segmentPointA),
(const double*)(&a_segmentDirection)))
return (false);
}
// initialize objects for calls to left and right subtrees
cTriangle *l_colTriangle, *r_colTriangle;
cVector3d l_colPoint, r_colPoint;
double l_colSquareDistance = a_colSquareDistance;
double r_colSquareDistance = a_colSquareDistance;
bool l_result = false;
bool r_result = false;
// check collision between line and left subtree node; it will only
// return true if the distance between the segment origin and this
// triangle is less than the current closest intersecting triangle
// (whose distance squared is in l_colSquareDistance)
if ( m_leftSubTree && m_leftSubTree->computeCollision(a_segmentPointA,
a_segmentDirection, a_lineBox, l_colTriangle, l_colPoint,
l_colSquareDistance) )
{
l_result = true;
}
// check collision between line and right subtree node; it will only
// return true if the distance between the segment origin and this
// triangle is less than the current closest intersecting triangle
// (whose distance squared is in r_colSquareDistance)
if ( m_rightSubTree && m_rightSubTree->computeCollision(a_segmentPointA,
a_segmentDirection, a_lineBox, r_colTriangle, r_colPoint,
r_colSquareDistance) )
{
r_result = true;
}
// if there is an intersection in either subtree, return the closest one
if ((l_result && !r_result) || (l_result && r_result &&
(l_colSquareDistance <= r_colSquareDistance)))
{
a_colTriangle = l_colTriangle;
a_colPoint = l_colPoint;
a_colSquareDistance = l_colSquareDistance;
}
else
{
a_colTriangle = r_colTriangle;
a_colPoint = r_colPoint;
a_colSquareDistance = r_colSquareDistance;
}
// return result
return (l_result || r_result);
}
//===========================================================================
/*!
Return whether this node contains the specified triangle tag.
\fn void cCollisionAABBInternal::contains_triangle(int tag)
\param tag Tag to inquire about
*/
//===========================================================================
bool cCollisionAABBInternal::contains_triangle(int a_tag)
{
return (m_leftSubTree->contains_triangle(a_tag) ||
m_rightSubTree->contains_triangle(a_tag));
}
//===========================================================================
/*!
Sets this node's parent pointer and optionally propagate
assignments to its children (setting their parent pointers to this node).
\fn void cCollisionAABBInternal::setParent(cCollisionAABBNode* a_parent,
int a_recursive);
\param a_parent Pointer to this node's parent.
\param a_recursive Propagate assignment down the tree?
*/
//===========================================================================
void cCollisionAABBInternal::setParent(cCollisionAABBNode* a_parent, int a_recursive)
{
m_parent = a_parent;
if (m_leftSubTree && a_recursive) m_leftSubTree->setParent(this,1);
if (m_rightSubTree && a_recursive) m_rightSubTree->setParent(this,1);
}
| [
"[email protected]"
] | [
[
[
1,
510
]
]
] |
b3cedad3763995c119ac462fb5fbec48627d5b89 | 282e6353fbdf90100119bc4c2106109db7e18d15 | /parallel/nnz.cpp | caccae0b88c2f6172fdf94bd767f2f88c1997752 | [] | no_license | lipshitz/hfk-parallel | 80c891803ca640d3509cfb7ed9d01b8298779eab | 9b43f87f42270d65422623f1ac66e215c6d13250 | refs/heads/master | 2020-06-04T05:28:32.790747 | 2011-09-08T23:11:26 | 2011-09-08T23:11:26 | 32,195,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,423 | cpp | // This just counts the number of nonzeros in a matrix, it doesn't do any calculation
#include <sys/time.h>
#include <iostream>
#include <stdlib.h>
#include "mpi.h"
#include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>
#include <list>
#include <assert.h>
#include <algorithm>
#include <unistd.h>
using std::list;
using std::vector;
//#define PROFILE
int find_option( int argc, char **argv, const char *option )
{
for( int i = 1; i < argc; i++ )
if( strcmp( argv[i], option ) == 0 )
return i;
return -1;
}
int read_int( int argc, char **argv, const char *option, int default_value )
{
int iplace = find_option( argc, argv, option );
if( iplace >= 0 && iplace < argc-1 )
return atoi( argv[iplace+1] );
return default_value;
}
char *read_string( int argc, char **argv, const char *option, char *default_value )
{
int iplace = find_option( argc, argv, option );
if( iplace >= 0 && iplace < argc-1 )
return argv[iplace+1];
return default_value;
}
double read_timer( )
{
static bool initialized = false;
static struct timeval start;
struct timeval end;
if( !initialized )
{
gettimeofday( &start, NULL );
initialized = true;
}
gettimeofday( &end, NULL );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
//Globals
int gridsize = 12; // arc-index
int *white;
int *black;
int default_white[12] = {9,5,11,7,8,1,10,4,0,3,2,6};
int default_black[12] = {1,0,4,3,2,6,5,9,8,11,7,10};
long long *Factorial;
// Function Prototypes
inline int max( int a, int b ) { return a > b ? a : b; }
inline int min( int a, int b ) { return a < b ? a : b; }
void getPerm( long long n, int *P);
void NextPerm(short counter[], int h[]);
bool RectDotFree(int xll, int yll, int xur, int yur, int which);
// Decides whether one of the four rectangles on the torus with corners at(xll,yll) and (xur,yur) contains no white or black dots
/*
1 | 2 | 1
---+---+---
3 | 0 | 3
---+---+---
1 | 2 | 1
*/
long long getIndex( int *P);
int WindingNumber(int x, int y); // Return winding number of the knot projection around (x,y)
int MaslovGrading(int y []);
int NumComp(); //Returns the number of components of the link.
bool ValidGrid();
int Find(vector<long long> & V, long long x); // Returns i if V[i]=x or -1 if x isn't V[i] for any i, assuming V is sorted
// Main
int main(int argc, char *argv[]){
// set up mpi
int n_proc, rank;
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &n_proc );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
char *saveDir = read_string( argc, argv, "-i", NULL );
bool justTime = read_int( argc, argv, "-t", 1 );
int aGrading = read_int( argc, argv, "-a", -100 );
int mGrading = read_int( argc, argv, "-m", -100 );
int BLOCKSIZE = read_int( argc, argv, "-b", 10 );
int maxQueueSize = read_int( argc, argv, "-q", n_proc );
int AHEAD_LIMIT = read_int( argc, argv, "-l", n_proc/2 );
int MAX_ROWS_PER_CYCLE_INPUT = read_int( argc, argv, "-r", 10 );
int MAX_ROWS_PER_CYCLE = MAX_ROWS_PER_CYCLE_INPUT;
if( aGrading == -100 || mGrading == -100 ) {
printf("Must specify in which grading to calculate the boundary image and kernel dimensions with -a and -m\n");
MPI_Finalize();
exit(0);
}
if( n_proc <= 1 ) {
printf("Run with at least 2 threads\n");
MPI_Finalize();
exit(0);
}
if( !saveDir ) {
printf("Use -i to specify where the output of gradings was written\n");
MPI_Finalize();
exit(0);
}
char knotFile[30];
sprintf(knotFile, "%s/knot", saveDir);
FILE *f = fopen(knotFile, "r");
if( !f ) {
printf("Error opening file %s\n", knotFile);
MPI_Finalize();
exit(-1);
}
fscanf(f, "%d\n", &gridsize);
white = (int*) malloc( gridsize*sizeof(int) );
black = (int*) malloc( gridsize*sizeof(int) );
for( int i = 0; i < gridsize; i++ )
fscanf(f, "%d ", white+i);
fscanf(f, "\n");
for( int i = 0; i < gridsize; i++ )
fscanf(f, "%d ", black+i);
fclose(f);
Factorial = (long long *) malloc( gridsize * sizeof( long long ) );
Factorial[0] = 1;
for( int i = 1; i < gridsize; i++ )
Factorial[i] = i*Factorial[i-1];
int numcomp = NumComp();
if( rank == 0 && !justTime )
printf("Number of components: %d\n", numcomp);
if( rank == 0 )
if(!ValidGrid()) {printf("Invalid grid!!\n"); return 0;} // Check that the grid is valid
// Record for later use whether every possible rectangle has a black or white dot in it
// This will speed boundary computations.
if( rank == 0 && !justTime )
printf("Computing which rectangles on the torus have no black or white dots inside.\n");
bool Rectangles[gridsize][gridsize][gridsize][gridsize][4];
for(int xll=0; xll < gridsize; xll++) {
for(int xur=xll+1; xur < gridsize; xur++) {
for(int yll=0; yll < gridsize; yll++) {
for(int yur=yll+1; yur < gridsize; yur++) {
Rectangles[xll][yll][xur][yur][0] = RectDotFree(xll,yll,xur,yur,0);
Rectangles[xll][yll][xur][yur][1] = RectDotFree(xll,yll,xur,yur,1);
Rectangles[xll][yll][xur][yur][2] = RectDotFree(xll,yll,xur,yur,2);
Rectangles[xll][yll][xur][yur][3] = RectDotFree(xll,yll,xur,yur,3);
}
}
}
}
vector<long long> rows, cols;
int g[gridsize];
#define NGEN 5
#define GEN 6
// Read in the sorted list of generators for both rows and columns
if( rank == 0 ) {
if( !justTime )
printf("reading in rows\n");
char rowFile[30];
sprintf(rowFile, "%s/gen%d,%d.dat", saveDir, aGrading+30, mGrading+30);
FILE *f;
f = fopen(rowFile, "r");
if( f ) {
int num;
fscanf(f, "%d\n", &num);
rows.reserve(num);
for( int i = 0; i < num; i++ ) {
long long g;
fscanf(f, "%lld\n", &g);
rows.push_back(g);
}
fclose(f);
} else {
if( !justTime )
printf("warning, no such file %s\n", rowFile);
}
if( !justTime )
printf("reading in columns\n");
char colFile[30];
sprintf(colFile, "%s/gen%d,%d.dat", saveDir, aGrading+30, mGrading+31);
f = fopen(colFile, "r");
if( f ) {
int num;
fscanf(f, "%d\n", &num);
cols.reserve(num);
for( int i = 0; i < num; i++ ) {
long long g;
fscanf(f, "%lld\n", &g);
cols.push_back(g);
}
fclose(f);
} else {
if( !justTime )
printf("waring, no such file %s\n", colFile);
}
}
double starttime;
if( rank == 0 )
starttime = read_timer(); // Used to record how long this takes
// Send rows and cols to everyone
int num_generators;
if( rank == 0 )
num_generators = rows.size();
MPI_Bcast( &num_generators, 1, MPI_INT, 0, MPI_COMM_WORLD );
long long *buffer;
if( rank == 0 )
buffer = &(rows.front());
else
buffer = (long long*) malloc( num_generators * sizeof(long long) );
MPI_Bcast( buffer, num_generators, MPI_LONG_LONG_INT, 0, MPI_COMM_WORLD );
if( rank != 0 )
rows.assign(buffer, buffer+num_generators);
if( rank == 0 )
num_generators = cols.size();
MPI_Bcast( &num_generators, 1, MPI_INT, 0, MPI_COMM_WORLD );
if( rank == 0 )
buffer = &(cols.front());
else
buffer = (long long*) malloc( num_generators * sizeof(long long) );
MPI_Bcast( buffer, num_generators, MPI_LONG_LONG_INT, 0, MPI_COMM_WORLD );
if( rank != 0 )
cols.assign(buffer, buffer+num_generators);
int imageDimension, kernelDimension;
int local_nnz = 0;
if( cols.size() == 0 || rows.size() == 0 ) {
imageDimension = 0;
kernelDimension = cols.size();
} else {
// Decide who has ownership of what subset of the generators (without communication).
// The division will be block cyclic, with size set by BLOCKSIZE
int blocksPerProcMin = num_generators/BLOCKSIZE/n_proc;
int extraBlocks = (num_generators - n_proc * blocksPerProcMin * BLOCKSIZE)/BLOCKSIZE;
int extraCols = num_generators - n_proc * blocksPerProcMin * BLOCKSIZE - extraBlocks*BLOCKSIZE;
int numFullBlocks, tailSize, numBlocks; // the number of complete blocks, the size of the last block (usually zero), and the total number of blocks including that one
if( rank < extraBlocks ) {
numFullBlocks = blocksPerProcMin+1;
tailSize = 0;
} else if( rank == extraBlocks ) {
numFullBlocks = blocksPerProcMin;
tailSize = extraCols;
} else {
numFullBlocks = blocksPerProcMin;
tailSize = 0;
}
if( tailSize )
numBlocks = numFullBlocks+1;
else
numBlocks = numFullBlocks;
int numCols = numFullBlocks*BLOCKSIZE + tailSize;
if( !justTime )
printf("(%d) ownership determined, I have %d blocks of size %d and %d extra columns at the end for a total of %d columns\n", rank, numFullBlocks, BLOCKSIZE, tailSize, numCols);
// Each proc calculates the part of the matrix that it owns, storing both rows and columns as in the serial code. It holds entire columns, but only certain rows
int globalIndex = BLOCKSIZE*rank-BLOCKSIZE*(n_proc-1)-1;
for(int index=0; index < numCols; index++) {
// update globalIndex
if( index % BLOCKSIZE == 0 )
globalIndex += BLOCKSIZE*(n_proc-1);
globalIndex++;
getPerm(cols[globalIndex],g);
bool firstrect, secondrect;
for(int i=0; i<gridsize; i++) {
for(int j=i+1; j<gridsize; j++) {
if(g[i]<g[j]) {
firstrect = Rectangles[i][g[i]][j][g[j]][0];
for(int k=i+1; k<j && firstrect; k++) {
if(g[i] < g[k] && g[k] < g[j]) firstrect=0;
}
secondrect = Rectangles[i][g[i]][j][g[j]][1];
for(int k=0; k<i && secondrect; k++) {
if(g[k]<g[i] || g[k] > g[j]) secondrect=0;
}
for(int k=j+1; k<gridsize && secondrect; k++) {
if(g[k]<g[i] || g[k] > g[j]) secondrect=0;
}
}
if(g[j]<g[i]) {
firstrect = Rectangles[i][g[j]][j][g[i]][2];
for(int k=i+1; k<j && firstrect; k++) {
if(g[k]<g[j] || g[k] > g[i]) firstrect=0;
}
secondrect = Rectangles[i][g[j]][j][g[i]][3];
for(int k=0; k<i && secondrect; k++) {
if(g[k]>g[j] && g[k]<g[i]) secondrect=0;
}
for(int k=j+1; k<gridsize && secondrect; k++) {
if(g[k]>g[j] && g[k]<g[i]) secondrect=0;
}
}
if(firstrect != secondrect) { // Exactly one rectangle is a boundary
local_nnz++;
}
}
}
}
}
int nnz;
MPI_Reduce( &local_nnz, &nnz, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD );
if( rank == 0 )
printf("Number of non-zeros: %d, matrix size is %lu %lu fill rate: %e\n", nnz, rows.size(), cols.size(), 1.*nnz/(rows.size()*cols.size()));
MPI_Finalize();
exit(0);
}
// Actual Functions
int NumComp(){
int nc = 0;
int c[gridsize];
int d=0;
int k;
for (int i=0; i<gridsize; i++) c[i]=i;
int dblack[gridsize];
//int dwhite[gridsize];
for (int i =0; i<gridsize; i++){
dblack[black[i]]=i;
//dwhite[white[i]]=i;
}
bool t=0;
while(!t){
d=0;
k=0;
while(c[k]==-1){
d++;
k++;
}
c[d]=-1;
int l = dblack[white[d]];
while(l!=d){
c[l]=-1;
l=dblack[white[l]];
}
nc++;
t=1;
for (int j=0; j<gridsize; j++) t = t&& (c[j] ==-1);
}
return nc;
}
int Find(vector<long long> & V, long long x) {
int above=V.size()-1;
int below=0;
while(above - below > 1) {
if (x >= V[below+(above-below)/2]) below += (above-below)/2;
else above = below+(above-below)/2;
}
if (V[below] == x) return below;
if (V[above] == x) return above;
return -1;
}
int WindingNumber(int x, int y){ // Return winding number around (x,y)
int ret=0;
for(int i=0; i<x; i++) {
if ((black[i] >= y) && (white[i] < y)) ret++;
if ((white[i] >= y) && (black[i] < y)) ret--;
}
return ret;
}
int MaslovGrading(int y []) {
// Use the formula:
// 4M(y) = 4M(white)+4P_y(R_{y, white})+4P_{white}(R_{y, white})-8W(R_{y, white})
// = 4-4*gridsize+4P_y(R_{y, white})+4P_{x_0}(R_{y, white})-8W(R_{y, white})
int P=4-4*gridsize; // Four times the Maslov grading
for(int i=0; i<gridsize; i++) {
// Calculate incidence number R_{y x_0}.S for each of the four
// squares S having (i,white[i]) as a corner and each of the
// four squares having (i,y[i]) as a corner and shift P appropriately
for(int j=0; j<=i; j++) { // Squares whose BL corners are (i,white[i]) and (i,y[i])
if ((white[j] > white[i]) && (y[j] <= white[i])) P-=7; // because of the -8W(R_{y, white}) contribution
if ((y[j] > white[i]) && (white[j] <= white[i])) P+=7;
if ((white[j] > y[i]) && (y[j] <= y[i])) P++;
if ((y[j] > y[i]) && (white[j] <= y[i])) P--;
}
for(int j=0; j<=((i-1)% gridsize); j++) { // Squares whose BR corners are (i,white[i]) and (i,y[i]) (mod gridsize)
if ((white[j] > white[i]) && (y[j] <= white[i])) P++;
if ((y[j] > white[i]) && (white[j] <= white[i])) P--;
if ((white[j] > y[i]) && (y[j] <= y[i])) P++;
if ((y[j] > y[i]) && (white[j] <= y[i])) P--;
}
for(int j=0; j<=((i-1) % gridsize); j++) { // Squares whose TR corners are...
if ((white[j] > ((white[i]-1) % gridsize)) && (y[j] <= ((white[i]-1) % gridsize))) P++;
if ((y[j] > ((white[i]-1) % gridsize) ) && (white[j] <= ((white[i]-1) % gridsize))) P--;
if ((white[j] > ((y[i]-1) % gridsize)) && (y[j] <= ((y[i]-1) % gridsize))) P++;
if ((y[j] > ((y[i]-1) % gridsize) ) && (white[j] <= ((y[i]-1) % gridsize))) P--;
}
for(int j=0; j<=i; j++) { // Squares whose TL corners are...
if ((white[j] > ((white[i]-1) % gridsize)) && (y[j] <= ((white[i]-1) % gridsize))) P++;
if ((y[j] > ((white[i]-1) % gridsize) ) && (white[j] <= ((white[i]-1) % gridsize))) P--;
if ((white[j] > ((y[i]-1) % gridsize)) && (y[j] <= ((y[i]-1) % gridsize))) P++;
if ((y[j] > ((y[i]-1) % gridsize) ) && (white[j] <= ((y[i]-1) % gridsize))) P--;
}
}
return (P/4);
}
bool RectDotFree(int xll, int yll, int xur, int yur, int which) {
bool dotfree = 1;
switch (which) {
case 0:
for(int x=xll; x<xur && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
return dotfree;
case 1:
for(int x=0; x<xll && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
for(int x=xur; x<gridsize && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
return dotfree;
case 2:
for(int x=xll; x<xur && dotfree; x++) {
if (white[x] < yll || white[x] >= yur) dotfree = 0;
if (black[x] < yll || black[x] >= yur) dotfree = 0;
}
return dotfree;
case 3:
for(int x=0; x<xll && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
for(int x=xur; x<gridsize && dotfree; x++) {
if (white[x] >= yll && white[x] < yur) dotfree = 0;
if (black[x] >= yll && black[x] < yur) dotfree = 0;
}
return dotfree;
}
return 0; //Error!
}
bool ValidGrid() {
int numwhite=0;
int numblack=0;
for(int i=0; i<gridsize; i++) {
for(int j=0; j<gridsize; j++) {
if (white[j]==i) numwhite++;
if (black[j]==i) numblack++;
}
if (numwhite != 1 || numblack != 1) {
std::cout << "\nInvalid Grid!\n";
return 0;
}
numwhite=0;
numblack=0;
}
return 1;
}
long long getIndex( int *P ) {
long long index = 0;
for( int i = gridsize-2; i >= 0; i-- ) {
int r = P[i];
int m = 0;
for( int j = 0; j < i; j++ )
if( P[j] < r )
m++;
index += Factorial[gridsize-1-i]*(r-m);
}
return index;
}
// Inverse mapping, from integers < gridsize! to permutations of size n
// Writes the permutation corresponding to n into the array P.
void getPerm( long long n, int *P ) {
int taken[gridsize];
int offset;
for( int i = 0; i < gridsize; i++ )
taken[i] = 0;
for( int i = 0; i < gridsize; i++ ) {
offset = n / Factorial[gridsize-1-i];
n -= offset*Factorial[gridsize-1-i];
for( int j = 0; j <= offset; j++ )
if( taken[j] )
offset++;
P[i] = offset;
taken[P[i]] = 1;
}
}
| [
"benjamin.lip@c2f0229c-37c9-6e89-a4ff-2bb24d9bb920"
] | [
[
[
1,
523
]
]
] |
86dd161960cc6f1e252be29024cee685fc693708 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Common/CostFunctions/itkParzenWindowHistogramImageToImageMetric.hxx | acdd08c627a2c6418d872554be9b991c3cb82e40 | [] | no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55,654 | hxx | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef _itkParzenWindowHistogramImageToImageMetric_HXX__
#define _itkParzenWindowHistogramImageToImageMetric_HXX__
#include "itkParzenWindowHistogramImageToImageMetric.h"
#include "itkBSplineDerivativeKernelFunction.h"
#include "itkImageRegionIterator.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkImageSliceIteratorWithIndex.h"
#include "vnl/vnl_math.h"
namespace itk
{
/**
* ********************* Constructor ****************************
*/
template < class TFixedImage, class TMovingImage >
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::ParzenWindowHistogramImageToImageMetric()
{
this->m_NumberOfFixedHistogramBins = 32;
this->m_NumberOfMovingHistogramBins = 32;
this->m_JointPDF = 0;
this->m_JointPDFDerivatives = 0;
this->m_FixedImageNormalizedMin = 0.0;
this->m_MovingImageNormalizedMin = 0.0;
this->m_FixedImageBinSize = 0.0;
this->m_MovingImageBinSize = 0.0;
this->m_Alpha = 0.0;
this->m_FixedIncrementalMarginalPDFRight = 0;
this->m_MovingIncrementalMarginalPDFRight = 0;
this->m_FixedIncrementalMarginalPDFLeft = 0;
this->m_MovingIncrementalMarginalPDFLeft = 0;
this->m_FixedKernel = 0;
this->m_MovingKernel = 0;
this->m_DerivativeMovingKernel = 0;
this->m_FixedKernelBSplineOrder = 0;
this->m_MovingKernelBSplineOrder = 3;
this->m_FixedParzenTermToIndexOffset = 0.5;
this->m_MovingParzenTermToIndexOffset = -1.0;
this->m_UseDerivative = false;
this->m_UseFiniteDifferenceDerivative = false;
this->m_FiniteDifferencePerturbation = 1.0;
this->SetUseImageSampler( true );
this->SetUseFixedImageLimiter( true );
this->SetUseMovingImageLimiter( true );
this->m_UseExplicitPDFDerivatives = true;
} // end Constructor
/**
* ********************* PrintSelf ******************************
*
* Print out internal information about this class.
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::PrintSelf( std::ostream& os, Indent indent ) const
{
/** Call the superclass' PrintSelf. */
Superclass::PrintSelf( os, indent );
/** Add debugging information. */
os << indent << "NumberOfFixedHistogramBins: "
<< this->m_NumberOfFixedHistogramBins << std::endl;
os << indent << "NumberOfMovingHistogramBins: "
<< this->m_NumberOfMovingHistogramBins << std::endl;
os << indent << "FixedKernelBSplineOrder: "
<< this->m_FixedKernelBSplineOrder << std::endl;
os << indent << "MovingKernelBSplineOrder: "
<< this->m_MovingKernelBSplineOrder << std::endl;
/*double m_MovingImageNormalizedMin;
double m_FixedImageNormalizedMin;
double m_FixedImageBinSize;
double m_MovingImageBinSize;
double m_FixedParzenTermToIndexOffset;
double m_MovingParzenTermToIndexOffset;
bool m_UseDerivative;
m_UseExplicitPDFDerivatives
bool m_UseFiniteDifferenceDerivative;
double m_FiniteDifferencePerturbation;*/
/** This function is not complete, but we don't use it anyway. */
} // end PrintSelf()
/**
* ********************* Initialize *****************************
*/
template <class TFixedImage, class TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::Initialize( void ) throw ( ExceptionObject )
{
/** Call the superclass to check that standard components are available. */
this->Superclass::Initialize();
/** Set up the histograms. */
this->InitializeHistograms();
/** Set up the Parzen windows. */
this->InitializeKernels();
/** If the user plans to use a finite difference derivative,
* allocate some memory for the perturbed alpha variables.
*/
if ( this->GetUseDerivative() && this->GetUseFiniteDifferenceDerivative() )
{
this->m_PerturbedAlphaRight.SetSize( this->GetNumberOfParameters() );
this->m_PerturbedAlphaLeft.SetSize( this->GetNumberOfParameters() );
}
else
{
this->m_PerturbedAlphaRight.SetSize( 0 );
this->m_PerturbedAlphaLeft.SetSize( 0 );
}
} // end Initialize()
/**
* ****************** InitializeHistograms *****************************
*/
template <class TFixedImage, class TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::InitializeHistograms( void )
{
/* Compute binsize for the histogram.
*
* The binsize for the image intensities needs to be adjusted so that
* we can avoid dealing with boundary conditions using the cubic
* spline as the Parzen window. We do this by increasing the size
* of the bins so that the joint histogram becomes "padded" at the
* borders. Because we are changing the binsize,
* we also need to shift the minimum by the padded amount in order to
* avoid minimum values filling in our padded region.
*
* Note that there can still be non-zero bin values in the padded region,
* it's just that these bins will never be a central bin for the Parzen
* window.
*/
//int fixedPadding = 2; // this will pad by 2 bins
//int movingPadding = 2; // this will pad by 2 bins
int fixedPadding = this->m_FixedKernelBSplineOrder / 2; // should be enough
int movingPadding = this->m_MovingKernelBSplineOrder / 2;
/** The ratio times the expected bin size will be added twice to the image range. */
const double smallNumberRatio = 0.001;
const double smallNumberFixed = smallNumberRatio *
( this->m_FixedImageMaxLimit - this->m_FixedImageMinLimit ) /
static_cast<double>( this->m_NumberOfFixedHistogramBins - 2 * fixedPadding - 1 );
const double smallNumberMoving = smallNumberRatio *
( this->m_MovingImageMaxLimit - this->m_MovingImageMinLimit ) /
static_cast<double>( this->m_NumberOfFixedHistogramBins - 2 * movingPadding - 1 );
/** Compute binsizes. */
const double fixedHistogramWidth = static_cast<double>(
static_cast<OffsetValueType>( this->m_NumberOfFixedHistogramBins ) // requires cast to signed type!
- 2.0 * fixedPadding - 1.0 );
this->m_FixedImageBinSize
= ( this->m_FixedImageMaxLimit - this->m_FixedImageMinLimit
+ 2.0 * smallNumberFixed ) / fixedHistogramWidth;
this->m_FixedImageBinSize = vnl_math_max( this->m_FixedImageBinSize, 1e-10 );
this->m_FixedImageBinSize = vnl_math_min( this->m_FixedImageBinSize, 1e+10 );
this->m_FixedImageNormalizedMin
= ( this->m_FixedImageMinLimit - smallNumberFixed )
/ this->m_FixedImageBinSize - static_cast<double>( fixedPadding );
const double movingHistogramWidth = static_cast<double>(
static_cast<OffsetValueType>( this->m_NumberOfMovingHistogramBins ) // requires cast to signed type!
- 2.0 * movingPadding - 1.0 );
this->m_MovingImageBinSize
= ( this->m_MovingImageMaxLimit - this->m_MovingImageMinLimit
+ 2.0 * smallNumberMoving ) / movingHistogramWidth;
this->m_MovingImageBinSize = vnl_math_max( this->m_MovingImageBinSize, 1e-10 );
this->m_MovingImageBinSize = vnl_math_min( this->m_MovingImageBinSize, 1e+10 );
this->m_MovingImageNormalizedMin
= ( this->m_MovingImageMinLimit - smallNumberMoving )
/ this->m_MovingImageBinSize - static_cast<double>( movingPadding );
/** Allocate memory for the marginal PDF. */
this->m_FixedImageMarginalPDF.SetSize( this->m_NumberOfFixedHistogramBins );
this->m_MovingImageMarginalPDF.SetSize( this->m_NumberOfMovingHistogramBins );
/** Allocate memory for the joint PDF and joint PDF derivatives. */
/** First set these ones to zero */
this->m_FixedIncrementalMarginalPDFRight = 0;
this->m_MovingIncrementalMarginalPDFRight = 0;
this->m_FixedIncrementalMarginalPDFLeft = 0;
this->m_MovingIncrementalMarginalPDFLeft = 0;
/** For the joint PDF define a region starting from {0,0}
* with size {this->m_NumberOfMovingHistogramBins, this->m_NumberOfFixedHistogramBins}
* The dimension represents moving image Parzen window index
* and fixed image Parzen window index, respectively.
* The moving Parzen index is chosen as the first dimension,
* because probably the moving B-spline kernel order will be larger
* than the fixed B-spline kernel order and it is faster to iterate along
* the first dimension.
*/
this->m_JointPDF = JointPDFType::New();
JointPDFRegionType jointPDFRegion;
JointPDFIndexType jointPDFIndex;
JointPDFSizeType jointPDFSize;
jointPDFIndex.Fill( 0 );
jointPDFSize[0] = this->m_NumberOfMovingHistogramBins;
jointPDFSize[1] = this->m_NumberOfFixedHistogramBins;
jointPDFRegion.SetIndex( jointPDFIndex );
jointPDFRegion.SetSize( jointPDFSize );
this->m_JointPDF->SetRegions( jointPDFRegion );
this->m_JointPDF->Allocate();
if ( this->GetUseDerivative() )
{
/** For the derivatives of the joint PDF define a region starting from {0,0,0}
* with size {GetNumberOfParameters(),m_NumberOfMovingHistogramBins,
* m_NumberOfFixedHistogramBins}. The dimension represents transform parameters,
* moving image Parzen window index and fixed image Parzen window index,
* respectively.
* For the incremental pdfs (used for finite difference derivative estimation)
* the same size happens to be valid.
*/
JointPDFDerivativesRegionType jointPDFDerivativesRegion;
JointPDFDerivativesIndexType jointPDFDerivativesIndex;
JointPDFDerivativesSizeType jointPDFDerivativesSize;
jointPDFDerivativesIndex.Fill( 0 );
jointPDFDerivativesSize[0] = this->GetNumberOfParameters();
jointPDFDerivativesSize[1] = this->m_NumberOfMovingHistogramBins;
jointPDFDerivativesSize[2] = this->m_NumberOfFixedHistogramBins;
jointPDFDerivativesRegion.SetIndex( jointPDFDerivativesIndex );
jointPDFDerivativesRegion.SetSize( jointPDFDerivativesSize );
if ( this->GetUseFiniteDifferenceDerivative() )
{
this->m_JointPDFDerivatives = 0;
this->m_IncrementalJointPDFRight = JointPDFDerivativesType::New();
this->m_IncrementalJointPDFLeft = JointPDFDerivativesType::New();
this->m_IncrementalJointPDFRight->SetRegions( jointPDFDerivativesRegion );
this->m_IncrementalJointPDFLeft->SetRegions( jointPDFDerivativesRegion );
this->m_IncrementalJointPDFRight->Allocate();
this->m_IncrementalJointPDFLeft->Allocate();
/** Also initialize the incremental marginal pdfs. */
IncrementalMarginalPDFRegionType fixedIMPDFRegion;
IncrementalMarginalPDFIndexType fixedIMPDFIndex;
IncrementalMarginalPDFSizeType fixedIMPDFSize;
IncrementalMarginalPDFRegionType movingIMPDFRegion;
IncrementalMarginalPDFIndexType movingIMPDFIndex;
IncrementalMarginalPDFSizeType movingIMPDFSize;
fixedIMPDFIndex.Fill( 0 );
fixedIMPDFSize[0] = this->GetNumberOfParameters();
fixedIMPDFSize[1] = this->m_NumberOfFixedHistogramBins;
fixedIMPDFRegion.SetSize( fixedIMPDFSize );
fixedIMPDFRegion.SetIndex( fixedIMPDFIndex );
movingIMPDFIndex.Fill( 0 );
movingIMPDFSize[0] = this->GetNumberOfParameters();
movingIMPDFSize[1] = this->m_NumberOfMovingHistogramBins;
movingIMPDFRegion.SetSize( movingIMPDFSize );
movingIMPDFRegion.SetIndex( movingIMPDFIndex );
this->m_FixedIncrementalMarginalPDFRight = IncrementalMarginalPDFType::New();
this->m_MovingIncrementalMarginalPDFRight = IncrementalMarginalPDFType::New();
this->m_FixedIncrementalMarginalPDFLeft = IncrementalMarginalPDFType::New();
this->m_MovingIncrementalMarginalPDFLeft = IncrementalMarginalPDFType::New();
this->m_FixedIncrementalMarginalPDFRight->SetRegions( fixedIMPDFRegion );
this->m_MovingIncrementalMarginalPDFRight->SetRegions( movingIMPDFRegion );
this->m_FixedIncrementalMarginalPDFLeft->SetRegions( fixedIMPDFRegion );
this->m_MovingIncrementalMarginalPDFLeft->SetRegions( movingIMPDFRegion );
this->m_FixedIncrementalMarginalPDFRight->Allocate();
this->m_MovingIncrementalMarginalPDFRight->Allocate();
this->m_FixedIncrementalMarginalPDFLeft->Allocate();
this->m_MovingIncrementalMarginalPDFLeft->Allocate();
} // end if this->GetUseFiniteDifferenceDerivative()
else
{
if ( this->m_UseExplicitPDFDerivatives )
{
this->m_IncrementalJointPDFRight = 0;
this->m_IncrementalJointPDFLeft = 0;
this->m_JointPDFDerivatives = JointPDFDerivativesType::New();
this->m_JointPDFDerivatives->SetRegions( jointPDFDerivativesRegion );
this->m_JointPDFDerivatives->Allocate();
}
else
{
/** De-allocate large amount of memory for the m_JointPDFDerivatives. */
if ( !this->m_JointPDFDerivatives.IsNull() )
{
jointPDFDerivativesSize.Fill( 0 );
jointPDFDerivativesRegion.SetSize( jointPDFDerivativesSize );
this->m_JointPDFDerivatives->SetRegions( jointPDFDerivativesRegion );
this->m_JointPDFDerivatives->Allocate();
this->m_JointPDFDerivatives->GetPixelContainer()->Squeeze();
}
}
}
}
else
{
this->m_JointPDFDerivatives = 0;
this->m_IncrementalJointPDFRight = 0;
this->m_IncrementalJointPDFLeft = 0;
}
} // end InitializeHistograms()
/**
* ****************** InitializeKernels *****************************
* Setup the kernels used for the Parzen windows.
*/
template <class TFixedImage, class TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::InitializeKernels( void )
{
switch ( this->m_FixedKernelBSplineOrder )
{
case 0:
this->m_FixedKernel = BSplineKernelFunction<0>::New(); break;
case 1:
this->m_FixedKernel = BSplineKernelFunction<1>::New(); break;
case 2:
this->m_FixedKernel = BSplineKernelFunction<2>::New(); break;
case 3:
this->m_FixedKernel = BSplineKernelFunction<3>::New(); break;
default:
itkExceptionMacro(<< "The following FixedKernelBSplineOrder is not implemented: "\
<< this->m_FixedKernelBSplineOrder );
} // end switch FixedKernelBSplineOrder
switch ( this->m_MovingKernelBSplineOrder )
{
case 0:
this->m_MovingKernel = BSplineKernelFunction<0>::New();
/** The derivative of a zero order B-spline makes no sense. Using the
* derivative of a first order gives a kind of finite difference idea
* Anyway, if you plan to call GetValueAndDerivative you should use
* a higher B-spline order.
*/
this->m_DerivativeMovingKernel = BSplineDerivativeKernelFunction<1>::New();
break;
case 1:
this->m_MovingKernel = BSplineKernelFunction<1>::New();
this->m_DerivativeMovingKernel = BSplineDerivativeKernelFunction<1>::New();
break;
case 2:
this->m_MovingKernel = BSplineKernelFunction<2>::New();
this->m_DerivativeMovingKernel = BSplineDerivativeKernelFunction<2>::New();
break;
case 3:
this->m_MovingKernel = BSplineKernelFunction<3>::New();
this->m_DerivativeMovingKernel = BSplineDerivativeKernelFunction<3>::New();
break;
default:
itkExceptionMacro(<< "The following MovingKernelBSplineOrder is not implemented: "\
<< this->m_MovingKernelBSplineOrder );
} // end switch MovingKernelBSplineOrder
/** The region of support of the Parzen window determines which bins
* of the joint PDF are effected by the pair of image values.
* For example, if we are using a cubic spline for the moving image Parzen
* window, four bins are affected. If the fixed image Parzen window is
* a zero-order spline (box car) only one bin is affected. */
/** Set the size of the Parzen window. */
JointPDFSizeType parzenWindowSize;
parzenWindowSize[ 0 ] = this->m_MovingKernelBSplineOrder + 1;
parzenWindowSize[ 1 ] = this->m_FixedKernelBSplineOrder + 1;
this->m_JointPDFWindow.SetSize( parzenWindowSize );
this->m_JointPDFWindow.SetSize( parzenWindowSize );
/** The ParzenIndex is the lowest bin number that is affected by a
* pixel and computed as:
* ParzenIndex = vcl_floor( ParzenTerm + ParzenTermToIndexOffset )
* where ParzenTermToIndexOffset = 1/2, 0, -1/2, or -1.
*/
this->m_FixedParzenTermToIndexOffset =
0.5 - static_cast<double>( this->m_FixedKernelBSplineOrder ) / 2.0;
this->m_MovingParzenTermToIndexOffset =
0.5 - static_cast<double>( this->m_MovingKernelBSplineOrder ) / 2.0;
} // end InitializeKernels()
/**
* ******************** GetDerivative ***************************
*
* Get the match measure derivative.
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::GetDerivative( const ParametersType& parameters, DerivativeType & derivative ) const
{
/** Call the combined version, since the additional computation of
* the value does not take extra time.
*/
MeasureType value;
this->GetValueAndDerivative( parameters, value, derivative );
} // end GetDerivative()
/**
* ******************** GetValueAndDerivative ***************************
*
* Get the metric value and derivative
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::GetValueAndDerivative( const ParametersType& parameters,
MeasureType& value, DerivativeType& derivative ) const
{
if ( this->GetUseFiniteDifferenceDerivative() )
{
this->GetValueAndFiniteDifferenceDerivative( parameters, value, derivative );
}
else
{
this->GetValueAndAnalyticDerivative( parameters, value, derivative );
}
} // end GetValueAndDerivative()
/*
* ********************** EvaluateParzenValues ***************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::EvaluateParzenValues(
double parzenWindowTerm, OffsetValueType parzenWindowIndex,
const KernelFunctionType * kernel, ParzenValueContainerType & parzenValues ) const
{
const unsigned int max_i = parzenValues.GetSize();
for ( unsigned int i = 0 ; i < max_i; ++i, ++parzenWindowIndex )
{
parzenValues[ i ] = kernel->Evaluate(
static_cast<double>( parzenWindowIndex ) - parzenWindowTerm );
}
} // end EvaluateParzenValues()
/**
* ********************** UpdateJointPDFAndDerivatives ***************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::UpdateJointPDFAndDerivatives(
RealType fixedImageValue, RealType movingImageValue,
const DerivativeType * imageJacobian,
const NonZeroJacobianIndicesType * nzji) const
{
typedef ImageSliceIteratorWithIndex< JointPDFType > PDFIteratorType;
/** Determine Parzen window arguments (see eq. 6 of Mattes paper [2]). */
const double fixedImageParzenWindowTerm =
fixedImageValue / this->m_FixedImageBinSize - this->m_FixedImageNormalizedMin;
const double movingImageParzenWindowTerm =
movingImageValue / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
/** The lowest bin numbers affected by this pixel: */
const OffsetValueType fixedImageParzenWindowIndex =
static_cast<OffsetValueType>( vcl_floor(
fixedImageParzenWindowTerm + this->m_FixedParzenTermToIndexOffset ) );
const OffsetValueType movingImageParzenWindowIndex =
static_cast<OffsetValueType>( vcl_floor(
movingImageParzenWindowTerm + this->m_MovingParzenTermToIndexOffset ) );
/** The Parzen values. */
ParzenValueContainerType fixedParzenValues( this->m_JointPDFWindow.GetSize()[ 1 ] );
ParzenValueContainerType movingParzenValues( this->m_JointPDFWindow.GetSize()[ 0 ] );
this->EvaluateParzenValues(
fixedImageParzenWindowTerm, fixedImageParzenWindowIndex,
this->m_FixedKernel, fixedParzenValues );
this->EvaluateParzenValues(
movingImageParzenWindowTerm, movingImageParzenWindowIndex,
this->m_MovingKernel, movingParzenValues );
/** Position the JointPDFWindow. */
JointPDFIndexType pdfWindowIndex;
pdfWindowIndex[ 0 ] = movingImageParzenWindowIndex;
pdfWindowIndex[ 1 ] = fixedImageParzenWindowIndex;
this->m_JointPDFWindow.SetIndex( pdfWindowIndex );
PDFIteratorType it( this->m_JointPDF, this->m_JointPDFWindow );
it.GoToBegin();
it.SetFirstDirection( 0 );
it.SetSecondDirection( 1 );
if ( !imageJacobian )
{
/** Loop over the Parzen window region and increment the values. */
for ( unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f )
{
const double fv = fixedParzenValues[ f ];
for ( unsigned int m = 0; m < movingParzenValues.GetSize(); ++m )
{
it.Value() += static_cast<PDFValueType>( fv * movingParzenValues[ m ] );
++it;
}
it.NextLine();
}
}
else
{
/** Compute the derivatives of the moving Parzen window. */
ParzenValueContainerType derivativeMovingParzenValues(
this->m_JointPDFWindow.GetSize()[0] );
this->EvaluateParzenValues(
movingImageParzenWindowTerm, movingImageParzenWindowIndex,
this->m_DerivativeMovingKernel, derivativeMovingParzenValues );
const double et = static_cast<double>( this->m_MovingImageBinSize );
/** Loop over the Parzen window region and increment the values
* Also update the pdf derivatives.
*/
for ( unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f )
{
const double fv = fixedParzenValues[ f ];
const double fv_et = fv / et;
for ( unsigned int m = 0; m < movingParzenValues.GetSize(); ++m )
{
it.Value() += static_cast<PDFValueType>( fv * movingParzenValues[ m ] );
this->UpdateJointPDFDerivatives(
it.GetIndex(), fv_et * derivativeMovingParzenValues[ m ],
*imageJacobian, *nzji );
++it;
}
it.NextLine();
}
}
} // end UpdateJointPDFAndDerivatives()
/**
* *************** UpdateJointPDFDerivatives ***************************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::UpdateJointPDFDerivatives(
const JointPDFIndexType & pdfIndex, double factor,
const DerivativeType & imageJacobian,
const NonZeroJacobianIndicesType & nzji ) const
{
/** Get the pointer to the element with index [0, pdfIndex[0], pdfIndex[1]]. */
PDFValueType * derivPtr = this->m_JointPDFDerivatives->GetBufferPointer() +
( pdfIndex[0] * this->m_JointPDFDerivatives->GetOffsetTable()[1] ) +
( pdfIndex[1] * this->m_JointPDFDerivatives->GetOffsetTable()[2] );
if ( nzji.size() == this->GetNumberOfParameters() )
{
/** Loop over all Jacobians. */
typename DerivativeType::const_iterator imjac = imageJacobian.begin();
for ( unsigned int mu = 0; mu < this->GetNumberOfParameters(); ++mu )
{
*(derivPtr) -= static_cast<PDFValueType>( (*imjac) * factor );
++derivPtr;
++imjac;
}
}
else
{
/** Loop only over the non-zero Jacobians. */
for ( unsigned int i = 0; i < imageJacobian.GetSize(); ++i )
{
const unsigned int mu = nzji[ i ];
PDFValueType * ptr = derivPtr + mu;
*(ptr) -= static_cast<PDFValueType>( imageJacobian[ i ] * factor );
}
}
} // end UpdateJointPDFDerivatives()
/**
* *************** EvaluateTransformJacobianInnerProduct ****************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::EvaluateTransformJacobianInnerProduct(
const TransformJacobianType & jacobian,
const MovingImageDerivativeType & movingImageDerivative,
DerivativeType & imageJacobian ) const
{
typedef typename TransformJacobianType::const_iterator JacobianIteratorType;
typedef typename DerivativeType::iterator DerivativeIteratorType;
JacobianIteratorType jac = jacobian.begin();
imageJacobian.Fill( 0.0 );
const unsigned int sizeImageJacobian = imageJacobian.GetSize();
for ( unsigned int dim = 0; dim < FixedImageDimension; dim++ )
{
const double imDeriv = movingImageDerivative[ dim ];
DerivativeIteratorType imjac = imageJacobian.begin();
for ( unsigned int mu = 0; mu < sizeImageJacobian ; mu++ )
{
(*imjac) += (*jac) * imDeriv;
++imjac;
++jac;
}
}
} // end EvaluateTransformJacobianInnerProduct()
/**
* *********************** NormalizeJointPDF ***********************
* Multiply the pdf entries by the given normalization factor
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::NormalizeJointPDF( JointPDFType * pdf, double factor ) const
{
typedef ImageRegionIterator<JointPDFType> JointPDFIteratorType;
JointPDFIteratorType it( pdf, pdf->GetBufferedRegion() );
it.GoToBegin();
const PDFValueType castfac = static_cast<PDFValueType>( factor );
while ( !it.IsAtEnd() )
{
it.Value() *= castfac;
++it;
}
} // end NormalizeJointPDF()
/**
* *********************** NormalizeJointPDFDerivatives ***********************
* Multiply the pdf derivatives entries by the given normalization factor
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::NormalizeJointPDFDerivatives( JointPDFDerivativesType * pdf, double factor ) const
{
typedef ImageRegionIterator<JointPDFDerivativesType> JointPDFDerivativesIteratorType;
JointPDFDerivativesIteratorType it( pdf, pdf->GetBufferedRegion() );
it.GoToBegin();
const PDFValueType castfac = static_cast<PDFValueType>( factor );
while ( !it.IsAtEnd() )
{
it.Value() *= castfac;
++it;
}
} // end NormalizeJointPDFDerivatives()
/**
* ************************ ComputeMarginalPDF ***********************
* Compute marginal pdf by summing over the joint pdf
* direction = 0: fixed marginal pdf
* direction = 1: moving marginal pdf
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::ComputeMarginalPDF(
const JointPDFType * jointPDF,
MarginalPDFType & marginalPDF, unsigned int direction ) const
{
typedef ImageLinearIteratorWithIndex<JointPDFType> JointPDFLinearIterator;
JointPDFLinearIterator linearIter(
this->m_JointPDF, this->m_JointPDF->GetBufferedRegion() );
linearIter.SetDirection( direction );
linearIter.GoToBegin();
unsigned int marginalIndex = 0;
while( !linearIter.IsAtEnd() )
{
double sum = 0.0;
while( !linearIter.IsAtEndOfLine() )
{
sum += linearIter.Get();
++linearIter;
}
marginalPDF[ marginalIndex ] = static_cast<PDFValueType>( sum );
linearIter.NextLine();
++marginalIndex;
}
} // end ComputeMarginalPDFs()
/**
* ******************** ComputeIncrementalMarginalPDFs *******************
* Compute incremental marginal pdfs. Integrates the incremental PDF
* to obtain the marginal pdfs. Used for finite differences.
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::ComputeIncrementalMarginalPDFs(
const JointPDFDerivativesType * incrementalPDF,
IncrementalMarginalPDFType * fixedIncrementalMarginalPDF,
IncrementalMarginalPDFType * movingIncrementalMarginalPDF ) const
{
typedef itk::ImageRegionConstIterator<JointPDFDerivativesType> IncIteratorType;
typedef itk::ImageLinearIteratorWithIndex<IncrementalMarginalPDFType> IncMargIteratorType;
fixedIncrementalMarginalPDF->FillBuffer( itk::NumericTraits<PDFValueType>::Zero );
movingIncrementalMarginalPDF->FillBuffer( itk::NumericTraits<PDFValueType>::Zero );
IncIteratorType incit( incrementalPDF, incrementalPDF->GetLargestPossibleRegion() );
IncMargIteratorType fixincit( fixedIncrementalMarginalPDF,
fixedIncrementalMarginalPDF->GetLargestPossibleRegion() );
IncMargIteratorType movincit( movingIncrementalMarginalPDF,
movingIncrementalMarginalPDF->GetLargestPossibleRegion() );
incit.GoToBegin();
fixincit.GoToBegin();
movincit.GoToBegin();
/** Loop over the incremental pdf and update the incremental marginal pdfs. */
for ( unsigned int f = 0; f < this->m_NumberOfFixedHistogramBins; ++f )
{
for ( unsigned int m = 0; m < this->m_NumberOfMovingHistogramBins; ++m )
{
for ( unsigned int p = 0; p < this->GetNumberOfParameters(); ++p )
{
fixincit.Value() += incit.Get();
movincit.Value() += incit.Get();
++incit;
++fixincit;
++movincit;
}
fixincit.GoToBeginOfLine();
movincit.NextLine();
}
fixincit.NextLine();
movincit.GoToBegin();
}
} // end ComputeIncrementalMarginalPDFs()
/**
* ******************* UpdateJointPDFAndIncrementalPDFs *******************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::UpdateJointPDFAndIncrementalPDFs(
RealType fixedImageValue, RealType movingImageValue, RealType movingMaskValue,
const DerivativeType & movingImageValuesRight,
const DerivativeType & movingImageValuesLeft,
const DerivativeType & movingMaskValuesRight,
const DerivativeType & movingMaskValuesLeft,
const NonZeroJacobianIndicesType & nzji ) const
{
/** Pointers to the first pixels in the incremental joint pdfs. */
PDFValueType * incRightBasePtr = this->m_IncrementalJointPDFRight->GetBufferPointer();
PDFValueType * incLeftBasePtr = this->m_IncrementalJointPDFLeft->GetBufferPointer();
/** The Parzen value containers. */
ParzenValueContainerType fixedParzenValues( this->m_JointPDFWindow.GetSize()[1] );
ParzenValueContainerType movingParzenValues( this->m_JointPDFWindow.GetSize()[0] );
/** Determine fixed image Parzen window arguments (see eq. 6 of Mattes paper [2]). */
const double fixedImageParzenWindowTerm
= fixedImageValue / this->m_FixedImageBinSize - this->m_FixedImageNormalizedMin;
/** The lowest bin numbers affected by this pixel: */
const OffsetValueType fixedImageParzenWindowIndex =
static_cast<OffsetValueType>( vcl_floor(
fixedImageParzenWindowTerm + this->m_FixedParzenTermToIndexOffset ) );
this->EvaluateParzenValues(
fixedImageParzenWindowTerm, fixedImageParzenWindowIndex,
this->m_FixedKernel, fixedParzenValues );
if ( movingMaskValue > 1e-10 )
{
/** Determine moving image Parzen window arguments (see eq. 6 of Mattes paper [2]). */
const double movingImageParzenWindowTerm =
movingImageValue / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
const OffsetValueType movingImageParzenWindowIndex =
static_cast<OffsetValueType>( vcl_floor(
movingImageParzenWindowTerm + this->m_MovingParzenTermToIndexOffset ) );
this->EvaluateParzenValues(
movingImageParzenWindowTerm, movingImageParzenWindowIndex,
this->m_MovingKernel, movingParzenValues);
/** Position the JointPDFWindow (set the start index). */
JointPDFIndexType pdfIndex;
pdfIndex[0] = movingImageParzenWindowIndex;
pdfIndex[1] = fixedImageParzenWindowIndex;
/** Loop over the Parzen window region and do the following update:
*
* m_JointPDF(M,F) += movingMask * fixedParzen(F) * movingParzen(M);
* m_IncrementalJointPDF<Right/Left>(k,M,F) -= movingMask * fixedParzen(F) * movingParzen(M);
* for all k with nonzero Jacobian.
*/
for ( unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f )
{
const double fv_mask = fixedParzenValues[ f ] * movingMaskValue;
for ( unsigned int m = 0; m < movingParzenValues.GetSize(); ++m )
{
const PDFValueType fv_mask_mv =
static_cast<PDFValueType>( fv_mask * movingParzenValues[ m ] );
this->m_JointPDF->GetPixel( pdfIndex ) += fv_mask_mv;
unsigned long offset = static_cast<unsigned long>(
pdfIndex[ 0 ] * this->m_IncrementalJointPDFRight->GetOffsetTable()[ 1 ] +
pdfIndex[ 1 ] * this->m_IncrementalJointPDFRight->GetOffsetTable()[ 2 ] );
/** Get the pointer to the element with index [0, pdfIndex[0], pdfIndex[1]]. */
PDFValueType * incRightPtr = incRightBasePtr + offset;
PDFValueType * incLeftPtr = incLeftBasePtr + offset;
/** Loop only over the non-zero Jacobians. */
for ( unsigned int i = 0; i < nzji.size(); ++i )
{
const unsigned int mu = nzji[ i ];
PDFValueType * rPtr = incRightPtr + mu;
PDFValueType * lPtr = incLeftPtr + mu;
*(rPtr) -= fv_mask_mv;
*(lPtr) -= fv_mask_mv;
} // end for i
++(pdfIndex[ 0 ]);
} // end for m
pdfIndex[ 0 ] = movingImageParzenWindowIndex;
++(pdfIndex[ 1 ]);
} // end for f
} // end if movingMaskValue > 1e-10
/** Loop only over the non-zero Jacobians and update the incremental pdfs and
* update the perturbed alphas:
*
* m_IncrementalJointPDF<Right/Left>(k,M,F) +=
* movingMask<Right/Left>[k] * fixedParzen(F) * movingParzen<Right/Left>(M)[k];
* m_PerturbedAlpha<Right/Left>[k] += movingMask<Right/Left>[k] - movingMask;
* for all k with nonzero Jacobian.
*/
JointPDFDerivativesIndexType rindex;
JointPDFDerivativesIndexType lindex;
for ( unsigned int i = 0; i < nzji.size(); ++i)
{
const unsigned int mu = nzji[ i ];
const double maskr = movingMaskValuesRight[ i ];
const double maskl = movingMaskValuesLeft[ i ];
if ( maskr > 1e-10 )
{
/** Compute Parzen stuff; note: we reuse the movingParzenValues container. */
const double movr = movingImageValuesRight[i];
const double movParzenWindowTermRight =
movr / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
const OffsetValueType movParzenWindowIndexRight
= static_cast<OffsetValueType>( vcl_floor(
movParzenWindowTermRight + this->m_MovingParzenTermToIndexOffset ) );
this->EvaluateParzenValues(
movParzenWindowTermRight, movParzenWindowIndexRight,
this->m_MovingKernel, movingParzenValues);
/** Initialize index in IncrementalJointPDFRight. */
rindex[ 0 ] = mu;
rindex[ 1 ] = movParzenWindowIndexRight;
rindex[ 2 ] = fixedImageParzenWindowIndex;
/** Loop over Parzen window and update IncrementalJointPDFRight. */
for ( unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f )
{
const double fv_mask = fixedParzenValues[f] * maskr;
for ( unsigned int m = 0; m < movingParzenValues.GetSize(); ++m )
{
const PDFValueType fv_mask_mv =
static_cast<PDFValueType>( fv_mask * movingParzenValues[m] );
this->m_IncrementalJointPDFRight->GetPixel( rindex ) += fv_mask_mv;
++(rindex[ 1 ]);
} // end for m
++(rindex[ 2 ]);
rindex[ 1 ] = movParzenWindowIndexRight;
} // end for f
} // end if maskr
if ( maskl > 1e-10 )
{
/** Compute Parzen stuff; note: we reuse the movingParzenValues container. */
const double movl = movingImageValuesLeft[ i ];
const double movParzenWindowTermLeft =
movl / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
const OffsetValueType movParzenWindowIndexLeft
= static_cast<OffsetValueType>( vcl_floor(
movParzenWindowTermLeft + this->m_MovingParzenTermToIndexOffset ) );
this->EvaluateParzenValues(
movParzenWindowTermLeft, movParzenWindowIndexLeft,
this->m_MovingKernel, movingParzenValues );
/** Initialize index in IncrementalJointPDFLeft. */
lindex[ 0 ] = mu;
lindex[ 1 ] = movParzenWindowIndexLeft;
lindex[ 2 ] = fixedImageParzenWindowIndex;
/** Loop over Parzen window and update IncrementalJointPDFLeft. */
for ( unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f )
{
const double fv_mask = fixedParzenValues[ f ] * maskl;
for ( unsigned int m = 0; m < movingParzenValues.GetSize(); ++m )
{
const PDFValueType fv_mask_mv =
static_cast<PDFValueType>( fv_mask * movingParzenValues[ m ] );
this->m_IncrementalJointPDFLeft->GetPixel( lindex ) += fv_mask_mv;
++(lindex[ 1 ]);
} // end for m
++(lindex[ 2 ]);
lindex[ 1 ] = movParzenWindowIndexLeft;
} // end for f
} // end if maskl
/** Update the perturbed alphas. */
this->m_PerturbedAlphaRight[mu] += ( maskr - movingMaskValue );
this->m_PerturbedAlphaLeft[mu] += ( maskl - movingMaskValue );
} // end for i
} // end UpdateJointPDFAndIncrementalPDFs()
/**
* ************************ ComputePDFs **************************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::ComputePDFs( const ParametersType& parameters ) const
{
/** Initialize some variables. */
this->m_JointPDF->FillBuffer( 0.0 );
this->m_NumberOfPixelsCounted = 0;
this->m_Alpha = 0.0;
/** Set up the parameters in the transform. */
this->SetTransformParameters( parameters );
/** Update the imageSampler and get a handle to the sample container. */
this->GetImageSampler()->Update();
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Create iterator over the sample container. */
typename ImageSampleContainerType::ConstIterator fiter;
typename ImageSampleContainerType::ConstIterator fbegin = sampleContainer->Begin();
typename ImageSampleContainerType::ConstIterator fend = sampleContainer->End();
/** Loop over sample container and compute contribution of each sample to pdfs. */
for ( fiter = fbegin; fiter != fend; ++fiter )
{
/** Read fixed coordinates and initialize some variables. */
const FixedImagePointType & fixedPoint = (*fiter).Value().m_ImageCoordinates;
RealType movingImageValue;
MovingImagePointType mappedPoint;
/** Transform point and check if it is inside the B-spline support region. */
bool sampleOk = this->TransformPoint( fixedPoint, mappedPoint );
/** Check if point is inside mask. */
if ( sampleOk )
{
sampleOk = this->IsInsideMovingMask( mappedPoint );
}
/** Compute the moving image value and check if the point is
* inside the moving image buffer.
*/
if ( sampleOk )
{
sampleOk = this->EvaluateMovingImageValueAndDerivative(
mappedPoint, movingImageValue, 0 );
}
if ( sampleOk )
{
this->m_NumberOfPixelsCounted++;
/** Get the fixed image value. */
RealType fixedImageValue = static_cast<RealType>( (*fiter).Value().m_ImageValue );
/** Make sure the values fall within the histogram range. */
fixedImageValue = this->GetFixedImageLimiter()->Evaluate( fixedImageValue );
movingImageValue = this->GetMovingImageLimiter()->Evaluate( movingImageValue );
/** Compute this sample's contribution to the joint distributions. */
this->UpdateJointPDFAndDerivatives(
fixedImageValue, movingImageValue, 0, 0 );
}
} // end iterating over fixed image spatial sample container for loop
/** Check if enough samples were valid. */
this->CheckNumberOfSamples( sampleContainer->Size(), this->m_NumberOfPixelsCounted );
/** Compute alpha. */
this->m_Alpha = 0.0;
if ( this->m_NumberOfPixelsCounted > 0 )
{
this->m_Alpha = 1.0 / static_cast<double>( this->m_NumberOfPixelsCounted );
}
} // end ComputePDFs()
/**
* ************************ ComputePDFsAndPDFDerivatives *******************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::ComputePDFsAndPDFDerivatives( const ParametersType& parameters ) const
{
/** Initialize some variables. */
this->m_JointPDF->FillBuffer( 0.0 );
this->m_JointPDFDerivatives->FillBuffer( 0.0 );
this->m_Alpha = 0.0;
this->m_NumberOfPixelsCounted = 0;
/** Array that stores dM(x)/dmu, and the sparse jacobian+indices. */
NonZeroJacobianIndicesType nzji( this->m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices() );
DerivativeType imageJacobian( nzji.size() );
TransformJacobianType jacobian;
/** Set up the parameters in the transform. */
this->SetTransformParameters( parameters );
/** Update the imageSampler and get a handle to the sample container. */
this->GetImageSampler()->Update();
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Create iterator over the sample container. */
typename ImageSampleContainerType::ConstIterator fiter;
typename ImageSampleContainerType::ConstIterator fbegin = sampleContainer->Begin();
typename ImageSampleContainerType::ConstIterator fend = sampleContainer->End();
/** Loop over sample container and compute contribution of each sample to pdfs. */
for ( fiter = fbegin; fiter != fend; ++fiter )
{
/** Read fixed coordinates and initialize some variables. */
const FixedImagePointType & fixedPoint = (*fiter).Value().m_ImageCoordinates;
RealType movingImageValue;
MovingImagePointType mappedPoint;
MovingImageDerivativeType movingImageDerivative;
/** Transform point and check if it is inside the B-spline support region. */
bool sampleOk = this->TransformPoint( fixedPoint, mappedPoint);
/** Check if point is inside mask. */
if ( sampleOk )
{
sampleOk = this->IsInsideMovingMask( mappedPoint );
}
/** Compute the moving image value M(T(x)) and derivative dM/dx and check if
* the point is inside the moving image buffer.
*/
if ( sampleOk )
{
sampleOk = this->EvaluateMovingImageValueAndDerivative(
mappedPoint, movingImageValue, &movingImageDerivative );
}
if ( sampleOk )
{
this->m_NumberOfPixelsCounted++;
/** Get the fixed image value. */
RealType fixedImageValue = static_cast<RealType>( (*fiter).Value().m_ImageValue );
/** Make sure the values fall within the histogram range. */
fixedImageValue = this->GetFixedImageLimiter()->Evaluate( fixedImageValue );
movingImageValue = this->GetMovingImageLimiter()->Evaluate(
movingImageValue, movingImageDerivative );
/** Get the TransformJacobian dT/dmu. */
this->EvaluateTransformJacobian( fixedPoint, jacobian, nzji );
/** Compute the inner product (dM/dx)^T (dT/dmu). */
this->EvaluateTransformJacobianInnerProduct(
jacobian, movingImageDerivative, imageJacobian );
/** Update the joint pdf and the joint pdf derivatives. */
this->UpdateJointPDFAndDerivatives(
fixedImageValue, movingImageValue, &imageJacobian, &nzji );
} //end if-block check sampleOk
} // end iterating over fixed image spatial sample container for loop
/** Check if enough samples were valid. */
this->CheckNumberOfSamples(
sampleContainer->Size(), this->m_NumberOfPixelsCounted );
/** Compute alpha. */
this->m_Alpha = 0.0;
if ( this->m_NumberOfPixelsCounted > 0 )
{
this->m_Alpha = 1.0 / static_cast<double>( this->m_NumberOfPixelsCounted );
}
} // end ComputePDFsAndPDFDerivatives()
/**
* ************************ ComputePDFsAndIncrementalPDFs *******************
*/
template < class TFixedImage, class TMovingImage >
void
ParzenWindowHistogramImageToImageMetric<TFixedImage,TMovingImage>
::ComputePDFsAndIncrementalPDFs( const ParametersType& parameters ) const
{
/** Initialize some variables. */
this->m_JointPDF->FillBuffer( 0.0 );
this->m_IncrementalJointPDFRight->FillBuffer( 0.0 );
this->m_IncrementalJointPDFLeft->FillBuffer( 0.0 );
this->m_Alpha = 0.0;
this->m_PerturbedAlphaRight.Fill( 0.0 );
this->m_PerturbedAlphaLeft.Fill( 0.0 );
this->m_NumberOfPixelsCounted = 0;
double sumOfMovingMaskValues = 0.0;
const double delta = this->GetFiniteDifferencePerturbation();
/** sparse jacobian+indices. */
NonZeroJacobianIndicesType nzji( this->m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices() );
TransformJacobianType jacobian;
/** Arrays that store dM(x)/dmu and dMask(x)/dmu. */
DerivativeType movingImageValuesRight( nzji.size() );
DerivativeType movingImageValuesLeft( nzji.size() );
DerivativeType movingMaskValuesRight( nzji.size() );
DerivativeType movingMaskValuesLeft( nzji.size() );
/** Set up the parameters in the transform. */
this->SetTransformParameters( parameters );
/** Update the imageSampler and get a handle to the sample container. */
this->GetImageSampler()->Update();
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Create iterator over the sample container. */
typename ImageSampleContainerType::ConstIterator fiter;
typename ImageSampleContainerType::ConstIterator fbegin = sampleContainer->Begin();
typename ImageSampleContainerType::ConstIterator fend = sampleContainer->End();
/** Loop over sample container and compute contribution of each sample to pdfs. */
for ( fiter = fbegin; fiter != fend; ++fiter )
{
/** Read fixed coordinates. */
const FixedImagePointType & fixedPoint = (*fiter).Value().m_ImageCoordinates;
/** Transform point and check if it is inside the B-spline support region.
* if not, skip this sample.
*/
MovingImagePointType mappedPoint;
bool sampleOk = this->TransformPoint( fixedPoint, mappedPoint );
if ( sampleOk )
{
/** Get the fixed image value and make sure the value falls within the histogram range. */
RealType fixedImageValue = static_cast<RealType>( (*fiter).Value().m_ImageValue );
fixedImageValue = this->GetFixedImageLimiter()->Evaluate( fixedImageValue );
/** Check if point is inside mask. */
sampleOk = this->IsInsideMovingMask( mappedPoint );
RealType movingMaskValue =
static_cast<RealType>( static_cast<unsigned char>( sampleOk ) );
/** Compute the moving image value M(T(x)) and check if
* the point is inside the moving image buffer.
*/
RealType movingImageValue = itk::NumericTraits<RealType>::Zero;
if ( sampleOk )
{
sampleOk = this->EvaluateMovingImageValueAndDerivative(
mappedPoint, movingImageValue, 0 );
if ( sampleOk )
{
movingImageValue = this->GetMovingImageLimiter()->Evaluate( movingImageValue );
}
else
{
/** this movingImageValueRight is invalid, even though the mask indicated it is valid. */
movingMaskValue = 0.0;
}
}
/** Stop with this sample. It may be possible that with a perturbed parameter
* a valid voxel pair is obtained, but:
* - this chance is small,
* - quitting now saves a lot of time, especially because this situation
* occurs at border pixels (there are a lot of those)
* - if we would analytically compute the gradient the same choice is
* somehow made.
*/
if ( !sampleOk ) continue;
/** count how many samples were used. */
sumOfMovingMaskValues += movingMaskValue;
this->m_NumberOfPixelsCounted += static_cast<unsigned int>( sampleOk );
/** Get the TransformJacobian dT/dmu. We assume the transform is a linear
* function of its parameters, so that we can evaluate T(x;\mu+delta_ek)
* as T(x) + delta * dT/dmu_k.
*/
this->EvaluateTransformJacobian( fixedPoint, jacobian, nzji );
MovingImagePointType mappedPointRight;
MovingImagePointType mappedPointLeft;
/** Loop over all parameters to perturb (parameters with nonzero Jacobian). */
for ( unsigned int i = 0; i < nzji.size(); ++i )
{
/** Compute the transformed input point after perturbation. */
for ( unsigned int j = 0; j < MovingImageDimension; ++j )
{
const double delta_jac = delta * jacobian[ j ][ i ];
mappedPointRight[ j ] = mappedPoint[ j ] + delta_jac;
mappedPointLeft[ j ] = mappedPoint[ j ] - delta_jac;
}
/** Compute the moving mask 'value' and moving image value at the right perturbed positions. */
sampleOk = this->IsInsideMovingMask( mappedPointRight );
RealType movingMaskValueRight =
static_cast<RealType>( static_cast<unsigned char>( sampleOk ) );
if ( sampleOk )
{
RealType movingImageValueRight = 0.0;
sampleOk = this->EvaluateMovingImageValueAndDerivative(
mappedPointRight, movingImageValueRight, 0 );
if ( sampleOk )
{
movingImageValueRight =
this->GetMovingImageLimiter()->Evaluate( movingImageValueRight );
movingImageValuesRight[ i ] = movingImageValueRight;
}
else
{
/** this movingImageValueRight is invalid, even though the mask indicated it is valid. */
movingMaskValueRight = 0.0;
}
}
movingMaskValuesRight[i] = movingMaskValueRight;
/** Compute the moving mask and moving image value at the left perturbed positions. */
sampleOk = this->IsInsideMovingMask( mappedPointLeft );
RealType movingMaskValueLeft =
static_cast<RealType>( static_cast<unsigned char>( sampleOk ) );
if ( sampleOk )
{
RealType movingImageValueLeft = 0.0;
sampleOk = this->EvaluateMovingImageValueAndDerivative(
mappedPointLeft, movingImageValueLeft, 0 );
if ( sampleOk )
{
movingImageValueLeft =
this->GetMovingImageLimiter()->Evaluate( movingImageValueLeft );
movingImageValuesLeft[ i ] = movingImageValueLeft;
}
else
{
/** this movingImageValueLeft is invalid, even though the mask indicated it is valid. */
movingMaskValueLeft = 0.0;
}
}
movingMaskValuesLeft[ i ] = movingMaskValueLeft;
} // next parameter to perturb
/** Update the joint pdf and the incremental joint pdfs, and the
* perturbed alpha arrays.
*/
this->UpdateJointPDFAndIncrementalPDFs(
fixedImageValue, movingImageValue, movingMaskValue,
movingImageValuesRight, movingImageValuesLeft,
movingMaskValuesRight, movingMaskValuesLeft, nzji );
} //end if-block check sampleOk
} // end iterating over fixed image spatial sample container for loop
/** Check if enough samples were valid. */
this->CheckNumberOfSamples(
sampleContainer->Size(), this->m_NumberOfPixelsCounted );
/** Compute alpha and its perturbed versions. */
this->m_Alpha = 0.0;
if ( sumOfMovingMaskValues > 1e-14 )
{
this->m_Alpha = 1.0 / sumOfMovingMaskValues;
}
for ( unsigned int i = 0; i < this->GetNumberOfParameters(); ++i )
{
this->m_PerturbedAlphaRight[ i ] += sumOfMovingMaskValues;
this->m_PerturbedAlphaLeft[ i ] += sumOfMovingMaskValues;
if ( this->m_PerturbedAlphaRight[i] > 1e-10 )
{
this->m_PerturbedAlphaRight[ i ] = 1.0 / this->m_PerturbedAlphaRight[ i ];
}
else
{
this->m_PerturbedAlphaRight[ i ] = 0.0;
}
if ( this->m_PerturbedAlphaLeft[ i ] > 1e-10 )
{
this->m_PerturbedAlphaLeft[ i ] = 1.0 / this->m_PerturbedAlphaLeft[ i ];
}
else
{
this->m_PerturbedAlphaLeft[ i ] = 0.0;
}
}
} // end ComputePDFsAndIncrementalPDFs()
} // end namespace itk
#endif // end #ifndef _itkParzenWindowHistogramImageToImageMetric_HXX__
| [
"[email protected]"
] | [
[
[
1,
1385
]
]
] |
e3e90f6bdd10e834ff7a325925f21f44c6c441aa | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Modules/UiCtrl/AudioClipsEnum.h | 203001d8a48c1d1d3ca4cfc4a7ae82ad5f4b86fb | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,875 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef AUDIO_CLIPS_ENUM_H
#define AUDIO_CLIPS_ENUM_H
#undef USE_OLD_ENGLISH
namespace isab{
// Note that if the order of these change, AudioClipTable must also
// be changed so that it is sorted.
namespace AudioClipsEnum {
const static int sv_base = 100;
const static int en_base = 200;
const static int de_base = 300;
const static int da_base = 400;
const static int it_base = 500;
const static int fr_base = 600;
const static int es_base = 700;
const static int nl_base = 800;
const static int fi_base = 900;
const static int no_base = 1000;
const static int us_base = 1100;
const static int pt_base = 1200;
const static int hu_base = 1300;
const static int pl_base = 1400;
const static int cs_base = 1500;
const static int sl_base = 1600;
enum Clips {
/* Meta sounds */
SoundEnd = -1,
SoundMayBreak = -2,
SoundTimingMarker = -3,
SoundNoKnownSound = -4,
/* Universal sounds (used by several languages) */
SoundNewCrossing = 0,
/* Swedish */
SvSoundSvangVanster = sv_base,
SvSoundSvangHoger,
SvSoundHaer,
SvSoundOmTjugofemMeter,
SvSoundOmFemtioMeter,
SvSoundOmEttHundraMeter,
SvSoundOmTvaHundraMeter,
SvSoundOmFemHundraMeter,
SvSoundOmEnKilometer,
SvSoundOmTvaKilometer,
SvSoundHaallVanster,
SvSoundHaallHoger,
SvSoundIRondellen,
SvSoundDuHarAvvikitFranRutten,
SvSoundDuKorAtFelHall,
SvSoundDuArFrammeVidDinDest,
SvSoundVidDestinationen,
SvSoundKorRaktFram,
SvSoundKorAv,
SvSoundKorUr,
SvSoundUtfarten,
SvSoundTa,
SvSoundGorEnUSvang,
SvSoundForsta,
SvSoundAndra,
SvSoundTredje,
SvSoundFjarde,
SvSoundFemte,
SvSoundSjatte,
SvSoundSjunde,
SvSoundAttonde,
SvSoundOchDarefter,
SvSoundDirekt,
SvSoundCamera,
#ifdef USE_OLD_ENGLISH
/* English */
EnSoundTheFirst = en_base,
EnSoundTheSecond,
EnSoundTheThird,
EnSoundTheFourth,
EnSoundTheFifth,
EnSoundTheSixth,
EnSoundTheSeventh,
EnSoundTheEighth,
EnSoundAndThen,
EnSoundAtTheDestination,
EnSoundDriveStraightAhead,
EnSoundExit,
EnSoundYouHaveReachedYourDestination,
EnSoundHere,
EnSoundInOneHundredMeters,
EnSoundInOneKilometer,
EnSoundInTwohundredMeters,
EnSoundInTwentyfiveMeters,
EnSoundInTwoKilometers,
EnSoundInFiftyMeters,
EnSoundInFivehundredMeters,
EnSoundInTheRoundabout,
EnSoundKeepLeft,
EnSoundKeepRight,
EnSoundMeters,
EnSoundTake,
EnSoundTurnLeft,
EnSoundTurnRight,
EnSoundUturn,
EnSoundYouAreDrivingInTheWrongDirection,
EnSoundYouAreNowOffTrack,
EnSoundCamera,
#else
EnSoundIn100Feet = en_base,
EnSoundIn200Feet,
EnSoundIn500Feet,
EnSoundInAQuarterOfAMile,
EnSoundInHalfAMile,
EnSoundIn1Mile,
EnSoundIn2Miles,
EnSoundIn2Kilometers,
EnSoundIn1Kilometer,
EnSoundIn500Meters,
EnSoundIn200Meters,
EnSoundIn100Meters,
EnSoundIn50Meters,
EnSoundIn25Meters,
EnSoundIn500Yards,
EnSoundIn200Yards,
EnSoundIn100Yards,
EnSoundIn50Yards,
EnSoundIn25Yards,
EnSoundTheFirst,
EnSoundTheSecond,
EnSoundTheThird,
EnSoundTheFourth,
EnSoundTheFifth,
EnSoundTheSixth,
EnSoundTheSeventh,
EnSoundTheEighth,
EnSoundAndThen,
EnSoundAtTheDestination,
EnSoundAtTheRoundabout,
EnSoundDriveStraightAhead,
EnSoundExitNoun,
EnSoundExitVerb,
EnSoundHere,
EnSoundImmediately,
EnSoundKeepLeft,
EnSoundKeepRight,
EnSoundMakeAUTurn,
EnSoundPleaseTurnAround,
EnSoundTake,
EnSoundTurnLeft,
EnSoundTurnRight,
EnSoundYouAreNowOffTrack,
EnSoundYouHaveReachedYourDestination,
EnSoundCamera,
#endif
/* German */
DeSoundDieErste = de_base,
DeSoundDieZweite,
DeSoundDieDritte,
DeSoundDieVierte,
DeSoundDieFunfte,
DeSoundDieSechte,
DeSoundDieSibte,
DeSoundDieAchrte,
DeSoundUndDann,
// DeSoundDasZielBefindetSichGeradeaus,
DeSoundAmZiel,
DeSoundGeradeausWeiterfahren,
DeSoundAusfahrt,
DeSoundAbfahren,
DeSoundSieHabenDasZielErreicht,
DeSoundHier,
DeSoundInFunfUndZwanzigMetern,
DeSoundInFunfzigMetern,
DeSoundInEinhundertMetern,
DeSoundInZweihundertMetern,
DeSoundInFunfhundertMetern,
DeSoundInEinemKilometer,
DeSoundInZweiKilometern,
DeSoundImKreisel,
DeSoundLinksHalten,
DeSoundRechtsHalten,
DeSoundLinksAbbiegen,
DeSoundRechtsAbbiegen,
DeSoundSieFahrenJetztInDieFalsheRichtung,
DeSoundSieHabenJetztDieGeplanteRouteVerlassen,
DeSoundBitteWenden,
DeSoundWennMoglichBitteWenden,
DeSoundSofort,
DeSoundCamera,
/* Danish */
DaSoundDenForste = da_base,
DaSoundDenAnnen,
DaSoundDenTredje,
DaSoundDenFjerre,
DaSoundDenFemte,
DaSoundDenSjaette,
DaSoundDenSuvene,
DaSoundDenAttande,
DaSoundDarefter,
DaSoundKorLigeUd,
DaSoundVej,
DaSoundFrakorsel,
DaSoundDuErFrammeVidMalet,
DaSoundNu,
DaSoundOmEttHundredeMeter,
DaSoundOmEnKilometer,
DaSoundOmTuHundredeMeter,
DaSoundOmFemOgTuveMeter,
DaSoundOmTuKilometer,
DaSoundOmHalvtredsMeter,
DaSoundOmFemhundredeMeter,
DaSoundIRundkorseln,
DaSoundHallTillVenstre,
DaSoundHallTillHojre,
DaSoundRetframLigeUd,
DaSoundTa,
DaSoundMaletErRaettfram,
DaSoundDrejTillVenstre,
DaSoundDrejTillHojre,
DaSoundLavEnUVandning,
DaSoundDuKorIDenForkerteRaktning,
DaSoundDuErAvviketFraRutten,
DaSoundMeddetsamme,
DaSoundCamera,
/* Italian */
ItSoundLaPrima = it_base,
ItSoundLaSeconda,
ItSoundLaTerza,
ItSoundLaQuarta,
ItSoundLaQuinta,
ItSoundLaSesta,
ItSoundLaSettima,
ItSoundLottava,
ItSoundQuindi,
ItSoundADestinazione,
ItSoundProcedoDiritto,
ItSoundUscita,
ItSoundEsci,
ItSoundHaiRaggiunto,
ItSoundQui,
ItSoundTra25Metri,
ItSoundTra50Metri,
ItSoundTra100Metri,
ItSoundTra200Metri,
ItSoundTra500Metri,
ItSoundTra1Chilometro,
ItSoundTra2Chilometri,
ItSoundAllaRotonda,
ItSoundMantieniLaSinistra,
ItSoundMantieniLaDestra,
ItSoundSvoltaASinistra,
ItSoundSvoltaADestra,
ItSoundSeiFuoriStrada,
ItSoundStaiProcedendo,
ItSoundQuandoPossibile,
ItSoundImmediatamente,
ItSoundPrendi,
ItSoundEsciDallAutostrada,
ItSoundEseguiUnInversioneAU,
ItSoundCamera,
/* French */
FrSoundLaPremiere = fr_base,
FrSoundLaDeuxieme,
FrSoundLaTroisieme,
FrSoundLaQuatrieme,
FrSoundLaCinquieme,
FrSoundLaSixieme,
FrSoundLaSeptieme,
FrSoundLaHuitieme,
FrSoundImmediatement,
FrSoundIci,
FrSoundA25Metres,
FrSoundA50Metres,
FrSoundA100Metres,
FrSoundA200Metres,
FrSoundA500Metres,
FrSoundA1Kilometre,
FrSoundA2Kilometres,
FrSoundADestination,
FrSoundADroite,
FrSoundAGauche,
FrSoundAPresentVousEtes,
FrSoundAuRondpoint,
FrSoundConduisezToutDroit,
FrSoundContinuez,
FrSoundDesQuePossible,
FrSoundFaitesDemitour,
FrSoundPrenez,
FrSoundQuittezLautoroute,
FrSoundSortez,
FrSoundSortie,
FrSoundTournez,
FrSoundVousEtesArrive,
FrSoundPuis,
FrSoundCamera,
/* Spanish */
EsSoundLaPrimera = es_base,
EsSoundLaSegunda,
EsSoundLaTercera,
EsSoundLaCuarta,
EsSoundLaQuinta,
EsSoundLaSexta,
EsSoundLaSeptima,
EsSoundLaOctava,
EsSoundAqui,
EsSoundCambiaDeSentido,
EsSoundConduceTodoRecto,
EsSoundCuandoPuedas,
EsSoundElDestino,
EsSoundEn100Metros,
EsSoundEn1Kilometro,
EsSoundEn200Metros,
EsSoundEn25Metros,
EsSoundEn2Kilometros,
EsSoundEn500Metros,
EsSoundEn50Metros,
EsSoundEnElDestino,
EsSoundEnLaRotonda,
EsSoundEstasConduciendo,
EsSoundEstasFueraDeLaRuta,
EsSoundGiraALaDerecha,
EsSoundGiraALaIzquierda,
EsSoundHasLlegadoATuDestino,
EsSoundInmeditamente,
EsSoundMantenteALaDerecha,
EsSoundMantenteALaIzquierda,
EsSoundSalida,
EsSoundSal,
EsSoundSalDeLaAutopista,
EsSoundToma,
EsSoundYDespues,
EsSoundCamera,
/* Dutch */
NlSoundAfrit = nl_base,
NlSoundBijDeBestemming,
NlSoundDeEerste,
NlSoundDeTweede,
NlSoundDeDerde,
NlSoundDeVierde,
NlSoundDeVijfde,
NlSoundDeZesde,
NlSoundDeZevende,
NlSoundDeAchtste,
NlSoundEnDan,
NlSoundHier,
NlSoundKeerOmIndienMogelijk,
NlSoundLinksAfslaan,
NlSoundLinksHouden,
NlSoundLinks,
NlSoundNa100Meter,
NlSoundNa1Kilometer,
NlSoundNa200Meter,
NlSoundNa25Meter,
NlSoundNa2Kilometer,
NlSoundNa500Meter,
NlSoundNa50Meter,
NlSoundNaarLinks,
NlSoundNaarRechts,
NlSoundOmkeren,
NlSoundOnmiddellijk,
NlSoundOpDeRotonde,
NlSoundRechtdoorRijden,
NlSoundRechtsAfslaan,
NlSoundRechtsHouden,
NlSoundRechts,
NlSoundSnelwegVerlaten,
NlSoundUBevindtZichNuBuitenDeRoute,
NlSoundUHebtUwBestemmingBereikt,
NlSoundURijdtInDeVerkeerdeRichting,
NlSoundCamera,
/* Finnish */
FiSound25Metrin = fi_base,
FiSound50Metrin,
FiSound100Metrin,
FiSound200Metrin,
FiSound500Metrin,
FiSound1Kilometrin,
FiSound2Kilometrin,
FiSoundEnsimmainen,
FiSoundToinen,
FiSoundKolmas,
FiSoundNeljas,
FiSoundViides,
FiSoundKuudes,
FiSoundSeitsemas,
FiSoundKahdeksas,
FiSoundEtSeuraaAnnettuaReittia,
FiSoundJaSitten,
FiSoundKaannyOikealle,
FiSoundKaannyVasemmalle,
FiSoundJalkeen,
FiSoundPaassa,
FiSoundLiikenneympyrasta,
FiSoundOletTullutPerille,
FiSoundPoistu,
FiSoundPysyOikealla,
FiSoundPysyVasemmalla,
FiSoundTassa,
FiSoundTasta,
FiSoundTeeUKaannosHeti,
FiSoundUloskaynti,
FiSoundValitseLiikenneympyrasta,
FiSoundValittomasti,
FiSoundKaanny,
FiSoundYmpari,
FiSoundMaaranpaasiOn,
FiSoundSuoraanEteenpain,
FiSoundVasemmalle,
FiSoundOikealle,
FiSoundAjaLiikenneymparastaSouraanEteenpain,
FiSoundCamera,
/* Norwegian */
NoSound25 = no_base,
NoSound50,
NoSound100,
NoSound200,
NoSound500,
NoSound1,
NoSound2,
NoSoundForste,
NoSoundAndre,
NoSoundTredje,
NoSoundFjerde,
NoSoundFemte,
NoSoundSjette,
NoSoundSjuende,
NoSoundAttende,
NoSoundAvkjoring,
NoSoundDestinasjonenErRettFrem,
NoSoundDuErFremmeVedDestinasjonen,
NoSoundDuErUtenforRuten,
NoSoundForlatHovedveien,
NoSoundGjorEnUSvingNarDetBlirMulig,
NoSoundHer,
NoSoundHold,
NoSoundIEndenAvGaten,
NoSoundIRundkjoringen,
NoSoundKilometer,
NoSoundKjorAv,
NoSoundKjorHeleVeienRundt,
NoSoundKjorRettFrem,
NoSoundKjorUt,
NoSoundMeter,
NoSoundMiles,
NoSoundOgSa,
NoSoundOm,
NoSoundSving,
NoSoundTa,
NoSoundTilHoyre,
NoSoundTilVenstre,
NoSoundUmiddelbart,
NoSoundVedDestinasjonen,
NoSoundVennligstSnu,
NoSoundVenstre,
NoSoundYards,
NoSoundCamera,
/* American English */
UsSoundIn100Feet = us_base,
UsSoundIn200Feet,
UsSoundIn500Feet,
UsSoundInAQuarterOfAMile,
UsSoundInHalfAMile,
UsSoundIn1Mile,
UsSoundIn2Miles,
UsSoundIn2Kilometers,
UsSoundIn1Kilometer,
UsSoundIn500Meters,
UsSoundIn200Meters,
UsSoundIn100Meters,
UsSoundIn50Meters,
UsSoundIn25Meters,
UsSoundIn500Yards,
UsSoundIn200Yards,
UsSoundIn100Yards,
UsSoundIn50Yards,
UsSoundIn25Yards,
UsSoundTheFirst,
UsSoundTheSecond,
UsSoundTheThird,
UsSoundTheFourth,
UsSoundTheFifth,
UsSoundTheSixth,
UsSoundTheSeventh,
UsSoundTheEighth,
UsSoundAndThen,
UsSoundAtTheDestination,
UsSoundAtTheRoundabout,
UsSoundDriveStraightAhead,
UsSoundExitNoun,
UsSoundExitVerb,
UsSoundHere,
UsSoundImmediately,
UsSoundKeepLeft,
UsSoundKeepRight,
UsSoundMakeAUTurn,
UsSoundPleaseTurnAround,
UsSoundTake,
UsSoundTurnLeft,
UsSoundTurnRight,
UsSoundYouAreNowOffTrack,
UsSoundYouHaveReachedYourDestination,
UsSoundCamera,
/* Portuguese */
PtSound100Feet = pt_base,
PtSound200Feet,
PtSound500Feet,
PtSoundAQuarterOfAMile,
PtSoundHalfAMile,
PtSound1Mile,
PtSound2Miles,
PtSound25Metros,
PtSound50Metros,
PtSound100Metros,
PtSound200Metros,
PtSound500Metros,
PtSound1Quilometro,
PtSound2Quilometros,
PtSound25Yards,
PtSound50Yards,
PtSound100Yards,
PtSound200Yards,
PtSound500Yards,
PtSoundNaPrimeira,
PtSoundNaSegunda,
PtSoundNaTerceira,
PtSoundNaQuarta,
PtSoundNaQuinta,
PtSoundNaSexta,
PtSoundNaSetima,
PtSoundNaOitava,
PtSoundA,
PtSoundAqui,
PtSoundDaquiA,
PtSoundEASeguir,
PtSoundFacaInversaoDeMarcha,
PtSoundImediatamente,
PtSoundMantenhaSeADireita,
PtSoundMantenhaSeAEsquerda,
PtSoundNaRotunda,
PtSoundNoDestino,
PtSoundQuandoPossivel,
PtSoundSaia,
PtSoundSaida,
PtSoundSigaEmFrente,
PtSoundVire,
PtSoundVireADireita,
PtSoundVireAEsquerda,
PtSoundVoceChegouAoSeuDestino,
PtSoundVoceEstaForaDeRota,
PtSoundCamera,
/* Hungarian */
HuSound100 = hu_base,
HuSound1,
HuSound200,
HuSound25,
HuSound2,
HuSound500,
HuSound50,
HuSoundAzElso,
HuSoundAMasodik,
HuSoundAHarmadik,
HuSoundANegyedik,
HuSoundAzOtodik,
HuSoundAHatodik,
HuSoundAHetedik,
HuSoundANyolcadik,
HuSoundAKijaratig,
HuSoundAKorforgalomnal,
HuSoundAKorforgalomban,
HuSoundACelpontElottedVan,
HuSoundACelpontig,
HuSoundBalra,
HuSoundEgyenesen,
HuSoundElertedACelpontot,
HuSoundFel,
HuSoundForduljVisszaAmintLehet,
HuSoundForduljVissza,
HuSoundFordulj,
HuSoundHajtsKi,
HuSoundItt,
HuSoundJardot,
HuSoundJobbra,
HuSoundKijaraton,
HuSoundKilometert,
HuSoundLabat,
HuSoundMajdUtana,
HuSoundMenjTovabbEgyenesen1,
HuSoundMenjTovabbEgyenesen2,
HuSoundMenj,
HuSoundMerfoldet,
HuSoundMetert,
HuSoundMostLetertelAzUtvonalrol,
HuSoundMost,
HuSoundNegyed,
HuSoundNyolcad,
HuSoundRosszIranybaMesz,
HuSoundTarts,
HuSoundCamera,
/* Polish */
PlSoundWPierwszy = pl_base,
PlSoundWDrugi,
PlSoundWTrzeci,
PlSoundWCzwarty,
PlSoundWPiaty,
PlSoundWSzusty,
PlSoundWSiodmy,
PlSoundWOsmy,
PlSoundTutaj,
PlSoundNatychmiast,
PlSoundZa25Metrow,
PlSoundZa50Metrow,
PlSoundZa100Metrow,
PlSoundZa200Metrow,
PlSoundZa500Metrow,
PlSoundZa25Jardow,
PlSoundZa50Jardow,
PlSoundZa100Jardow,
PlSoundZa200Jardow,
PlSoundZa500Jardow,
PlSoundZa25Stop,
PlSoundZa50Stop,
PlSoundZa100Stop,
PlSoundZa200Stop,
PlSoundZa500Stop,
PlSoundZa1Kilometr,
PlSoundZa2Kilometry,
PlSoundZaPuMili,
PlSoundZaJednotwartoMili,
PlSoundZaJednoossmoMili,
PlSoundZa1Mile,
PlSoundZa2Mile,
PlSoundAPotem,
PlSoundDojechales,
PlSoundJedz,
PlSoundJedzProsto,
PlSoundKamera,
PlSoundNaRondzie,
PlSoundOstrzezenie,
PlSoundProszeZawrocic,
PlSoundPunkt,
PlSoundSkrecWLewo,
PlSoundSkrecWPrawo,
PlSoundTeraz,
PlSoundTrzymajSieLewej,
PlSoundTrzymajSiePrawej,
PlSoundWlasnie,
PlSoundWMiejscuPrzeznaczenia,
PlSoundZawrocGdyBedzieToMozliwe,
PlSoundZjazd,
PlSoundZjedz,
PlSoundZjedzZAutostrade,
PlSoundCamera,
/* Czech */
CsSoundPrvnim = cs_base,
CsSoundDruhym,
CsSoundTretim,
CsSoundCtvrtym,
CsSoundPatym,
CsSoundSestym,
CsSoundSedmym,
CsSoundOsmym,
CsSoundZde,
CsSoundIhned,
CsSoundPo25Metrech,
CsSoundPo50Metrech,
CsSoundPo100Metrech,
CsSoundPo200Metrech,
CsSoundPo500Metrech,
CsSoundPo25Yardech,
CsSoundPo50Yardech,
CsSoundPo100Yardech,
CsSoundPo200Yardech,
CsSoundPo500Yardech,
CsSoundPo25Stopach,
CsSoundPo50Stopach,
CsSoundPo100Stopach,
CsSoundPo200Stopach,
CsSoundPo500Stopach,
CsSoundPo1Kilometru,
CsSoundPo2Kilometrech,
CsSoundPoPulMile,
CsSoundPoCtvrtMile,
CsSoundPoOsmineMile,
CsSoundPo1Mili,
CsSoundPo2Milich,
CsSoundAPotom,
CsSoundCilJePredVami,
CsSoundDrzteSeVlevo,
CsSoundDrzteSeVpravo,
CsSoundJedte,
CsSoundJedtePrimo,
CsSoundJsteVCili,
CsSoundNaKruhovemObjezdu,
CsSoundNebezpeci,
CsSoundNyniJedeteNespravnymSmerem,
CsSoundNyniJsteMimoTrasu,
CsSoundOdbocteVlevo,
CsSoundOdbocteVpravo,
CsSoundOpustteDalnici,
CsSoundOtocteSeAzJeToMozne,
CsSoundProsimOtocteSe,
CsSoundRychlostniKamera,
CsSoundVCili,
CsSoundVyjedte,
CsSoundVyjezdem,
CsSoundCamera,
/* Slovenian */
SlSoundPrvi = sl_base,
SlSoundDrugi,
SlSoundTretji,
SlSoundCetrti,
SlSoundPeti,
SlSoundSesti,
SlSoundSedmi,
SlSoundOsmi,
SlSoundIzhod,
SlSoundCez25Metrov,
SlSoundCez50Metrov,
SlSoundCez100Metrov,
SlSoundCez200Metrov,
SlSoundCez500Metrov,
SlSoundCez1Kilometer,
SlSoundCez2Kilometra,
SlSoundInPotem,
SlSoundIzberite,
SlSoundKameriZaNadzorHitrosti,
SlSoundKoBoMogoceNareditePolkrozniZavoj,
SlSoundNaCilju,
SlSoundNaKroznemKriziscu,
SlSoundNemudoma,
SlSoundOpozorilo,
SlSoundOstaniteNaDesnemPasu,
SlSoundOstaniteNaLevemPasu,
SlSoundPrisliSteNaSvojCilj,
SlSoundProsimoObrnite,
SlSoundTukaj,
SlSoundVasCiljJeNaravnost,
SlSoundZapeljiteIzAvtoceste,
SlSoundZapeljiteNaravnost,
SlSoundZavijteDesno,
SlSoundZavijteLevo,
SlSoundZavijte,
SlSoundZdajSteZasliSPoti,
// SlSoundKroznegaKrizisca,
// SlSoundSKroznegaKrizisca,
// SlSoundZdajVoziteVNapacnoSmer,
}; /* Enum Clips */
} /* namespace AudioClipsEnum */
} /* namespace isab */
#endif /* AUDIO_CLIPS_ENUM_H */
| [
"[email protected]"
] | [
[
[
1,
787
]
]
] |
013f035503174916f390d867df0fc006d91f1e92 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/ipappprotocols/sip/sipcodec/inc/t_csiprefertoheader.h | f612208d1a6c42f8ebbca159fc7c70a60012faff | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,702 | h | /*
* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
// This contains CT_DataSIPReferToHeader
#ifndef __T_DATASIPREFERTOHEADER_H__
#define __T_DATASIPREFERTOHEADER_H__
#include "t_csipaddressheaderbase.h"
#include <siprefertoheader.h>
class CT_DataSIPReferToHeader : public CT_DataSIPAddressHeaderBase
{
public:
static CT_DataSIPReferToHeader* NewL();
~CT_DataSIPReferToHeader();
virtual TBool DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt aAsyncErrorIndex);
virtual TAny* GetObject();
virtual void SetObjectL(TAny* aAny);
virtual void DisownObjectL();
void SetIsOwner(TBool aIsOwner);
protected:
CT_DataSIPReferToHeader();
void ConstructL();
virtual CSIPHeaderBase* GetSIPHeaderBase() const;
private:
void DoCmdNewL(const TTEFSectionName& aSection);
void DoCmdNewLC(const TTEFSectionName& aSection);
void DoCmdDecodeL(const TTEFSectionName& aSection);
void DoCmdInternalizeValueL(const TTEFSectionName& aSection);
void DoCmdDestructor(const TTEFSectionName& aSection);
void DestroyData();
private:
CSIPReferToHeader* iSIPReferToHeader;
TBool iIsOwner;
};
#endif /* __T_DATASIPREFERTOHEADER_H__ */
| [
"none@none"
] | [
[
[
1,
58
]
]
] |
ad555bd20026f8165dbec1efdc4a16121ea843c2 | 460d5c0a45d3d377bfc4ce71de99f4abc517e2b6 | /Proj2/playGame.cpp | a7559bd53f21bb202376eac66dd218c3639c539d | [] | no_license | wilmer/CS211 | 3ba910e9cc265ca7e3ecea2c71cf1246d430f269 | 1b0191c4ab7ebbe873fc5a09b9da2441a28d93d0 | refs/heads/master | 2020-12-25T09:38:34.633541 | 2011-03-06T04:53:54 | 2011-03-06T04:53:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | #include <iostream>
#include "game.h" //includes others - deck, card, player, etc.
using namespace std;
int main()
{
int start; //variable to determine who starts first
game Game;
start = Game.turn();
if (start >=4)
{
cout << "Computer starts!" << endl << endl;
}
else
{
cout << "You start!" << endl << endl;
}
Game.playGame(start);
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
9fede67c9e51fcd0baa681d310e4577eee26b705 | e47722025231d67c684f8072265cdb832487b4f3 | /cpp/client/game_elements.cpp | b8d75a2511fd888cac886e2d15098873fb62850c | [] | no_license | Gamer2k4/basinrogue | 0950c049b9e7a9dd543c892b8b0d4f30b460faf7 | 0fac183e94ddb8d7b6a5b3333f137b11a2b72b58 | refs/heads/master | 2021-01-19T07:54:05.228849 | 2007-02-25T13:35:25 | 2007-02-25T13:35:25 | 40,727,740 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,876 | cpp | //
// C++ Implementation: game_elements
//
// Description:
//
//
// Author: Cavalaria Christophe <[email protected]>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include <iostream>
#pragma warning(disable:4786)
#include "game_elements.h"
GameWorld::GameWorld() : elem_array ( 0 ), back_buffer_elem_array ( 0 )
{}
GameWorld::~GameWorld()
{
delete elem_array;
delete back_buffer_elem_array;
}
void GameWorld::Resize ( int _sizex, int _sizey )
{
sizex = _sizex;
sizey = _sizey;
delete elem_array;
delete back_buffer_elem_array;
elem_array = new std::vector<std::vector<TileIdType> > ( sizex * sizey );
back_buffer_elem_array = new std::vector<std::vector<TileIdType> > ( sizex * sizey );
}
const std::vector<TileIdType>& GameWorld::GetTileList ( int x, int y ) const
{
if ( x >= sizex || x < 0 || y >= sizey || y < 0 )
{
std::cout << "Tile out of range :" << x << ", " << y << "\n";
}
return elem_array->at ( x + y * sizex );
}
void GameWorld::ClearAll()
{
for ( unsigned ii=0; ii < elem_array->size(); ++ii )
back_buffer_elem_array->at ( ii ).clear();
}
void GameWorld::ClearTile ( int posx, int posy )
{
if ( posx >= sizex || posx < 0 || posy >= sizey || posy < 0 )
{
std::cout << "Tile out of range :" << posx << ", " << posy << "\n";
}
back_buffer_elem_array->at ( posx + posy * sizex ).clear();
}
void GameWorld::AddTile ( int posx, int posy, TileIdType id )
{
if ( posx >= sizex || posx < 0 || posy >= sizey || posy < 0 )
{
std::cout << "Tile out of range :" << posx << ", " << posy << "\n";
}
back_buffer_elem_array->at ( posx + posy * sizex ).push_back ( id );
};
void GameWorld::SwapBuffers()
{
*elem_array = *back_buffer_elem_array;
}
//-------------------------------------------------------------------------------------------------
GameView::GameView ( const GameWorld& world, const TileLib& tile_lib, SDL_Surface* dest_surface, int sizex, int sizey, int originx, int originy ) :
dest_surface ( dest_surface ),
world ( world ),
tile_lib ( tile_lib ),
sizex ( sizex ),
sizey ( sizey ),
originx ( originx ),
originy ( originy ),
viewx ( -1 ),
viewy ( -1 ),
ready_to_go( 0 )
{
dest.x = originx;
dest.y = originy;
dest.w = tile_lib.sizex * sizex;
dest.h = tile_lib.sizey * sizey;
}
void GameView::SetReadyToGo()
{
ready_to_go = 1;
}
int GameView::CheckReadyToGo()
{
return ready_to_go;
}
void GameView::DrawTile ( int posx, int posy, int scrolled_posx, int scrolled_posy )
{
SDL_Rect this_tile;
this_tile.x = originx + scrolled_posx * tile_lib.sizex;
this_tile.y = originy + scrolled_posy * tile_lib.sizey;
this_tile.w = tile_lib.sizex;
this_tile.h = tile_lib.sizey;
const std::vector<TileIdType>& tile_list = world.GetTileList ( posx, posy );
if ( tile_list.empty() )
{
SDL_FillRect ( dest_surface,&this_tile,0 );
}
else
{
//TODO Blit without alpha
TileIdType id;
SDL_Surface* surface;
id = tile_list[0];
surface = tile_lib.GetTileById ( id );
SDL_BlitSurface ( surface, NULL, dest_surface, &this_tile );
for ( unsigned ii = 1; ii < tile_list.size(); ++ii )
{
id = tile_list[ii];
surface = tile_lib.GetTileById ( id );
SDL_BlitSurface ( surface, NULL, dest_surface, &this_tile );
}
}
}
void GameView::DrawView()
{
SDL_FillRect ( dest_surface, &dest, 0 );
for ( int scrolled_jj = 0; scrolled_jj < sizey; scrolled_jj++ )
{
int jj = scrolled_jj + viewy - ( ( sizey-1 ) /2 );
for ( int scrolled_ii = 0; scrolled_ii < sizex; scrolled_ii++ )
{
int ii = scrolled_ii + viewx - ( ( sizex-1 ) /2 );
if ( ii>=0 && ii<world.sizex && jj>=0 && jj<world.sizey )
{
DrawTile ( ii, jj, scrolled_ii, scrolled_jj );
}
}
}
SDL_UpdateRect ( dest_surface, dest.x, dest.y, dest.w, dest.h );
}
void GameView::SetCharacterPos ( int posx, int posy )
{
// handles scrolling, a bit messy currently
if ( viewx < 0 )
{
viewx = ( posx < ( sizex+1 ) /2 ) ? ( ( sizex-1 ) /2 ) : ( ( posx >= world.sizex - ( sizex+1 ) /2 ) ? world.sizex - ( sizex+1 ) /2 : sizex );
viewy = ( posy < ( sizey+1 ) /2 ) ? ( ( sizey-1 ) /2 ) : ( ( posy >= world.sizey - ( sizey+1 ) /2 ) ? world.sizey - ( sizey+1 ) /2 : sizey );
}
else
{
if ( posx > viewx + 5 || posx < viewx - 5 )
{
if ( posx >= ( sizex-1 ) /2 && posx < world.sizex- ( sizex-1 ) /2 )
{
viewx = posx;
}
else if ( posx < ( sizex-1 ) /2 )
{
viewx = ( sizex-1 ) /2;
}
else if ( posx >= ( world.sizex- ( sizex-1 ) /2 ) )
{
viewx = world.sizex - ( sizex+1 ) /2;
}
}
if ( posy > viewy + 5 || posy < viewy - 5 )
{
if ( posy >= ( sizey-1 ) /2 && posy < world.sizey- ( sizey-1 ) /2 )
{
viewy = posy;
}
else if ( posy < ( sizey-1 ) /2 )
{
viewy = ( sizey-1 ) /2;
}
else if ( posy >= ( world.sizey- ( sizey-1 ) /2 ) )
{
viewy = world.sizey - ( sizey+1 ) /2;
}
}
}
}
| [
"christophe.cavalaria@712ddccb-0227-0410-9f85-29faccf8bd71",
"antoine.from.rgrd@712ddccb-0227-0410-9f85-29faccf8bd71"
] | [
[
[
1,
14
],
[
20,
29
],
[
31,
87
],
[
96,
96
],
[
108,
108
],
[
114,
116
],
[
118,
128
],
[
130,
133
],
[
135,
138
],
[
143,
144
],
[
146,
151
],
[
157,
196
],
[
198,
198
]
],
[
[
15,
19
],
[
30,
30
],
[
88,
95
],
[
97,
107
],
[
109,
113
],
[
117,
117
],
[
129,
129
],
[
134,
134
],
[
139,
142
],
[
145,
145
],
[
152,
156
],
[
197,
197
]
]
] |
6ff0c92b0b85c56fab229dac3be73008ccabd169 | 4accfbc787e4c21fa63f207dd7870de106082b61 | /Assignment 1/EmployeeCsvReader.h | 6a892162086e69c580124ec8c5cbc699b20c5bc5 | [] | no_license | kevbite/CProformanceAss1 | 66efde3925f826738781966292205b0a740c584b | 9bf5dfd96792f4f12e638bc910840c78aa9bb865 | refs/heads/master | 2021-01-01T18:38:05.712343 | 2009-03-29T15:28:14 | 2009-03-29T15:28:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 472 | h | #pragma once
#include <string>
#include <fstream>
#include <string>
#include <sstream>
#include "Employee.h"
typedef std::vector<Employee*> empContainer;
/* Loads data from a Csv file to a empContainer */
class EmployeeCsvReader
{
private:
void parseCSV(std::istream &input, empContainer *output) const;
Employee *parseCSVLine(std::string &csvStream) const;
public:
empContainer* loadData(const char *filePath, const int &reserve) const;
};
| [
"[email protected]"
] | [
[
[
1,
22
]
]
] |
4a1da451e245daba5067682ad48cca3cdea2ec5a | 294d277502d9d0d2ca1f3535d3517d7d21a9141a | /evaluator.h | c7e4cf760452cf109d430941f1c517dc88218b69 | [] | 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 | 4,881 | h | // (c) Microsoft Corporation. All rights reserved.
#ifndef EVALUATOR_H
#define EVALUATOR_H
#include <math.h>
#include "typmidas.h"
#include "dijkstra.h"
class LandmarkEvaluator {
public:
// compute a lower bound on the distance from s to t
// using distances to a single landmark
inline TCost LowerBound(VertexId s, VertexId t, TCost *landdist) const {
TCost ds, dt;
ds = landdist[s];
dt = landdist[t];
TCost answer = (ds > dt) ? ds - dt : dt - ds;
return answer;
}
// compute the upper bound on the distance from s to t using distances
// to a single landmark
inline TCost UpperBound(VertexId s, VertexId t, TCost *landdist) const {
return (landdist[s] + landdist[t]);
}
// compute the ratio between the lower and upper bounds
// (with a special case when both are zero)
inline double ComputeRatio(TCost lower, TCost upper) const {
double ratio = 1.0; //ratio equals 1 if they are equal (including both zero)
if (upper != lower) {
if (lower < 0) {cerr << "ERROR: " << lower << "is an invalid lower bound.\n"; exit(-1);}
ratio = (double)lower / (double)upper;
}
return ratio;
}
//Compute the score of a particular query, defined as
//score = (101^(lower/upper)) - 1
inline double ComputeScore(TCost lower, TCost upper) const {
double ratio = ComputeRatio(lower, upper);
double score = exp (ratio * log (101.0)) - 1;
return score;
}
//------------------------------------------------------------------------
// Evaluate a list of k landmarks (list[0],...,list[k-1]) on npairs random
// pairs of distinct vertices. Returns the score for these landmarks.
// If 'verbose' is true, outputs the score and other statistics to stdout.
// Runs in O(k*m*log n) time (m=number of edges, n=number of vertices).
//-----------------------------------------------------------------------*/
double EvaluateLandmarks(Graph *g, VertexId k, VertexId *list, double npairs, bool verbose) {
VertexId i, n = g->VertexCount();
//compute distances from each landmark to all vertices
TCost **landdist = new TCost*[k];
Dijkstra *dijkstra = new Dijkstra(g);
for (i=0; i<k; i++) {
VertexId v = list[i]; //a landmark
dijkstra->RunDijkstra(v);
landdist[i] = new TCost[n+1];
for (v=1; v<=n; v++) landdist[i][v] = dijkstra->GetDistance(v);
}
delete dijkstra;
double score = EvaluateLandmarks(g, k, landdist, npairs, verbose);
for (i=0; i<k; i++) delete [] landdist[i];
delete [] landdist;
return score;
}
//-----------------------------------------------------------------------------------
// Evaluates a set of k landmarks on a set of npairs pairs of distinct vertices.
// Variable 'landdist' is a matrix representing the distances between all landmarks
// and all vertices. "landist[i][v]" must contain the distance between the i-th
// landmark (with i=0...k-1) and vertex v (with v=1...n). Runs in O(kn) time.
// Returns the score of these landmarks. If verbose=true, outputs the score and
// other statistics to stdout.
//-----------------------------------------------------------------------------------
double EvaluateLandmarks(Graph *g, VertexId k, TCost **landdist, double npairs, bool verbose) {
VertexId n = g->VertexCount();
double sumratio = 0; //sum of all ratios (lower/upper)
double sumdiff = 0; //sum of all differences (upper - lower)
double sumscore = 0; //sum of all scores (101^(lower/upper) - 1)
for (double p=0; p<npairs; p++) {
VertexId s = MTRandom::GetInteger(1,n);
VertexId t = MTRandom::GetInteger(1,n);
if (s==t) {p--; continue;} //only allow distinct pairs
//compute current upper and lower bounds
TCost upper = MIDAS_INFINITY;
TCost lower = 0;
for (VertexId i=0; i<k; i++) {
TCost curlower = LowerBound(s,t,landdist[i]);
TCost curupper = UpperBound(s,t,landdist[i]);
if (curupper < curlower) {
fprintf (stderr, "%d: s:%d %d t:%d %d\n", i,s, landdist[i][s], t, landdist[i][t]);
exit(-1);
}
if (curlower > lower) lower = curlower;
if (curupper < upper) upper = curupper;
}
TCost diff = upper - lower;
double ratio = ComputeRatio(lower,upper); //ratio equals 1 if they are equal (including zero)
double score = ComputeScore(lower, upper); //exp (ratio * log (101.0)) - 1;
sumscore += score;
sumratio += ratio;
sumdiff += (double)diff;
}
double score = (sumscore / npairs);
if (verbose) {
fprintf (stderr, "npairs %.0f\n", npairs);
fprintf (stderr, "avgdiff %.6f\n", sumdiff /npairs);
fprintf (stderr, "avgratio %.12f\n", sumratio / npairs);
fprintf (stderr, "avgscore %.10f\n", score);
}
return score;
}
};
#endif
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
120
],
[
125,
131
]
],
[
[
121,
124
]
]
] |
93bb42a9ece3f4106005c717ba28ad5e834b5531 | 0b55a33f4df7593378f58b60faff6bac01ec27f3 | /Konstruct/Tools/UIEditor/DisplayWnd.h | d596605d89d8d42319ec98c707db12f4e66e2705 | [] | 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 | 1,730 | h | // DisplayWnd.h : interface of the CDisplayWnd class
//
#pragma once
#include "External/Tinyxml/tinyxml.h"
#include "Common/Utility/kpuLinkedList.h"
#include "Common/Graphics/kpgUIWindow.h"
class kpgRenderer;
// CDisplayWnd window
class CDisplayWnd : public CWnd
{
// Construction
public:
CDisplayWnd();
// Attributes
public:
void SaveLayout(TiXmlDocument* pDoc);
void LoadLayout(TiXmlDocument* pDoc);
protected:
kpgRenderer* m_pRenderer;
kpuLinkedList m_lWindowList;
CPoint m_ptPreviousCursor;
bool m_bDrag;
kpgUIWindow::eHitLocation m_eHitLocation;
kpgUIWindow::eHitLocation m_eDragLocation;
kpgUIWindow* m_pHitWindow;
kpgUIWindow* m_pDragWindow;
CPoint m_ptContextPoint;
// Operations
private:
void UpdateCursor(const kpgUIWindow* pWindow, const kpgUIWindow::eHitLocation eHitLocation);
kpgUIWindow* HitTest(CPoint ptPoint, kpgUIWindow::eHitLocation& eHitLocation);
void AddWindow(kpgUIWindow* pWindow);
void Clear();
// Overrides
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
// Implementation
public:
virtual ~CDisplayWnd();
// Generated message map functions
protected:
afx_msg void OnPaint();
afx_msg void OnNewWindow();
afx_msg void OnNewStaticText();
afx_msg void OnNewTextInput();
afx_msg void OnNewButton();
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnMouseMove( UINT nFlags, CPoint ptPoint );
afx_msg void OnLButtonDown( UINT nFlags, CPoint ptPoint );
afx_msg void OnLButtonUp( UINT nFlags, CPoint ptPoint );
afx_msg void OnContextMenu( CWnd* pWnd, CPoint ptPoint );
DECLARE_MESSAGE_MAP()
public:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
};
| [
"acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e"
] | [
[
[
1,
68
]
]
] |
a9be7216ec7d1b87e33a61457c787277d9278c22 | 59b44667b5c07ad988cd8715cc93bbb8d7dc485d | /JGE/include/JTypes.h | 280502634edb451aef44b608c026ed8cf33252d7 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | CBE7F1F65/aacb7938f4e32c8eaf01afb3c2653d84 | 3c733a0d75e670297e4465e32a6b3339fd332684 | a9974df54e7946f9ff2d84717462e3df9b6805f4 | refs/heads/master | 2020-04-01T16:38:48.576804 | 2010-04-09T02:11:56 | 2010-04-09T02:11:56 | 32,192,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,427 | h | //-------------------------------------------------------------------------------------
//
// JGE++ is a hardware accelerated 2D game SDK for PSP/Windows.
//
// Licensed under the BSD license, see LICENSE in JGE root for details.
//
// Copyright (c) 2007 James Hui (a.k.a. Dr.Watson) <[email protected]>
//
//-------------------------------------------------------------------------------------
#ifndef _JTYPES_H
#define _JTYPES_H
#ifdef WIN32
#else
#include <pspgu.h>
#include <pspgum.h>
#include <pspkernel.h>
#include <pspdisplay.h>
#include <pspdebug.h>
#include <pspctrl.h>
#include <time.h>
#include <string.h>
#include <pspaudiolib.h>
#include <psprtc.h>
#include "e:/Jge_Release/JGE/include/JAudio.h"
#endif
#define MAX_CHANNEL 128
#ifndef M_PI
#define M_PI 3.14159265358979323846f
#define M_PI_2 1.57079632679489661923f
#define M_PI_4 0.785398163397448309616f
#define M_1_PI 0.318309886183790671538f
#define M_2_PI 0.636619772367581343076f
#endif
#define RAD2DEG 57.29577951f
#define DEG2RAD 0.017453293f
#define SAFE_DELETE(x) if (x) { delete x; x = NULL; }
#define SAFE_DELETE_ARRAY(x) if (x) { delete [] x; x = NULL; }
#define SCREEN_WIDTH 480
#define SCREEN_HEIGHT 272
#define SCREEN_WIDTH_F 480.0f
#define SCREEN_HEIGHT_F 272.0f
#ifdef WIN32
// #define DEFAULT_BLEND BLEND_DEFAULT
// #define BLEND_OPTION_ADD BLEND_COLORADD
// #define BLEND_OPTION_BLEND (BLEND_COLORADD | BLEND_ALPHABLEND | BLEND_NOZWRITE)
#define ALIGN16
#else
#define DEFAULT_BLEND GU_TFX_MODULATE
#define BLEND_OPTION_ADD GU_TFX_ADD
#define BLEND_OPTION_BLEND GU_TFX_BLEND
#define ALIGN16 __attribute__((aligned(16)))
#endif
#if defined (WIN32)
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include "../Dependencies/include/fmod.h"
//#include "../HGE/include/hge.h"
//#include "../HGE/include/hgeSprite.h"
//#define u8 BYTE
//#define u16 WORD
//#define u32 DWORD
typedef signed char s8;
typedef signed short s16;
typedef signed long s32;
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long u32;
#define BLEND_ZERO GL_ZERO
#define BLEND_ONE GL_ONE
#define BLEND_SRC_COLOR GL_SRC_COLOR
#define BLEND_ONE_MINUS_SRC_COLOR GL_ONE_MINUS_SRC_COLOR
#define BLEND_SRC_ALPHA GL_SRC_ALPHA
#define BLEND_ONE_MINUS_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
#define BLEND_DST_ALPHA GL_DST_ALPHA
#define BLEND_ONE_MINUS_DST_ALPHA GL_ONE_MINUS_DST_ALPHA
#define BLEND_DST_COLOR GL_DST_COLOR
#define BLEND_ONE_MINUS_DST_COLOR GL_ONE_MINUS_DST_COLOR
#define BLEND_SRC_ALPHA_SATURATE GL_SRC_ALPHA_SATURATE
#define ARGB(a, r, g, b) ((a << 24) | (r << 16) | (g << 8) | b)
#define RGBA(r, g, b, a) ((a << 24) | (b << 16) | (g << 8) | r)
enum PspCtrlButtons
{
PSP_CTRL_SELECT = 0x000001,
PSP_CTRL_START = 0x000008,
PSP_CTRL_UP = 0x000010,
PSP_CTRL_RIGHT = 0x000020,
PSP_CTRL_DOWN = 0x000040,
PSP_CTRL_LEFT = 0x000080,
PSP_CTRL_LTRIGGER = 0x000100,
PSP_CTRL_RTRIGGER = 0x000200,
PSP_CTRL_TRIANGLE = 0x001000,
PSP_CTRL_CIRCLE = 0x002000,
PSP_CTRL_CROSS = 0x004000,
PSP_CTRL_SQUARE = 0x008000,
PSP_CTRL_HOME = 0x010000,
PSP_CTRL_HOLD = 0x020000,
PSP_CTRL_NOTE = 0x800000,
};
#define PIXEL_TYPE DWORD
#else // PSP
#ifndef ABGR8888
#define ABGR8888
#endif
#if defined (ABGR8888)
#ifndef ARGB
#define ARGB(a, r, g, b) ((a << 24) | (b << 16) | (g << 8) | r) // macro to assemble pixels in correct format
#endif
#define MAKE_COLOR(a, c) (a << 24 | c)
#define MASK_ALPHA 0xFF000000 // masks for accessing individual pixels
#define MASK_BLUE 0x00FF0000
#define MASK_GREEN 0x0000FF00
#define MASK_RED 0x000000FF
#define PIXEL_TYPE u32
#define PIXEL_SIZE 4
#define PIXEL_FORMAT PSP_DISPLAY_PIXEL_FORMAT_8888
#define BUFFER_FORMAT GU_PSM_8888
#define TEXTURE_FORMAT GU_PSM_8888
#define TEXTURE_COLOR_FORMAT GU_COLOR_8888
#elif defined (ABGR5551)
#ifndef ARGB
#define ARGB(a, r, g, b) ((r >> 3) | ((g >> 3) << 5) | ((b >> 3) << 10) | ((a >> 7) << 15))
#endif
#define MAKE_COLOR(a, c) (((a>>7)<<15) | c)
#define MASK_ALPHA 0x8000
#define MASK_BLUE 0x7C00
#define MASK_GREEN 0x03E0
#define MASK_RED 0x001F
#define PIXEL_TYPE u16
#define PIXEL_SIZE 2
#define PIXEL_FORMAT PSP_DISPLAY_PIXEL_FORMAT_5551
#define BUFFER_FORMAT GU_PSM_8888
#define TEXTURE_FORMAT GU_PSM_5551
#define TEXTURE_COLOR_FORMAT GU_COLOR_5551
#elif defined (ABGR4444)
#ifndef ARGB
#define ARGB(a, r, g, b) ((r >> 4) | ((g >> 4) << 4) | ((b >> 4) << 8) | ((a >> 4) << 12))
#endif
#define MAKE_COLOR(a, c) (((a>>4)<<12) | c)
#define MASK_ALPHA 0xF000
#define MASK_BLUE 0x0F00
#define MASK_GREEN 0x00F0
#define MASK_RED 0x000F
#define PIXEL_TYPE u16
#define PIXEL_SIZE 2
#define PIXEL_FORMAT PSP_DISPLAY_PIXEL_FORMAT_4444
#define BUFFER_FORMAT GU_PSM_4444
#define TEXTURE_FORMAT GU_PSM_4444
#define TEXTURE_COLOR_FORMAT GU_COLOR_4444
#endif
#define FRAME_BUFFER_WIDTH 512
#define FRAME_BUFFER_SIZE FRAME_BUFFER_WIDTH*SCREEN_HEIGHT*PIXEL_SIZE
#define SLICE_SIZE_F 64.0f
typedef u32 DWORD;
#define BLEND_ZERO 0x1000
#define BLEND_ONE 0x1002
#define BLEND_SRC_COLOR GU_SRC_COLOR
#define BLEND_ONE_MINUS_SRC_COLOR GU_ONE_MINUS_SRC_COLOR
#define BLEND_SRC_ALPHA GU_SRC_ALPHA
#define BLEND_ONE_MINUS_SRC_ALPHA GU_ONE_MINUS_SRC_ALPHA
#define BLEND_DST_ALPHA GU_DST_ALPHA
#define BLEND_ONE_MINUS_DST_ALPHA GU_ONE_MINUS_DST_ALPHA
#define BLEND_DST_COLOR GU_DST_COLOR
#define BLEND_ONE_MINUS_DST_COLOR GU_ONE_MINUS_DST_COLOR
#define BLEND_SRC_ALPHA_SATURATE BLEND_ONE
typedef struct
{
ScePspFVector2 texture;
//PIXEL_TYPE color;
//ScePspFVector3 normal;
ScePspFVector3 pos;
} PSPVertex3D;
#endif
//------------------------------------------------------------------------------------------------
struct Vertex
{
float u, v;
PIXEL_TYPE color;
float x, y, z;
};
//------------------------------------------------------------------------------------------------
struct Vertex3D
{
float u, v;
//float nx, ny, nz;
float x, y, z;
};
//------------------------------------------------------------------------------------------------
struct VertexColor
{
PIXEL_TYPE color;
float x, y, z;
};
struct JColor
{
union
{
struct
{
u8 b;
u8 g;
u8 r;
u8 a;
};
DWORD color;
};
};
enum
{
TEX_TYPE_NONE,
TEX_TYPE_USE_VRAM,
TEX_TYPE_MIPMAP,
TEX_TYPE_NORMAL,
TEX_TYPE_SKYBOX
};
enum
{
MODE_UNKNOWN,
MODE_2D,
MODE_3D
};
enum
{
TEX_FILTER_NONE,
TEX_FILTER_LINEAR,
TEX_FILTER_NEAREST
};
//------------------------------------------------------------------------------------------------
class JTexture
{
public:
JTexture();
~JTexture();
void UpdateBits(int x, int y, int width, int height, PIXEL_TYPE* bits);
int mWidth;
int mHeight;
int mTexWidth;
int mTexHeight;
int mFilter;
#ifdef WIN32
GLuint mTexId;
#else
int mTexId;
bool mInVideoRAM;
PIXEL_TYPE* mBits;
#endif
};
//////////////////////////////////////////////////////////////////////////
/// Custom filter for processing the texture image while loading. You
/// can change the pixels by using a custom filter before the image is
/// created as a texture.
///
//////////////////////////////////////////////////////////////////////////
class JImageFilter
{
public:
//////////////////////////////////////////////////////////////////////////
/// Pure virtual function for the custom filter to implement.
///
/// @param pix - Image data.
/// @param width - Width of the image.
/// @param height - Height of the image.
///
//////////////////////////////////////////////////////////////////////////
virtual void ProcessImage(PIXEL_TYPE* pix, int width, int height) = 0;
};
//////////////////////////////////////////////////////////////////////////
/// Image quad.
///
//////////////////////////////////////////////////////////////////////////
class JQuad
{
public:
//////////////////////////////////////////////////////////////////////////
/// Constructor.
///
/// @param tex - Texture of the quad.
/// @param x - X position of the quad in texture.
/// @param y - Y position of the quad in texture.
/// @param width - Width of the quad.
/// @param height - Height of the quad.
///
//////////////////////////////////////////////////////////////////////////
JQuad(JTexture *tex, float x, float y, float width, float height);
//////////////////////////////////////////////////////////////////////////
/// Set blending color of the quad.
///
/// @param color - Color.
///
//////////////////////////////////////////////////////////////////////////
void SetColor(PIXEL_TYPE color);
//////////////////////////////////////////////////////////////////////////
/// Set anchor point of the quad.
///
/// @param x - X position of the anchor point.
/// @param y - Y position of the anchor point.
///
//////////////////////////////////////////////////////////////////////////
void SetHotSpot(float x, float y);
//////////////////////////////////////////////////////////////////////////
/// Set UV positions of the quad.
///
/// @param x - X position of the quad in texture.
/// @param y - Y position of the quad in texture.
/// @param w - Width of the quad.
/// @param h - Height of the quad.
///
//////////////////////////////////////////////////////////////////////////
void SetTextureRect(float x, float y, float w, float h);
//////////////////////////////////////////////////////////////////////////
/// Get UV positions of the quad.
///
/// @return x - X position of the quad in texture.
/// @return y - Y position of the quad in texture.
/// @return w - Width of the quad.
/// @return h - Height of the quad.
///
//////////////////////////////////////////////////////////////////////////
void GetTextureRect(float *x, float *y, float *w, float *h);
//////////////////////////////////////////////////////////////////////////
/// Set horizontal flipping.
///
/// @param hflip - flipping flag;
///
//////////////////////////////////////////////////////////////////////////
void SetHFlip(bool hflip) { mHFlipped = hflip; }
//////////////////////////////////////////////////////////////////////////
/// Set vetical flipping.
///
/// @param hflip - flipping flag;
///
//////////////////////////////////////////////////////////////////////////
void SetVFlip(bool vflip) { mVFlipped = vflip; }
JTexture* mTex;
#ifdef WIN32
float mTX0;
float mTY0;
float mTX1;
float mTY1;
JColor mColor[4]; // up to 4 vertices
#else
PIXEL_TYPE mColor[4]; // up to 4 vertices
int mBlend; // GU_TFX_MODULATE, GU_TFX_DECAL, GU_TFX_BLEND, GU_TFX_REPLACE, GU_TFX_ADD
#endif
float mX;
float mY;
float mWidth;
float mHeight;
float mHotSpotX;
float mHotSpotY;
bool mHFlipped;
bool mVFlipped;
};
//#endif
//////////////////////////////////////////////////////////////////////////
/// \enum JFONT_TEXT_ALIGNMENT
///
/// Font alignment.
///
//////////////////////////////////////////////////////////////////////////
enum JFONT_TEXT_ALIGNMENT
{
JGETEXT_LEFT, ///< Text alignment to left.
JGETEXT_CENTER, ///< Text alignment to center.
JGETEXT_RIGHT ///< Text alignment to right.
};
enum JINIT_FLAG
{
JINIT_FLAG_NORMAL,
JINIT_FLAG_ENABLE3D
};
//------------------------------------------------------------------------------------------------
class JFont
{
public:
JQuad* mQuad;
int mWidth;
int mHeight;
int mSpacing;
int mAlign;
float mScale;
};
//------------------------------------------------------------------------------------------------
class Rect
{
public:
int x;
int y;
int width;
int height;
public:
Rect(int _x, int _y, int _width, int _height): x(_x), y(_y), width(_width), height(_height) {}
};
#endif
| [
"CBE7F1F65@49891f33-ffc5-8b0e-831d-a250345ee88b"
] | [
[
[
1,
495
]
]
] |
59cd68023f57b562ec03ff6bdeac9a0d6b6e606c | 22d9640edca14b31280fae414f188739a82733e4 | /Code/VTK/include/vtk-5.2/vtkOrientedGlyphContourRepresentation.h | 7d47cef7d6382e498657df71f4eee62b5b62a81e | [] | no_license | tack1/Casam | ad0a98febdb566c411adfe6983fcf63442b5eed5 | 3914de9d34c830d4a23a785768579bea80342f41 | refs/heads/master | 2020-04-06T03:45:40.734355 | 2009-06-10T14:54:07 | 2009-06-10T14:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,859 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkOrientedGlyphContourRepresentation.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkOrientedGlyphContourRepresentation - Default representation for the contour widget
// .SECTION Description
// This class provides the default concrete representation for the
// vtkContourWidget. It works in conjunction with the
// vtkContourLineInterpolator and vtkPointPlacer. See vtkContourWidget
// for details.
// .SECTION See Also
// vtkContourRepresentation vtkContourWidget vtkPointPlacer
// vtkContourLineInterpolator
#ifndef __vtkOrientedGlyphContourRepresentation_h
#define __vtkOrientedGlyphContourRepresentation_h
#include "vtkContourRepresentation.h"
class vtkProperty;
class vtkActor;
class vtkPolyDataMapper;
class vtkPolyData;
class vtkGlyph3D;
class vtkPoints;
class VTK_WIDGETS_EXPORT vtkOrientedGlyphContourRepresentation : public vtkContourRepresentation
{
public:
// Description:
// Instantiate this class.
static vtkOrientedGlyphContourRepresentation *New();
// Description:
// Standard methods for instances of this class.
vtkTypeRevisionMacro(vtkOrientedGlyphContourRepresentation,vtkContourRepresentation);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Specify the cursor shape. Keep in mind that the shape will be
// aligned with the constraining plane by orienting it such that
// the x axis of the geometry lies along the normal of the plane.
void SetCursorShape(vtkPolyData *cursorShape);
vtkPolyData *GetCursorShape();
// Description:
// Specify the shape of the cursor (handle) when it is active.
// This is the geometry that will be used when the mouse is
// close to the handle or if the user is manipulating the handle.
void SetActiveCursorShape(vtkPolyData *activeShape);
vtkPolyData *GetActiveCursorShape();
// Description:
// This is the property used when the handle is not active
// (the mouse is not near the handle)
vtkGetObjectMacro(Property,vtkProperty);
// Description:
// This is the property used when the user is interacting
// with the handle.
vtkGetObjectMacro(ActiveProperty,vtkProperty);
// Description:
// This is the property used by the lines.
vtkGetObjectMacro(LinesProperty,vtkProperty);
// Description:
// Subclasses of vtkOrientedGlyphContourRepresentation must implement these methods. These
// are the methods that the widget and its representation use to
// communicate with each other.
virtual void SetRenderer(vtkRenderer *ren);
virtual void BuildRepresentation();
virtual void StartWidgetInteraction(double eventPos[2]);
virtual void WidgetInteraction(double eventPos[2]);
virtual int ComputeInteractionState(int X, int Y, int modified=0);
// Description:
// Methods to make this class behave as a vtkProp.
virtual void GetActors(vtkPropCollection *);
virtual void ReleaseGraphicsResources(vtkWindow *);
virtual int RenderOverlay(vtkViewport *viewport);
virtual int RenderOpaqueGeometry(vtkViewport *viewport);
virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport);
virtual int HasTranslucentPolygonalGeometry();
// Description:
// Get the points in this contour as a vtkPolyData.
virtual vtkPolyData * GetContourRepresentationAsPolyData();
// Description:
// Controls whether the contour widget should always appear on top
// of other actors in the scene. (In effect, this will disable OpenGL
// Depth buffer tests while rendering the contour).
// Default is to set it to false.
vtkSetMacro( AlwaysOnTop, int );
vtkGetMacro( AlwaysOnTop, int );
vtkBooleanMacro( AlwaysOnTop, int );
protected:
vtkOrientedGlyphContourRepresentation();
~vtkOrientedGlyphContourRepresentation();
// Render the cursor
vtkActor *Actor;
vtkPolyDataMapper *Mapper;
vtkGlyph3D *Glypher;
vtkActor *ActiveActor;
vtkPolyDataMapper *ActiveMapper;
vtkGlyph3D *ActiveGlypher;
vtkPolyData *CursorShape;
vtkPolyData *ActiveCursorShape;
vtkPolyData *FocalData;
vtkPoints *FocalPoint;
vtkPolyData *ActiveFocalData;
vtkPoints *ActiveFocalPoint;
vtkPolyData *Lines;
vtkPolyDataMapper *LinesMapper;
vtkActor *LinesActor;
// Support picking
double LastPickPosition[3];
double LastEventPosition[2];
// Methods to manipulate the cursor
void Translate(double eventPos[2]);
void Scale(double eventPos[2]);
// Properties used to control the appearance of selected objects and
// the manipulator in general.
vtkProperty *Property;
vtkProperty *ActiveProperty;
vtkProperty *LinesProperty;
void CreateDefaultProperties();
// Distance between where the mouse event happens and where the
// widget is focused - maintain this distance during interaction.
double InteractionOffset[2];
int AlwaysOnTop;
void BuildLines();
private:
vtkOrientedGlyphContourRepresentation(const vtkOrientedGlyphContourRepresentation&); //Not implemented
void operator=(const vtkOrientedGlyphContourRepresentation&); //Not implemented
};
#endif
| [
"nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f"
] | [
[
[
1,
160
]
]
] |
5b46e6ce289140c86f6bee88d41f74d5172dd46e | 1cacbe790f7c6e04ca6b0068c7b2231ed2b827e1 | /Oolong Engine2/Renderer/Core/GraphicsDevice/PFXParser.h | 1d61d14d2be47f2d5042c67984f2eb65ef34aedb | [] | no_license | tianxiao/oolongengine | f3d2d888afb29e19ee93f28223fce6ea48f194ad | 8d80085c65ff3eed548549657e7b472671789e6a | refs/heads/master | 2020-05-30T06:02:32.967513 | 2010-05-05T05:52:03 | 2010-05-05T05:52:03 | 8,245,292 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 12,942 | h | /******************************************************************************
@File PFXParser.h
@Title PFX file parser.
@Copyright Copyright (C) Imagination Technologies Limited.
@Platform Windows + Linux
@Description Declaration of PFX file parser
******************************************************************************/
#ifndef _PFXPARSER_H_
#define _PFXPARSER_H_
/*****************************************************************************
** Includes
******************************************************************************/
#include <string>
using namespace std;
//#include "Error.h"
/****************************************************************************
** Structures
****************************************************************************/
/*!**************************************************************************
@Struct SPFXParserHeader
@Brief Struct for storing PFX file header data
****************************************************************************/
struct SPFXParserHeader
{
char *pszVersion;
char *pszDescription;
char *pszCopyright;
};
/*!**************************************************************************
@Struct SPFXParserTexture
@Brief Struct for storing PFX data from the texture block
****************************************************************************/
struct SPFXParserTexture
{
char *pszName;
char *pszFile;
unsigned int nMin, nMag, nMIP;
unsigned int nWrapS, nWrapT, nWrapR; // either GL_CLAMP or GL_REPEAT
};
/*!**************************************************************************
@Struct SPFXParserShader
@Brief Struct for storing PFX data from the shader block
****************************************************************************/
struct SPFXParserShader
{
char *pszName;
bool bUseFileName;
char *pszGLSLfile;
char *pszGLSLBinaryFile;
char *pszGLSLcode;
char *pbGLSLBinary;
unsigned int nGLSLBinarySize;
unsigned int nFirstLineNumber; // Line number in the text file where this code began; use to correct line-numbers in compiler errors
};
/*!**************************************************************************
@Enum ESemanticDefaultDataType
@Brief Enum values for the various variable types supported
****************************************************************************/
enum ESemanticDefaultDataType
{
eDataTypeMat2,
eDataTypeMat3,
eDataTypeMat4,
eDataTypeVec2,
eDataTypeVec3,
eDataTypeVec4,
eDataTypeIvec2,
eDataTypeIvec3,
eDataTypeIvec4,
eDataTypeBvec2,
eDataTypeBvec3,
eDataTypeBvec4,
eDataTypeFloat,
eDataTypeInt,
eDataTypeBool,
eNumDefaultDataTypes,
eDataTypeNone
};
/*!**************************************************************************
@Enum EDefaultDataInternalType
@Brief Enum values for defining whether a variable is float, interger or bool
****************************************************************************/
enum EDefaultDataInternalType
{
eFloating,
eInteger,
eBoolean
};
struct SSemanticDefaultDataTypeInfo
{
ESemanticDefaultDataType eType;
const char *pszName;
unsigned int nNumberDataItems;
EDefaultDataInternalType eInternalType;
};
const static SSemanticDefaultDataTypeInfo c_psSemanticDefaultDataTypeInfo[] =
{
{ eDataTypeMat2, "mat2", 4, eFloating },
{ eDataTypeMat3, "mat3", 9, eFloating },
{ eDataTypeMat4, "mat4", 16, eFloating },
{ eDataTypeVec2, "vec2", 2, eFloating },
{ eDataTypeVec3, "vec3", 3, eFloating },
{ eDataTypeVec4, "vec4", 4, eFloating },
{ eDataTypeIvec2, "ivec2", 2, eInteger },
{ eDataTypeIvec3, "ivec3", 3, eInteger },
{ eDataTypeIvec4, "ivec4", 4, eInteger },
{ eDataTypeBvec2, "bvec2", 2, eBoolean },
{ eDataTypeBvec3, "bvec3", 3, eBoolean },
{ eDataTypeBvec4, "bvec4", 4, eBoolean },
{ eDataTypeFloat, "float", 1, eFloating },
{ eDataTypeInt, "int", 1, eInteger },
{ eDataTypeBool, "bool", 1, eBoolean }
};
/*!**************************************************************************
@Struct SSemanticDefaultData
@Brief Stores a default value
****************************************************************************/
struct SSemanticDefaultData
{
float pfData[16];
int pnData[4];
bool pbData[4];
ESemanticDefaultDataType eType;
};
/*!**************************************************************************
@Struct SPFXParserSemantic
@Brief Stores semantic information
****************************************************************************/
struct SPFXParserSemantic
{
char *pszName; /*!< The variable name as used in the shader-language code */
char *pszValue; /*!< For example: LIGHTPOSITION */
unsigned int nIdx; /*!< Index; for example two semantics might be LIGHTPOSITION0 and LIGHTPOSITION1 */
SSemanticDefaultData sDefaultValue; /*!< Default value */
};
/*!**************************************************************************
@Struct SPFXParserEffectTexture
@Brief Stores effect texture information
****************************************************************************/
struct SPFXParserEffectTexture
{
unsigned int nNumber; /*!< Texture number to set */
char *pszName; /*!< Name of the texture to set there */
unsigned int u32Type; /*!< Identifying cube maps etc. */
};
/*!**************************************************************************
@Struct SPFXParserEffect
@Brief Stores effect information
****************************************************************************/
struct SPFXParserEffect
{
char *pszName;
char *pszAnnotation;
char *pszVertexShaderName;
char *pszFragmentShaderName;
SPFXParserSemantic *psUniform;
unsigned int nNumUniforms, nMaxUniforms;
SPFXParserSemantic *psAttribute;
unsigned int nNumAttributes, nMaxAttributes;
SPFXParserEffectTexture *psTextures;
unsigned int nNumTextures, nMaxTextures;
};
class CPFXParserReadContext;
/*!**************************************************************************
@Class CPFXParser
@Brief PFX parser
****************************************************************************/
class CPFXParser
{
public:
/*!***************************************************************************
@Function CPFXParser
@Description Sets initial values.
*****************************************************************************/
CPFXParser();
/*!***************************************************************************
@Function ~CPFXParser
@Description Frees memory used.
*****************************************************************************/
~CPFXParser();
/*!***************************************************************************
@Function ParseFromMemory
@Input pszScript PFX script
@Output pReturnError error string
@Return EError SUCCESS for success parsing file
FAIL if file doesn't exist or is invalid
@Description Parses a PFX script from memory.
*****************************************************************************/
unsigned int ParseFromMemory(const char * const pszScript, string * const pReturnError);
/*!***************************************************************************
@Function ParseFromFile
@Input pszFileName PFX file name
@Output pReturnError error string
@Return EError PVR_SUCCESS for success parsing file
PVR_FAIL if file doesn't exist or is invalid
@Description Reads the PFX file and calls the parser.
*****************************************************************************/
unsigned int ParseFromFile(const char * const pszFileName, string * const pReturnError);
/*!***************************************************************************
@Function DebugDump
@Description Debug output.
*****************************************************************************/
void DebugDump() const;
SPFXParserHeader m_sHeader;
SPFXParserTexture *m_psTexture;
unsigned int m_nNumTextures, m_nMaxTextures;
SPFXParserShader *m_psFragmentShader;
unsigned int m_nNumFragShaders, m_nMaxFragShaders;
SPFXParserShader *m_psVertexShader;
unsigned int m_nNumVertShaders, m_nMaxVertShaders;
SPFXParserEffect *m_psEffect;
unsigned int m_nNumEffects, m_nMaxEffects;
private:
CPFXParserReadContext *m_psContext;
/*!***************************************************************************
@Function Parse
@Output pReturnError error string
@Return bool true for success parsing file
@Description Parses a loaded PFX file.
*****************************************************************************/
bool Parse(string * const pReturnError);
/*!***************************************************************************
@Function ReduceWhitespace
@Output line output text
@Input line input text
@Description Reduces all white space characters in the string to one
blank space.
*****************************************************************************/
void ReduceWhitespace(char *line);
/*!***************************************************************************
@Function GetEndTag
@Input pszTagName tag name
@Input nStartLine start line
@Output pnEndLine line end tag found
@Return true if tag found
@Description Searches for end tag pszTagName from line nStartLine.
Returns true and outputs the line number of the end tag if
found, otherwise returning false.
*****************************************************************************/
bool GetEndTag(char *pszTagName, int nStartLine, int *pnEndLine);
/*!***************************************************************************
@Function ParseHeader
@Input nStartLine start line number
@Input nEndLine end line number
@Output pReturnError error string
@Return bool true if parse is successful
@Description Parses the HEADER section of the PFX file.
*****************************************************************************/
bool ParseHeader(int nStartLine, int nEndLine, string * const pReturnError);
/*!***************************************************************************
@Function ParseTextures
@Input nStartLine start line number
@Input nEndLine end line number
@Output pReturnError error string
@Return bool true if parse is successful
@Description Parses the TEXTURE section of the PFX file.
*****************************************************************************/
bool ParseTextures(int nStartLine, int nEndLine, string * const pReturnError);
/*!***************************************************************************
@Function ParseShader
@Input nStartLine start line number
@Input nEndLine end line number
@Output pReturnError error string
@Output shader shader data object
@Input pszBlockName name of block in PFX file
@Return bool true if parse is successful
@Description Parses the VERTEXSHADER or FRAGMENTSHADER section of the
PFX file.
*****************************************************************************/
bool ParseShader(int nStartLine, int nEndLine, string *pReturnError, SPFXParserShader &shader, const char * const pszBlockName);
/*!***************************************************************************
@Function ParseSemantic
@Output semantic semantic data object
@Input nStartLine start line number
@Input nEndLine end line number
@Output pReturnError error string
@Return bool true if parse is successful
@Description Parses a semantic.
*****************************************************************************/
bool ParseSemantic(SPFXParserSemantic &semantic, const int nStartLine, const int nEndLine, string * const pReturnError);
/*!***************************************************************************
@Function ParseEffect
@Output effect effect data object
@Input nStartLine start line number
@Input nEndLine end line number
@Output pReturnError error string
@Return bool true if parse is successful
@Description Parses the EFFECT section of the PFX file.
*****************************************************************************/
bool ParseEffect(SPFXParserEffect &effect, const int nStartLine, const int nEndLine, string * const pReturnError);
};
#endif /* _PFXPARSER_H_ */
/*****************************************************************************
End of file (PFXParser.h)
*****************************************************************************/
| [
"atgreen@7fa7efda-f44a-0410-a86a-c1fddb4bcab7"
] | [
[
[
1,
344
]
]
] |
c6c75e7c3c7a905de44c6fdb8f0cbffccde49761 | d9a78f212155bb978f5ac27d30eb0489bca87c3f | /PB/src/PbFt/GeneratedFiles/Debug/moc_fttables_a.cpp | c1e7c3150f61168841cd6d4f5d0da53c5edfd0b3 | [] | no_license | marchon/pokerbridge | 1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c | 97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9 | refs/heads/master | 2021-01-10T07:15:26.496252 | 2010-05-17T20:01:29 | 2010-05-17T20:01:29 | 36,398,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,738 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'fttables_a.h'
**
** Created: Thu 25. Mar 16:20:35 2010
** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "stdafx.h"
#include "..\..\fttables_a.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'fttables_a.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 61
#error "This file was generated using the moc from 4.5.2. 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_FTTablesAdaptor[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
2, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// signals: signature, parameters, type, tag, flags
26, 17, 16, 16, 0x05,
// slots: signature, parameters, type, tag, flags
60, 52, 16, 16, 0x09,
0 // eod
};
static const char qt_meta_stringdata_FTTablesAdaptor[] = {
"FTTablesAdaptor\0\0tableUrl\0"
"tableOpenedEvent(QString)\0tableId\0"
"onTableOpenedEvent(QString)\0"
};
const QMetaObject FTTablesAdaptor::staticMetaObject = {
{ &RpcAdaptor::staticMetaObject, qt_meta_stringdata_FTTablesAdaptor,
qt_meta_data_FTTablesAdaptor, 0 }
};
const QMetaObject *FTTablesAdaptor::metaObject() const
{
return &staticMetaObject;
}
void *FTTablesAdaptor::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_FTTablesAdaptor))
return static_cast<void*>(const_cast< FTTablesAdaptor*>(this));
return RpcAdaptor::qt_metacast(_clname);
}
int FTTablesAdaptor::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = RpcAdaptor::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: tableOpenedEvent((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 1: onTableOpenedEvent((*reinterpret_cast< QString(*)>(_a[1]))); break;
default: ;
}
_id -= 2;
}
return _id;
}
// SIGNAL 0
void FTTablesAdaptor::tableOpenedEvent(QString _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
87
]
]
] |
45d76ee17744275d6947ab4fedb33326fe893179 | cfcd2a448c91b249ea61d0d0d747129900e9e97f | /thirdparty/OpenCOLLADA/COLLADAFramework/src/COLLADAFWRoot.cpp | 67e9f59d01f299ff0e3d71e5a3b0d86907692d60 | [] | no_license | fire-archive/OgreCollada | b1686b1b84b512ffee65baddb290503fb1ebac9c | 49114208f176eb695b525dca4f79fc0cfd40e9de | refs/heads/master | 2020-04-10T10:04:15.187350 | 2009-05-31T15:33:15 | 2009-05-31T15:33:15 | 268,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | /*
Copyright (c) 2008 NetAllied Systems GmbH
This file is part of COLLADAFramework.
Licensed under the MIT Open Source License,
for details please see LICENSE file or the website
http://www.opensource.org/licenses/mit-license.php
*/
#include "COLLADAFWStableHeaders.h"
#include "COLLADAFWRoot.h"
#include "COLLADAFWILoader.h"
namespace COLLADAFW
{
//--------------------------------------------------------------------
Root::~Root()
{
}
bool Root::loadDocument( const String& fileName )
{
if ( !mLoader || !mWriter )
return false;
return mLoader->loadDocument(fileName, mWriter);
}
} // namespace COLLADAFW
| [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
18778aaf14a53597aeaffeebb54b352184a8cabe | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_代码统计专用文件夹/C++Primer中文版(第4版)/第四章 数组和指针/20090321_习题4.7_将一个vector对象赋给另一个vector对象.cpp | 543664c160819b1d231e3d16007dce779013fab9 | [] | no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | cpp | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
size_t cnt = 10;
string str;
vector<string> svec1, svec2;
cout << "Enter something(How about 10?):" << endl;
while (cnt--) {
cin >> str;
svec1.push_back(str);
}
vector<string>::iterator iter1 = svec1.begin();
for (;iter1 != svec1.end(); ++iter1) {
svec2.push_back(*iter1);
}
for (iter1 = svec1.begin(); iter1 != svec1.end(); ++iter1) {
cout << *iter1 << " ";
}
cout << endl;
return 0;
} | [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
] | [
[
[
1,
28
]
]
] |
1142a76877a4c271666da6a3186853c974c4d3b0 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEToolsCommon/SECollada/SEColladaInputArray.inl | 3a37026c35a4430524663d1f395e8290d164dd73 | [] | 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 | 2,679 | inl | // 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
//----------------------------------------------------------------------------
inline int SEColladaInputArray::GetMaxOffset() const
{
return m_iMaxOffset;
}
//----------------------------------------------------------------------------
inline int SEColladaInputArray::GetPositionOffset() const
{
return m_iPosition;
}
//----------------------------------------------------------------------------
inline int SEColladaInputArray::GetNormalOffset() const
{
return m_iNormal;
}
//----------------------------------------------------------------------------
inline int SEColladaInputArray::GetTCoordOffset() const
{
return m_iTCoord;
}
//----------------------------------------------------------------------------
inline int SEColladaInputArray::GetPositionStride() const
{
return m_iPositionStride;
}
//----------------------------------------------------------------------------
inline int SEColladaInputArray::GetNormalStride() const
{
return m_iNormalStride;
}
//----------------------------------------------------------------------------
inline int SEColladaInputArray::GetTCoordStride() const
{
return m_iTCoordStride;
}
//----------------------------------------------------------------------------
inline domListOfFloats* SEColladaInputArray::GetPositionData()
{
return m_pDomPositionData;
}
//----------------------------------------------------------------------------
inline domListOfFloats* SEColladaInputArray::GetNormalData()
{
return m_pDomNormalData;
}
//----------------------------------------------------------------------------
inline domListOfFloats* SEColladaInputArray::GetTCoordData()
{
return m_pDomTCoordData;
}
//---------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
71
]
]
] |
338bd3185a9bc312fffed3c8cf6bb29a322169d7 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/nv38box/Math/WmlVector3.h | 740641ae3362a3f631d6c0c1c53733ff8bc48bc0 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,976 | 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 WMLVECTOR3_H
#define WMLVECTOR3_H
#include "WmlVector.h"
#include "WmlMatrix4.h"
namespace Wml
{
template<class Real>
class Vector4;
template<class Real>
class WML_ITEM Vector3: public Vector<3, Real>
{
public:
// construction
Vector3();
Vector3(Real fX, Real fY, Real fZ);
Vector3(const Vector3& rkV);
Vector3(const Vector<3, Real>& rkV);
// operator Matrix4<Real>() const;
operator Vector4<Real>() const;
// member access
Real X() const;
Real& X();
Real Y() const;
Real& Y();
Real Z() const;
Real& Z();
// assignment
Vector3& operator=(const Vector3& rkV);
Vector3& operator=(const Vector<3, Real>& rkV);
Real Unitize(Real fTolerance = 1e-06f);
// The cross products are computed using the right-handed rule. Be aware
// that some graphics APIs use a left-handed rule. If you have to compute
// a cross product with these functions and send the result to the API
// that expects left-handed, you will need to change sign on the vector
// (replace each component value c by -c).
Vector3 Cross(const Vector3& rkV) const;
Vector3 UnitCross(const Vector3& rkV) const;
// Gram-Schmidt orthonormalization. Take linearly independent vectors
// U, V, and W and compute an orthonormal set (unit length, mutually
// perpendicular).
static void Orthonormalize(Vector3& rkU, Vector3& rkV, Vector3& rkW);
static void Orthonormalize(Vector3 akV[/*3*/]);
// Input W must be initialized to a nonzero vector, output is {U,V,W},
// an orthonormal basis. A hint is provided about whether or not W
// is already unit length.
static void GenerateOrthonormalBasis(Vector3& rkU, Vector3& rkV, Vector3& rkW, bool bUnitLengthW);
// special vectors
static const Vector3 ZERO;
static const Vector3 UNIT_X;
static const Vector3 UNIT_Y;
static const Vector3 UNIT_Z;
static const Vector3 UNIT_XYZ;
};
typedef Vector3<float> Vector3f;
typedef Vector3<double> Vector3d;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
80
]
]
] |
ddb2912cacea39cddd758b943c7ca5a8bf32c6ab | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/pcsx2/x86/microVU_IR.h | bf43b1c0fde0b761fb941a89c8551c0cf638de31 | [] | no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,506 | h | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 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 PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
union regInfo {
u32 reg;
struct {
u8 x;
u8 y;
u8 z;
u8 w;
};
};
// microRegInfo is carefully ordered for faster compares. The "important" information is
// housed in a union that is accessed via 'quick32' so that several u8 fields can be compared
// using a pair of 32-bit equalities.
// vi15 is only used if microVU const-prop is enabled (it is *not* by default). When constprop
// is disabled the vi15 field acts as additional padding that is required for 16 byte alignment
// needed by the xmm compare.
union __aligned16 microRegInfo {
struct {
u32 vi15; // Constant Prop Info for vi15 (only valid if sign-bit set)
union {
struct {
u8 needExactMatch; // If set, block needs an exact match of pipeline state
u8 q;
u8 p;
u8 flags; // clip x2 :: status x2
u8 xgkick;
u8 viBackUp; // VI reg number that was written to on branch-delay slot
u8 blockType; // 0 = Normal; 1,2 = Compile one instruction (E-bit/Branch Ending)
u8 r;
};
u32 quick32[2];
};
struct {
u8 VI[16];
regInfo VF[32];
};
};
u128 full128[160/sizeof(u128)];
u64 full64[160/sizeof(u64)];
u32 full32[160/sizeof(u32)];
};
C_ASSERT(sizeof(microRegInfo) == 160);
struct __aligned16 microBlock {
microRegInfo pState; // Detailed State of Pipeline
microRegInfo pStateEnd; // Detailed State of Pipeline at End of Block (needed by JR/JALR opcodes)
u8* x86ptrStart; // Start of code
};
struct microTempRegInfo {
regInfo VF[2]; // Holds cycle info for Fd, VF[0] = Upper Instruction, VF[1] = Lower Instruction
u8 VFreg[2]; // Index of the VF reg
u8 VI; // Holds cycle info for Id
u8 VIreg; // Index of the VI reg
u8 q; // Holds cycle info for Q reg
u8 p; // Holds cycle info for P reg
u8 r; // Holds cycle info for R reg (Will never cause stalls, but useful to know if R is modified)
u8 xgkick; // Holds the cycle info for XGkick
};
struct microVFreg {
u8 reg; // Reg Index
u8 x; // X vector read/written to?
u8 y; // Y vector read/written to?
u8 z; // Z vector read/written to?
u8 w; // W vector read/written to?
};
struct microVIreg {
u8 reg; // Reg Index
u8 used; // Reg is Used? (Read/Written)
};
struct microConstInfo {
u8 isValid; // Is the constant in regValue valid?
u32 regValue; // Constant Value
};
struct microUpperOp {
bool eBit; // Has E-bit set
bool iBit; // Has I-bit set
bool mBit; // Has M-bit set
microVFreg VF_write; // VF Vectors written to by this instruction
microVFreg VF_read[2]; // VF Vectors read by this instruction
};
struct microLowerOp {
microVFreg VF_write; // VF Vectors written to by this instruction
microVFreg VF_read[2]; // VF Vectors read by this instruction
microVIreg VI_write; // VI reg written to by this instruction
microVIreg VI_read[2]; // VI regs read by this instruction
microConstInfo constJump; // Constant Reg Info for JR/JARL instructions
u32 branch; // Branch Type (0 = Not a Branch, 1 = B. 2 = BAL, 3~8 = Conditional Branches, 9 = JALR, 10 = JR)
bool badBranch; // This instruction is a Branch who has another branch in its Delay Slot
bool evilBranch;// This instruction is a Branch in a Branch Delay Slot (Instruction after badBranch)
bool isNOP; // This instruction is a NOP
bool isFSSET; // This instruction is a FSSET
bool noWriteVF; // Don't write back the result of a lower op to VF reg if upper op writes to same reg (or if VF = 0)
bool backupVI; // Backup VI reg to memory if modified before branch (branch uses old VI value unless opcode is ILW or ILWR)
bool memReadIs; // Read Is (VI reg) from memory (used by branches)
bool memReadIt; // Read If (VI reg) from memory (used by branches)
bool readFlags; // Current Instruction reads Status, Mac, or Clip flags
};
struct microFlagInst {
bool doFlag; // Update Flag on this Instruction
bool doNonSticky; // Update O,U,S,Z (non-sticky) bits on this Instruction (status flag only)
u8 write; // Points to the instance that should be written to (s-stage write)
u8 lastWrite; // Points to the instance that was last written to (most up-to-date flag)
u8 read; // Points to the instance that should be read by a lower instruction (t-stage read)
};
struct microFlagCycles {
int xStatus[4];
int xMac[4];
int xClip[4];
int cycles;
};
struct microOp {
u8 stall; // Info on how much current instruction stalled
bool isBadOp; // Cur Instruction is a bad opcode (not a legal instruction)
bool isEOB; // Cur Instruction is last instruction in block (End of Block)
bool isBdelay; // Cur Instruction in Branch Delay slot
bool swapOps; // Run Lower Instruction before Upper Instruction
bool backupVF; // Backup mVUlow.VF_write.reg, and restore it before the Upper Instruction is called
bool doXGKICK; // Do XGKICK transfer on this instruction
bool doDivFlag; // Transfer Div flag to Status Flag on this instruction
int readQ; // Q instance for reading
int writeQ; // Q instance for writing
int readP; // P instance for reading
int writeP; // P instance for writing
microFlagInst sFlag; // Status Flag Instance Info
microFlagInst mFlag; // Mac Flag Instance Info
microFlagInst cFlag; // Clip Flag Instance Info
microUpperOp uOp; // Upper Op Info
microLowerOp lOp; // Lower Op Info
};
template<u32 pSize>
struct microIR {
microBlock block; // Block/Pipeline info
microBlock* pBlock; // Pointer to a block in mVUblocks
microTempRegInfo regsTemp; // Temp Pipeline info (used so that new pipeline info isn't conflicting between upper and lower instructions in the same cycle)
microOp info[pSize/2]; // Info for Instructions in current block
microConstInfo constReg[16]; // Simple Const Propagation Info for VI regs within blocks
u8 branch;
u32 cycles; // Cycles for current block
u32 count; // Number of VU 64bit instructions ran (starts at 0 for each block)
u32 curPC; // Current PC
u32 startPC; // Start PC for Cur Block
u32 sFlagHack; // Optimize out all Status flag updates if microProgram doesn't use Status flags
};
//------------------------------------------------------------------
// Reg Alloc
//------------------------------------------------------------------
struct microMapXMM {
int VFreg; // VF Reg Number Stored (-1 = Temp; 0 = vf0 and will not be written back; 32 = ACC; 33 = I reg)
int xyzw; // xyzw to write back (0 = Don't write back anything AND cached vfReg has all vectors valid)
int count; // Count of when last used
bool isNeeded; // Is needed for current instruction
};
class microRegAlloc {
protected:
static const u32 xmmTotal = 7; // Don't allocate PQ?
microMapXMM xmmMap[xmmTotal];
int counter; // Current allocation count
int index; // VU0 or VU1
// Helper functions to get VU regs
VURegs& regs() const { return ::vuRegs[index]; }
__fi REG_VI& getVI(uint reg) const { return regs().VI[reg]; }
__fi VECTOR& getVF(uint reg) const { return regs().VF[reg]; }
__ri void loadIreg(const xmm& reg, int xyzw) {
xMOVSSZX(reg, ptr32[&getVI(REG_I)]);
if (!_XYZWss(xyzw)) xSHUF.PS(reg, reg, 0);
}
int findFreeRegRec(int startIdx) {
for(int i = startIdx; i < xmmTotal; i++) {
if (!xmmMap[i].isNeeded) {
int x = findFreeRegRec(i+1);
if (x == -1) return i;
return ((xmmMap[i].count < xmmMap[x].count) ? i : x);
}
}
return -1;
}
int findFreeReg() {
for(int i = 0; i < xmmTotal; i++) {
if (!xmmMap[i].isNeeded && (xmmMap[i].VFreg < 0)) {
return i; // Reg is not needed and was a temp reg
}
}
int x = findFreeRegRec(0);
pxAssumeDev( x >= 0, "microVU register allocation failure!" );
return x;
}
public:
microRegAlloc(int _index) {
index = _index;
}
// Fully resets the regalloc by clearing all cached data
void reset() {
for(int i = 0; i < xmmTotal; i++) {
clearReg(i);
}
counter = 0;
}
// Flushes all allocated registers (i.e. writes-back to memory all modified registers).
// If clearState is 0, then it keeps cached reg data valid
// If clearState is 1, then it invalidates all cached reg data after write-back
void flushAll(bool clearState = 1) {
for(int i = 0; i < xmmTotal; i++) {
writeBackReg(xmm(i));
if (clearState) clearReg(i);
}
}
void clearReg(const xmm& reg) { clearReg(reg.Id); }
void clearReg(int regId) {
microMapXMM& clear = xmmMap[regId];
clear.VFreg = -1;
clear.count = 0;
clear.xyzw = 0;
clear.isNeeded = 0;
}
void clearRegVF(int VFreg) {
for(int i = 0; i < xmmTotal; i++) {
if (xmmMap[i].VFreg == VFreg) clearReg(i);
}
}
// Writes back modified reg to memory.
// If all vectors modified, then keeps the VF reg cached in the xmm register.
// If reg was not modified, then keeps the VF reg cached in the xmm register.
void writeBackReg(const xmm& reg, bool invalidateRegs = 1) {
microMapXMM& mapX = xmmMap[reg.Id];
if ((mapX.VFreg > 0) && mapX.xyzw) { // Reg was modified and not Temp or vf0
if (mapX.VFreg == 33) xMOVSS(ptr32[&getVI(REG_I)], reg);
elif (mapX.VFreg == 32) mVUsaveReg(reg, ptr[®s().ACC], mapX.xyzw, 1);
else mVUsaveReg(reg, ptr[&getVF(mapX.VFreg)], mapX.xyzw, 1);
if (invalidateRegs) {
for(int i = 0; i < xmmTotal; i++) {
microMapXMM& mapI = xmmMap[i];
if ((i == reg.Id) || mapI.isNeeded) continue;
if (mapI.VFreg == mapX.VFreg) {
if (mapI.xyzw && mapI.xyzw < 0xf) DevCon.Error("microVU Error: writeBackReg() [%d]", mapI.VFreg);
clearReg(i); // Invalidate any Cached Regs of same vf Reg
}
}
}
if (mapX.xyzw == 0xf) { // Make Cached Reg if All Vectors were Modified
mapX.count = counter;
mapX.xyzw = 0;
mapX.isNeeded = 0;
return;
}
clearReg(reg);
}
elif (mapX.xyzw) clearReg(reg); // Clear reg if modified and is VF0 or temp reg...
}
// Use this when done using the allocated register, it clears its "Needed" status.
// The register that was written to, should be cleared before other registers are cleared.
// This is to guarantee proper merging between registers... When a written-to reg is cleared,
// it invalidates other cached registers of the same VF reg, and merges partial-vector
// writes into them.
void clearNeeded(const xmm& reg) {
if ((reg.Id < 0) || (reg.Id >= xmmTotal)) return; // Sometimes xmmPQ hits this
microMapXMM& clear = xmmMap[reg.Id];
clear.isNeeded = 0;
if (clear.xyzw) { // Reg was modified
if (clear.VFreg > 0) {
int mergeRegs = 0;
if (clear.xyzw < 0xf) mergeRegs = 1; // Try to merge partial writes
for(int i = 0; i < xmmTotal; i++) { // Invalidate any other read-only regs of same vfReg
if (i == reg.Id) continue;
microMapXMM& mapI = xmmMap[i];
if (mapI.VFreg == clear.VFreg) {
if (mapI.xyzw && mapI.xyzw < 0xf) {
DevCon.Error("microVU Error: clearNeeded() [%d]", mapI.VFreg);
}
if (mergeRegs == 1) {
mVUmergeRegs(xmm(i), reg, clear.xyzw, 1);
mapI.xyzw = 0xf;
mapI.count = counter;
mergeRegs = 2;
}
else clearReg(i); // Clears when mergeRegs is 0 or 2
}
}
if (mergeRegs==2) clearReg(reg); // Clear Current Reg if Merged
elif (mergeRegs==1) writeBackReg(reg); // Write Back Partial Writes if couldn't merge
}
else clearReg(reg); // If Reg was temp or vf0, then invalidate itself
}
}
// vfLoadReg = VF reg to be loaded to the xmm register
// vfWriteReg = VF reg that the returned xmm register will be considered as
// xyzw = XYZW vectors that will be modified (and loaded)
// cloneWrite = When loading a reg that will be written to,
// it copies it to its own xmm reg instead of overwriting the cached one...
// Notes:
// To load a temp reg use the default param values, vfLoadReg = -1 and vfWriteReg = -1.
// To load a full reg which won't be modified and you want cached, specify vfLoadReg >= 0 and vfWriteReg = -1
// To load a reg which you don't want written back or cached, specify vfLoadReg >= 0 and vfWriteReg = 0
const xmm& allocReg(int vfLoadReg = -1, int vfWriteReg = -1, int xyzw = 0, bool cloneWrite = 1) {
//DevCon.WriteLn("vfLoadReg = %02d, vfWriteReg = %02d, xyzw = %x, clone = %d",vfLoadReg,vfWriteReg,xyzw,(int)cloneWrite);
counter++;
if (vfLoadReg >= 0) { // Search For Cached Regs
for(int i = 0; i < xmmTotal; i++) {
const xmm& xmmI = xmm::GetInstance(i);
microMapXMM& mapI = xmmMap[i];
if ((mapI.VFreg == vfLoadReg) && (!mapI.xyzw // Reg Was Not Modified
|| (mapI.VFreg && (mapI.xyzw==0xf)))) { // Reg Had All Vectors Modified and != VF0
int z = i;
if (vfWriteReg >= 0) { // Reg will be modified
if (cloneWrite) { // Clone Reg so as not to use the same Cached Reg
z = findFreeReg();
const xmm& xmmZ = xmm::GetInstance(z);
writeBackReg(xmmZ);
if (xyzw == 4) xPSHUF.D(xmmZ, xmmI, 1);
elif (xyzw == 2) xPSHUF.D(xmmZ, xmmI, 2);
elif (xyzw == 1) xPSHUF.D(xmmZ, xmmI, 3);
elif (z != i) xMOVAPS (xmmZ, xmmI);
mapI.count = counter; // Reg i was used, so update counter
}
else { // Don't clone reg, but shuffle to adjust for SS ops
if ((vfLoadReg!=vfWriteReg)||(xyzw!=0xf)) writeBackReg(xmmI);
if (xyzw == 4) xPSHUF.D(xmmI, xmmI, 1);
elif (xyzw == 2) xPSHUF.D(xmmI, xmmI, 2);
elif (xyzw == 1) xPSHUF.D(xmmI, xmmI, 3);
}
xmmMap[z].VFreg = vfWriteReg;
xmmMap[z].xyzw = xyzw;
}
xmmMap[z].count = counter;
xmmMap[z].isNeeded = 1;
return xmm::GetInstance(z);
}
}
}
int x = findFreeReg();
const xmm& xmmX = xmm::GetInstance(x);
writeBackReg(xmmX);
if (vfWriteReg >= 0) { // Reg Will Be Modified (allow partial reg loading)
if ((vfLoadReg == 0) && !(xyzw & 1)) xPXOR(xmmX, xmmX);
elif (vfLoadReg == 33) loadIreg (xmmX, xyzw);
elif (vfLoadReg == 32) mVUloadReg(xmmX, ptr[®s().ACC], xyzw);
elif (vfLoadReg >= 0) mVUloadReg(xmmX, ptr[&getVF(vfLoadReg)], xyzw);
xmmMap[x].VFreg = vfWriteReg;
xmmMap[x].xyzw = xyzw;
}
else { // Reg Will Not Be Modified (always load full reg for caching)
if (vfLoadReg == 33) loadIreg(xmmX, 0xf);
elif (vfLoadReg == 32) xMOVAPS (xmmX, ptr128[®s().ACC]);
elif (vfLoadReg >= 0) xMOVAPS (xmmX, ptr128[&getVF(vfLoadReg)]);
xmmMap[x].VFreg = vfLoadReg;
xmmMap[x].xyzw = 0;
}
xmmMap[x].count = counter;
xmmMap[x].isNeeded = 1;
return xmmX;
}
};
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
] | [
[
[
1,
401
]
]
] |
fe55266482c6f99d5c5da9798f74c8cc0c7e5798 | 252e638cde99ab2aa84922a2e230511f8f0c84be | /reflib/src/StopSelectForm.h | 836fdfc80b4c9cdbfd13049ed43550b882a41167 | [] | no_license | openlab-vn-ua/tour | abbd8be4f3f2fe4d787e9054385dea2f926f2287 | d467a300bb31a0e82c54004e26e47f7139bd728d | refs/heads/master | 2022-10-02T20:03:43.778821 | 2011-11-10T12:58:15 | 2011-11-10T12:58:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,916 | h | //---------------------------------------------------------------------------
#ifndef StopSelectFormH
#define StopSelectFormH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "Placemnt.h"
#include "RXDBCtrl.h"
#include "TableGridSelectForm.h"
#include "VADODataSourceOrdering.h"
#include "VCustomDataSourceOrdering.h"
#include "VDBGridFilterDialog.h"
#include "VDBSortGrid.h"
#include "VStringStorage.h"
#include <ActnList.hpp>
#include <ADODB.hpp>
#include <ComCtrls.hpp>
#include <Db.hpp>
#include <DBGrids.hpp>
#include <Grids.hpp>
#include <ImgList.hpp>
#include <Menus.hpp>
#include <ToolWin.hpp>
#include "VCustomDBGridFilterDialog.h"
//---------------------------------------------------------------------------
class TTourRefBookStopSelectForm : public TTourRefBookTableGridSelectForm
{
__published: // IDE-managed Components
TADOQuery *StopOwnerQuery;
TStringField *MainQuerystop_id;
TStringField *MainQuerycity_zip;
TStringField *MainQuerystop_model;
TStringField *MainQuerystopowner_id;
TStringField *MainQuerystop_name;
TADOQuery *StopModelQuery;
TADOQuery *CityQuery;
TStringField *MainQuerycity_name;
TStringField *MainQuerystopmodel_name;
TStringField *MainQuerystopowner_name;
void __fastcall FormCreate(TObject *Sender);
void __fastcall RefreshActionExecute(TObject *Sender);
void __fastcall FormDestroy(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TTourRefBookStopSelectForm(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TTourRefBookStopSelectForm *TourRefBookStopSelectForm;
//---------------------------------------------------------------------------
#endif
| [
"[email protected]"
] | [
[
[
1,
53
]
]
] |
98341d53927c5c383342e4264a630dd48aeceed3 | 99d3989754840d95b316a36759097646916a15ea | /tags/2011_09_07_to_baoxin_gpd_0.1/ferrylibs/src/ferry/feature_tracking/TwoViewFeatureTrackerFactory.h | 14261739f1f57a0de07890e5e3aba0d4e60fd8c0 | [] | no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,542 | h | #pragma once
#include <iostream>
#include "TwoViewFeatureTracker.h"
using namespace std;
namespace ferry {
namespace feature_tracking {
class TrackerParam {
public:
friend ostream& operator<<(ostream& os, const TrackerParam& tp) {
os<<tp.corner_count<<" ";
os<<tp.quality_level<<" ";
os<<tp.points_min_distance<<" ";
os<<tp.max_search_range<<" ";
os<<tp.half_win_size<<" ";
os<<tp.half_adjust_range<<" ";
os<<tp.max_difference<<" ";
return os;
}
friend istream& operator>>(istream& is, TrackerParam& tp) {
is>>tp.corner_count;
is>>tp.quality_level;
is>>tp.points_min_distance;
is>>tp.max_search_range;
is>>tp.half_win_size;
is>>tp.half_adjust_range;
is>>tp.max_difference;
return is;
}
public:
int corner_count;
double quality_level;
double points_min_distance;
double max_search_range;
int half_win_size;
int half_adjust_range;
double max_difference;
};
class TwoViewFeatureTrackerFactory
{
public:
TwoViewFeatureTrackerFactory(void) {}
~TwoViewFeatureTrackerFactory(void) {}
public:
//default configuration
//OpenCV, SimpleWindow
static TwoViewFeatureTracker* create(TrackerParam tp) {
CornerDetector* pcd = new OpenCVCornerDetector(tp.corner_count, tp.quality_level, tp.points_min_distance);
PointsOutFeatureMatcher* ppofm = new SimpleWindowPOFM(new SimpleWindowSSDFDC(tp.half_win_size, tp.half_adjust_range, (int)tp.max_difference), tp.max_search_range);
return new TwoViewFeatureTracker(pcd, ppofm);
}
};
}
} | [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
] | [
[
[
1,
63
]
]
] |
f5a52697803c17d4db502d6eefe495a8a3be73c5 | 593b85562f3e570a5a6e75666d8cd1c535daf3b6 | /Editors/MenuEditor/Project.cpp | 1caa007174cc8f8b4eae628cf34d26d4aa1eb5eb | [] | no_license | rayjohannessen/songofalbion | fc62c317d829ceb7c215b805fed4276788a22154 | 83d7e87719bfb3ade14096d4969aa32c524c1902 | refs/heads/master | 2021-01-23T13:18:10.028635 | 2011-02-13T00:23:37 | 2011-02-13T00:23:37 | 32,121,693 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 479 | cpp | #include "StdAfx.h"
#include "Project.h"
CProject::CProject(void)
{
}
CProject::~CProject(void)
{
}
//////////////////////////////////////////////////////////////////////////
void CProject::Render()
{
}
void CProject::Update(float fElapsed)
{
}
//////////////////////////////////////////////////////////////////////////
bool Load(const string& file)
{
// load clear colors
return true;
}
bool Save(const string& file)
{
return true;
} | [
"AllThingsCandid@cb80bfb0-ca38-a83e-6856-ee7c686669b9"
] | [
[
[
1,
34
]
]
] |
f53f221b8d9ba5d4abe4378d8243a37fcd5b2adf | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/SysCAD/OLE/XL5OBJ32.CPP | 8efb92bde0a1487ca445a3ac19fd51a02244560d | [] | 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 | 27,087 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
/* KGA: 11/6/96: This code is based on the machine generated IDispatch driver
classes created with ClassWizard. The required objects with the required
methods were copied from xl5en32.h and xl5en32.cpp. These two files can be
regenerated using class wizard OLE automation functionality by selecting
all objects. These are based on Excel version 5 32 bit edition. The
interface, naming etc have been changed to hide more of the OLE stuff and
to make the interface more simple and direct. For further references see
vba_xl.hlp which is shipped with Excel 5. Also see autodemo sample project
found on Microsoft Developer Network CD October 95. */
/* KGA: 12/6/97: This code has been extended to use Excel version 8. As before,
the class wizard was used to generate excel8.h and excel8.cpp. A global flag
is set determining which version is being used, the commands have been extended
to call the correct OLE dispatch etc based on the Excel version. ie One set of
classes calls the required Excel version. */
/* KGA: 5/7/99: Above process repeated to use Excel version 9 (part of Office2000).
Excel 8 and Excel 9 appear to be identical.*/
//===========================================================================
//#pragma warning (disable : 4237) // keyword reserved for future use : eg flag
#include "stdafx.h"
#include "sc_defs.h"
#include "xl5obj32.h"
#include "ole_base.h"
//#include "optoff.h"
//===========================================================================
LPDISPATCH OExcelApplication::GetActiveSheet()
{
LPDISPATCH lpDispatch;
if (UsingExcel8or9)
InvokeHelper(0x133, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, NULL);
else
GetProperty(0x133, VT_DISPATCH, (void*)&lpDispatch);
return lpDispatch;
}
LPDISPATCH OExcelApplication::GetActiveWindow()
{
LPDISPATCH lpDispatch;
if (UsingExcel8or9)
InvokeHelper(0x2f7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, NULL);
else
GetProperty(0x2f7, VT_DISPATCH, (void*)&lpDispatch);
return lpDispatch;
}
void OExcelApplication::SetDefaultFilePath(LPCTSTR lpszNewValue)
{
static BYTE parms[] = VTS_BSTR;
InvokeHelper(0x40e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, lpszNewValue);
}
void OExcelApplication::SetScreenUpdating(BOOL bUpdating)
{
if (UsingExcel8or9)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x17e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bUpdating);
}
else
{
OVariant propVal(bUpdating);
SetProperty(0x17e, VT_VARIANT, &propVal);
}
}
void OExcelApplication::SetStatusBar(LPCTSTR pStatusBarTxt)
{
static BYTE parms[] = VTS_BSTR;
InvokeHelper(0x182, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, pStatusBarTxt);
}
void OExcelApplication::RestoreStatusBar()
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x182, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, FALSE);
}
BOOL OExcelApplication::GetVisible()
{
if (UsingExcel8or9)
{
BOOL result;
InvokeHelper(0x22e, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
return result;
}
COleVariant result;
GetProperty(0x22e, VT_VARIANT, (void*)&result);
return result.boolVal;
}
void OExcelApplication::SetVisible(BOOL bVisible)
{
if (UsingExcel8or9)
{
static BYTE parms[] = VTS_BOOL;
InvokeHelper(0x22e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bVisible);
}
else
{
OVariant propVal(bVisible);
SetProperty(0x22e, VT_VARIANT, &propVal);
}
}
long OExcelApplication::GetCalculation()
{
long result;
InvokeHelper(0x13c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void OExcelApplication::SetCalculation(long nNewValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x13c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue);
}
void OExcelApplication::Quit()
{
if (UsingExcel8or9)
InvokeHelper(0x12e, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
else
{
VARIANT result;
InvokeHelper(0x12e, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
//return result;
}
}
LPDISPATCH OExcelApplication::Workbooks(short iIndex)
{
COleVariant Index(iIndex);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
if (UsingExcel8or9)
InvokeHelper(0x23c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
else
InvokeHelper(0x23c, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
return lpDispatch;
}
LPDISPATCH OExcelApplication::Workbooks(char* pName)
{
COleVariant Name(pName);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
if (UsingExcel8or9)
InvokeHelper(0x23c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Name);
else
InvokeHelper(0x23c, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Name);
return lpDispatch;
}
LPDISPATCH OExcelApplication::Workbooks()
{
LPDISPATCH lpDispatch;
if (UsingExcel8or9)
InvokeHelper(0x23c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, NULL);
else
InvokeHelper(0x23c, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, NULL);
return lpDispatch;
}
LPDISPATCH OExcelApplication::Worksheets(char* pName)
{
COleVariant Name(pName);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
if (UsingExcel8or9)
InvokeHelper(0x1ee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Name);
else
InvokeHelper(0x1ee, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Name);
return lpDispatch;
}
LPDISPATCH OExcelApplication::Worksheets(short iIndex)
{
COleVariant Index(iIndex);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
if (UsingExcel8or9)
InvokeHelper(0x1ee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
else
InvokeHelper(0x1ee, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
return lpDispatch;
}
LPDISPATCH OExcelApplication::Worksheets()
{
LPDISPATCH lpDispatch;
if (UsingExcel8or9)
InvokeHelper(0x1ee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, NULL);
else
InvokeHelper(0x1ee, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, NULL);
return lpDispatch;
}
VARIANT OExcelApplication::Run(const VARIANT& Macro)//, const VARIANT& Arg1, const VARIANT& Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9,
//const VARIANT& Arg10, const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19,
//const VARIANT& Arg20, const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29,
//const VARIANT& Arg30)
{
VARIANT result;
static BYTE parms[] =
VTS_VARIANT;// VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT
//VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT;
InvokeHelper(0x103, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms,
&Macro);//, &Arg1, &Arg2, &Arg3, &Arg4, &Arg5, &Arg6, &Arg7, &Arg8, &Arg9, &Arg10, &Arg11, &Arg12, &Arg13, &Arg14, &Arg15, &Arg16, &Arg17, &Arg18, &Arg19, &Arg20, &Arg21, &Arg22, &Arg23, &Arg24, &Arg25, &Arg26, &Arg27, &Arg28, &Arg29, &Arg30);
return result;
}
//===========================================================================
short ORange::GetColumn()
{
COleVariant result;
GetProperty(0xf0, VT_VARIANT, (void*)&result);
return result.iVal;
}
void ORange::SetColumnWidth(short Width)
{
COleVariant propVal(Width);
SetProperty(0xf2, VT_VARIANT, &propVal);
}
LPDISPATCH ORange::GetFont()
{
LPDISPATCH lpDispatch;
GetProperty(0x92, VT_DISPATCH, (void*)&lpDispatch);
return lpDispatch;
}
VARIANT ORange::GetFormula()
{
VARIANT result;
GetProperty(0x105, VT_VARIANT, (void*)&result);
return result;
}
void ORange::SetNumberFormat(char* pFormat)
{
COleVariant propVal(pFormat);
SetProperty(0xc1, VT_VARIANT, &propVal);
}
short ORange::GetRow()
{
COleVariant result;
GetProperty(0x101, VT_VARIANT, (void*)&result);
return result.iVal;
}
VARIANT ORange::GetValue()
{
VARIANT result;
GetProperty(0x6, VT_VARIANT, (void*)&result);
return result;
}
short ORange::GetShortValue()
{
OVariant V = GetValue();
V.ForceType(VT_I2);
return V.iVal;
}
long ORange::GetLongValue()
{
OVariant V = GetValue();
V.ForceType(VT_I4);
return V.lVal;
}
double ORange::GetDoubleValue()
{
OVariant V = GetValue();
V.ForceType(VT_R8);
return V.dblVal;
}
CString ORange::GetStringValue()
{
OVariant V = GetValue();
V.ForceType(VT_BSTR);
CString s = V.bstrVal;
return s;
}
void ORange::SetValue(char* pTxt)
{
COleVariant propVal(pTxt);
SetProperty(0x6, VT_VARIANT, &propVal);
}
void ORange::SetValue(double Val)
{
COleVariant propVal(Val);
SetProperty(0x6, VT_VARIANT, &propVal);
}
void ORange::SetValue(const VARIANT& propVal)
{
SetProperty(0x6, VT_VARIANT, &propVal);
}
VARIANT ORange::Activate()
{
VARIANT result;
InvokeHelper(0x130, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
return result;
}
VARIANT ORange::Clear()
{
VARIANT result;
InvokeHelper(0x6f, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
return result;
}
LPDISPATCH ORange::Find(char* pWhat)
{
LPDISPATCH lpDispatch;
COleVariant What(pWhat);
if (1)
{//KGA Jan2008: changed the find function to use XlPart and MatchCase=false because state of previous Excel find may be wrong
VARIANT argNULL;
VariantInit(&argNULL);
V_VT(&argNULL) = VT_ERROR;
V_ERROR(&argNULL) = DISP_E_PARAMNOTFOUND;
OVariant LookAt((unsigned char)2); //xlWhole==1; xlPart==2
BOOL bMatchCase = false;
OVariant MatchCase(bMatchCase);
static BYTE parms[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT;
InvokeHelper(0x18e, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &What, &argNULL, &argNULL, &LookAt, &argNULL, &argNULL, &MatchCase);
//Cells.Find(What:="SysCAD_", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
}
else
{
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x18e, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &What);
//, &After, &LookIn, &LookAt, &SearchOrder, &SearchDirection, &MatchCase);
}
return lpDispatch;
}
LPDISPATCH ORange::FindNext(LPDISPATCH lpDispatchAfter)
{
LPDISPATCH lpDispatch;
OVariant After(lpDispatchAfter);
//After.ChangeType(VT_DISPATCH);
//After.vt = VT_DISPATCH;
//After.pdispVal = lpDispatchAfter;
//After.Set(lpDispatchAfter);
static BYTE parms[] = VTS_VARIANT;//VTS_DISPATCH;
InvokeHelper(0x18f, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &After);
return lpDispatch;
}
LPDISPATCH ORange::FindNext(const VARIANT& After)
{
LPDISPATCH lpDispatch;
static BYTE parms[] = VTS_VARIANT;
InvokeHelper(0x18f, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &After);
return lpDispatch;
}
//===========================================================================
LPDISPATCH OWorkbook::GetActiveChart()
{
LPDISPATCH lpDispatch;
GetProperty(0xb7, VT_DISPATCH, (void*)&lpDispatch);
return lpDispatch;
}
LPDISPATCH OWorkbook::GetActiveSheet()
{
LPDISPATCH lpDispatch;
GetProperty(0x133, VT_DISPATCH, (void*)&lpDispatch);
return lpDispatch;
}
CString OWorkbook::GetFullName()
{
VARIANT result;
GetProperty(0x121, VT_VARIANT, (void*)&result);
CString s = result.bstrVal;
return s;
}
CString OWorkbook::GetName()
{
VARIANT result;
GetProperty(0x6e, VT_VARIANT, (void*)&result);
CString s = result.bstrVal;
return s;
}
BOOL OWorkbook::GetReadOnly()
{
VARIANT result;
GetProperty(0x128, VT_VARIANT, (void*)&result);
return result.boolVal;
}
BOOL OWorkbook::GetSaved()
{
BOOL result;
InvokeHelper(0x12a, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
return result;
}
void OWorkbook::SetSaved(BOOL bSaved)
{
OVariant propVal(bSaved);
SetProperty(0x12a, VT_VARIANT, &propVal);
}
VARIANT OWorkbook::Activate()
{
VARIANT result;
InvokeHelper(0x130, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
return result;
}
LPDISPATCH OWorkbook::Charts(short iIndex)
{
COleVariant Index(iIndex);
Index.ChangeType(VT_I2);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
if (UsingExcel8or9)
InvokeHelper(0x79, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
else
InvokeHelper(0x79, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
return lpDispatch;
}
LPDISPATCH OWorkbook::Charts()
{
LPDISPATCH lpDispatch;
if (UsingExcel8or9)
InvokeHelper(0x79, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, NULL);
else
InvokeHelper(0x79, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, NULL);
return lpDispatch;
}
void OWorkbook::Close(BOOL bSaveChanges)
{
OVariant SaveChanges(bSaveChanges);
static BYTE parms[] = VTS_VARIANT;// VTS_VARIANT VTS_VARIANT;
InvokeHelper(0x115, DISPATCH_METHOD, VT_EMPTY, NULL, parms, &SaveChanges);//, &Filename, &RouteWorkbook);
}
VARIANT OWorkbook::Save()
{
VARIANT result;
InvokeHelper(0x11b, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
return result;
}
LPDISPATCH OWorkbook::Windows(short iIndex)
{
COleVariant Index(iIndex);
Index.ChangeType(VT_I2);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
if (UsingExcel8or9)
InvokeHelper(0x1ae, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
else
InvokeHelper(0x1ae, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
return lpDispatch;
}
LPDISPATCH OWorkbook::Windows()
{
LPDISPATCH lpDispatch;
if (UsingExcel8or9)
InvokeHelper(0x1ae, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, NULL);
else
InvokeHelper(0x1ae, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, NULL);
return lpDispatch;
}
LPDISPATCH OWorkbook::Worksheets(char* pName)
{
COleVariant Name(pName);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
if (UsingExcel8or9)
InvokeHelper(0x1ee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Name);
else
InvokeHelper(0x1ee, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Name);
return lpDispatch;
}
LPDISPATCH OWorkbook::Worksheets(short iIndex)
{
COleVariant Index(iIndex);
Index.ChangeType(VT_I2);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
if (UsingExcel8or9)
InvokeHelper(0x1ee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
else
InvokeHelper(0x1ee, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
return lpDispatch;
}
LPDISPATCH OWorkbook::Worksheets()
{
LPDISPATCH lpDispatch;
if (UsingExcel8or9)
InvokeHelper(0x1ee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, NULL);
else
InvokeHelper(0x1ee, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, NULL);
return lpDispatch;
}
//===========================================================================
short OWorkbooks::GetCount()
{
COleVariant result;
GetProperty(0x76, VT_VARIANT, (void*)&result);
return result.iVal;
}
/*From Excel5:
VARIANT OpenText(const VARIANT& Filename, const VARIANT& Origin, const VARIANT& StartRow,
const VARIANT& DataType, const VARIANT& TextQualifier, const VARIANT& ConsecutiveDelimiter,
const VARIANT& Tab, const VARIANT& Semicolon, const VARIANT& Comma,
const VARIANT& Space, const VARIANT& Other, const VARIANT& OtherChar,
const VARIANT& FieldInfo);
From Excel8:
LPDISPATCH Open(LPCTSTR Filename, const VARIANT& UpdateLinks, const VARIANT& ReadOnly,
const VARIANT& Format, const VARIANT& Password, const VARIANT& WriteResPassword,
const VARIANT& IgnoreReadOnlyRecommended, const VARIANT& Origin, const VARIANT& Delimiter,
const VARIANT& Editable, const VARIANT& Notify, const VARIANT& Converter,
const VARIANT& AddToMru);*/
LPDISPATCH OWorkbooks::Open(char* pFilename, BOOL bIgnoreReadOnlyRecommended, int iUpdateLinks/*=0*/)
{
// NOTE: in order to specify the correct syntax of the "Open" method, we
// have to pass NULL arguments for the unused parameters. To pass a
// NULL argument we use a VARIANT indicating VT_ERROR and initialize
// it's "scode" member to "DISP_E_PARAMNOTFOUND"
/*VARIANT argNULL;
VariantInit(&argNULL);
V_VT(&argNULL) = VT_ERROR;
V_ERROR(&argNULL) = DISP_E_PARAMNOTFOUND;
static BYTE parms[] =
VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT;
COleVariant sFilename(pFilename);
VARIANT result;
InvokeHelper(0x2aa, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &sFilename,
&argNULL, &argNULL, &argNULL, &argNULL, &argNULL, &argNULL, &argNULL, &argNULL, &argNULL, &argNULL, &argNULL);*/
//UpdateLinks : 0 Doesn't update any references
// 1 Updates external references but not remote references
// 2 Updates remote references but not external references
// 3 Updates both remote and external references
//NB: Excel5 and Excel8 have different parameters for the open method!!!
COleVariant sFilename(pFilename);
OVariant IgnoreReadOnlyRecommended(bIgnoreReadOnlyRecommended);
OVariant UpdateLinks(iUpdateLinks);
LPDISPATCH result;
static BYTE parms5[] = VTS_VARIANT;
static BYTE parms8[] = VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT;
if (UsingExcel8or9)
{
//static BYTE parms[] = VTS_BSTR VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT;
//InvokeHelper(0x2aa, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, Filename, &UpdateLinks, &ReadOnly, &Format, &Password, &WriteResPassword, &IgnoreReadOnlyRecommended, &Origin, &Delimiter, &Editable, &Notify, &Converter, &AddToMru);
VARIANT argNULL;
VariantInit(&argNULL);
V_VT(&argNULL) = VT_ERROR;
V_ERROR(&argNULL) = DISP_E_PARAMNOTFOUND;
InvokeHelper(0x2aa, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms8, &sFilename, &UpdateLinks, &argNULL, &argNULL, &argNULL, &argNULL, &IgnoreReadOnlyRecommended);
}
else
{
InvokeHelper(0x2aa, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms5, &sFilename);
}
return result;
}
//===========================================================================
BOOL OWorksheet::GetProtectContents()
{
COleVariant result;
GetProperty(0x124, VT_VARIANT, (void*)&result);
return result.boolVal;
}
CString OWorksheet::GetName()
{
VARIANT result;
GetProperty(0x6e, VT_VARIANT, (void*)&result);
CString s = result.bstrVal;
return s;
}
void OWorksheet::SetName(char* pName)
{
COleVariant propVal(pName);
SetProperty(0x6e, VT_VARIANT, &propVal);
}
VARIANT OWorksheet::Activate()
{
VARIANT result;
InvokeHelper(0x130, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
return result;
}
LPDISPATCH OWorksheet::Cells(short iRowIndex, short iColumnIndex)
{
LPDISPATCH lpDispatch;
static BYTE parms[] = VTS_VARIANT VTS_VARIANT;
COleVariant RowIndex(iRowIndex);
COleVariant ColumnIndex(iColumnIndex);
if (UsingExcel8or9)
InvokeHelper(0xee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &RowIndex, &ColumnIndex);
else
InvokeHelper(0xee, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &RowIndex, &ColumnIndex);
return lpDispatch;
}
LPDISPATCH OWorksheet::Columns()
{
LPDISPATCH lpDispatch;
if (UsingExcel8or9)
InvokeHelper(0xf1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, NULL);
else
InvokeHelper(0xf1, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, NULL);
return lpDispatch;
}
LPDISPATCH OWorksheet::Columns(short iColumnIndex)
{
LPDISPATCH lpDispatch;
static BYTE parms[] = VTS_VARIANT;
COleVariant ColumnIndex(iColumnIndex);
if (UsingExcel8or9)
InvokeHelper(0xf1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &ColumnIndex);
else
InvokeHelper(0xf1, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &ColumnIndex);
return lpDispatch;
}
LPDISPATCH OWorksheet::Range(short iRowIndex1, short iColumnIndex1, short iRowIndex2, short iColumnIndex2)
{
LPDISPATCH lpDis1 = Cells(iRowIndex1, iColumnIndex1);
OVariant Cell1(lpDis1);
LPDISPATCH lpDis2 = Cells(iRowIndex2, iColumnIndex2);
OVariant Cell2(lpDis2);
LPDISPATCH lpDispatch;
static BYTE parms[] = VTS_VARIANT VTS_VARIANT;//VTS_DISPATCH VTS_DISPATCH;
if (UsingExcel8or9)
InvokeHelper(0xc5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Cell1, &Cell2);
else
InvokeHelper(0xc5, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Cell1, &Cell2);
return lpDispatch;
}
//CNM
LPDISPATCH OWorksheet::Range(LPCTSTR Name)
{
//LPDISPATCH lpDis1 = Cells(iRowIndex1, iColumnIndex1);
OVariant Cell1(Name);
//LPDISPATCH lpDis2 = Cells(iRowIndex2, iColumnIndex2);
//OVariant Cell2(lpDis2);
LPDISPATCH lpDispatch;
static BYTE parms[] = VTS_VARIANT ;//VTS_DISPATCH VTS_DISPATCH;
if (UsingExcel8or9)
InvokeHelper(0xc5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&lpDispatch, parms, &Cell1);
else
InvokeHelper(0xc5, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Cell1);
return lpDispatch;
}
//===========================================================================
short OWorksheets::GetCount()
{
COleVariant result;
GetProperty(0x76, VT_VARIANT, (void*)&result);
return result.iVal;
}
VARIANT OWorksheets::Add()
{
VARIANT result;
InvokeHelper(0xb5, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
return result;
}
//===========================================================================
void OFont::SetBold(BOOL bBold)
{
OVariant propVal(bBold);
SetProperty(0x60, VT_VARIANT, &propVal);
}
void OFont::SetColor(COLORREF Color)
{
COleVariant propVal((long)Color);
SetProperty(0x63, VT_VARIANT, &propVal);
}
//===========================================================================
CString OChart::GetName()
{
VARIANT result;
GetProperty(0x6e, VT_VARIANT, (void*)&result);
CString s = result.bstrVal;
return s;
}
void OChart::SetName(char* pName)
{
COleVariant propVal(pName);
SetProperty(0x6e, VT_VARIANT, &propVal);
}
void OChart::SetType(short Type)
{
COleVariant propVal(Type);
SetProperty(0x6c, VT_VARIANT, &propVal);
}
LPDISPATCH OChart::SeriesCollection(short iIndex)
{
COleVariant Index(iIndex);
Index.ChangeType(VT_I2);
LPDISPATCH lpDispatch;
static BYTE BASED_CODE parms[] = VTS_VARIANT;
InvokeHelper(0x44, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, parms, &Index);
return lpDispatch;
}
LPDISPATCH OChart::SeriesCollection()
{
LPDISPATCH lpDispatch;
InvokeHelper(0x44, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, NULL);
return lpDispatch;
}
//===========================================================================
short OCharts::GetCount()
{
COleVariant result;
GetProperty(0x76, VT_VARIANT, (void*)&result);
return result.iVal;
}
VARIANT OCharts::Add()
{
VARIANT result;
InvokeHelper(0xb5, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
return result;
}
//===========================================================================
void OSeries::SetValues(LPDISPATCH pDispatch)
{
OVariant propVal(pDispatch);
SetProperty(0xa4, VT_VARIANT, &propVal);
}
void OSeries::SetXValues(LPDISPATCH pDispatch)
{
OVariant propVal(pDispatch);
SetProperty(0x457, VT_VARIANT, &propVal);
}
VARIANT OSeries::Delete()
{
VARIANT result;
InvokeHelper(0x75, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL);
return result;
}
LPDISPATCH OSeries::Points()
{
LPDISPATCH lpDispatch;
InvokeHelper(0x46, DISPATCH_METHOD, VT_DISPATCH, (void*)&lpDispatch, NULL);
return lpDispatch;
}
//===========================================================================
short OSeriesCollection::GetCount()
{
COleVariant result;
GetProperty(0x76, VT_VARIANT, (void*)&result);
return result.iVal;
}
VARIANT OSeriesCollection::Add(LPDISPATCH pDispatch)
{
VARIANT result;
static BYTE parms[] = VTS_VARIANT;// VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT;
OVariant Source(pDispatch);
InvokeHelper(0xb5, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &Source);
return result;
}
//===========================================================================
long OWindow::GetView()
{
long result;
InvokeHelper(0x4aa, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void OWindow::SetView(long nNewValue)
{
static BYTE parms[] = VTS_I4;
InvokeHelper(0x4aa, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue);
}
//===========================================================================
short OWindows::GetCount()
{
COleVariant result;
GetProperty(0x76, VT_VARIANT, (void*)&result);
return result.iVal;
}
//===========================================================================
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
29
],
[
31,
332
],
[
350,
350
],
[
352,
677
],
[
693,
848
]
],
[
[
30,
30
],
[
333,
349
],
[
351,
351
]
],
[
[
678,
692
]
]
] |
d2a5d092d2b4c793a62f9a193b6eae5c7aafa4f1 | da9e4cd28021ecc9e17e48ac3ded33b798aae59c | /SRC/DRIVERS/DISPLAY_BROADSHEET/display_drv/s3c6410_disp.h | 6183aa1959a889a3f775aa899440d318aa0be541 | [] | 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 | 1,352 | h |
#ifndef __S3C6410_DISP_H__
#define __S3C6410_DISP_H__
class S3C6410Disp : public GPE
{
private:
GPEMode m_ModeInfo;
void *m_pVirtualFrameBuffer;
SCODE WrappedEmulatedLine(GPELineParms *pParms);
SCODE WrappedEmulatedBlt(GPEBltParms *pParms);
public:
S3C6410Disp();
virtual int NumModes();
virtual SCODE SetMode(int modeId, HPALETTE *pPalette);
virtual int InVBlank();
virtual SCODE SetPalette(const PALETTEENTRY *src, unsigned short firstEntry, unsigned short numEntries);
virtual SCODE GetModeInfo(GPEMode *pMode, int modeNo);
virtual SCODE SetPointerShape(GPESurf *pMask, GPESurf *pColorSurf, int xHot, int yHot, int cx, int cy);
virtual SCODE MovePointer(int x, int y);
virtual void WaitForNotBusy();
virtual int IsBusy();
virtual void GetPhysicalVideoMemory(unsigned long *pPhysicalMemoryBase, unsigned long *pVideoMemorySize);
virtual SCODE AllocSurface(GPESurf **ppSurf, int width, int height, EGPEFormat format, int surfaceFlags);
virtual SCODE Line(GPELineParms *pLineParms, EGPEPhase phase);
virtual SCODE BltPrepare(GPEBltParms *pBltParms);
virtual SCODE BltComplete(GPEBltParms *pBltParms);
virtual VOID PowerHandler(BOOL bOff);
virtual ULONG DrvEscape(SURFOBJ *pso, ULONG iEsc, ULONG cjIn, PVOID pvIn, ULONG cjOut, PVOID pvOut);
};
#endif //__S3C6410_DISP_H__
| [
"jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006"
] | [
[
[
1,
39
]
]
] |
a84a93f4cb1da19eab89cf7672e7cc84af20019a | 40e58042e635ea2a61a6216dc3e143fd3e14709c | /chopshop11/TimerTask.cpp | 2c89c3279e7b7eeeefb33c05c51fd39511f90a5f | [] | no_license | chopshop-166/frc-2011 | 005bb7f0d02050a19bdb2eb33af145d5d2916a4d | 7ef98f84e544a17855197f491fc9f80247698dd3 | refs/heads/master | 2016-09-05T10:59:54.976527 | 2011-10-20T22:50:17 | 2011-10-20T22:50:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,637 | cpp | /*******************************************************************************
* Project : Chopshop11
* File Name : TimerTask.cpp
* Owner : Software Group (FIRST Chopshop Team 166)
* File Description : Task to send the remaining match time to the dashboard
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* Copyright (c) MHS Chopshop Team 166, 2011. All Rights Reserved. */
/*----------------------------------------------------------------------------*/
#include "WPILib.h"
#include "TimerTask.h"
// To locally enable debug printing: set true, to disable false
#define DPRINTF if(false)dprintf
// task constructor
TimerTask::TimerTask(void):Team166Task(0)
{
Start((char *)"166TimerTask", TIMER_CYCLE_TIME);
// Register the proxy
proxy = Proxy::getInstance();
return;
};
// task destructor
TimerTask::~TimerTask(void)
{
return;
};
// Main function of the task
int TimerTask::Main(int a2, int a3, int a4, int a5,
int a6, int a7, int a8, int a9, int a10)
{
// Let the world know we're in
DPRINTF(LOG_DEBUG,"In the 166 Timer task\n");
// Wait for Robot go-ahead (e.g. entering Autonomous or Tele-operated mode)
WaitForGoAhead();
// Register main robot task
lHandle = Robot::getInstance();
// General main loop (while in Autonomous or Tele mode)
while (true) {
// SmartDashboard::Log(proxy->get("matchtimer"), "Remaining Time");
// Wait for our next lap
WaitForNextLoop();
}
return (0);
};
| [
"devnull@localhost",
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
4,
4
],
[
6,
7
],
[
9,
17
],
[
19,
19
],
[
24,
37
],
[
39,
41
],
[
46,
46
],
[
50,
55
]
],
[
[
2,
3
],
[
5,
5
],
[
8,
8
],
[
18,
18
],
[
20,
23
],
[
42,
45
],
[
47,
47
],
[
49,
49
]
],
[
[
38,
38
],
[
48,
48
]
]
] |
ac74974e1e00a32f87a86c2d0b52e10b47b6fc55 | a7eff8a49855a81c2649cd329a2adc7e82016dee | /.LibReader/f_Main.cpp | ed59da5f9e3776488f48843312c5b10b6af810d0 | [] | no_license | szavalishin/Libs | 2f16a6498f1181eee4d2f59ab96bbf5f43e285b4 | bdb9d482cd12a28eec4233d773fd2b9b0131d510 | refs/heads/master | 2020-04-15T16:08:29.104347 | 2011-12-16T19:32:29 | 2011-12-16T19:32:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,536 | cpp | // ---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "f_Main.h"
#include "f_Register.h"
#include <IOUtils.hpp>
// ---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "IdBaseComponent"
#pragma link "IdComponent"
#pragma link "IdHTTP"
#pragma link "IdTCPClient"
#pragma link "IdTCPConnection"
#pragma resource "*.dfm"
TfMain *fMain;
// ---------------------------------------------------------------------------
__fastcall TfMain::TfMain(TComponent* Owner) : TForm(Owner) {
}
// ---------------------------------------------------------------------------
void __fastcall TfMain::sbOpenBookClick(TObject *Sender) {
odOpenBook->Execute(this->Handle);
}
// ---------------------------------------------------------------------------
void __fastcall TfMain::odOpenBookCanClose(TObject *Sender, bool &CanClose) {
mBook->Lines->LoadFromFile(odOpenBook->FileName);
TListItem* Item = lvLib->Items->Add();
Item->Caption = ExtractFileName(odOpenBook->FileName);
Item->GroupID = 0;
Item->SubItems->Add(odOpenBook->FileName); //path [0]
Item->SubItems->Add("1"); //bookmark [1]
Item->SubItems->Add(IntToStr(mBook->Text.Length())); //size [2]
lbBookName->Caption = Item->Caption;
CurBook = Item;
tsReading->TabVisible = true;
pcMenuPages->ActivePage = tsReading;
}
// ---------------------------------------------------------------------------
void __fastcall TfMain::sbDeleteBookClick(TObject *Sender) {
if (lvLib->Selected){
lvLib->Selected->Delete();
if(CurBook == lvLib->Selected)
CurBook = 0;
}
}
// ---------------------------------------------------------------------------
void __fastcall TfMain::pcMenuPagesMouseUp
(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) {
if (pcMenuPages->ActivePage == tsWeb)
wbLibs->Navigate(leServer->Text);
}
// ---------------------------------------------------------------------------
void __fastcall TfMain::sbBookmarkClick(TObject *Sender)
{
if(CurBook){
CurBook->SubItems->Strings[1] = IntToStr(mBook->SelStart); //adding bookmark
}
}
//---------------------------------------------------------------------------
void __fastcall TfMain::lvLibDblClick(TObject *Sender)
{
if(lvLib->Selected){
tsReading->TabVisible = true;
pcMenuPages->ActivePage = tsReading;
CurBook = lvLib->Selected;
lbBookName->Caption = CurBook->Caption;
mBook->Lines->LoadFromFile(CurBook->SubItems->Strings[0]);
mBook->SelStart = StrToInt(CurBook->SubItems->Strings[1]);
mBook->SelLength = 1;
}
}
//---------------------------------------------------------------------------
void __fastcall TfMain::sbBackClick(TObject *Sender)
{
unsigned short Key = VK_PRIOR;
fMain->KeyDown(Key, TShiftState()); //Page up
}
//---------------------------------------------------------------------------
void __fastcall TfMain::FormClose(TObject *Sender, TCloseAction &Action)
{
TFile f;
TStringList* sl = new(TStringList);
for(int i = 0; i < lvLib->Items->Count; i++)
sl->Add(lvLib->Items->Item[i]->SubItems->Strings[0] + '=' +
lvLib->Items->Item[i]->SubItems->Strings[1] + '/' +
lvLib->Items->Item[i]->SubItems->Strings[2]);
sl->SaveToFile(ExtractFileDir(Application->ExeName) + "\\Library.lb");
sl->Clear();
sl->Add("Login=" + leLogin->Text);
if(cbRememberPass->Checked)
sl->Add("Pass=" + lePass->Text);
else
sl->Add("Pass=");
if(cbRememberPass->Checked)
sl->Add("RememberPass=1");
else
sl->Add("RememberPass=0");
sl->Add("Server=" + leServer->Text);
sl->SaveToFile(ExtractFileDir(Application->ExeName) + "\\Settings.ini");
sl->~TStringList();
}
//---------------------------------------------------------------------------
void __fastcall TfMain::FormShow(TObject *Sender)
{
TStringList* sl = new(TStringList);
sl->NameValueSeparator = '=';
TFile f;
if(f.Exists(ExtractFileDir(Application->ExeName) + "\\Library.lb")){
sl->LoadFromFile(GetCurrentDir() + "\\Library.lb");
for(int i = 0; i < sl->Count; i++){
TListItem* Item = lvLib->Items->Add();
Item->Caption = ExtractFileName(sl->Names[i]);
Item->GroupID = 0;
Item->SubItems->Add(sl->Names[i]); //path [0]
TStringList* ss = new(TStringList);
ss->NameValueSeparator = '/';
ss->Add(sl->ValueFromIndex[i]);
Item->SubItems->Add(ss->Names[0]); //bookmark [1]
Item->SubItems->Add(ss->ValueFromIndex[0]); //size [2]
ss->~TStringList();
}
}
sl->Clear();
if(f.Exists(ExtractFileDir(Application->ExeName) + "\\Settings.ini")){
sl->LoadFromFile(GetCurrentDir() + "\\Settings.ini");
leLogin->Text = sl->ValueFromIndex[0];
lePass->Text = sl->ValueFromIndex[1];
if(sl->ValueFromIndex[2] == "1")
cbRememberPass->Checked = true;
else
cbRememberPass->Checked = false;
leServer->Text = sl->ValueFromIndex[3];
}
sl->~TStringList();
}
//---------------------------------------------------------------------------
void __fastcall TfMain::leServerExit(TObject *Sender)
{
if(leServer->Text == "")
leServer->Text = "localhost:3000";
}
//---------------------------------------------------------------------------
void __fastcall TfMain::btnRegisterClick(TObject *Sender)
{
fRegister->ShowModal();
}
//---------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
185
]
]
] |
fe091db3e0a8fd611002204fdccceeec9783dafd | 96f796a966025265020459ca2a38346c3c292b1e | /Ansoply/Movie.cpp | aa604eef3e54b6c971eb0d073dc3f985d1934bfd | [] | no_license | shanewfx/ansoply | 222979843662ddb98fb444ce735d607e3033dd5e | 99e91008048d0c1afbf80152d0dc173a15e068ee | refs/heads/master | 2020-05-18T15:53:46.618329 | 2009-06-17T01:04:47 | 2009-06-17T01:04:47 | 32,243,359 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,013 | cpp | //----------------------------------------------------------------------------
// File: Movie.cpp
//
// Desc: DirectShow sample code
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
#include "stdafx.h"
#include "project.h"
#include <wmsdk.h>
BOOL IsFileASavedFG( WCHAR* FileName );
//
// Implementation of CMovie
//
//-------------------------------------------------------------------------
// CMovie constructor
//-------------------------------------------------------------------------
CMovie::CMovie() :
m_MediaEvent(NULL),
m_TimeFormat(TIME_FORMAT_MEDIA_TIME),
m_dwUserID(NULL),
m_lpDDTexture(NULL),
m_Bf(NULL),
m_Fg(NULL),
m_Gb(NULL),
m_Mc(NULL),
m_Ms(NULL),
m_Me(NULL),
m_bInitialized( false),
m_pAP(NULL),
m_SAN(NULL),
m_bDirectedFlips(FALSE),
m_bAlpha(0x7F),
m_bUseInTheScene(FALSE),
m_bDelete(FALSE),
m_bPresented(FALSE)
{
ZeroMemory( m_achPath, sizeof(m_achPath));
ZeroMemory( &m_rcSrc, sizeof(RECT));
ZeroMemory( &m_rcDst, sizeof(RECT));
ZeroMemory( &m_VideoSize, sizeof(SIZE));
ZeroMemory( &m_VideoAR, sizeof(SIZE));
ZeroMemory( m_Vdef, 4 * sizeof(Vertex) );
ZeroMemory( m_Vcur, 4 * sizeof(Vertex) );
}
//-------------------------------------------------------------------------
// ~CMovie destructor
//-------------------------------------------------------------------------
CMovie::~CMovie()
{
Release();
}
//-------------------------------------------------------------------------
// Release
// Unadvises custom AP and stops the movie
//-------------------------------------------------------------------------
void CMovie::Release()
{
try
{
if( m_SAN)
{
m_SAN->AdviseSurfaceAllocator(m_dwUserID, NULL);
}
if( m_Mc )
{
m_Mc->Stop();
}
SAFERELEASE( m_pAP );
m_bInitialized = false;
}
catch(...)
{}
}
// configuring functions
//-------------------------------------------------------------------------
// Initialize
// sets movie parameters
//-------------------------------------------------------------------------
void CMovie::Initialize( sMovieInfo * pMovInf, CMultiSAP * pSAP)
{
ASSERT( pMovInf );
ASSERT( pSAP );
m_pAP = pSAP;
m_pAP->AddRef();
wcscpy(m_achPath, pMovInf->achPath);
m_dwUserID = pMovInf->pdwUserID;
m_bInitialized = true;
}
//-------------------------------------------------------------------------
// OpenMovie
// Creates filter graph for specified movie, advises custom AP and render media source
//-------------------------------------------------------------------------
HRESULT CMovie::OpenMovie()
{
CComPtr<IUnknown> pUnk;
HRESULT hres;
WCHAR FileName[MAX_PATH];
CComPtr<IObjectWithSite> pObjWithSite;
wcsncpy(FileName, m_achPath, NUMELMS(FileName));
/*
hres = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if(hres == S_FALSE)
{
CoUninitialize();
}
*/
hres = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
IID_IUnknown, (LPVOID *)&pUnk);
// IUnknown *punkCert;
// HRESULT hr = WMCreateCertificate(&punkCert);
if(SUCCEEDED(hres))
{
hres = pUnk->QueryInterface(IID_IFilterGraph, (LPVOID *)&m_Fg);
if(FAILED(hres))
{
pUnk = NULL;
return hres;
}
// hook verifier to the filter graph to prevent unwanted Video Renderers
// and have control over whether graph utilizes our customized VMR
hres = m_Fg->QueryInterface(IID_IObjectWithSite, (LPVOID*)&pObjWithSite);
if( SUCCEEDED( hres ) && m_pAP)
{
hres = pObjWithSite->SetSite( (IAMGraphBuilderCallback*)(this->m_pAP));
// hres = pObjWithSite->SetSite( punkCert );
}
hres = AddVideoMixingRendererToFG();
if(FAILED(hres))
{
pObjWithSite = NULL;
m_Fg = NULL;
return hres;
}
hres = pUnk->QueryInterface(IID_IGraphBuilder, (LPVOID *)&m_Gb);
if(FAILED(hres))
{
if( m_SAN )
{
m_SAN->AdviseSurfaceAllocator(m_dwUserID, NULL);
}
pObjWithSite = NULL;
pUnk = NULL;
m_Gb = NULL;
return hres;
}
hres = m_Gb->RenderFile(FileName, NULL);
if(FAILED(hres) || VFW_E_NOT_CONNECTED == CheckVMRConnection())
{
IEnumFilters *pEnum = NULL;
HRESULT hr = m_Gb->EnumFilters(&pEnum);
if (SUCCEEDED(hr))
{
IBaseFilter *pFilter = NULL;
CComPtr<IGraphConfig> GC;
m_Gb->QueryInterface(IID_IGraphConfig, (LPVOID *)&GC);
while (S_OK == pEnum->Next(1, &pFilter, NULL))
{
// Remove the filter.
//pVideoObject->m_Gb->RemoveFilter(pFilter);
GC->RemoveFilterEx(pFilter, 0);
// Reset the enumerator.
pEnum->Reset();
pFilter->Release();
}
pEnum->Release();
}
//m_SAN->AdviseSurfaceAllocator(m_dwUserID, NULL);
m_Gb = NULL;
m_Bf = NULL;
m_Fg = NULL;
m_SAN = NULL;
m_pAP = NULL;
m_lpDDTexture = NULL ;
m_lpDDDecode = NULL;
if( SUCCEEDED(hres))
{
hres = VFW_E_NOT_CONNECTED;
}
return hres;
}
// if we managed to build the graph, we do not need verifier anymore
hres = pObjWithSite->SetSite( NULL );
pObjWithSite = NULL;
hres = pUnk->QueryInterface(IID_IMediaControl, (LPVOID *)&m_Mc);
if(FAILED(hres))
{
if( m_SAN )
{
m_SAN->AdviseSurfaceAllocator(m_dwUserID, NULL);
}
pUnk = NULL;
m_Fg = NULL;
m_Gb = NULL;
return hres;
}
//
// Not being able to get the IMediaEvent interface does not
// necessarily mean that we can't play the graph.
//
pUnk->QueryInterface(IID_IMediaEvent, (LPVOID *)&m_Me);
pUnk->QueryInterface(IID_IMediaSeeking, (LPVOID *)&m_Ms);
m_llDuration = 0L;
if( m_Ms )
{
m_Ms->GetDuration( &m_llDuration );
}
//GetMovieEventHandle();
//pUnk = NULL;
return S_OK;
} // if FilterGraph was coCreated successfully
else
{
m_Fg = NULL;
}
return hres;
}
//-------------------------------------------------------------------------
// AddVideoMixingRendererToFG
// creates instance of VMR, configures it, and advises custom AP
//-------------------------------------------------------------------------
HRESULT CMovie::AddVideoMixingRendererToFG()
{
HRESULT hRes = CoCreateInstance(CLSID_VideoMixingRenderer, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, (LPVOID *)&m_Bf);
if(SUCCEEDED(hRes))
{
WCHAR wcFilterName[MAX_PATH];
swprintf( wcFilterName, L"VMR for VMRMulti 0x%08x\0", m_dwUserID);
hRes = m_Fg->AddFilter(m_Bf, wcFilterName);
if(SUCCEEDED(hRes))
{
IVMRFilterConfig* pConfig = NULL;
hRes = m_Bf->QueryInterface(__uuidof(IVMRFilterConfig), (LPVOID *)&pConfig);
/*hRes = m_Bf->QueryInterface(IID_IVMRMixerBitmap, (void**)&m_pAP->m_pBMP);
if(SUCCEEDED(hRes))
{
}*/
if(SUCCEEDED(hRes))
{
pConfig->SetRenderingMode(VMRMode_Renderless);
pConfig->SetNumberOfStreams(1);
pConfig->Release();
}
if(SUCCEEDED(hRes))
{
hRes = m_Bf->QueryInterface(__uuidof(IVMRSurfaceAllocatorNotify),
(LPVOID *)&m_SAN);
}
if(SUCCEEDED(hRes))
{
// IMPORTANT: this is the moment we advise custom AP
hRes = m_SAN->AdviseSurfaceAllocator(m_dwUserID, m_pAP);
}
if(SUCCEEDED(hRes))
{
hRes = m_SAN->SetDDrawDevice(m_pAP->GetDDObject(), m_pAP->GetMonitor());
}
if(SUCCEEDED(hRes))
{
hRes = m_SAN->SetBorderColor(NULL);
}
}
}
if(FAILED(hRes))
{
if(m_SAN)
{
m_SAN = NULL;
}
}
return hRes;
}
//-------------------------------------------------------------------------
// CheckVMRConnection
//-------------------------------------------------------------------------
HRESULT CMovie::CheckVMRConnection()
{
HRESULT hr = S_OK;
CComPtr<IEnumPins> pEnum;
CComPtr<IPin> pPin;
bool bConnected = false;
if( !m_Bf )
return E_UNEXPECTED;
hr = m_Bf->EnumPins( &pEnum );
if( FAILED(hr ))
{
return hr;
}
hr = pEnum->Next(1, &pPin, NULL);
while( SUCCEEDED(hr) && pPin )
{
CComPtr<IPin> pPinUpstream;
hr = pPin->ConnectedTo( &pPinUpstream );
if( S_OK == hr )
{
bConnected = true;
break;
}
pPin = NULL;
hr = pEnum->Next(1, &pPin, NULL);
}// while
if( false == bConnected)
{
return VFW_E_NOT_CONNECTED;
}
return S_OK;
}
//-------------------------------------------------------------------------
// CloseMovie
//-------------------------------------------------------------------------
HRESULT CMovie::CloseMovie()
{
if (m_Mc)
{
if (m_Me)
{
m_MediaEvent = NULL;
m_Me = NULL;
}
if (m_Ms)
{
m_Ms = NULL;
}
m_Mc = NULL;
if (m_Gb)
{
m_Gb = NULL;
}
if (m_Fg)
{
m_Fg = NULL;
}
}
return S_OK;
}
// command functions
//-------------------------------------------------------------------------
// PlayMovie
// Calls IMediaControl::Run() method; if we are at the end of the stream,
// we reset it to the beginning
//-------------------------------------------------------------------------
HRESULT CMovie::PlayMovie(BOOL bPause)
{
HRESULT hr = S_OK;
// LONGLONG llCur = 0L;
// LONGLONG llD = 0L;
if( !m_Mc )
return E_POINTER;
if( m_Ms && !bPause )
{
// hr = m_Ms->GetCurrentPosition( &llCur);
// hr = m_Ms->GetDuration( &llD);
// if( llCur >= llD )
// {
LONGLONG llStart = 0L;
hr = m_Ms->SetPositions(&llStart, AM_SEEKING_AbsolutePositioning, NULL, AM_SEEKING_NoPositioning);
// }
}
hr = m_Mc->Run();
return hr;
}
//-------------------------------------------------------------------------
// PauseMovie
//-------------------------------------------------------------------------
HRESULT CMovie::PauseMovie()
{
HRESULT hr = S_OK;
if( !m_Mc )
return E_POINTER;
hr = m_Mc->Pause();
return hr;
}
//-------------------------------------------------------------------------
// StopMovie
//-------------------------------------------------------------------------
HRESULT CMovie::StopMovie()
{
HRESULT hr = S_OK;
if( !m_Mc )
return E_POINTER;
hr = m_Mc->Stop();
return hr;
}
//-------------------------------------------------------------------------
// SeekToPosition
// seeks to specified media position
//-------------------------------------------------------------------------
BOOL CMovie::SeekToPosition(REFTIME rt, BOOL bFlushData)
{
HRESULT hr=S_OK;
LONGLONG llTime = LONGLONG( m_TimeFormat == TIME_FORMAT_MEDIA_TIME ? rt * double(UNITS) : rt );
if (m_Ms != NULL)
{
FILTER_STATE fs;
m_Mc->GetState(100, (OAFilterState *)&fs);
m_Ms->SetPositions(&llTime, AM_SEEKING_AbsolutePositioning, NULL, 0);
// This gets new data through to the renderers
if (fs == State_Stopped && bFlushData)
{
m_Mc->Pause();
hr = m_Mc->GetState(INFINITE, (OAFilterState *)&fs);
m_Mc->Stop();
}
if (SUCCEEDED(hr))
{
return TRUE;
}
}
return FALSE;
}
// "get" functions
//-------------------------------------------------------------------------
// GetDuration
// Returns the duration of the current movie
//-------------------------------------------------------------------------
REFTIME CMovie::GetDuration()
{
if( !m_Ms )
return 0;
HRESULT hr;
LONGLONG Duration;
if (m_TimeFormat != TIME_FORMAT_MEDIA_TIME)
{
hr = m_Ms->GetDuration(&Duration);
if (SUCCEEDED(hr))
{
return double(Duration);
}
}
else if (m_Ms != NULL)
{
hr = m_Ms->GetDuration(&Duration);
if (SUCCEEDED(hr))
{
return double(Duration) / UNITS;
}
}
return 0;
}
//-------------------------------------------------------------------------
// GetMovieEventHandle
// returns result of IMediaEvent::GetEventHandle()
//-------------------------------------------------------------------------
HANDLE CMovie::GetMovieEventHandle()
{
HRESULT hr;
if(m_Me != NULL)
{
if(m_MediaEvent == NULL)
{
hr = m_Me->GetEventHandle((OAEVENT *)&m_MediaEvent);
}
}
else
{
m_MediaEvent = NULL;
}
return m_MediaEvent;
}
//-------------------------------------------------------------------------
// GetMovieEventCode
// returns output of IMediaEvent::GetEvent()
//-------------------------------------------------------------------------
long CMovie::GetMovieEventCode()
{
HRESULT hr;
long lEventCode;
LONG_PTR lParam1, lParam2;
if (m_Me != NULL)
{
hr = m_Me->GetEvent(&lEventCode, &lParam1, &lParam2, 0);
if (SUCCEEDED(hr))
{
m_Me->FreeEventParams(lEventCode, lParam1, lParam2);
return lEventCode;
}
}
return 0L;
}
//-------------------------------------------------------------------------
// GetCurrentPosition
// returns current media position, in REFTIME
//-------------------------------------------------------------------------
REFTIME CMovie::GetCurrentPosition()
{
REFTIME rt = (REFTIME)0;
HRESULT hr;
LONGLONG Position;
if (m_TimeFormat != TIME_FORMAT_MEDIA_TIME)
{
hr = m_Ms->GetPositions(&Position, NULL);
if (SUCCEEDED(hr))
{
return double(Position);
}
}
else if (m_Ms != NULL)
{
hr = m_Ms->GetPositions(&Position, NULL);
if (SUCCEEDED(hr))
{
return double(Position) / UNITS;
}
}
return rt;
}
//-------------------------------------------------------------------------
// GetStateMovie
// returns state of IMediaControl of the movie (running, paused, or stopped)
//-------------------------------------------------------------------------
OAFilterState CMovie::GetStateMovie()
{
OAFilterState state = State_Running;
if( m_Mc )
{
m_Mc->GetState(3, &state);
}
return state;
}
// helper functions
//-------------------------------------------------------------------------
// FindInterfaceFromFilterGraph
//
// Useful function for finding specific filters - not 100% robust though
//-------------------------------------------------------------------------
HRESULT CMovie::FindInterfaceFromFilterGraph( REFIID iid, // interface to look for
LPVOID *lp )// place to return interface pointer in
{
IEnumFilters* pEF;
IBaseFilter* pFilter;
// Grab an enumerator for the filter graph.
HRESULT hr = m_Fg->EnumFilters(&pEF);
if (FAILED(hr))
return hr;
// Check out each filter.
while (pEF->Next(1, &pFilter, NULL) == S_OK)
{
hr = pFilter->QueryInterface(iid, lp);
pFilter->Release();
if (SUCCEEDED(hr))
{
break;
}
}
pEF->Release();
return hr;
}
BOOL CMovie::GetNativeMovieSize(LONG *cx, LONG *cy)
{
return TRUE;
}
//-------------------------------------------------------------------------
// IsFileASavedFG
// Checks if the requested media source is a saved GraphEdit datafile
//-------------------------------------------------------------------------
BOOL IsFileASavedFG( WCHAR* FileName )
{
BOOL fOK = FALSE;
HANDLE hf = CreateFileW(FileName, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
NULL);
if (hf != INVALID_HANDLE_VALUE)
{
DWORD data[2];
DWORD dwRead;
if (ReadFile(hf, data, sizeof(data), &dwRead, NULL) &&
dwRead == sizeof(data))
{
if (data[0] == 0xe011cfd0 && data[1] == 0xe11ab1a1)
{
fOK = TRUE;
}
}
CloseHandle(hf);
}
return fOK;
}
//
// CMovieList class implementation
//
//-------------------------------------------------------------------------
// constructor
//-------------------------------------------------------------------------
CMovieList::CMovieList()
: m_nsize(0)
, m_dwSelectedMovieID(NULL)
{
ZeroMemory( m_ppMovies, MaxNumberOfMovies * sizeof(CMovie*) );
m_rcDefaultTarget.left = m_rcDefaultTarget.top = 0;
m_rcDefaultTarget.right = 1024;
m_rcDefaultTarget.bottom = 768;
}
//-------------------------------------------------------------------------
// destructor
//-------------------------------------------------------------------------
CMovieList::~CMovieList()
{
}
//-------------------------------------------------------------------------
// GetDefaultTarget
// All the coordinate computation is performed for a fixed render target
// rectangle; At the moment of presenting image on the screen,
// coordinates are simly scaled according to current video window size
//-------------------------------------------------------------------------
RECT CMovieList::GetDefaultTarget()
{
return m_rcDefaultTarget;
}
//-------------------------------------------------------------------------
// SetDefaultTarget
// All the coordinate computation is performed for a fixed render target
// rectangle; At the moment of presenting image on the screen,
// coordinates are simly scaled according to current video window size
//-------------------------------------------------------------------------
void CMovieList::SetDefaultTarget( RECT rcDT)
{
m_rcDefaultTarget = rcDT;
}
//-------------------------------------------------------------------------
// GetMovie
// returns pointer to the movie with specified dwUserID, or NULL if such movie
// is not in the list
//-------------------------------------------------------------------------
CMovie * CMovieList::GetMovie( DWORD_PTR dwID )
{
CMovie *pres = NULL;
for( int i=0; i<m_nsize; i++)
{
if( m_ppMovies[i]->m_dwUserID == dwID )
{
pres = m_ppMovies[i];
break;
}
}
return pres;
}
//-------------------------------------------------------------------------
// GetMovieByIndex
// returns pointer to the movie that is n'th in the List, or NULL otherwise
//-------------------------------------------------------------------------
CMovie * CMovieList::GetMovieByIndex( int n )
{
CMovie *pres = NULL;
if( n > -1 && n < m_nsize )
{
pres = m_ppMovies[n];
}
return pres;
}
//-------------------------------------------------------------------------
// GetSelectedMovie
// returns pointer to the movie that is selected as "main channel"
//-------------------------------------------------------------------------
CMovie* CMovieList::GetSelectedMovie()
{
CMovie *pres = NULL;
for( int i=0; i<m_nsize; i++)
{
if( m_dwSelectedMovieID == m_ppMovies[i]->m_dwUserID )
{
pres = m_ppMovies[i];
break;
}
}
return pres;
}
//-------------------------------------------------------------------------
// GetMovieFromRTPoint
// returns pointer to the movie that contains point (xRT, yRT) in
// render target rectangle (See class declaration if not sure what is it)
//-------------------------------------------------------------------------
CMovie * CMovieList::GetMovieFromRTPoint( float xRT, float yRT)
{
CMovie *pmovie = NULL;
if( !( m_rcDefaultTarget.left <= xRT && xRT <= m_rcDefaultTarget.right ) ||
!( m_rcDefaultTarget.top <= yRT && yRT <= m_rcDefaultTarget.bottom ) )
{
return NULL;
}
for( int i=0; i<m_nsize; i++)
{
// check if the requested point is within any of CMovie::m_Vcur
if( m_ppMovies[i]->m_Vcur[0].x <= xRT && xRT <= m_ppMovies[i]->m_Vcur[1].x &&
m_ppMovies[i]->m_Vcur[0].y <= yRT && yRT <= m_ppMovies[i]->m_Vcur[2].y )
{
pmovie = m_ppMovies[i];
break;
}
}
return pmovie;
}
//-------------------------------------------------------------------------
// GetSelectedMovieID
// returns dwUserID of the selected movie
//-------------------------------------------------------------------------
DWORD_PTR CMovieList::GetSelectedMovieID()
{
return m_dwSelectedMovieID;
}
//-------------------------------------------------------------------------
// SelectMovie
// changes
//-------------------------------------------------------------------------
BOOL CMovieList::SelectMovie( DWORD_PTR pdwID)
{
CMovie *pres = NULL;
pres = GetMovie( pdwID);
if( !pres )
{
return FALSE;
}
else
{
m_dwSelectedMovieID = (DWORD) pres->m_dwUserID;
}
return TRUE;
}
//-------------------------------------------------------------------------
// Add
// adds new movie to the list
//-------------------------------------------------------------------------
BOOL CMovieList::Add( CMovie *pmovie)
{
/* if( m_nsize >= MaxNumberOfMovies )
{
return FALSE;
}
*/
m_ppMovies[m_nsize++] = pmovie;
if( 1 == m_nsize ) // first movie becomes selected by default
{
m_dwSelectedMovieID = (DWORD) pmovie->m_dwUserID;
}
return TRUE;
}
//-------------------------------------------------------------------------
// Delete
// deletes movie from the list
//-------------------------------------------------------------------------
BOOL CMovieList::Delete( DWORD_PTR dwID)
{
CMovie * pres = NULL;
BOOL bRes = FALSE;
int nIndex = -1;
for( int i=0; i<m_nsize; i++)
{
if( dwID == m_ppMovies[i]->m_dwUserID )
{
pres = m_ppMovies[i];
nIndex = i;
break;
}
}
if( pres )
{
if( m_nsize == 1 )
{
m_dwSelectedMovieID = NULL;
}
else if( pres->m_dwUserID == m_dwSelectedMovieID )
{
if( nIndex == m_nsize-1 )
{
m_dwSelectedMovieID = (DWORD) m_ppMovies[0]->m_dwUserID;
}
else
{
m_dwSelectedMovieID = (DWORD) m_ppMovies[nIndex+1]->m_dwUserID;
}
}
// delete pres;
for( int i = nIndex; i < m_nsize - 1; i++)
{
m_ppMovies[i] = m_ppMovies[i+1];
}
m_ppMovies[m_nsize-1] = NULL;
m_nsize--;
bRes = TRUE;
}
return bRes;
}
//-------------------------------------------------------------------------
// SortByZ
// sorts movies by z-order
//-------------------------------------------------------------------------
void CMovieList::SortByZ()
{
int i;
int j;
CMovie *pswap;
for( i=0; i<m_nsize-1; i++)
{
for( j=0; j<m_nsize-i-1; j++)
{
if( m_ppMovies[j]->m_fZ > m_ppMovies[j+1]->m_fZ )
{
pswap = m_ppMovies[j+1];
m_ppMovies[j+1] = m_ppMovies[j];
m_ppMovies[j] = pswap;
}
}
}
}
//-------------------------------------------------------------------------
// ActivateAll
// sets flag m_bUseInTheScene for all movies in the list
//-------------------------------------------------------------------------
void CMovieList::ActivateAll()
{
for( int i=0; i<m_nsize; i++)
{
m_ppMovies[i]->m_bUseInTheScene = TRUE;
}
}
//-------------------------------------------------------------------------
// RemoveDeletedMovies
// deletes all the movies singed to be deleted
//-------------------------------------------------------------------------
void CMovieList::RemoveDeletedMovies()
{
bool bContinue = true;
while( bContinue )
{
bContinue = false;
for( int i=0; i<m_nsize; i++)
{
if( m_ppMovies[i]->m_bDelete )
{
bContinue = true;
Delete( m_ppMovies[i]->m_dwUserID);
break;
}
}
}
}
| [
"Gmagic10@26f92a05-6149-0410-981d-7deb1f891687",
"gmagic10@26f92a05-6149-0410-981d-7deb1f891687"
] | [
[
[
1,
68
],
[
84,
172
],
[
207,
239
],
[
242,
274
],
[
276,
277
],
[
279,
282
],
[
284,
286
],
[
288,
849
],
[
851,
853
],
[
855,
901
],
[
903,
976
]
],
[
[
69,
83
],
[
173,
206
],
[
240,
241
],
[
275,
275
],
[
278,
278
],
[
283,
283
],
[
287,
287
],
[
850,
850
],
[
854,
854
],
[
902,
902
]
]
] |
512da0a05541c95ced62d855bce3bbf0fee16a05 | dadf8e6f3c1adef539a5ad409ce09726886182a7 | /airplay/h/TinyOpenEngine.App.h | 419895c1496842b9324c0bd4c729fbb72ffe2284 | [] | no_license | sarthakpandit/toe | 63f59ea09f2c1454c1270d55b3b4534feedc7ae3 | 196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b | refs/heads/master | 2021-01-10T04:04:45.575806 | 2011-06-09T12:56:05 | 2011-06-09T12:56:05 | 53,861,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | h | #pragma once
#include "toeApp.h"
namespace TinyOpenEngine
{
void toeAppInit();
void toeAppTerminate();
} | [
"[email protected]"
] | [
[
[
1,
8
]
]
] |
52049cd74b13d36f6f4be1b7594ceeaaff9d3519 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Depend/Foundation/Mathematics/Wm4LinComp2.h | ddd72422d54e6abfcbadf9280698fd6db8bed72a | [] | 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,584 | 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 WM4LINCOMP2_H
#define WM4LINCOMP2_H
#include "Wm4FoundationLIB.h"
#include "Wm4LinComp.h"
#include "Wm4Vector2.h"
namespace Wm4
{
template <class Real>
class LinComp2 : public LinComp<Real>
{
public:
// P is set to (0,0), D is set to (0,0), and [min,max] is set to
// [MAX_REAL,-MAX_REAL]. The type is CT_EMPTY.
LinComp2 ();
// P and D are specified. D must be unit length.
LinComp2 (const Vector2<Real>& rkOrigin, const Vector2<Real>& rkDirection,
Real fMin, Real fMax);
// copy constructor
LinComp2 (const LinComp2& rkComponent);
// assignment
LinComp2& operator= (const LinComp2& rkComponent);
virtual void MakeCanonical ();
Vector2<Real> Origin, Direction;
protected:
using LinComp<Real>::CT_EMPTY;
using LinComp<Real>::CT_POINT;
using LinComp<Real>::CT_SEGMENT;
using LinComp<Real>::CT_RAY;
using LinComp<Real>::CT_LINE;
using LinComp<Real>::m_iType;
using LinComp<Real>::m_fMin;
using LinComp<Real>::m_fMax;
};
#include "Wm4LinComp2.inl"
typedef LinComp2<float> LinComp2f;
typedef LinComp2<double> LinComp2d;
}
#endif
| [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
] | [
[
[
1,
61
]
]
] |
45d8de82bc69c873579ba7c63bcf3b47ecfc7b7a | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ClientShellDLL/ClientShellShared/ShellCasingFX.cpp | 783067ae476049b35a05b2237050cbb02fb34888 | [] | 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 | 10,821 | cpp | // ----------------------------------------------------------------------- //
//
// MODULE : SHELLCASINGFX.CPP
//
// PURPOSE : defines class for ejected shells
//
// CREATED : 5/1/98
//
// (c) 1998-2002 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
// Includes....
#include "stdafx.h"
#include "ShellCasingFX.h"
#include "iltclient.h"
#include "ltlink.h"
#include "ClientUtilities.h"
#include "WeaponMgr.h"
#include "GameClientShell.h"
#include "ClientWeaponUtils.h"
#include "SurfaceFunctions.h"
#include "VarTrack.h"
#include "FXButeMgr.h"
VarTrack g_vtShellMaxBounceCountTrack;
VarTrack g_vtShellMinUpVelocity;
VarTrack g_vtShellMaxUpVelocity;
VarTrack g_vtShellMinRightVelocity;
VarTrack g_vtShellMaxRightVelocity;
VarTrack g_vtShellMinForwardVelocity;
VarTrack g_vtShellMaxForwardVelocity;
VarTrack g_vtShellMinLifetime;
VarTrack g_vtShellMaxLifetime;
VarTrack g_vtShellScaleTime;
VarTrack g_vtShellMaxScale;
VarTrack g_vtShellMinSpinsPerSecond;
VarTrack g_vtShellMaxSpinsPerSecond;
#define MAX_BOUNCE_COUNT 3
extern PhysicsState g_normalPhysicsState;
extern PhysicsState g_waterPhysicsState;
//-------------------------------------------------------------------------
// Utility functions
//-------------------------------------------------------------------------
// this function will return a random value that can be used for a random
// pitch/yaw velocity
float GenerateRandomVelocity()
{
//find a random number between that range
float fRand = GetRandom(g_vtShellMinSpinsPerSecond.GetFloat(), g_vtShellMaxSpinsPerSecond.GetFloat());
//scale it to be either positive or negative
if(rand() % 2 == 0)
fRand = -fRand;
//now map it into rotations
return /*MATH_CIRCLE * */ fRand;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CShellCasingFX::CShellCasingFX
//
// PURPOSE: Initialize
//
// ----------------------------------------------------------------------- //
CShellCasingFX::CShellCasingFX()
{
m_rRot.Init();
m_vStartPos.Init();
m_vStartVel.Init();
m_nWeaponId = WMGR_INVALID_ID;
m_nAmmoId = WMGR_INVALID_ID;
m_b3rdPerson = LTFALSE;
m_fPitchVel = 0.0f;
m_fYawVel = 0.0f;
m_fPitch = 0.0f;
m_fYaw = 0.0f;
m_vInitialScale.Init(1.0f, 1.0f, 1.0f);
m_vFinalScale.Init(1.0f, 1.0f, 1.0f);
m_dwFlags = FLAG_VISIBLE; // | FLAG_NOLIGHT;
m_fDieTime = 15.0f;
m_bResting = LTFALSE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CShellCasingFX::Init
//
// PURPOSE: Create the shell casing
//
// ----------------------------------------------------------------------- //
LTBOOL CShellCasingFX::Init(SFXCREATESTRUCT* psfxCreateStruct)
{
if (!psfxCreateStruct) return LTFALSE;
CSpecialFX::Init(psfxCreateStruct);
SHELLCREATESTRUCT* pShell = (SHELLCREATESTRUCT*)psfxCreateStruct;
m_rRot = pShell->rRot;
m_vStartPos = pShell->vStartPos;
m_nWeaponId = pShell->nWeaponId;
m_nAmmoId = pShell->nAmmoId;
m_dwFlags |= pShell->dwFlags;
m_vStartVel = pShell->vStartVel;
m_b3rdPerson = pShell->b3rdPerson;
m_vInitialScale.Init(1.0f, 1.0f, 1.0f);
m_vFinalScale.Init(1.0f, 1.0f, 1.0f);
if (!g_vtShellMaxBounceCountTrack.IsInitted())
{
g_vtShellMaxBounceCountTrack.Init(g_pLTClient, "ShellMaxBounceCount", NULL, 3.0);
}
if (!g_vtShellMinUpVelocity.IsInitted())
{
g_vtShellMinUpVelocity.Init(g_pLTClient, "ShellMinUpVelocity", NULL, 30.0f);
}
if (!g_vtShellMaxUpVelocity.IsInitted())
{
g_vtShellMaxUpVelocity.Init(g_pLTClient, "ShellMaxUpVelocity", NULL, 75.0f);
}
if (!g_vtShellMinRightVelocity.IsInitted())
{
g_vtShellMinRightVelocity.Init(g_pLTClient, "ShellMinRightVelocity", NULL, 50.0f);
}
if (!g_vtShellMaxRightVelocity.IsInitted())
{
g_vtShellMaxRightVelocity.Init(g_pLTClient, "ShellMaxRightVelocity", NULL, 75.0f);
}
if (!g_vtShellMinForwardVelocity.IsInitted())
{
g_vtShellMinForwardVelocity.Init(g_pLTClient, "ShellMinForwardVelocity", NULL, 20.0f);
}
if (!g_vtShellMaxForwardVelocity.IsInitted())
{
g_vtShellMaxForwardVelocity.Init(g_pLTClient, "ShellMaxForwardVelocity", NULL, 50.0f);
}
if (!g_vtShellMinLifetime.IsInitted())
{
g_vtShellMinLifetime.Init(g_pLTClient, "ShellMinLifetime", NULL, 10.0f);
}
if (!g_vtShellMaxLifetime.IsInitted())
{
g_vtShellMaxLifetime.Init(g_pLTClient, "ShellMaxLifetime", NULL, 15.0f);
}
if (!g_vtShellScaleTime.IsInitted())
{
g_vtShellScaleTime.Init(g_pLTClient, "ShellScaleTime", NULL, 0.5f);
}
if (!g_vtShellMaxScale.IsInitted())
{
g_vtShellMaxScale.Init(g_pLTClient, "ShellMaxScale", NULL, 2.0f);
}
if (!g_vtShellMinSpinsPerSecond.IsInitted())
{
g_vtShellMinSpinsPerSecond.Init(g_pLTClient, "ShellMinSpinsPerSecond", NULL, 2.0f);
}
if (!g_vtShellMaxSpinsPerSecond.IsInitted())
{
g_vtShellMaxSpinsPerSecond.Init(g_pLTClient, "ShellMaxSpinsPerSecond", NULL, 10.0f);
}
m_nBounceCount = (int)g_vtShellMaxBounceCountTrack.GetFloat();
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CShellCasingFX::CreateObject
//
// PURPOSE: Create the model associated with the shell
//
// ----------------------------------------------------------------------- //
LTBOOL CShellCasingFX::CreateObject(ILTClient *pClientDE)
{
if (!CSpecialFX::CreateObject(pClientDE)) return LTFALSE;
// Setup the shell...
AMMO const *pAmmo = g_pWeaponMgr->GetAmmo(m_nAmmoId);
if (!pAmmo || !pAmmo->pFireFX) return LTFALSE;
ObjectCreateStruct createStruct;
INIT_OBJECTCREATESTRUCT(createStruct);
SAFE_STRCPY(createStruct.m_Filename, pAmmo->pFireFX->szShellModel);
SAFE_STRCPY(createStruct.m_SkinName, pAmmo->pFireFX->szShellSkin);
m_vInitialScale = pAmmo->pFireFX->vShellScale;
m_vFinalScale = (m_vInitialScale * g_vtShellMaxScale.GetFloat());
createStruct.m_ObjectType = OT_MODEL;
createStruct.m_Flags = m_dwFlags;
createStruct.m_Pos = m_vStartPos;
createStruct.m_Rotation = m_rRot;
m_hObject = m_pClientDE->CreateObject(&createStruct);
if (!m_hObject) return LTFALSE;
m_pClientDE->SetObjectScale(m_hObject, &m_vInitialScale);
// User camera rotation if not 3rd person ;)
if (!m_b3rdPerson)
{
g_pPlayerMgr->GetCameraRotation(m_rRot);
}
m_vStartVel += (m_rRot.Up() * GetRandom(g_vtShellMinUpVelocity.GetFloat(), g_vtShellMaxUpVelocity.GetFloat()));
m_vStartVel += (m_rRot.Right() * GetRandom(g_vtShellMinRightVelocity.GetFloat(), g_vtShellMaxRightVelocity.GetFloat()));
m_vStartVel += (m_rRot.Forward() * GetRandom(g_vtShellMinForwardVelocity.GetFloat(), g_vtShellMaxForwardVelocity.GetFloat()));
InitMovingObject(&m_movingObj, m_vStartPos, m_vStartVel);;
m_fElapsedTime = 0.0f;
m_fDieTime = GetRandom(g_vtShellMinLifetime.GetFloat(), g_vtShellMaxLifetime.GetFloat());
m_fPitchVel = GenerateRandomVelocity();
m_fYawVel = GenerateRandomVelocity();
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CShellCasingFX::Update
//
// PURPOSE: Update the shell
//
// ----------------------------------------------------------------------- //
LTBOOL CShellCasingFX::Update()
{
if (!m_hObject || !m_pClientDE) return LTFALSE;
if (g_pGameClientShell->IsServerPaused())
{
return LTTRUE;
}
m_fElapsedTime += g_pGameClientShell->GetFrameTime();
m_fDieTime -= g_pGameClientShell->GetFrameTime();
if (m_fDieTime <= 0.0f) return LTFALSE;
// Update object scale if necessary...
LTVector vScale;
m_pClientDE->GetObjectScale(m_hObject, &vScale);
if (vScale != m_vFinalScale)
{
if (m_fElapsedTime <= g_vtShellScaleTime.GetFloat())
{
LTVector vScaleRange = (m_vFinalScale - m_vInitialScale);
vScale = m_vInitialScale + (vScaleRange * (m_fElapsedTime/g_vtShellScaleTime.GetFloat()));
if (vScale > m_vFinalScale)
{
vScale = m_vFinalScale;
}
m_pClientDE->SetObjectScale(m_hObject, &vScale);
}
else
{
m_pClientDE->SetObjectScale(m_hObject, &m_vFinalScale);
}
}
if (m_bResting) return LTTRUE;
LTRotation rRot;
g_pLTClient->GetObjectRotation(m_hObject, &rRot);
// If velocity slows enough, and we're on the ground, just stop bouncing and just wait to expire.
if (m_movingObj.m_dwPhysicsFlags & MO_RESTING)
{
m_bResting = LTTRUE;
// Stop the spinning...
rRot.Rotate(rRot.Up(), m_fYaw);
g_pLTClient->SetObjectRotation(m_hObject, &rRot);
// Shell is at rest, we can add a check here to see if we really want
// to keep it around depending on detail settings...
//HLOCALOBJ hObjs[1];
//uint32 nNumFound, nBogus;
//m_pClientDE->FindObjectsInSphere(&m_movingObj.m_vPos, 64.0f, hObjs, 1, &nBogus, &nNumFound);
// Remove thyself...
//if (nNumFound > 15) return LTFALSE;
}
else
{
if (m_fPitchVel != 0 || m_fYawVel != 0)
{
LTFLOAT fDeltaTime = g_pGameClientShell->GetFrameTime();
m_fPitch += m_fPitchVel * fDeltaTime;
m_fYaw += m_fYawVel * fDeltaTime;
rRot.Rotate(rRot.Up(), m_fYaw);
rRot.Rotate(rRot.Right(), m_fPitch);
g_pLTClient->SetObjectRotation(m_hObject, &rRot);
}
}
LTVector vNewPos;
if (UpdateMovingObject(LTNULL, &m_movingObj, vNewPos))
{
ClientIntersectInfo info;
LTBOOL bBouncedOnGround = LTFALSE;
if (BounceMovingObject(LTNULL, &m_movingObj, vNewPos, &info,
INTERSECT_HPOLY, true, bBouncedOnGround))
{
// If we hit the sky/invisible surface we're done...
SurfaceType eType = GetSurfaceType(info);
if (eType == ST_SKY || eType == ST_INVISIBLE)
{
return LTFALSE;
}
if (m_nBounceCount >= MAX_BOUNCE_COUNT)
{
if (!(m_movingObj.m_dwPhysicsFlags & MO_LIQUID))
{
SURFACE* pSurf = g_pSurfaceMgr->GetSurface(eType);
if (pSurf)
{
// Play appropriate sound...
if (pSurf->szShellImpactSnds[0])
{
g_pClientSoundMgr->PlaySoundFromPos(vNewPos, pSurf->szShellImpactSnds[0], pSurf->fShellSndRadius,
SOUNDPRIORITY_MISC_LOW);
}
}
}
}
// Adjust the bouncing..
m_fPitchVel *= 0.75f;
m_fYawVel *= -0.75f;
m_nBounceCount--;
if (m_nBounceCount <= 0)
{
m_movingObj.m_dwPhysicsFlags |= MO_RESTING;
}
}
m_movingObj.m_vPos = vNewPos;
if (g_pCommonLT->GetPointStatus(&vNewPos) == LT_OUTSIDE)
{
return LTFALSE;
}
g_pLTClient->SetObjectPos(m_hObject, &vNewPos);
}
return LTTRUE;
} | [
"[email protected]"
] | [
[
[
1,
389
]
]
] |
571b530c5eb6898890e27eea6f39cc7e7e742976 | eec70a1718c685c0dbabeee59eb7267bfaece58c | /Sense Management Irrlicht AI/Path.cpp | b913f99b099d57a1f302d2dc31a3f4bc12e864ce | [] | no_license | mohaider/sense-management-irrlicht-ai | 003939ee770ab32ff7ef3f5f5c1b77943a4c7489 | c5ef02f478d00a4957a294254fc4f3920037bd7a | refs/heads/master | 2020-12-24T14:44:38.254964 | 2011-05-19T14:29:53 | 2011-05-19T14:29:53 | 32,393,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55 | cpp | #include "Path.h"
void Path::Render() const
{
} | [
"[email protected]@2228f7ce-bb98-ac94-67a7-be962254a327"
] | [
[
[
1,
6
]
]
] |
bbbf2f3283f0fc2b4cbd5839e761755a04681536 | 037faae47a5b22d3e283555e6b5ac2a0197faf18 | /pcsx2/x86/ix86-32/iCore-32.cpp | 7bf2fd17e4ec4866a4cc2ef7933429595db2aa73 | [] | no_license | isabella232/pcsx2-sourceforge | 6e5aac8d0b476601bfc8fa83ded66c1564b8c588 | dbb2c3a010081b105a8cba0c588f1e8f4e4505c6 | refs/heads/master | 2023-03-18T22:23:15.102593 | 2008-11-17T20:10:17 | 2008-11-17T20:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,834 | cpp | /* Pcsx2 - Pc Ps2 Emulator
* Copyright (C) 2002-2008 Pcsx2 Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <malloc.h>
extern "C" {
#include "PS2Etypes.h"
#if defined(_WIN32)
#include <windows.h>
#endif
#include "System.h"
#include "R5900.h"
#include "Vif.h"
#include "VU.h"
#include "ix86/ix86.h"
#include "iCore.h"
#include "R3000A.h"
u16 x86FpuState, iCWstate;
u16 g_mmxAllocCounter = 0;
// used to make sure regs don't get changed while in recompiler
// use FreezeMMXRegs, FreezeXMMRegs
u8 g_globalMMXSaved = 0;
#ifdef _DEBUG
char g_globalMMXLocked = 0;
#endif
PCSX2_ALIGNED16(u64 g_globalMMXData[8]);
// X86 caching
extern _x86regs x86regs[X86REGS];
int g_x86checknext;
extern u16 g_x86AllocCounter;
} // end extern "C"
#include <vector>
using namespace std;
// use special x86 register allocation for ia32
#ifndef __x86_64__
void _initX86regs() {
memset(x86regs, 0, sizeof(x86regs));
g_x86AllocCounter = 0;
g_x86checknext = 0;
}
u32 _x86GetAddr(int type, int reg)
{
switch(type&~X86TYPE_VU1) {
case X86TYPE_GPR: return (u32)&cpuRegs.GPR.r[reg];
case X86TYPE_VI: {
//assert( reg < 16 || reg == REG_R );
return (type&X86TYPE_VU1)?(u32)&VU1.VI[reg]:(u32)&VU0.VI[reg];
}
case X86TYPE_MEMOFFSET: return 0;
case X86TYPE_VIMEMOFFSET: return 0;
case X86TYPE_VUQREAD: return (type&X86TYPE_VU1)?(u32)&VU1.VI[REG_Q]:(u32)&VU0.VI[REG_Q];
case X86TYPE_VUPREAD: return (type&X86TYPE_VU1)?(u32)&VU1.VI[REG_P]:(u32)&VU0.VI[REG_P];
case X86TYPE_VUQWRITE: return (type&X86TYPE_VU1)?(u32)&VU1.q:(u32)&VU0.q;
case X86TYPE_VUPWRITE: return (type&X86TYPE_VU1)?(u32)&VU1.p:(u32)&VU0.p;
case X86TYPE_PSX: return (u32)&psxRegs.GPR.r[reg];
case X86TYPE_PCWRITEBACK:
return (u32)&g_recWriteback;
case X86TYPE_VUJUMP:
return (u32)&g_recWriteback;
default: assert(0);
}
return 0;
}
int _getFreeX86reg(int mode)
{
int i, tempi;
u32 bestcount = 0x10000;
int maxreg = (mode&MODE_8BITREG)?4:X86REGS;
for (i=0; i<X86REGS; i++) {
int reg = (g_x86checknext+i)%X86REGS;
if( reg == 0 || reg == ESP ) continue;
if( reg >= maxreg ) continue;
if( (mode&MODE_NOFRAME) && reg==EBP ) continue;
if (x86regs[reg].inuse == 0) {
g_x86checknext = (reg+1)%X86REGS;
return reg;
}
}
tempi = -1;
for (i=1; i<maxreg; i++) {
if( i == ESP ) continue;
if( (mode&MODE_NOFRAME) && i==EBP ) continue;
if (x86regs[i].needed) continue;
if (x86regs[i].type != X86TYPE_TEMP) {
if( x86regs[i].counter < bestcount ) {
tempi = i;
bestcount = x86regs[i].counter;
}
continue;
}
_freeX86reg(i);
return i;
}
if( tempi != -1 ) {
_freeX86reg(tempi);
return tempi;
}
SysPrintf("*PCSX2*: x86 error\n");
assert(0);
return -1;
}
int _allocX86reg(int x86reg, int type, int reg, int mode)
{
int i;
assert( reg >= 0 && reg < 32 );
// if( X86_ISVI(type) )
// assert( reg < 16 || reg == REG_R );
// don't alloc EAX and ESP,EBP if MODE_NOFRAME
int oldmode = mode;
int noframe = mode&MODE_NOFRAME;
int maxreg = (mode&MODE_8BITREG)?4:X86REGS;
mode &= ~(MODE_NOFRAME|MODE_8BITREG);
int readfromreg = -1;
if( type != X86TYPE_TEMP ) {
if( maxreg < X86REGS ) {
// make sure reg isn't in the higher regs
for(i = maxreg; i < X86REGS; ++i) {
if (!x86regs[i].inuse || x86regs[i].type != type || x86regs[i].reg != reg) continue;
if( mode & MODE_READ ) {
readfromreg = i;
x86regs[i].inuse = 0;
break;
}
else if( mode & MODE_WRITE ) {
x86regs[i].inuse = 0;
break;
}
}
}
for (i=1; i<maxreg; i++) {
if( i == ESP ) continue;
if (!x86regs[i].inuse || x86regs[i].type != type || x86regs[i].reg != reg) continue;
if( (noframe && i == EBP) || (i >= maxreg) ) {
if( x86regs[i].mode & MODE_READ )
readfromreg = i;
//if( xmmregs[i].mode & MODE_WRITE ) mode |= MODE_WRITE;
mode |= x86regs[i].mode&MODE_WRITE;
x86regs[i].inuse = 0;
break;
}
if( x86reg >= 0 ) {
// requested specific reg, so return that instead
if( i != x86reg ) {
if( x86regs[i].mode & MODE_READ ) readfromreg = i;
//if( x86regs[i].mode & MODE_WRITE ) mode |= MODE_WRITE;
mode |= x86regs[i].mode&MODE_WRITE;
x86regs[i].inuse = 0;
break;
}
}
if( type != X86TYPE_TEMP && !(x86regs[i].mode & MODE_READ) && (mode&MODE_READ)) {
if( type == X86TYPE_GPR ) _flushConstReg(reg);
if( X86_ISVI(type) && reg < 16 ) MOVZX32M16toR(i, _x86GetAddr(type, reg));
else MOV32MtoR(i, _x86GetAddr(type, reg));
x86regs[i].mode |= MODE_READ;
}
x86regs[i].needed = 1;
x86regs[i].mode|= mode;
return i;
}
}
if (x86reg == -1) {
x86reg = _getFreeX86reg(oldmode);
}
else {
_freeX86reg(x86reg);
}
x86regs[x86reg].type = type;
x86regs[x86reg].reg = reg;
x86regs[x86reg].mode = mode;
x86regs[x86reg].needed = 1;
x86regs[x86reg].inuse = 1;
if( mode & MODE_READ ) {
if( readfromreg >= 0 ) MOV32RtoR(x86reg, readfromreg);
else {
if( type == X86TYPE_GPR ) {
if( reg == 0 ) {
XOR32RtoR(x86reg, x86reg);
}
else {
_flushConstReg(reg);
_deleteMMXreg(MMX_GPR+reg, 1);
_deleteGPRtoXMMreg(reg, 1);
_eeMoveGPRtoR(x86reg, reg);
_deleteMMXreg(MMX_GPR+reg, 0);
_deleteGPRtoXMMreg(reg, 0);
}
}
else {
if( X86_ISVI(type) && reg < 16 ) {
if( reg == 0 ) XOR32RtoR(x86reg, x86reg);
else MOVZX32M16toR(x86reg, _x86GetAddr(type, reg));
}
else MOV32MtoR(x86reg, _x86GetAddr(type, reg));
}
}
}
return x86reg;
}
int _checkX86reg(int type, int reg, int mode)
{
int i;
for (i=0; i<X86REGS; i++) {
if (x86regs[i].inuse && x86regs[i].reg == reg && x86regs[i].type == type) {
if( !(x86regs[i].mode & MODE_READ) && (mode&MODE_READ) ) {
if( X86_ISVI(type) ) MOVZX32M16toR(i, _x86GetAddr(type, reg));
else MOV32MtoR(i, _x86GetAddr(type, reg));
}
x86regs[i].mode |= mode;
x86regs[i].counter = g_x86AllocCounter++;
x86regs[i].needed = 1;
return i;
}
}
return -1;
}
void _addNeededX86reg(int type, int reg)
{
int i;
for (i=0; i<X86REGS; i++) {
if (!x86regs[i].inuse || x86regs[i].reg != reg || x86regs[i].type != type ) continue;
x86regs[i].counter = g_x86AllocCounter++;
x86regs[i].needed = 1;
}
}
void _clearNeededX86regs() {
int i;
for (i=0; i<X86REGS; i++) {
if (x86regs[i].needed ) {
if( x86regs[i].inuse && (x86regs[i].mode&MODE_WRITE) )
x86regs[i].mode |= MODE_READ;
}
x86regs[i].needed = 0;
}
}
void _deleteX86reg(int type, int reg, int flush)
{
int i;
for (i=0; i<X86REGS; i++) {
if (x86regs[i].inuse && x86regs[i].reg == reg && x86regs[i].type == type) {
switch(flush) {
case 0:
_freeX86reg(i);
break;
case 1:
if( x86regs[i].mode & MODE_WRITE) {
if( X86_ISVI(type) && x86regs[i].reg < 16 ) MOV16RtoM(_x86GetAddr(type, x86regs[i].reg), i);
else MOV32RtoM(_x86GetAddr(type, x86regs[i].reg), i);
// get rid of MODE_WRITE since don't want to flush again
x86regs[i].mode &= ~MODE_WRITE;
x86regs[i].mode |= MODE_READ;
}
return;
case 2:
x86regs[i].inuse = 0;
break;
}
}
}
}
void _freeX86reg(int x86reg)
{
assert( x86reg >= 0 && x86reg < X86REGS );
if( x86regs[x86reg].inuse && (x86regs[x86reg].mode&MODE_WRITE) ) {
x86regs[x86reg].mode &= ~MODE_WRITE;
if( X86_ISVI(x86regs[x86reg].type) && x86regs[x86reg].reg < 16 ) {
MOV16RtoM(_x86GetAddr(x86regs[x86reg].type, x86regs[x86reg].reg), x86reg);
}
else
MOV32RtoM(_x86GetAddr(x86regs[x86reg].type, x86regs[x86reg].reg), x86reg);
}
x86regs[x86reg].inuse = 0;
}
void _freeX86regs() {
int i;
for (i=0; i<X86REGS; i++) {
if (!x86regs[i].inuse) continue;
_freeX86reg(i);
}
}
#endif // __x86_64__
// MMX Caching
_mmxregs mmxregs[8], s_saveMMXregs[8];
static int s_mmxchecknext = 0;
void _initMMXregs()
{
memset(mmxregs, 0, sizeof(mmxregs));
g_mmxAllocCounter = 0;
s_mmxchecknext = 0;
}
__forceinline void* _MMXGetAddr(int reg)
{
assert( reg != MMX_TEMP );
if( reg == MMX_LO ) return &cpuRegs.LO;
if( reg == MMX_HI ) return &cpuRegs.HI;
if( reg == MMX_FPUACC ) return &fpuRegs.ACC;
if( reg >= MMX_GPR && reg < MMX_GPR+32 ) return &cpuRegs.GPR.r[reg&31];
if( reg >= MMX_FPU && reg < MMX_FPU+32 ) return &fpuRegs.fpr[reg&31];
if( reg >= MMX_COP0 && reg < MMX_COP0+32 ) return &cpuRegs.CP0.r[reg&31];
assert( 0 );
return NULL;
}
int _getFreeMMXreg()
{
int i, tempi;
u32 bestcount = 0x10000;
for (i=0; i<MMXREGS; i++) {
if (mmxregs[(s_mmxchecknext+i)%MMXREGS].inuse == 0) {
int ret = (s_mmxchecknext+i)%MMXREGS;
s_mmxchecknext = (s_mmxchecknext+i+1)%MMXREGS;
return ret;
}
}
// check for dead regs
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].needed) continue;
if (mmxregs[i].reg >= MMX_GPR && mmxregs[i].reg < MMX_GPR+34 ) {
if( !(g_pCurInstInfo->regs[mmxregs[i].reg-MMX_GPR] & (EEINST_LIVE0|EEINST_LIVE1)) ) {
_freeMMXreg(i);
return i;
}
if( !(g_pCurInstInfo->regs[mmxregs[i].reg-MMX_GPR]&EEINST_USED) ) {
_freeMMXreg(i);
return i;
}
}
}
// check for future xmm usage
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].needed) continue;
if (mmxregs[i].reg >= MMX_GPR && mmxregs[i].reg < MMX_GPR+34 ) {
if( !(g_pCurInstInfo->regs[mmxregs[i].reg] & EEINST_MMX) ) {
_freeMMXreg(i);
return i;
}
}
}
tempi = -1;
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].needed) continue;
if (mmxregs[i].reg != MMX_TEMP) {
if( mmxregs[i].counter < bestcount ) {
tempi = i;
bestcount = mmxregs[i].counter;
}
continue;
}
_freeMMXreg(i);
return i;
}
if( tempi != -1 ) {
_freeMMXreg(tempi);
return tempi;
}
SysPrintf("*PCSX2*: mmx error\n");
assert(0);
return -1;
}
int _allocMMXreg(int mmxreg, int reg, int mode)
{
int i;
if( reg != MMX_TEMP ) {
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].inuse == 0 || mmxregs[i].reg != reg ) continue;
if( MMX_ISGPR(reg)) {
assert( _checkXMMreg(XMMTYPE_GPRREG, reg-MMX_GPR, 0) == -1 );
}
mmxregs[i].needed = 1;
if( !(mmxregs[i].mode & MODE_READ) && (mode&MODE_READ) && reg != MMX_TEMP ) {
SetMMXstate();
if( reg == MMX_GPR ) {
// moving in 0s
PXORRtoR(i, i);
}
else {
if( MMX_ISGPR(reg) ) _flushConstReg(reg-MMX_GPR);
if( (mode & MODE_READHALF) || (MMX_IS32BITS(reg)&&(mode&MODE_READ)) )
MOVDMtoMMX(i, (u32)_MMXGetAddr(reg));
else {
MOVQMtoR(i, (u32)_MMXGetAddr(reg));
}
}
mmxregs[i].mode |= MODE_READ;
}
mmxregs[i].counter = g_mmxAllocCounter++;
mmxregs[i].mode|= mode;
return i;
}
}
if (mmxreg == -1) {
mmxreg = _getFreeMMXreg();
}
mmxregs[mmxreg].inuse = 1;
mmxregs[mmxreg].reg = reg;
mmxregs[mmxreg].mode = mode&~MODE_READHALF;
mmxregs[mmxreg].needed = 1;
mmxregs[mmxreg].counter = g_mmxAllocCounter++;
SetMMXstate();
if( reg == MMX_GPR ) {
// moving in 0s
PXORRtoR(mmxreg, mmxreg);
}
else {
int xmmreg;
if( MMX_ISGPR(reg) && (xmmreg = _checkXMMreg(XMMTYPE_GPRREG, reg-MMX_GPR, 0)) >= 0 ) {
if (cpucaps.hasStreamingSIMD2Extensions) {
SSE_MOVHPS_XMM_to_M64((u32)_MMXGetAddr(reg)+8, xmmreg);
if( mode & MODE_READ )
SSE2_MOVDQ2Q_XMM_to_MM(mmxreg, xmmreg);
if( xmmregs[xmmreg].mode & MODE_WRITE )
mmxregs[mmxreg].mode |= MODE_WRITE;
// don't flush
xmmregs[xmmreg].inuse = 0;
}
else {
_freeXMMreg(xmmreg);
if( (mode & MODE_READHALF) || (MMX_IS32BITS(reg)&&(mode&MODE_READ)) ) {
MOVDMtoMMX(mmxreg, (u32)_MMXGetAddr(reg));
}
else if( mode & MODE_READ ) {
MOVQMtoR(mmxreg, (u32)_MMXGetAddr(reg));
}
}
}
else {
if( MMX_ISGPR(reg) ) {
if(mode&(MODE_READHALF|MODE_READ)) _flushConstReg(reg-MMX_GPR);
}
if( (mode & MODE_READHALF) || (MMX_IS32BITS(reg)&&(mode&MODE_READ)) ) {
MOVDMtoMMX(mmxreg, (u32)_MMXGetAddr(reg));
}
else if( mode & MODE_READ ) {
MOVQMtoR(mmxreg, (u32)_MMXGetAddr(reg));
}
}
}
return mmxreg;
}
int _checkMMXreg(int reg, int mode)
{
int i;
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].inuse && mmxregs[i].reg == reg ) {
if( !(mmxregs[i].mode & MODE_READ) && (mode&MODE_READ) ) {
if( reg == MMX_GPR ) {
// moving in 0s
PXORRtoR(i, i);
}
else {
if( MMX_ISGPR(reg) && (mode&(MODE_READHALF|MODE_READ)) ) _flushConstReg(reg-MMX_GPR);
if( (mode & MODE_READHALF) || (MMX_IS32BITS(reg)&&(mode&MODE_READ)) )
MOVDMtoMMX(i, (u32)_MMXGetAddr(reg));
else
MOVQMtoR(i, (u32)_MMXGetAddr(reg));
}
SetMMXstate();
}
mmxregs[i].mode |= mode;
mmxregs[i].counter = g_mmxAllocCounter++;
mmxregs[i].needed = 1;
return i;
}
}
return -1;
}
void _addNeededMMXreg(int reg)
{
int i;
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].inuse == 0) continue;
if (mmxregs[i].reg != reg) continue;
mmxregs[i].counter = g_mmxAllocCounter++;
mmxregs[i].needed = 1;
}
}
void _clearNeededMMXregs()
{
int i;
for (i=0; i<MMXREGS; i++) {
if( mmxregs[i].needed ) {
// setup read to any just written regs
if( mmxregs[i].inuse && (mmxregs[i].mode&MODE_WRITE) )
mmxregs[i].mode |= MODE_READ;
mmxregs[i].needed = 0;
}
}
}
// when flush is 0 - frees all of the reg, when flush is 1, flushes all of the reg, when
// it is 2, just stops using the reg (no flushing)
void _deleteMMXreg(int reg, int flush)
{
int i;
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].inuse && mmxregs[i].reg == reg ) {
switch(flush) {
case 0:
_freeMMXreg(i);
break;
case 1:
if( mmxregs[i].mode & MODE_WRITE) {
assert( mmxregs[i].reg != MMX_GPR );
if( MMX_IS32BITS(reg) )
MOVDMMXtoM((u32)_MMXGetAddr(mmxregs[i].reg), i);
else
MOVQRtoM((u32)_MMXGetAddr(mmxregs[i].reg), i);
SetMMXstate();
// get rid of MODE_WRITE since don't want to flush again
mmxregs[i].mode &= ~MODE_WRITE;
mmxregs[i].mode |= MODE_READ;
}
return;
case 2:
mmxregs[i].inuse = 0;
break;
}
return;
}
}
}
int _getNumMMXwrite()
{
int num = 0, i;
for (i=0; i<MMXREGS; i++) {
if( mmxregs[i].inuse && (mmxregs[i].mode&MODE_WRITE) ) ++num;
}
return num;
}
u8 _hasFreeMMXreg()
{
int i;
for (i=0; i<MMXREGS; i++) {
if (!mmxregs[i].inuse) return 1;
}
// check for dead regs
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].needed) continue;
if (mmxregs[i].reg >= MMX_GPR && mmxregs[i].reg < MMX_GPR+34 ) {
if( !EEINST_ISLIVE64(mmxregs[i].reg-MMX_GPR) ) {
return 1;
}
}
}
// check for dead regs
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].needed) continue;
if (mmxregs[i].reg >= MMX_GPR && mmxregs[i].reg < MMX_GPR+34 ) {
if( !(g_pCurInstInfo->regs[mmxregs[i].reg-MMX_GPR]&EEINST_USED) ) {
return 1;
}
}
}
return 0;
}
void _freeMMXreg(int mmxreg)
{
assert( mmxreg < MMXREGS );
if (!mmxregs[mmxreg].inuse) return;
if (mmxregs[mmxreg].mode & MODE_WRITE ) {
if( mmxregs[mmxreg].reg >= MMX_GPR && mmxregs[mmxreg].reg < MMX_GPR+32 )
assert( !(g_cpuHasConstReg & (1<<(mmxregs[mmxreg].reg-MMX_GPR))) );
assert( mmxregs[mmxreg].reg != MMX_GPR );
if( MMX_IS32BITS(mmxregs[mmxreg].reg) )
MOVDMMXtoM((u32)_MMXGetAddr(mmxregs[mmxreg].reg), mmxreg);
else
MOVQRtoM((u32)_MMXGetAddr(mmxregs[mmxreg].reg), mmxreg);
SetMMXstate();
}
mmxregs[mmxreg].mode &= ~MODE_WRITE;
mmxregs[mmxreg].inuse = 0;
}
void _moveMMXreg(int mmxreg)
{
int i;
if( !mmxregs[mmxreg].inuse ) return;
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].inuse) continue;
break;
}
if( i == MMXREGS ) {
_freeMMXreg(mmxreg);
return;
}
// move
mmxregs[i] = mmxregs[mmxreg];
mmxregs[mmxreg].inuse = 0;
MOVQRtoR(i, mmxreg);
}
// write all active regs
void _flushMMXregs()
{
int i;
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].inuse == 0) continue;
if( mmxregs[i].mode & MODE_WRITE ) {
assert( !(g_cpuHasConstReg & (1<<mmxregs[i].reg)) );
assert( mmxregs[i].reg != MMX_TEMP );
assert( mmxregs[i].mode & MODE_READ );
assert( mmxregs[i].reg != MMX_GPR );
if( MMX_IS32BITS(mmxregs[i].reg) )
MOVDMMXtoM((u32)_MMXGetAddr(mmxregs[i].reg), i);
else
MOVQRtoM((u32)_MMXGetAddr(mmxregs[i].reg), i);
SetMMXstate();
mmxregs[i].mode &= ~MODE_WRITE;
mmxregs[i].mode |= MODE_READ;
}
}
}
void _freeMMXregs()
{
int i;
for (i=0; i<MMXREGS; i++) {
if (mmxregs[i].inuse == 0) continue;
assert( mmxregs[i].reg != MMX_TEMP );
assert( mmxregs[i].mode & MODE_READ );
_freeMMXreg(i);
}
}
void FreezeMMXRegs_(int save)
{
assert( g_EEFreezeRegs );
if( save ) {
if( g_globalMMXSaved ){
//SysPrintf("MMX Already Saved!\n");
return;
}
g_globalMMXSaved = 1;
#ifdef _MSC_VER
__asm {
movntq mmword ptr [g_globalMMXData + 0], mm0
movntq mmword ptr [g_globalMMXData + 8], mm1
movntq mmword ptr [g_globalMMXData + 16], mm2
movntq mmword ptr [g_globalMMXData + 24], mm3
movntq mmword ptr [g_globalMMXData + 32], mm4
movntq mmword ptr [g_globalMMXData + 40], mm5
movntq mmword ptr [g_globalMMXData + 48], mm6
movntq mmword ptr [g_globalMMXData + 56], mm7
emms
}
#else
__asm__(".intel_syntax\n"
"movq [%0+0x00], %%mm0\n"
"movq [%0+0x08], %%mm1\n"
"movq [%0+0x10], %%mm2\n"
"movq [%0+0x18], %%mm3\n"
"movq [%0+0x20], %%mm4\n"
"movq [%0+0x28], %%mm5\n"
"movq [%0+0x30], %%mm6\n"
"movq [%0+0x38], %%mm7\n"
"emms\n"
".att_syntax\n" : : "r"(g_globalMMXData) );
#endif
}
else {
if( !g_globalMMXSaved ){
//SysPrintf("MMX Not Saved!\n");
return;
}
g_globalMMXSaved = 0;
#ifdef _MSC_VER
__asm {
movq mm0, mmword ptr [g_globalMMXData + 0]
movq mm1, mmword ptr [g_globalMMXData + 8]
movq mm2, mmword ptr [g_globalMMXData + 16]
movq mm3, mmword ptr [g_globalMMXData + 24]
movq mm4, mmword ptr [g_globalMMXData + 32]
movq mm5, mmword ptr [g_globalMMXData + 40]
movq mm6, mmword ptr [g_globalMMXData + 48]
movq mm7, mmword ptr [g_globalMMXData + 56]
emms
}
#else
__asm__(".intel_syntax\n"
"movq %%mm0, [%0+0x00]\n"
"movq %%mm1, [%0+0x08]\n"
"movq %%mm2, [%0+0x10]\n"
"movq %%mm3, [%0+0x18]\n"
"movq %%mm4, [%0+0x20]\n"
"movq %%mm5, [%0+0x28]\n"
"movq %%mm6, [%0+0x30]\n"
"movq %%mm7, [%0+0x38]\n"
"emms\n"
".att_syntax\n" : : "r"(g_globalMMXData) );
#endif
}
}
void SetFPUstate() {
_freeMMXreg(6);
_freeMMXreg(7);
if (x86FpuState==MMX_STATE) {
if (cpucaps.has3DNOWInstructionExtensions) FEMMS();
else EMMS();
x86FpuState=FPU_STATE;
}
}
void _callPushArg(u32 arg, uptr argmem, x86IntRegType X86ARG)
{
if( IS_X86REG(arg) ) PUSH32R(arg&0xff);
else if( IS_CONSTREG(arg) ) PUSH32I(argmem);
else if( IS_GPRREG(arg) ) {
SUB32ItoR(ESP, 4);
_eeMoveGPRtoRm(ESP, arg&0xff);
}
else if( IS_XMMREG(arg) ) {
SUB32ItoR(ESP, 4);
SSEX_MOVD_XMM_to_Rm(ESP, arg&0xf);
}
else if( IS_MMXREG(arg) ) {
SUB32ItoR(ESP, 4);
MOVD32MMXtoRm(ESP, arg&0xf);
}
else if( IS_EECONSTREG(arg) ) {
PUSH32I(g_cpuConstRegs[(arg>>16)&0x1f].UL[0]);
}
else if( IS_PSXCONSTREG(arg) ) {
PUSH32I(g_psxConstRegs[(arg>>16)&0x1f]);
}
else if( IS_MEMORYREG(arg) ) PUSH32M(argmem);
else {
assert( (arg&0xfff0) == 0 );
// assume it is a GPR reg
PUSH32R(arg&0xf);
}
}
void _callFunctionArg1(uptr fn, u32 arg1, uptr arg1mem)
{
_callPushArg(arg1, arg1mem, -1);
CALLFunc((uptr)fn);
ADD32ItoR(ESP, 4);
}
void _callFunctionArg2(uptr fn, u32 arg1, u32 arg2, uptr arg1mem, uptr arg2mem)
{
_callPushArg(arg2, arg2mem, -1);
_callPushArg(arg1, arg1mem, -1);
CALLFunc((uptr)fn);
ADD32ItoR(ESP, 8);
}
void _callFunctionArg3(uptr fn, u32 arg1, u32 arg2, u32 arg3, uptr arg1mem, uptr arg2mem, uptr arg3mem)
{
_callPushArg(arg3, arg3mem, -1);
_callPushArg(arg2, arg2mem, -1);
_callPushArg(arg1, arg1mem, -1);
CALLFunc((uptr)fn);
ADD32ItoR(ESP, 12);
}
// EE
void _eeMoveGPRtoR(x86IntRegType to, int fromgpr)
{
if( GPR_IS_CONST1(fromgpr) )
MOV32ItoR( to, g_cpuConstRegs[fromgpr].UL[0] );
else {
int mmreg;
if( (mmreg = _checkXMMreg(XMMTYPE_GPRREG, fromgpr, MODE_READ)) >= 0 && (xmmregs[mmreg].mode&MODE_WRITE)) {
SSE2_MOVD_XMM_to_R(to, mmreg);
}
else if( (mmreg = _checkMMXreg(MMX_GPR+fromgpr, MODE_READ)) >= 0 && (mmxregs[mmreg].mode&MODE_WRITE) ) {
MOVD32MMXtoR(to, mmreg);
SetMMXstate();
}
else {
MOV32MtoR(to, (int)&cpuRegs.GPR.r[ fromgpr ].UL[ 0 ] );
}
}
}
void _eeMoveGPRtoM(u32 to, int fromgpr)
{
if( GPR_IS_CONST1(fromgpr) )
MOV32ItoM( to, g_cpuConstRegs[fromgpr].UL[0] );
else {
int mmreg;
if( (mmreg = _checkXMMreg(XMMTYPE_GPRREG, fromgpr, MODE_READ)) >= 0 ) {
SSEX_MOVD_XMM_to_M32(to, mmreg);
}
else if( (mmreg = _checkMMXreg(MMX_GPR+fromgpr, MODE_READ)) >= 0 ) {
MOVDMMXtoM(to, mmreg);
SetMMXstate();
}
else {
MOV32MtoR(EAX, (int)&cpuRegs.GPR.r[ fromgpr ].UL[ 0 ] );
MOV32RtoM(to, EAX );
}
}
}
void _eeMoveGPRtoRm(x86IntRegType to, int fromgpr)
{
if( GPR_IS_CONST1(fromgpr) )
MOV32ItoRmOffset( to, g_cpuConstRegs[fromgpr].UL[0], 0 );
else {
int mmreg;
if( (mmreg = _checkXMMreg(XMMTYPE_GPRREG, fromgpr, MODE_READ)) >= 0 ) {
SSEX_MOVD_XMM_to_Rm(to, mmreg);
}
else if( (mmreg = _checkMMXreg(MMX_GPR+fromgpr, MODE_READ)) >= 0 ) {
MOVD32MMXtoRm(to, mmreg);
SetMMXstate();
}
else {
MOV32MtoR(EAX, (int)&cpuRegs.GPR.r[ fromgpr ].UL[ 0 ] );
MOV32RtoRm(to, EAX );
}
}
}
void _recPushReg(int mmreg)
{
if( IS_XMMREG(mmreg) ) {
SUB32ItoR(ESP, 4);
SSEX_MOVD_XMM_to_Rm(ESP, mmreg&0xf);
}
else if( IS_MMXREG(mmreg) ) {
SUB32ItoR(ESP, 4);
MOVD32MMXtoRm(ESP, mmreg&0xf);
}
else if( IS_EECONSTREG(mmreg) ) {
PUSH32I(g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0]);
}
else if( IS_PSXCONSTREG(mmreg) ) {
PUSH32I(g_psxConstRegs[(mmreg>>16)&0x1f]);
}
else {
assert( (mmreg&0xfff0) == 0 );
PUSH32R(mmreg);
}
}
void _signExtendSFtoM(u32 mem)
{
LAHF();
SAR16ItoR(EAX, 15);
CWDE();
MOV32RtoM(mem, EAX );
}
int _signExtendMtoMMX(x86MMXRegType to, u32 mem)
{
int t0reg = _allocMMXreg(-1, MMX_TEMP, 0);
MOVDMtoMMX(t0reg, mem);
MOVQRtoR(to, t0reg);
PSRADItoR(t0reg, 31);
PUNPCKLDQRtoR(to, t0reg);
_freeMMXreg(t0reg);
return to;
}
int _signExtendGPRMMXtoMMX(x86MMXRegType to, u32 gprreg, x86MMXRegType from, u32 gprfromreg)
{
assert( to >= 0 && from >= 0 );
if( !EEINST_ISLIVE1(gprreg) ) {
EEINST_RESETHASLIVE1(gprreg);
if( to != from ) MOVQRtoR(to, from);
return to;
}
if( to == from ) return _signExtendGPRtoMMX(to, gprreg, 0);
if( !(g_pCurInstInfo->regs[gprfromreg]&EEINST_LASTUSE) ) {
if( EEINST_ISLIVE64(gprfromreg) ) {
MOVQRtoR(to, from);
return _signExtendGPRtoMMX(to, gprreg, 0);
}
}
// from is free for use
SetMMXstate();
if( g_pCurInstInfo->regs[gprreg] & EEINST_MMX ) {
if( EEINST_ISLIVE64(gprfromreg) ) {
_freeMMXreg(from);
}
MOVQRtoR(to, from);
PSRADItoR(from, 31);
PUNPCKLDQRtoR(to, from);
return to;
}
else {
MOVQRtoR(to, from);
MOVDMMXtoM((u32)&cpuRegs.GPR.r[gprreg].UL[0], from);
PSRADItoR(from, 31);
MOVDMMXtoM((u32)&cpuRegs.GPR.r[gprreg].UL[1], from);
mmxregs[to].inuse = 0;
return -1;
}
assert(0);
}
int _signExtendGPRtoMMX(x86MMXRegType to, u32 gprreg, int shift)
{
assert( to >= 0 && shift >= 0 );
if( !EEINST_ISLIVE1(gprreg) ) {
if( shift > 0 ) PSRADItoR(to, shift);
EEINST_RESETHASLIVE1(gprreg);
return to;
}
SetMMXstate();
if( g_pCurInstInfo->regs[gprreg] & EEINST_MMX ) {
if( _hasFreeMMXreg() ) {
int t0reg = _allocMMXreg(-1, MMX_TEMP, 0);
MOVQRtoR(t0reg, to);
PSRADItoR(to, 31);
if( shift > 0 ) PSRADItoR(t0reg, shift);
PUNPCKLDQRtoR(t0reg, to);
// swap mmx regs.. don't ask
mmxregs[t0reg] = mmxregs[to];
mmxregs[to].inuse = 0;
return t0reg;
}
else {
// will be used in the future as mmx
if( shift > 0 ) PSRADItoR(to, shift);
MOVDMMXtoM((u32)&cpuRegs.GPR.r[gprreg].UL[0], to);
PSRADItoR(to, 31);
MOVDMMXtoM((u32)&cpuRegs.GPR.r[gprreg].UL[1], to);
// read again
MOVQMtoR(to, (u32)&cpuRegs.GPR.r[gprreg].UL[0]);
mmxregs[to].mode &= ~MODE_WRITE;
return to;
}
}
else {
if( shift > 0 ) PSRADItoR(to, shift);
MOVDMMXtoM((u32)&cpuRegs.GPR.r[gprreg].UL[0], to);
PSRADItoR(to, 31);
MOVDMMXtoM((u32)&cpuRegs.GPR.r[gprreg].UL[1], to);
mmxregs[to].inuse = 0;
return -1;
}
assert(0);
}
int _allocCheckGPRtoMMX(EEINST* pinst, int reg, int mode)
{
if( pinst->regs[reg] & EEINST_MMX ) return _allocMMXreg(-1, MMX_GPR+reg, mode);
return _checkMMXreg(MMX_GPR+reg, mode);
}
void _recMove128MtoM(u32 to, u32 from)
{
MOV32MtoR(EAX, from);
MOV32MtoR(EDX, from+4);
MOV32RtoM(to, EAX);
MOV32RtoM(to+4, EDX);
MOV32MtoR(EAX, from+8);
MOV32MtoR(EDX, from+12);
MOV32RtoM(to+8, EAX);
MOV32RtoM(to+12, EDX);
}
void _recMove128RmOffsettoM(u32 to, u32 offset)
{
MOV32RmtoROffset(EAX, ECX, offset);
MOV32RmtoROffset(EDX, ECX, offset+4);
MOV32RtoM(to, EAX);
MOV32RtoM(to+4, EDX);
MOV32RmtoROffset(EAX, ECX, offset+8);
MOV32RmtoROffset(EDX, ECX, offset+12);
MOV32RtoM(to+8, EAX);
MOV32RtoM(to+12, EDX);
}
void _recMove128MtoRmOffset(u32 offset, u32 from)
{
MOV32MtoR(EAX, from);
MOV32MtoR(EDX, from+4);
MOV32RtoRmOffset(ECX, EAX, offset);
MOV32RtoRmOffset(ECX, EDX, offset+4);
MOV32MtoR(EAX, from+8);
MOV32MtoR(EDX, from+12);
MOV32RtoRmOffset(ECX, EAX, offset+8);
MOV32RtoRmOffset(ECX, EDX, offset+12);
}
static PCSX2_ALIGNED16(u32 s_ones[2]) = {0xffffffff, 0xffffffff};
void LogicalOpRtoR(x86MMXRegType to, x86MMXRegType from, int op)
{
switch(op) {
case 0: PANDRtoR(to, from); break;
case 1: PORRtoR(to, from); break;
case 2: PXORRtoR(to, from); break;
case 3:
PORRtoR(to, from);
PXORMtoR(to, (u32)&s_ones[0]);
break;
}
}
void LogicalOpMtoR(x86MMXRegType to, u32 from, int op)
{
switch(op) {
case 0: PANDMtoR(to, from); break;
case 1: PORMtoR(to, from); break;
case 2: PXORMtoR(to, from); break;
case 3:
PORRtoR(to, from);
PXORMtoR(to, (u32)&s_ones[0]);
break;
}
}
void LogicalOp32RtoM(u32 to, x86IntRegType from, int op)
{
switch(op) {
case 0: AND32RtoM(to, from); break;
case 1: OR32RtoM(to, from); break;
case 2: XOR32RtoM(to, from); break;
case 3: OR32RtoM(to, from); break;
}
}
void LogicalOp32MtoR(x86IntRegType to, u32 from, int op)
{
switch(op) {
case 0: AND32MtoR(to, from); break;
case 1: OR32MtoR(to, from); break;
case 2: XOR32MtoR(to, from); break;
case 3: OR32MtoR(to, from); break;
}
}
void LogicalOp32ItoR(x86IntRegType to, u32 from, int op)
{
switch(op) {
case 0: AND32ItoR(to, from); break;
case 1: OR32ItoR(to, from); break;
case 2: XOR32ItoR(to, from); break;
case 3: OR32ItoR(to, from); break;
}
}
void LogicalOp32ItoM(u32 to, u32 from, int op)
{
switch(op) {
case 0: AND32ItoM(to, from); break;
case 1: OR32ItoM(to, from); break;
case 2: XOR32ItoM(to, from); break;
case 3: OR32ItoM(to, from); break;
}
}
| [
"gigaherz@23c756db-88ba-2448-99d7-e6e4c676ec84",
"zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84",
"refractionpcsx2@23c756db-88ba-2448-99d7-e6e4c676ec84"
] | [
[
[
1,
17
]
],
[
[
18,
788
],
[
790,
791
],
[
793,
822
],
[
824,
825
],
[
827,
1227
]
],
[
[
789,
789
],
[
792,
792
],
[
823,
823
],
[
826,
826
]
]
] |
85eda698588b2d6b796f8cd9b2e32ad2a0251354 | a7a890e753c6f69e8067d16a8cd94ce8327f80b7 | /bClient/Tutorial4.cpp | 31437994ec6b2ef678607aaf520c3f98218022b0 | [] | no_license | jbreslin33/breslinservergame | 684ca8b97f36e265f30ae65e1a65435b2e7a3d8b | 292285f002661c3d9483fb080845564145d47999 | refs/heads/master | 2021-01-21T13:11:50.223394 | 2011-03-14T11:33:30 | 2011-03-14T11:33:30 | 37,391,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,378 | cpp | //#include "Tutorial4.h"
#include "common.h"
#include "ClientSinbadCharacterController.h"
CArmyWar* game;
bool keys[256];
void CArmyWar::createPlayer(int index)
{
/*
Ogre::Entity* NinjaEntity = mSceneMgr->createEntity("ninja.mesh");
//Ogre::Entity* ogreHead = mSceneMgr->createEntity("Head", "ogrehead.mesh");
Ogre::SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode();
node->attachObject(NinjaEntity);
//node->setPosition(Ogre::Vector3(10, 10, 10));
*/
clientData *client = game->GetClientPointer(index);
//client->character->mSceneMgr->getCamera();
client->character = new SinbadCharacterController(mSceneMgr->getCamera("PlayerCam"), "Sinbad" + index);
//client->myNode = node;
}
//-------------------------------------------------------------------------------------
void CArmyWar::createScene(void)
{
mSceneMgr->setAmbientLight(Ogre::ColourValue(0.75, 0.75, 0.75));
Ogre::Light* pointLight = mSceneMgr->createLight("pointLight");
pointLight->setType(Ogre::Light::LT_POINT);
pointLight->setPosition(Ogre::Vector3(250, 150, 250));
pointLight->setDiffuseColour(Ogre::ColourValue::White);
pointLight->setSpecularColour(Ogre::ColourValue::White);
}
//-------------------------------------------------------------------------------------
bool CArmyWar::processUnbufferedInput(const Ogre::FrameEvent& evt)
{
//LogString("processUnbufferedInput");
if (mKeyboard->isKeyDown(OIS::KC_I)) // Forward
{
//LogString("isKeyDown");
keys[VK_UP] = TRUE;
//localClient->character->simulateKeyDown(OIS::KC_I);
}
else
{
keys[VK_UP] = FALSE;
}
if (mKeyboard->isKeyDown(OIS::KC_K)) // Backward
{
keys[VK_DOWN] = TRUE;
}
else
{
keys[VK_DOWN] = FALSE;
}
if (mKeyboard->isKeyDown(OIS::KC_J)) // Left - yaw or strafe
{
keys[VK_LEFT] = TRUE;
}
else
{
keys[VK_LEFT] = FALSE;
}
if (mKeyboard->isKeyDown(OIS::KC_L)) // Right - yaw or strafe
{
keys[VK_RIGHT] = TRUE;
}
else
{
keys[VK_RIGHT] = FALSE;
}
return true;
}
//-------------------------------------------------------------------------------------
bool CArmyWar::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
//LogString("frameRenderingQueued");
bool ret = BaseApplication::frameRenderingQueued(evt);
if (localClient)
localClient->character->addTime(evt.timeSinceLastFrame);
//if(!processUnbufferedInput(evt)) return false;
if(game != NULL)
{
game->RunNetwork(evt.timeSinceLastFrame * 1000);
game->CheckKeys();
//game->Frame();
}
return ret;
}
bool CArmyWar::keyPressed(const OIS::KeyEvent& evt)
{
LogString("keyPressed");
//BaseApplication::keyPressed(evt);
// relay input events to character controller
//if (!mTrayMgr->isDialogVisible())
//mChara->injectKeyDown(evt);
localClient->character->injectKeyDown(evt);
//return BaseApplication::keyPressed(evt);
return 1;
}
bool CArmyWar::keyReleased(const OIS::KeyEvent& evt)
{
// relay input events to character controller
//if (!mTrayMgr->isDialogVisible())
//mChara->injectKeyUp(evt);
localClient->character->injectKeyUp(evt);
//return BaseApplication::keyReleased(evt);
return 1;
}
//-------------------------------------------------------------------------------------
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{
// Create application object
game = new CArmyWar;
//game = new CArmyWar;
game->StartConnection();
StartLogConsole();
try {
game->go();
} catch( Ogre::Exception& e ) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occured: " <<
e.getFullDescription().c_str() << std::endl;
#endif
}
return 0;
}
#ifdef __cplusplus
}
#endif | [
"jbreslin33@localhost"
] | [
[
[
1,
169
]
]
] |
bdbabb2a44e74e86359c29af8c7aa425fbc31cfc | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/Effect.cpp | aa5754e087582530c56b842feb9e60a64cbed286 | [] | 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 | 49 | cpp | #include <Halak/PCH.h>
#include <Halak/Effect.h> | [
"[email protected]"
] | [
[
[
1,
2
]
]
] |
127af631ca1d507328b070e5c92a023dc3d72765 | 93eac58e092f4e2a34034b8f14dcf847496d8a94 | /ncl30-cpp/ncl30-generator/include/generables/CausalConnectorGenerator.h | 6eb0eedddac433dc79454e2085e9446be45adcc9 | [] | no_license | lince/ginga-srpp | f8154049c7e287573f10c472944315c1c7e9f378 | 5dce1f7cded43ef8486d2d1a71ab7878c8f120b4 | refs/heads/master | 2020-05-27T07:54:24.324156 | 2011-10-17T13:59:11 | 2011-10-17T13:59:11 | 2,576,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,972 | h | /******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
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:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
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:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
*******************************************************************************/
/**
* @file CausalConnectorGenerator.h
* @author Caio Viel
* @date 29-01-10
*/
#ifndef _CAUSALCONNECTORGENERATOR_H
#define _CAUSALCONNECTORGENERATOR_H
#include <vector>
#include "ncl/connectors/CausalConnector.h"
using namespace ::br::pucrio::telemidia::ncl::connectors;
#include "Generable.h"
#include "ParameterGenerator.h"
#include "SimpleConditionGenerator.h"
#include "CompoundConditionGenerator.h"
#include "SimpleActionGenerator.h"
#include "CompoundActionGenerator.h"
namespace br {
namespace ufscar {
namespace lince {
namespace ncl {
namespace generator {
class CausalConnectorGenerator : public CausalConnector {
public:
/**
* Gera o código XML da entidade NCL CausalConnector.
* @return Uma string contendo o código NCL gerado.
*/
string generateCode();
};
}
}
}
}
}
#endif /* _CAUSALCONNECTORGENERATOR_H */
| [
"[email protected]"
] | [
[
[
1,
95
]
]
] |
e380222757e43fc1b15c2ddd1177f1be121f0b12 | 011400d5f1831c3771a3c15768a0a7509eb64b55 | /Plugins/DXSystemEx/DXSystemEx/Utils/VersionCheck.cpp | 51881ba3f0db8956486808d2d780da6f3751f43d | [] | no_license | lineCode/desktopx | 9d8bbb66ceabe8784725d4fa6960523f91e6e961 | 9d939bf1fbdccfa70c7d81246cf7b984e87f53f3 | refs/heads/master | 2021-05-27T15:28:08.371707 | 2011-10-01T16:14:32 | 2011-10-01T16:14:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,981 | cpp | ///////////////////////////////////////////////////////////////////////////////////////////////
//
// DXSystemEx - Extended System Information
//
// Copyright (c) 2009-2011, Julien Templier
// All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <windows.h>
#include "VersionCheck.h"
BOOL Is_WinVista_or_Later()
{
OSVERSIONINFOEX osvi;
DWORDLONG dwlConditionMask = 0;
// Initialize the OSVERSIONINFOEX structure.
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = 6;
// Initialize the condition mask.
VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
// Perform the test.
return VerifyVersionInfo(&osvi, VER_MAJORVERSION, dwlConditionMask);
}
BOOL Is_Win7()
{
OSVERSIONINFOEX osvi;
DWORDLONG dwlConditionMask = 0;
// Initialize the OSVERSIONINFOEX structure.
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = 6;
osvi.dwMinorVersion = 1;
// Initialize the condition mask.
VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION|VER_MINORVERSION, VER_EQUAL);
// Perform the test.
return VerifyVersionInfo(&osvi, VER_MAJORVERSION|VER_MINORVERSION, dwlConditionMask);
}
| [
"none@none",
"[email protected]"
] | [
[
[
1,
4
],
[
6,
70
]
],
[
[
5,
5
]
]
] |
a822081b87f3513f142f1fc409c7386620374eb4 | a2ba072a87ab830f5343022ed11b4ac365f58ef0 | / urt-bumpy-q3map2 --username [email protected]/libs/container/hashtable.cpp | bcad750d5fa0d2d4dc1004675a2434816866c871 | [] | no_license | Garey27/urt-bumpy-q3map2 | 7d0849fc8eb333d9007213b641138e8517aa092a | fcc567a04facada74f60306c01e68f410cb5a111 | refs/heads/master | 2021-01-10T17:24:51.991794 | 2010-06-22T13:19:24 | 2010-06-22T13:19:24 | 43,057,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 957 | cpp |
#include "hashtable.h"
#if defined(_DEBUG) || defined(DOXYGEN)
#include "hashfunc.h"
namespace ExampleHashTable
{
void testStuff()
{
// HashTable example
typedef HashTable<CopiedString, int, HashString> MyHashTable;
MyHashTable hashtable;
hashtable["bleh"] = 5;
hashtable.insert("blah", 17);
hashtable["foo"] = 99;
hashtable.insert("bar", 23);
int bleh = (*hashtable.find("bleh")).value; // 5
int blah = hashtable["blah"]; // 17
hashtable.erase("foo");
MyHashTable::iterator barIter = hashtable.find("bar");
hashtable.erase(barIter);
for(MyHashTable::iterator i = hashtable.begin(); i != hashtable.end(); ++i)
{
if((*i).key != "bleh")
{
++hashtable["count"]; // insertion does not invalidate iterators
}
}
// end example
}
struct Always
{
Always()
{
testStuff();
}
} always;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
45
]
]
] |
b2d98b36d93a3123c78b5f0f714e6cf2acd7bb59 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Network/Objects/Obj.h | 022d126e611f2d255bb7d2fea41ad2f3ad942f44 | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UHC | C++ | false | false | 39,225 | h | #ifndef __OBJ_H__
#define __OBJ_H__
#pragma once
#include <d3dx9math.h>
#include "Define.h"
#include "Data.h"
#include "Ar.h"
#include <string>
#include <map>
using namespace std;
#include "SkillInfluence.h"
#include "UserTaskBar.h"
#if defined(__DBSERVER) || defined(__VPW)
#include "..\DatabaseServer\Project.h"
extern CProject prj;
#endif //__DBSERVER || __VPW
#if defined(__DBSERVER)
#include "dbmanager.h"
#endif //
#ifdef __RT_1025
#include "rtmessenger.h"
#else // __RT_1025
#include "messenger.h"
#endif // __RT_1025
#ifdef __BUFF_1107
#include "buff.h"
#endif // __BUFF_1107
#if __VER >= 9 // __PET_0410
#include "pet.h"
#endif // __PET_0410
#include "Piercing.h"
typedef DWORD OBJID;
#define ITYPE_ITEM 0
#define ITYPE_CARD 1
#define ITYPE_CUBE 2
#define ITYPE_PET 3
#define MAX_INVENTORY 42
enum
{
METHOD_NONE, METHOD_EXCLUDE_ITEM
};
#if __VER >= 10 // __LEGEND // 10차 전승시스템 Neuz, World, Trans
#define MAX_SKILL_JOB ( MAX_JOB_SKILL + MAX_EXPERT_SKILL + MAX_PRO_SKILL + MAX_MASTER_SKILL + MAX_HERO_SKILL )
#else //__LEGEND // 10차 전승시스템 Neuz, World, Trans
#define MAX_SKILL_JOB ( MAX_JOB_SKILL + MAX_EXPERT_SKILL + MAX_PRO_SKILL )
#endif //__LEGEND // 10차 전승시스템 Neuz, World, Trans
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
class CObj
{
public:
DWORD m_dwType;
DWORD m_dwIndex;
D3DXVECTOR3 m_vScale;
DWORD m_dwMotion;
D3DXVECTOR3 m_vPos;
FLOAT m_fAngle;
public:
// Constructions
CObj();
virtual ~CObj() {}
// Operations
virtual void Serialize( CAr & ar );
public:
static int m_nMethod;
static int GetMethod( void ) { return m_nMethod; }
#ifdef __LAYER_1015
protected:
int m_nLayer;
public:
void SetLayer( int nLayer ) { m_nLayer = nLayer; }
int GetLayer() { return m_nLayer; }
#endif // __LAYER_1015
};
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
class CCtrl : public CObj
{
public:
OBJID m_objid;
public:
// Constructions
CCtrl();
virtual ~CCtrl() {}
// Operations
void SetId( OBJID objid ) { m_objid = objid; }
OBJID GetId( void ) { return m_objid; }
virtual void Serialize( CAr & ar );
};
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
class CItemBase
{
public:
OBJID m_dwObjId ; // 아이템 컨테이너에서 몇번째
DWORD m_dwItemId; // IID_ 값
TCHAR m_szItemText[ 32 ];
DWORD m_dwObjIndex; // 인벤토리에서 몇번째
private:
SERIALNUMBER m_liSerialNumber;
public:
// Constructions
CItemBase();
virtual ~CItemBase() {}
// Operations
BOOL IsEmpty() { return m_dwItemId ? FALSE : TRUE; }
virtual void Empty()
{
m_szItemText[0] = '\0';
m_dwItemId = 0;
}
virtual CItemBase& operator = ( CItemBase & ib );
virtual void Serialize( CAr & ar );
SERIALNUMBER GetSerialNumber( void ) { return m_liSerialNumber; }
void SetSerialNumber( SERIALNUMBER liSerialNumber ) { m_liSerialNumber = liSerialNumber; }
};
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
class CItemElem : public CItemBase
{
private:
CPiercing m_piercing;
public:
void SetPiercingSize( int nSize ) { m_piercing.SetPiercingSize( nSize ); }
int GetPiercingSize() { return m_piercing.GetPiercingSize(); }
void SetPiercingItem( int nth, DWORD dwItem) { m_piercing.SetPiercingItem( nth, dwItem ); }
DWORD GetPiercingItem( int nth ) { return m_piercing.GetPiercingItem( nth ); }
void CopyPiercing( const CPiercing & piercing ) { m_piercing = piercing; }
void SerializePiercing( CAr & ar ) { m_piercing.Serialize( ar ); }
BOOL IsPiercedItem() { return m_piercing.IsPiercedItem(); }
#ifdef __DBSERVER
#if __VER >= 12 // __EXT_PIERCING
void SetUltimatePiercingSize( int nSize ) { m_piercing.SetUltimatePiercingSize( nSize ); }
int GetUltimatePiercingSize() { return m_piercing.GetUltimatePiercingSize(); }
void SetUltimatePiercingItem( int nth, DWORD dwItem ) { m_piercing.SetUltimatePiercingItem( nth, dwItem ); }
DWORD GetUltimatePiercingItem( int nth ) { return m_piercing.GetUltimatePiercingItem( nth ); }
ItemProp* GetProp() { return prj.GetItemProp( m_dwItemId ); }
BOOL IsPierceAble( DWORD dwTargetItemKind3 = NULL_ID, BOOL bSize = FALSE );
#endif // __EXT_PIERCING
#endif // __DBSERVER
private:
int m_nAbilityOption;
public:
enum { expired = 0x01, binds = 0x02, };
int m_nRepair;
BYTE m_nRepairNumber;
BYTE m_byFlag;
short m_nItemNum;
int m_nHitPoint;
DWORD m_idGuild;
BYTE m_bItemResist; // 어느 속성 인가?
int m_nResistAbilityOption; // 속성 추가 능력치 가변 옵션
int m_nResistSMItemId;
// PIERCINGINFO m_piercingInfo;
BOOL m_bCharged; // 상용화 아이템인지 확인
DWORD m_dwKeepTime; // 지속시간
#if __VER >= 11 // __SYS_IDENTIFY
// 비트별 연산
// 12|12|16|16|8 = 64
private:
__int64 m_iRandomOptItemId;
public:
__int64 GetRandomOptItemId( void ) { return m_iRandomOptItemId; }
void SetRandomOptItemId( __int64 iRandomOptItemId ) { m_iRandomOptItemId = iRandomOptItemId; }
int GetRandomOpt( void ) { return static_cast<int>( m_iRandomOptItemId & 0x00000000000000FF ); }
#else // __SYS_IDENTIFY
private:
int m_nRandomOptItemId;
public:
int GetRandomOptItemId( void ) { return m_nRandomOptItemId; }
void SetRandomOptItemId( int nRandomOptItemId ) { m_nRandomOptItemId = nRandomOptItemId; }
int GetRandomOpt( void ) { return m_nRandomOptItemId; }
#endif // __SYS_IDENTIFY
#if __VER >= 9 // __PET_0410
CPet* m_pPet;
#endif // __PET_0410
public:
// Constructions
CItemElem();
virtual ~CItemElem();
// Operations
int GetOption( void ) { return m_nAbilityOption; }
void SetOption( int nOption ) { m_nAbilityOption = nOption; }
BOOL IsFlag( BYTE byFlag ) { return ( m_byFlag & byFlag ) ? TRUE : FALSE; }
BOOL IsInvalid( void );
virtual void Empty()
{
CItemBase::Empty();
#if __VER >= 9
SAFE_DELETE( m_pPet );
#endif // __PET_0410
}
virtual CItemElem& operator = ( CItemElem & ie );
virtual void Serialize( CAr & ar );
#ifdef __DBSERVER
#if __VER >= 15 // __PETVIS
BOOL IsVisPet() { return ( GetProp() && GetProp()->IsVisPet() ) || IsTransformVisPet() ; }
void SetVisKeepTimeSize( int nSize ) { m_piercing.SetVisKeepTimeSize( nSize ); }
void SetVisKeepTime( int nth, time_t tmKeep ) { m_piercing.SetVisKeepTime( nth, tmKeep ); }
time_t GetVisKeepTime( int nth ) { return m_piercing.GetVisKeepTime( nth ); }
BOOL IsTransformVisPet() { return GetProp() && GetProp()->dwItemKind3 == IK3_PET && m_bTranformVisPet; }
BOOL m_bTranformVisPet;
#endif // __PETVIS
#endif // __DBSERVER
};
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
typedef struct tagSKILL
{
DWORD dwSkill;
DWORD dwLevel;
void Init() {};
}
SKILL, *LPSKILL;
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
template <class T> class CItemContainer
{
public:
LPDWORD m_apIndex;
DWORD m_dwIndexNum;
T* m_apItem;
DWORD m_dwItemMax;
public:
// Constructions
CItemContainer();
// CItemContainer( DWORD dwItemType, DWORD dwItemMax, DWORD dwExtra = 0xffffffff );
virtual ~CItemContainer();
// Operations
void Clear();
void SetItemContainer( DWORD dwItemType, DWORD dwItemMax, DWORD dwExtra = 0xffffffff );
// T* Add( DWORD dwItemId );
BOOL Add( T* pElem, BYTE* pnId = NULL, short* pnNum = NULL, BYTE* pnCount = NULL );
#if __VER >= 11 // __SYS_IDENTIFY
#ifdef __SEND_ITEM_ULTIMATE
BOOL Add( DWORD dwItemId, short nNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist = 0, int nResistAbilityOption = 0, BYTE* pnId = NULL, short* pnNum = NULL, BYTE* pnCount = NULL, BOOL bCharged = FALSE, int nPiercedSize = 0, DWORD dwItemId0 = 0, DWORD dwItemId1 = 0, DWORD dwItemId2 = 0, DWORD dwItemId3 = 0, DWORD dwItemId4 = 0, DWORD dwKeepTime = 0, __int64 iRandomOptItemId = 0 );
#else // __SEND_ITEM_ULTIMATE
BOOL Add( DWORD dwItemId, short nNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist = 0, int nResistAbilityOption = 0, BYTE* pnId = NULL, short* pnNum = NULL, BYTE* pnCount = NULL, BOOL bCharged = FALSE, int nPiercedSize = 0, DWORD dwItemId0 = 0, DWORD dwItemId1 = 0, DWORD dwItemId2 = 0, DWORD dwItemId3 = 0, DWORD dwKeepTime = 0, __int64 iRandomOptItemId = 0 );
#endif // __SEND_ITEM_ULTIMATE
#else // __SYS_IDENTIFY
#ifdef __SEND_ITEM_ULTIMATE
BOOL Add( DWORD dwItemId, short nNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist = 0, int nResistAbilityOption = 0, BYTE* pnId = NULL, short* pnNum = NULL, BYTE* pnCount = NULL, BOOL bCharged = FALSE, int nPiercedSize = 0, DWORD dwItemId0 = 0, DWORD dwItemId1 = 0, DWORD dwItemId2 = 0, DWORD dwItemId3 = 0, DWORD dwItemId4 = 0, DWORD dwKeepTime = 0, int nRandomOptItemId = 0 );
#else // __SEND_ITEM_ULTIMATE
BOOL Add( DWORD dwItemId, short nNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist = 0, int nResistAbilityOption = 0, BYTE* pnId = NULL, short* pnNum = NULL, BYTE* pnCount = NULL, BOOL bCharged = FALSE, int nPiercedSize = 0, DWORD dwItemId0 = 0, DWORD dwItemId1 = 0, DWORD dwItemId2 = 0, DWORD dwItemId3 = 0, DWORD dwKeepTime = 0, int nRandomOptItemId = 0 );
#endif // __SEND_ITEM_ULTIMATE
#endif // __SYS_IDENTIFY
BOOL IsFull( ItemProp* pItemProp, short nNum, BOOL bCharged );
T* GetAt( DWORD dwIndex );
T* GetAtId( OBJID dwObjId );
T* GetItem( ItemProp * pItemProp, int nAbilityOption );
T* GetItem( ItemProp * pItemProp, int nAbilityOption, int nItemResist, int nResistAbilityOption );
BOOL IsEquip( DWORD dwObjId );
void RemoveAt( DWORD dwIndex );
void RemoveAtId( OBJID dwObjId );
T* GetEquip( DWORD dwIndex );
BOOL UnEquip( DWORD dwIndex );
void DoEquip( DWORD dwSrcIndex, DWORD dwDstIndex );
void Copy( CItemContainer<T> & rItemContainer );
void Serialize( CAr & ar );
};
template <class T> CItemContainer<T>::CItemContainer()
{
m_apItem = NULL;
m_apIndex = NULL;
}
/*
template <class T> CItemContainer<T>::CItemContainer( DWORD dwItemType, DWORD dwItemMax, DWORD dwExtra )
{
m_apItem = NULL;
m_apIndex = NULL;
SetItemContainer( dwItemType, dwItemMax, dwExtra );
}
*/
template <class T> CItemContainer<T>::~CItemContainer()
{
SAFE_DELETE_ARRAY( m_apItem );
SAFE_DELETE_ARRAY( m_apIndex );
}
template <class T> void CItemContainer<T>::Clear()
{
for( DWORD i = 0; i < m_dwItemMax; i++ )
{
m_apItem[ i ].Empty();
#if __VER >= 9
SAFE_DELETE( m_apItem[i].m_pPet );
#endif // __PET_0410
m_apItem[ i ].m_dwObjId = i;
if( i < m_dwIndexNum )
{
m_apItem[ i ].m_dwObjIndex = i;
m_apIndex[ i ] = i;
}
else
{
// m_apItem[i].m_dwObjIndex = NULL_ID:
m_apIndex[ i ] = NULL_ID;
}
}
}
template <class T> void CItemContainer<T>::SetItemContainer( DWORD dwItemType, DWORD dwItemMax, DWORD dwExtra )
{
m_dwIndexNum = dwItemMax;
m_dwItemMax = dwItemMax;
if( dwExtra != 0xffffffff )
m_dwItemMax += dwExtra;
SAFE_DELETE_ARRAY( m_apItem );
SAFE_DELETE_ARRAY( m_apIndex );
m_apItem = new T[ m_dwItemMax ];
m_apIndex = new DWORD[ m_dwItemMax ];
for( u_long i = 0; i < m_dwItemMax; i++ )
{
m_apItem[i].m_dwObjId = i;
if( i < m_dwIndexNum )
{
m_apItem[i].m_dwObjIndex = i;
m_apIndex[i] = i;
}
else
m_apIndex[i] = NULL_ID;
}
}
#if __VER >= 11 // __SYS_IDENTIFY
#ifdef __SEND_ITEM_ULTIMATE
template <class T> BOOL CItemContainer<T>::Add( DWORD dwItemId, short nNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist, int nResistAbilityOption, BYTE* pnId, short* pnNum, BYTE* pnCount, BOOL bCharged, int nPiercedSize, DWORD dwItemId0, DWORD dwItemId1, DWORD dwItemId2, DWORD dwItemId3, DWORD dwItemId4, DWORD dwKeepTime, __int64 iRandomOptItemId )
#else // __SEND_ITEM_ULTIMATE
template <class T> BOOL CItemContainer<T>::Add( DWORD dwItemId, short nNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist, int nResistAbilityOption, BYTE* pnId, short* pnNum, BYTE* pnCount, BOOL bCharged, int nPiercedSize, DWORD dwItemId0, DWORD dwItemId1, DWORD dwItemId2, DWORD dwItemId3, DWORD dwKeepTime, __int64 iRandomOptItemId )
#endif // __SEND_ITEM_ULTIMATE
#else // __SYS_IDENTIFY
#ifdef __SEND_ITEM_ULTIMATE
template <class T> BOOL CItemContainer<T>::Add( DWORD dwItemId, short nNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist, int nResistAbilityOption, BYTE* pnId, short* pnNum, BYTE* pnCount, BOOL bCharged, int nPiercedSize, DWORD dwItemId0, DWORD dwItemId1, DWORD dwItemId2, DWORD dwItemId3, DWORD dwItemId4, DWORD dwKeepTime, int nRandomOptItemId )
#else // __SEND_ITEM_ULTIMATE
template <class T> BOOL CItemContainer<T>::Add( DWORD dwItemId, short nNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist, int nResistAbilityOption, BYTE* pnId, short* pnNum, BYTE* pnCount, BOOL bCharged, int nPiercedSize, DWORD dwItemId0, DWORD dwItemId1, DWORD dwItemId2, DWORD dwItemId3, DWORD dwKeepTime, int nRandomOptItemId )
#endif // __SEND_ITEM_ULTIMATE
#endif // __SYS_IDENTIFY
{
#if defined(__DBSERVER)
if( pnId )
*pnCount = 0;
ItemProp* pItemProp = prj.GetItemProp( dwItemId );
ASSERT( pItemProp );
BOOL bPackItem = TRUE;
int nId;
short nNumtmp = nNum;
if( IsFull( pItemProp, nNum, bCharged ) )
return FALSE;
if( pItemProp->dwPackMax == 1 )
bPackItem = FALSE;
CItemElem* pElemtmp;
if( bPackItem )
{
for( DWORD i = 0; i < m_dwIndexNum; i++ ) // 합쳐질수 있으면 합치기
{
nId = m_apIndex[i];
pElemtmp = (CItemElem*)&m_apItem[nId];
if( pElemtmp->IsEmpty() == FALSE && pElemtmp->m_dwItemId == dwItemId && pElemtmp->m_nItemNum < (short)pItemProp->dwPackMax
&& pElemtmp->m_bCharged == bCharged && pElemtmp->m_byFlag == 0 ) // 아이템 플래그 0 아이템 머지 가능
{
if( pElemtmp->m_nItemNum + nNumtmp > (short)pItemProp->dwPackMax )
{
nNumtmp -= ( (short)pItemProp->dwPackMax - pElemtmp->m_nItemNum );
pElemtmp->m_nItemNum = (short)pItemProp->dwPackMax;
if( pnId ) {
pnId[*pnCount] = nId;
pnNum[*pnCount] = pElemtmp->m_nItemNum;
( *pnCount )++;
}
}
else {
pElemtmp->m_nItemNum += nNumtmp;
if( pnId ) {
pnId[*pnCount] = nId;
pnNum[*pnCount] = pElemtmp->m_nItemNum;
( *pnCount )++;
}
nNumtmp = 0;
break;
}
}
}
}
if( nNumtmp > 0 )
{
for( DWORD i = 0; i < m_dwIndexNum; i++ )
{
nId = m_apIndex[i];
pElemtmp = (CItemElem*)&m_apItem[nId];
if( pElemtmp->IsEmpty() )
{
pElemtmp->m_dwItemId = dwItemId;
pElemtmp->m_dwObjId = nId;
pElemtmp->m_dwObjIndex = i;
ItemProp* pItemProp = prj.GetItemProp( dwItemId );
if( pItemProp )
pElemtmp->m_nHitPoint = pItemProp->dwEndurance;
else
pElemtmp->m_nHitPoint = 0;
pElemtmp->m_nRepair = 0;
pElemtmp->SetOption( nOption );
pElemtmp->SetSerialNumber( iSerialNumber );
pElemtmp->m_bItemResist = nItemResist;
pElemtmp->m_nResistAbilityOption = nResistAbilityOption;
pElemtmp->m_bCharged = bCharged;
pElemtmp->m_dwKeepTime = 0;
pElemtmp->SetPiercingSize( nPiercedSize );
pElemtmp->SetPiercingItem( 0, dwItemId0 );
pElemtmp->SetPiercingItem( 1, dwItemId1 );
pElemtmp->SetPiercingItem( 2, dwItemId2 );
pElemtmp->SetPiercingItem( 3, dwItemId3 );
#ifdef __SEND_ITEM_ULTIMATE
pElemtmp->SetPiercingItem( 4, dwItemId4 );
#endif // __SEND_ITEM_ULTIMATE
if( dwKeepTime )
pElemtmp->m_dwKeepTime = dwKeepTime;
#if __VER >= 11 // __SYS_IDENTIFY
pElemtmp->SetRandomOptItemId( iRandomOptItemId );
#else // __SYS_IDENTIFY
pElemtmp->SetRandomOptItemId( nRandomOptItemId );
#endif // __SYS_IDENTIFY
if( nNumtmp > (short)pItemProp->dwPackMax )
{
pElemtmp->m_nItemNum = (short)pItemProp->dwPackMax;
nNumtmp -= (short)pItemProp->dwPackMax;
if( pnId ) {
pnId[*pnCount] = nId;
pnNum[*pnCount] = pElemtmp->m_nItemNum;
( *pnCount )++;
}
}
else
{
pElemtmp->m_nItemNum = nNumtmp;
nNumtmp = 0;
if( pnId ) {
pnId[*pnCount] = nId;
pnNum[*pnCount] = pElemtmp->m_nItemNum;
( *pnCount )++;
}
break;
}
}
}
}
if( nNumtmp > 0 )
Error( "template <class T> BOOL CItemContainer<T>::Add( DWORD dwItemId... : nNumtmp > 0" );
return TRUE;
#endif // __DBSERVER
return FALSE;
}
template <class T> BOOL CItemContainer<T>::Add( T* pElem, BYTE* pnId, short* pnNum, BYTE* pnCount )
{
if( pnId )
*pnCount = 0;
ItemProp* pItemProp = prj.GetItemProp( pElem->m_dwItemId );
if( !pItemProp )
return FALSE;
BOOL bPackItem = TRUE;
int nId;
short nNumtmp = ( (CItemElem*)pElem )->m_nItemNum;
if( IsFull( pItemProp, nNumtmp, pElem->m_bCharged ) ) // 아이템을 넣을수 있는지 검사
return FALSE;
if( pItemProp->dwPackMax == 1 )
bPackItem = FALSE;
CItemElem* pElemtmp;
if( bPackItem )
{
for( DWORD i = 0; i < m_dwIndexNum; i++ )
{
nId = m_apIndex[i];
if( nId < 0 || nId >= (int)( m_dwItemMax ) )
continue;
pElemtmp = (CItemElem*)&m_apItem[nId];
//if( pElemtmp->IsEmpty() == FALSE && pElemtmp->m_dwItemId == pElem->m_dwItemId && pElemtmp->m_nItemNum < (short)pItemProp->dwPackMax )
if( pElemtmp->IsEmpty() == FALSE && pElemtmp->m_dwItemId == pElem->m_dwItemId && pElemtmp->m_nItemNum < (short)pItemProp->dwPackMax
&& pElemtmp->m_bCharged == pElem->m_bCharged && pElemtmp->m_byFlag == 0 ) // mirchang 100114 아이템 겹침 문제 수정
{
if( pElemtmp->m_nItemNum + nNumtmp > (short)pItemProp->dwPackMax )
{
nNumtmp -= ( (short)pItemProp->dwPackMax - pElemtmp->m_nItemNum );
pElemtmp->m_nItemNum = (short)pItemProp->dwPackMax;
if( pnId )
{
pnId[*pnCount] = nId;
pnNum[*pnCount] = pElemtmp->m_nItemNum;
( *pnCount )++;
}
}
else {
pElemtmp->m_nItemNum += nNumtmp;
if( pnId ) {
pnId[*pnCount] = nId;
pnNum[*pnCount] = pElemtmp->m_nItemNum;
( *pnCount )++;
}
nNumtmp = 0;
break;
}
}
}
}
if( nNumtmp > 0 )
{
for( DWORD i = 0 ; i < m_dwIndexNum ; i++ )
{
nId = m_apIndex[i];
if( nId < 0 || nId >= (int)( m_dwItemMax ) )
continue;
pElemtmp = (CItemElem*)&m_apItem[nId];
if( pElemtmp->IsEmpty() ) // 빈공간인지 검사
{
*pElemtmp = *( (CItemElem*)pElem );
pElemtmp->m_dwObjId = nId;
pElemtmp->m_dwObjIndex = i;
if( nNumtmp > (short)pItemProp->dwPackMax )
{
pElemtmp->m_nItemNum = (short)pItemProp->dwPackMax;
nNumtmp -= (short)pItemProp->dwPackMax;
if( pnId ) {
pnId[*pnCount] = nId;
pnNum[*pnCount] = pElemtmp->m_nItemNum;
( *pnCount )++;
}
}
else
{
pElemtmp->m_nItemNum = nNumtmp;
nNumtmp = 0;
if( pnId )
{
pnId[*pnCount] = nId;
pnNum[*pnCount] = pElemtmp->m_nItemNum;
( *pnCount )++;
}
break;
}
}
}
}
return TRUE;
}
template <class T> BOOL CItemContainer<T>::IsFull( ItemProp* pItemProp, short nNum, BOOL bCharged )
{
int nId;
short nNumtmp = nNum;
CItemElem* pElemtmp;
for( DWORD i = 0; i < m_dwIndexNum; i++ )
{
nId = m_apIndex[i];
if( nId < 0 || nId >= (int)( m_dwItemMax ) )
continue;
pElemtmp = (CItemElem*)&m_apItem[nId];
if( pElemtmp->IsEmpty() )
{
if( nNumtmp > (short)pItemProp->dwPackMax )
nNumtmp -= (short)pItemProp->dwPackMax;
else
return FALSE;
}
else if( pElemtmp->m_dwItemId == pItemProp->dwID && pElemtmp->m_bCharged == bCharged && pElemtmp->m_byFlag == 0 )
{
if( pElemtmp->m_nItemNum + nNumtmp > (short)pItemProp->dwPackMax )
nNumtmp -= ( (short)pItemProp->dwPackMax - pElemtmp->m_nItemNum );
else
return FALSE;
}
}
return TRUE;
}
template <class T> T* CItemContainer<T>::GetAt( DWORD dwIndex )
{
DWORD dwIdx = m_apIndex[dwIndex];
if( dwIdx == NULL_ID )
return NULL;
T* pItemElem = &m_apItem[dwIdx];
if( pItemElem->IsEmpty() )
return NULL;
return pItemElem;
}
template <class T> T* CItemContainer<T>::GetAtId( OBJID dwObjId )
{
if( dwObjId >= m_dwItemMax ) return NULL;
T* pItemElem = &m_apItem[dwObjId];
if( pItemElem->IsEmpty() )
return NULL;
return pItemElem;
}
template <class T> T* CItemContainer<T>::GetItem( ItemProp * pItemProp, int nAbilityOption )
{
int nId;
for( int i = 0 ; i < m_dwItemMax ; i++ )
{
nId = m_apIndex[i];
if( 0 <= nId && m_apItem[nId].IsEmpty() == FALSE )
{
T* pItemElem = &m_apItem[nId];
if( pItemElem->m_dwItemId == pItemProp->dwID && pItemElem->GetOption() == nAbilityOption )
{
return pItemElem;
}
}
}
return NULL;
}
template <class T> T* CItemContainer<T>::GetItem( ItemProp * pItemProp, int nAbilityOption, int nItemResist, int nResistAbilityOption )
{
int nId;
for( DWORD i = 0 ; i < m_dwItemMax ; i++ )
{
nId = m_apIndex[i];
if( 0 <= nId && m_apItem[nId].IsEmpty() == FALSE )
{
T* pItemElem = &m_apItem[nId];
if( pItemElem->m_dwItemId == pItemProp->dwID && pItemElem->GetOption() == nAbilityOption && pItemElem->m_bItemResist == nItemResist && pItemElem->m_nResistAbilityOption == nResistAbilityOption )
{
return pItemElem;
}
}
}
return NULL;
}
template <class T> BOOL CItemContainer<T>::IsEquip( DWORD dwObjId )
{
if( m_apItem[ dwObjId ].m_dwObjIndex >= m_dwIndexNum )
return TRUE;
return FALSE;
}
template <class T> void CItemContainer<T>::RemoveAt( DWORD dwIndex )
{
m_apItem[ m_apIndex[ dwIndex ] ].Empty();
if( dwIndex >= m_dwIndexNum )
{
m_apItem[ m_apIndex[ dwIndex ] ].m_dwObjIndex = NULL_ID;
m_apIndex[ dwIndex ] = NULL_ID;
}
//for( int i = dwIndex; i < m_dwIndexNum - 1; i++ )
// m_apIndex[ i ] = m_apIndex[ i + 1 ];
//m_dwIndexNum--;
}
template <class T> void CItemContainer<T>::RemoveAtId( OBJID dwObjId )
{
if( dwObjId >= m_dwItemMax )
return;
if( m_apItem[ dwObjId ].m_dwObjIndex >= m_dwItemMax )
return;
m_apItem[ dwObjId ].Empty();
if( m_apItem[ dwObjId ].m_dwObjIndex >= m_dwIndexNum )
{
m_apIndex[ m_apItem[ dwObjId ].m_dwObjIndex ] = NULL_ID;
m_apItem[ dwObjId ].m_dwObjIndex = NULL_ID;
}
}
template <class T> T* CItemContainer<T>::GetEquip( DWORD dwIndex )
{
return GetAt( m_dwIndexNum + dwIndex );
}
template <class T> BOOL CItemContainer<T>::UnEquip( DWORD dwIndex )
{
dwIndex += m_dwIndexNum;
if( dwIndex >= m_dwItemMax )
return FALSE;
DWORD dwId = m_apIndex[dwIndex];
if( dwId >= m_dwItemMax )
return FALSE;
for( DWORD i = 0; i < m_dwIndexNum; i++ )
{
if( m_apIndex[i] >= m_dwItemMax )
continue;
if( m_apItem[m_apIndex[i]].IsEmpty() )
{
m_apItem[m_apIndex[i]].m_dwObjIndex = NULL_ID;
m_apIndex[dwIndex] = NULL_ID;
m_apItem[dwId].m_dwObjIndex = i;
m_apIndex[i] = dwId;
return TRUE;
}
}
return FALSE;
}
template <class T> void CItemContainer<T>::DoEquip( DWORD dwSrcIndex, DWORD dwDstIndex )
{
dwDstIndex += m_dwIndexNum;
for( int i = 0; i < m_dwItemMax; i++ )
{
if( m_apItem[i].IsEmpty() && m_apItem[i].m_dwObjIndex == NULL_ID )
{
m_apIndex[dwDstIndex] = m_apIndex[dwSrcIndex];
m_apIndex[dwSrcIndex] = i;
m_apItem[m_apIndex[dwSrcIndex]].m_dwObjIndex = dwSrcIndex;
m_apItem[m_apIndex[dwDstIndex]].m_dwObjIndex = dwDstIndex;
return;
}
}
}
template <class T> void CItemContainer<T>::Copy( CItemContainer<T> & rItemContainer )
{
m_dwIndexNum = rItemContainer.m_dwIndexNum;
memcpy( (void*)m_apIndex, (void*)rItemContainer.m_apIndex, sizeof(DWORD) * m_dwItemMax );
for( u_long i = 0; i < m_dwItemMax; i++ )
{
m_apItem[i].m_dwObjId = rItemContainer.m_apItem[i].m_dwObjId;
m_apItem[i].m_dwObjIndex = rItemContainer.m_apItem[i].m_dwObjIndex;
if( rItemContainer.m_apItem[i].IsEmpty() == FALSE )
m_apItem[i] = rItemContainer.m_apItem[i];
else
m_apItem[i].Empty();
}
}
template <class T> void CItemContainer<T>::Serialize( CAr & ar )
{
// for( int i = 0; i < m_dwItemMax; i++ ) // 462
// m_apItem[i].Serialize( ar );
DWORD adwObjIndex[128];
unsigned char chSize = 0;
if( ar.IsStoring() )
{
ar.Write( m_apIndex, sizeof(DWORD) * m_dwItemMax );
u_long uOffset = ar.GetOffset();
ar << chSize;
for( u_char ch = 0; ch < m_dwItemMax; ch++ ) // 0-504
{
if( m_apItem[ch].IsEmpty() == FALSE )
{
ar << ch;
m_apItem[ch].Serialize( ar );
chSize++;
}
adwObjIndex[ch] = m_apItem[ch].m_dwObjIndex;
}
ar.Write( adwObjIndex, sizeof(DWORD) * m_dwItemMax );
int nBufSize;
LPBYTE lpBuf = ar.GetBuffer( &nBufSize );
*( lpBuf + uOffset ) = chSize;
}
else
{
ar.Read( m_apIndex, sizeof(DWORD) * m_dwItemMax );
// Clear
u_int i;
for( i = 0; i < m_dwItemMax; i++ )
m_apItem[i].Empty();
ar >> chSize;
unsigned char ch;
for( i = 0; i < chSize; i++ )
{
ar >> ch;
m_apItem[ch].Serialize( ar );
}
ar.Read( adwObjIndex, sizeof(DWORD) * m_dwItemMax );
for( i = 0; i < m_dwItemMax; i++ )
{
m_apItem[i].m_dwObjIndex = adwObjIndex[i];
}
}
}
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
class CItem : public CCtrl
{
public:
CItemBase* m_pItemBase;
// Constructions
CItem();
virtual ~CItem();
// Operations
virtual void Serialize( CAr & ar );
};
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
class CAction
{
public:
DWORD m_dwState;
DWORD m_dwStateFlag;
public:
CAction()
{
m_dwState = 0;
m_dwStateFlag = 0;
}
void ClearStateFlag() { m_dwStateFlag = 0; }
void AddStateFlag( DWORD dwStateFlag ) { m_dwStateFlag |= dwStateFlag; }
DWORD GetStateFlag() { return m_dwStateFlag; }
virtual ~CAction() {}
};
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
class CMover;
class CActionMover : public CAction
{
public:
CActionMover() {}
CActionMover( CMover* pMover ) {}
virtual ~CActionMover() {}
DWORD GetState( void ) { return m_dwState; }
void __ForceSetState( DWORD dwState ) { m_dwState = dwState; }
};
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
typedef struct tagQuest
{
BYTE m_nState;
WORD m_wTime;
WORD m_wId;
// 추가
//BYTE m_nKillNPCNum[ 2 ]; // chipi_091015 - NPC Kill Quest 갯수 확장( BYTE -> WORD )
WORD m_nKillNPCNum[ 2 ]; // chipi_091015 - NPC Kill Quest 갯수 확장( BYTE -> WORD )
BYTE m_bPatrol : 1;
BYTE m_bReserve2 : 1;
BYTE m_bReserve3 : 1;
BYTE m_bReserve4 : 1;
BYTE m_bReserve5 : 1;
BYTE m_bReserve6 : 1;
BYTE m_bReserve7 : 1;
BYTE m_bReserve8 : 1;
} QUEST,* LPQUEST;
//#ifdef __DBSERVER
#if defined(__DBSERVER)
typedef MemPooler<CMover> CMoverPool;
#endif // __DBSERVER
typedef struct _EQUIP_INFO
{
DWORD dwId;
int nOption;
BYTE byFlag;
} EQUIP_INFO, *PEQUIP_INFO;
#if __VER >= 11 // __SYS_POCKET
#include "pocket.h"
#endif // __SYS_POCKET
class CMover: public CCtrl
{
private:
DWORD m_dwGold;
public:
/// 몬스터에 해당되는 것
TCHAR m_szCharacterKey[ 32 ];
BOOL m_bActiveAttack;
DWORD m_dwBelligerence;
int m_nMovePattern;
int m_nMoveEvent;
int m_nMoveEventCnt;
/// 몬스터에 해당되는 것
TCHAR m_szName[32];
BOOL m_bPlayer;
u_long m_idPlayer;
LONG m_nHitPoint;
LONG m_nManaPoint;
LONG m_nFatiguePoint;
DWORD m_dwSkinSet;
DWORD m_dwHairMesh;
DWORD m_dwHairColor;
DWORD m_dwHeadMesh;
#if __VER >= 12 // __MOD_TUTORIAL
private:
int m_nTutorialState;
#else // __MOD_TUTORIAL
LONG m_nFlightLv;
#endif // __MOD_TUTORIAL
public:
#if __VER >= 12 // __MOD_TUTORIAL
LONG GetFlightLv( void ) { return ( m_nLevel >= 20? 1: 0 ); }
void SetFlightLv( LONG nFlightLv ) {}
int GetTutorialState( void ) { return m_nTutorialState; }
void SetTutorialState( int nTutorialState ) { m_nTutorialState = nTutorialState; }
#else // __MOD_TUTORIAL
LONG GetFlightLv( void ) { return m_nFlightLv; }
void SetFlightLv( LONG nFlightLv ) { m_nFlightLv = nFlightLv; }
#endif // __MOD_TUTORIAL
BOOL IsEquipableNPC() { return FALSE; }
LONG m_nFxp;
BYTE m_bySex;
DWORD m_dwRideItemIdx;
int m_nFuel;
LONG m_nJob;
BYTE m_nSlot;
char m_szBankPass[5];
int m_idGuildCloak;
LONG m_nStr, m_nSta, m_nDex, m_nInt;
LONG m_nLevel, m_nDeathLevel;
EXPINTEGER m_nExp1, m_nDeathExp;
SKILL m_aJobSkill[ MAX_SKILL_JOB ];
#ifdef __SKILL_0205
BYTE m_abUpdateSkill[MAX_SKILL_JOB];
#endif // __SKILL_0205
OBJID m_idMarkingWorld;
D3DXVECTOR3 m_vMarkingPos;
long m_nRemainGP;
DWORD m_dwAuthorization;
DWORD m_dwMode;
CUserTaskBar m_UserTaskBar;
#ifdef __RT_1025
CRTMessenger m_RTMessenger;
#else // __RT_1025
CMessenger m_Messenger;
#endif // __RT_1025
u_long m_idparty;
u_long m_idGuild;
u_long m_idWar;
#if __VER >= 8 // __S8_PK
DWORD m_dwPKTime; /// 핑크 상태 시간
int m_nPKValue; /// PK 수치
DWORD m_dwPKPropensity; /// PK 성향
DWORD m_dwPKExp; /// PK 성향 습득 경험치
#else // __VER >= 8 // __S8_PK
int m_nNumKill;
int m_nSlaughter;
#endif // __VER >= 8 // __S8_PK
#if __VER >= 8 // __CSC_VER8_5
EXPINTEGER m_nAngelExp; /// 엔젤 경험치
LONG m_nAngelLevel; /// 엔젤 Level
#endif // __CSC_VER8_5
int m_nFame;
u_long m_idMurderer;
int m_nDuel; // 듀얼중인가.( 0:없음 1:개인듀얼중 2:파티듀얼중.
u_long m_idDuelParty; // 파티듀얼중이면 상대방 파티의 id
int m_nGuildCombatState;
int m_nSkillLevel; // 지금까지 올린 스킬레벨
int m_nSkillPoint; // SP
CActionMover* m_pActMover;
CItemContainer< CItemElem > m_Inventory ;
#if __VER >= 11 // __SYS_POCKET
CPocketController m_Pocket;
#endif // __SYS_POCKET
u_long m_idPlayerBank[3];
CItemContainer< CItemElem > m_Bank[ 3 ] ;
DWORD m_dwGoldBank[ 3 ];
D3DXVECTOR3 m_vReturnPos; //'귀환 두루마리'관련
DWORD m_dwReturnWorldID;
DWORD m_tmAccFuel;
#ifdef __DBSERVER
#ifdef __JEFF_9_20
DWORD m_dwMute;
#else // __JEFF_9_20
DWORD m_dwFlyTime;
#endif // __JEFF_9_20
DWORD m_dwWorldID;
CMclCritSec m_AccessLock;
#ifdef __EVENT_1101
#ifdef __EVENT_1101_2
__int64 m_nEventFlag; // 64비트 경과 일 번째 비트
#else // __EVENT_1101_2
DWORD m_dwEventFlag; // 경과 일 번째 비트
#endif // __EVENT_1101_2
DWORD m_dwEventTime; // 분 단위 계수
DWORD m_dwEventElapsed; // 경과 일
#endif // __EVENT_1101
#endif // __DBSERVER
#if __VER >= 15 // __PETVIS
private:
OBJID m_objIdVisPet; // 소환중인 비스펫의 인벤토리 위치
DWORD m_dwMoverSfxId; // 무버에 붙는 이펙트
#endif // __PETVIS
#if __VER >= 9 // __PET_0410
private:
DWORD m_dwPetId; // 소환중이 펫의 인벤토리 위치(自), 소환중인 펫 인덱스(他)
public:
DWORD GetPetId( void ) { return m_dwPetId; }
void SetPetId( DWORD dwPetId ) { m_dwPetId = dwPetId; }
CItemElem* GetPetItem( void );
#endif // __PET_0410
#if __VER >= 9 //__AI_0509
FLOAT m_fSpeedFactor;
#endif // __AI_0509
#ifdef __EXP_ANGELEXP_LOG
int m_nExpLog;
int m_nAngelExpLog;
#endif // __EXP_ANGELEXP_LOG
#ifdef __EVENTLUA_COUPON
int m_nCoupon;
#endif // __EVENTLUA_COUPON
#if __VER >= 13 // __HONORABLE_TITLE // 달인
int m_nHonor; // 달인선택
int m_aHonorTitle[MAX_HONOR_TITLE]; // 달인수치
void SetHonorCount(int nIdx , int nCount ) { m_aHonorTitle[nIdx] = nCount; }
#endif // __HONORABLE_TITLE // 달인
LONG m_nPlusMaxHitPoint;
DWORD m_dwSMTime[SM_MAX];
BYTE m_nAttackResistLeft;
BYTE m_nAttackResistRight;
BYTE m_nDefenseResist;
#ifdef __BUFF_1107
CBuffMgr m_buffs;
#else // __BUFF_1107
CSkillInfluence m_SkillState; // 지속성을 갖는 스킬의 상태 처리(예:프로텍션 ??초동안 방어력 얼마 증가)
#endif // __BUFF_1107
EQUIP_INFO m_aEquipInfo[MAX_HUMAN_PARTS];
void ClearEquipInfo( void )
{
memset( m_aEquipInfo, 0, sizeof(EQUIP_INFO) * MAX_HUMAN_PARTS );
for( int i = 0; i < MAX_HUMAN_PARTS; i++ )
m_aEquipInfo[i].dwId = NULL_ID;
}
DWORD m_dwStateMode;
OBJID m_dwUseItemId; // 비행 시전 시간
LPQUEST m_aQuest;
LPWORD m_aCompleteQuest;
BYTE m_nQuestSize;
BYTE m_nCompleteQuestSize;
DWORD m_dwPeriodicTick;
DWORD m_dwTickCheer;
int m_nCheerPoint;
#if __VER >= 14 // __PCBANG
DWORD m_dwPCBangClass;
#endif // __PCBANG
#if __VER >= 15 // __IMPROVE_QUEST_INTERFACE
LPWORD m_aCheckedQuest;
BYTE m_nCheckedQuestSize;
#endif // __IMPROVE_QUEST_INTERFACE
#if __VER >= 15 // __CAMPUS
private:
u_long m_idCampus;
int m_nCampusPoint;
public:
u_long GetCampusId() { return m_idCampus; }
void SetCampusId( u_long idCampus ) { m_idCampus = idCampus; }
int GetCampusPoint() { return m_nCampusPoint; }
void SetCampusPoint( int nMPPoint ) { m_nCampusPoint = nMPPoint; }
#endif // __CAMPUS
#if __VER >= 15 // __GUILD_HOUSE
public:
int m_nRestPoint;
time_t m_tLogOut;
#endif // __GUILD_HOUSE
public:
// Constructions
CMover();
virtual ~CMover();
// Operations
void InitProp( void );
int InitSkillExp( void );
#if defined(__DBSERVER)
MoverProp* GetProp( void ) { return( prj.GetMoverProp( m_dwIndex ) ); }
#endif // __DBSERVER
BOOL RemoveQuest( int nQuestId );
#if __VER >= 11 // __SYS_IDENTIFY
#ifdef __SEND_ITEM_ULTIMATE
BOOL AddItem( DWORD dwItemType, DWORD dwId, DWORD dwNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist = 0, int nResistAbilityOption = 0, int nCharged = 0, int nPiercedSize = 0, DWORD dwItemId0 = 0, DWORD dwItemId1 = 0, DWORD dwItemId2 = 0, DWORD dwItemId3 = 0, DWORD dwItemId4 = 0, DWORD dwKeepTime = 0, __int64 iRandomOptItemId = 0 );
#else // __SEND_ITEM_ULTIMATE
BOOL AddItem( DWORD dwItemType, DWORD dwId, DWORD dwNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist = 0, int nResistAbilityOption = 0, int nCharged = 0, int nPiercedSize = 0, DWORD dwItemId0 = 0, DWORD dwItemId1 = 0, DWORD dwItemId2 = 0, DWORD dwItemId3 = 0, DWORD dwKeepTime = 0, __int64 iRandomOptItemId = 0 );
#endif // __SEND_ITEM_ULTIMATE
#else // __SYS_IDENTIFY
#ifdef __SEND_ITEM_ULTIMATE
BOOL AddItem( DWORD dwItemType, DWORD dwId, DWORD dwNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist = 0, int nResistAbilityOption = 0, int nCharged = 0, int nPiercedSize = 0, DWORD dwItemId0 = 0, DWORD dwItemId1 = 0, DWORD dwItemId2 = 0, DWORD dwItemId3 = 0, DWORD dwItemId4 = 0, DWORD dwKeepTime = 0, int nRandomOptItemId = 0 );
#else // __SEND_ITEM_ULTIMATE
BOOL AddItem( DWORD dwItemType, DWORD dwId, DWORD dwNum, int nOption, SERIALNUMBER iSerialNumber, int nItemResist = 0, int nResistAbilityOption = 0, int nCharged = 0, int nPiercedSize = 0, DWORD dwItemId0 = 0, DWORD dwItemId1 = 0, DWORD dwItemId2 = 0, DWORD dwItemId3 = 0, DWORD dwKeepTime = 0, int nRandomOptItemId = 0 );
#endif // __SEND_ITEM_ULTIMATE
#endif // __SYS_IDENTIFY
BOOL AddItemBank( int nSlot, DWORD dwId, DWORD dwNum, int nOption, SERIALNUMBER iSerialNumber );
virtual void Serialize( CAr & ar );
// int GetMaxHitPoint() { return( ( m_nLevel * 16 ) + ( m_nSta * 6 ) + ( m_nStr * 3 ) ); }
// int GetMaxManaPoint() { return( ( m_nLevel + m_nInt ) * 2 + 20 ); }
// int GetMaxFatiguePoint() { return(int)( ( m_nLevel * 2 ) + ( m_nSta * m_nLevel / 40 ) + ( ( m_nStr + m_nSta + m_nDex ) * 2.5 ) ); }
BOOL IsAbnormalPlayerData();
BOOL NormalizePlayerData();
BOOL RemoveItemIK3();
BYTE GetSex() { return m_bySex; }
void SetSex( BYTE bySex ) { m_bySex = bySex; }
int GetGold();
void SetGold( int nGold );
BOOL AddGold( int nGold, BOOL bSend = TRUE );
void Copy( CMover* pMover, BOOL bCopyAll );
void PeriodTick();
#if defined(__DBSERVER)
void Lock( void ) { m_AccessLock.Enter(); }
void Unlock( void ) { m_AccessLock.Leave(); }
#ifdef __INVALID_LOGIN_0612
BOOL m_bLogout;
char m_szAccount[MAX_ACCOUNT];
#endif // __INVALID_LOGIN_0612
#ifndef __VM_0820
#ifndef __MEM_TRACE
public:
static CMoverPool* m_pPool;
void* operator new( size_t nSize ) { return CMover::m_pPool->Alloc(); }
void* operator new( size_t nSize, LPCSTR lpszFileName, int nLine ) { return CMover::m_pPool->Alloc(); }
void operator delete( void* lpMem ) { CMover::m_pPool->Free( (CMover*)lpMem ); }
void operator delete( void* lpMem, LPCSTR lpszFileName, int nLine ) { CMover::m_pPool->Free( (CMover*)lpMem ); }
#endif // __MEM_TRACE
#endif // __VM_0820
#endif // __DBSERVER
};
/*------------------------------------------------------------------------------------------------------------------------------------------------------------*/
inline int CMover::GetGold()
{
ASSERT( m_dwGold <= INT_MAX );
return m_dwGold;
}
inline void CMover::SetGold( int nGold )
{
ASSERT( nGold >= 0 );
m_dwGold = (DWORD)nGold;
}
inline BOOL CMover::AddGold( int nGold, BOOL bSend )
{
if( nGold == 0 )
return TRUE;
#ifdef __PERIN_BUY_BUG
float fTotal = static_cast<float>( GetGold() ) + static_cast<float>( nGold );
if( fTotal > static_cast<float>( INT_MAX ) )
fTotal = static_cast<float>( INT_MAX );
else if( fTotal < 0.0f )
return FALSE;
SetGold( static_cast<int>( fTotal ) );
#else // __PERIN_BUY_BUG
int nTotal = GetGold() + nGold;
if( nGold > 0 )
{
if( nTotal < 0 ) // overflow?
nTotal = INT_MAX;
}
else
{
if( nTotal < 0 ) // underflow?
return FALSE;
}
SetGold( nTotal );
#endif // __PERIN_BUY_BUG
if( bSend )
{
#ifdef __WORLDSERVER
g_UserMng.AddSetPointParam( this, DST_GOLD, nTotal );
#endif // __WORLDSERVER
}
return TRUE;
}
#endif // __OBJ_H__ | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
1273
]
]
] |
9d2a53f5a6724e88375a1074999e3be9c66a4e14 | d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189 | /tags/pyplusplus_dev_0.9.5/unittests/data/enums_to_be_exported.hpp | 2fa7fe427468a439b5fac2a110f4f3a3788b9745 | [
"BSL-1.0"
] | permissive | gatoatigrado/pyplusplusclone | 30af9065fb6ac3dcce527c79ed5151aade6a742f | a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede | refs/heads/master | 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 553 | hpp | // Copyright 2004-2008 Roman Yakovenko.
// 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)
#ifndef __enums_to_be_exported_hpp__
#define __enums_to_be_exported_hpp__
enum Chisla{ nol, odin, dva, tri };
namespace enums{
enum color{
red = 1
, green = 2
, blue = 4 };
enum numbers{
zero = 0
, noll = 0
};
inline int to_int( int x=red ){ return x; }
}
#endif//__enums_to_be_exported_hpp__
| [
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] | [
[
[
1,
28
]
]
] |
33ce071c1db6abf9a4f7d0e678c08fa703a19fa9 | 8b506bf34b36af04fa970f2749e0c8033f1a9d7a | /Code/Win32/dx/dxDeviceFactory.h | 9ddb0c54244f83dd2704d90a120bf7e5cfd46f8f | [] | no_license | gunstar/Prototype | a5155e25d7d54a1991425e7be85bfc7da42c634f | a4448b5f6d18048ecaedf26c71e2b107e021ea6e | refs/heads/master | 2021-01-10T21:42:24.221750 | 2011-11-06T10:16:26 | 2011-11-06T10:16:26 | 2,708,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 278 | h | /*
dxDeviceFactory
*/
#ifndef _dxDeviceFactory
#define _dxDeviceFactory
#include "dxDevice.h"
class dxDeviceFactory
{
public:
dxDeviceFactory (IDirect3D9* d9) { D9 = d9; }
dxDevice* makeDevice (HWND hwnd);
private:
IDirect3D9* D9;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
21
]
]
] |
f646a0a0273ee87cfe12254b551e4933f5013601 | bfe8eca44c0fca696a0031a98037f19a9938dd26 | /libjingle-0.4.0/talk/xmpp/saslcookiemechanism.h | e6f6db53a3b31accf1f7763043fc7f0d835a0a37 | [
"BSD-3-Clause"
] | permissive | luge/foolject | a190006bc0ed693f685f3a8287ea15b1fe631744 | 2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c | refs/heads/master | 2021-01-10T07:41:06.726526 | 2011-01-21T10:25:22 | 2011-01-21T10:25:22 | 36,303,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,537 | h | /*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SASLCOOKIEMECHANISM_H_
#define _SASLCOOKIEMECHANISM_H_
#include "talk/xmpp/saslmechanism.h"
#include "talk/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
namespace buzz {
class SaslCookieMechanism : public SaslMechanism {
public:
SaslCookieMechanism(const std::string & mechanism, const std::string & username, const std::string & cookie) :
mechanism_(mechanism), username_(username), cookie_(cookie) {}
virtual std::string GetMechanismName() { return mechanism_; }
virtual XmlElement * StartSaslAuth() {
// send initial request
XmlElement * el = new XmlElement(QN_SASL_AUTH, true);
el->AddAttr(QN_MECHANISM, mechanism_);
std::string credential;
credential.append("\0", 1);
credential.append(username_);
credential.append("\0", 1);
credential.append(cookie_);
el->AddText(Base64Encode(credential));
return el;
}
private:
std::string mechanism_;
std::string username_;
std::string cookie_;
};
}
#endif
| [
"[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30"
] | [
[
[
1,
67
]
]
] |
a7819c997a313d6ab6b432bee320f3691b8826fe | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /MassMailer/MassMailer/MassMailer/App/socket/MySocket.h | 1d6919f4089571e1b9710daef32c13d25815d85d | [] | no_license | win18216001/tpgame | bb4e8b1a2f19b92ecce14a7477ce30a470faecda | d877dd51a924f1d628959c5ab638c34a671b39b2 | refs/heads/master | 2021-04-12T04:51:47.882699 | 2011-03-08T10:04:55 | 2011-03-08T10:04:55 | 42,728,291 | 0 | 2 | null | null | null | null | ISO-8859-1 | C++ | false | false | 815 | h | // MySocket.h: Schnittstelle für die Klasse CMySocket.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_MYSOCKET_H__D972BDE0_B82B_4AAD_8232_2A5BAF040129__INCLUDED_)
#define AFX_MYSOCKET_H__D972BDE0_B82B_4AAD_8232_2A5BAF040129__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "AsyncProxySocket.h"
class CMySocket : public CAsyncProxySocket
{
public:
CStatic *m_pResponse;
virtual void OnConnect(int nErrorCode);
virtual void OnProxyOperationFailed(int nOpID);
virtual void OnListenFinished(unsigned long &retProxyIp,int &retProxyPort);
virtual void OnReceive(int nErrorCode);
CMySocket();
virtual ~CMySocket();
};
#endif // !defined(AFX_MYSOCKET_H__D972BDE0_B82B_4AAD_8232_2A5BAF040129__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
174fbd236c0c20d23b0170fffa5ee74ccf132b38 | 7f6f9788d020e97f729af85df4f6741260274bee | /test/gui_test/ListBoxTest.cpp | d8fbf49f4babde14781c715e06e7871dc26383b3 | [] | no_license | cnsuhao/nyanco | 0fb88ed1cf2aa9390fa62f6723e8424ba9a42ed4 | ba199267a33d4c6d2e473ed4b777765057aaf844 | refs/heads/master | 2021-05-31T05:37:51.892873 | 2008-05-27T05:23:19 | 2008-05-27T05:23:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,068 | cpp | /*!
@file ListBoxTest.cpp
@author dasyprocta
*/
#include "nyanco.h"
#include "gui/gui.h"
using namespace nyanco;
using namespace nyanco::gui;
// ============================================================================
class MyFrame : public Frame<MyFrame>
{
enum
{
ListBoxId,
AddButtonId,
DeleteButtonId,
};
ListBox::Ptr m_listBox;
public:
MyFrame()
{
ListBox::Ptr listBox = ListBox::Create(ListBoxId, ListBox::Arg().height(240));
listBox->addColumn("Column1", 100).addColumn("Column2", 100);
for (int i = 0; i < 20; ++i)
{
listBox->addRow();
for (int j = 0; j < 2; ++j)
{
std::string str = "test " + boost::lexical_cast<std::string>(i) + " " + boost::lexical_cast<std::string>(j);
listBox->getItem(i, j).set(str);
}
}
attach(listBox);
attach(TextEdit::Create(-1));
attach(Button::Create(AddButtonId, "Add"));
attach(Button::Create(DeleteButtonId, "Delete"));
attach(LabeledTextEdit::Create(LabeledTextEdit::Arg<>().text("Test LabeledEdit")));
registerHandler(AddButtonId, &MyFrame::onAddButtonEvent);
registerHandler(DeleteButtonId, &MyFrame::onDeleteButtonEvent);
m_listBox = listBox;
}
void onAddButtonEvent(Event<Button> const& e)
{
m_listBox->addRow();
}
void onDeleteButtonEvent(Event<Button> const& e)
{
}
};
// ============================================================================
class MyApplication : public Application
{
void onInitialize()
{
WindowManager& manager = WindowManager::GetInterface();
manager.attach(MyFrame::Create(-1, Frame<>::Arg().caption("Test ListBox").width(280)));
manager.dock(MyFrame::Create(-1, Frame<>::Arg().caption("Test ListBox").width(280)), Dock::Left);
}
};
NYA_REGIST_APP(MyApplication)
| [
"dasyprocta@27943c09-b335-0410-ab52-7f3c671fdcc1"
] | [
[
[
1,
74
]
]
] |
0e4a036fbd0ebc617b25044d75782e1865952604 | ee2e06bda0a5a2c70a0b9bebdd4c45846f440208 | /word/CppUTest/include/CppUTest/TestOutput.h | 2d4e3b46d273ad994237ad9cff8871b7063c9714 | [] | no_license | RobinLiu/Test | 0f53a376e6753ece70ba038573450f9c0fb053e5 | 360eca350691edd17744a2ea1b16c79e1a9ad117 | refs/heads/master | 2021-01-01T19:46:55.684640 | 2011-07-06T13:53:07 | 2011-07-06T13:53:07 | 1,617,721 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,634 | h | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef D_TestOutput_h
#define D_TestOutput_h
///////////////////////////////////////////////////////////////////////////////
//
// TestOutput.h
//
// This is a minimal printer inteface.
// We kept streams out too keep footprint small, and so the test
// harness could be used with less capable compilers so more
// platforms could use this test harness
//
///////////////////////////////////////////////////////////////////////////////
class Utest;
class Failure;
class TestResult;
class TestOutput
{
public:
explicit TestOutput();
virtual ~TestOutput();
virtual void printTestsStarted();
virtual void printTestsEnded(const TestResult& result);
virtual void printCurrentTestStarted(const Utest& test);
virtual void printCurrentTestEnded(const TestResult& res);
virtual void printCurrentGroupStarted(const Utest& test);
virtual void printCurrentGroupEnded(const TestResult& res);
virtual void verbose();
virtual void print(const char*)=0;
virtual void print(long);
virtual void printDouble(double);
virtual void printHex(long);
virtual void print(const Failure& failure);
virtual void printTestRun(int number, int total);
virtual void setProgressIndicator(const char*);
virtual void flush();
private:
virtual void printProgressIndicator();
TestOutput(const TestOutput&);
TestOutput& operator=(const TestOutput&);
int dotCount_;
bool verbose_;
const char* progressIndication;
};
TestOutput& operator<<(TestOutput&, const char*);
TestOutput& operator<<(TestOutput&, long);
///////////////////////////////////////////////////////////////////////////////
//
// ConsoleTestOutput.h
//
// Printf Based Solution
//
///////////////////////////////////////////////////////////////////////////////
class ConsoleTestOutput : public TestOutput
{
public:
explicit ConsoleTestOutput() {};
virtual ~ConsoleTestOutput() {};
virtual void print(const char* s);
virtual void flush();
private:
ConsoleTestOutput(const ConsoleTestOutput&);
ConsoleTestOutput& operator=(const ConsoleTestOutput&);
};
///////////////////////////////////////////////////////////////////////////////
//
// StringBufferTestOutput.h
//
// TestOutput for test purposes
//
///////////////////////////////////////////////////////////////////////////////
class StringBufferTestOutput : public TestOutput
{
public:
explicit StringBufferTestOutput()
{}
;
virtual ~StringBufferTestOutput()
{}
;
void print(const char* s)
{
output += s;
}
void flush()
{
output = "";
}
const SimpleString& getOutput()
{
return output;
}
private:
SimpleString output;
StringBufferTestOutput(const StringBufferTestOutput&);
StringBufferTestOutput& operator=(const StringBufferTestOutput&);
};
#endif // D_TestOutput_h
| [
"RobinofChina@43938a50-64aa-11de-9867-89bd1bae666e"
] | [
[
[
1,
149
]
]
] |
03788f0163dbc4ee79c1413f9858fb68de7e1c82 | b369aabb8792359175aedfa50e949848ece03180 | /src/wblib/wblib/Timer.h | cd6cf9c3a7e917ee444fd795adecfcc70f16f8ac | [] | no_license | LibreGamesArchive/magiccarpet | 6d49246817ab913f693f172fcfc53bf4cc153842 | 39210d57096d5c412de0f33289fbd4d08c20899b | refs/heads/master | 2021-05-08T02:00:46.182694 | 2009-01-06T20:25:36 | 2009-01-06T20:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | h | #ifndef _TIMER
#define _TIMER
#include <windows.h>
#include <stdio.h>
namespace wbLib {
class Timer {
public:
Timer();
void reset();
double getTime();
private:
LARGE_INTEGER ticksPerSecond;
LARGE_INTEGER last;
};
}
#endif | [
"[email protected]"
] | [
[
[
1,
18
]
]
] |
247293284bfaa703bcee83964d36d66f4b0dcfa7 | 5ff30d64df43c7438bbbcfda528b09bb8fec9e6b | /kserver/db/DbPool.cpp | ac606747a258825a47e6f10de2b76e064dc5ff5e | [] | no_license | lvtx/gamekernel | c80cdb4655f6d4930a7d035a5448b469ac9ae924 | a84d9c268590a294a298a4c825d2dfe35e6eca21 | refs/heads/master | 2016-09-06T18:11:42.702216 | 2011-09-27T07:22:08 | 2011-09-27T07:22:08 | 38,255,025 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 100 | cpp | #include "stdafx.h"
#include <kserver/serverbase.h>
#include <kserver/db/DbPool.h>
// empty
| [
"darkface@localhost"
] | [
[
[
1,
6
]
]
] |
0a6e15acb272f8536788741c9917390c2704294c | b86d7c8f28a0c243b4c578821e353d5efcaf81d2 | /clearcasehelper/WebPage.cpp | 21fb4c031b563f8ef3ed360e8dcbc776f99fdefd | [] | no_license | nk39/mototool | dd4998d38348e0e2d010098919f68cf2c982f26a | 34a0698fd274ae8b159fc8032f3065877ba2114d | refs/heads/master | 2021-01-10T19:26:23.675639 | 2008-01-04T04:47:54 | 2008-01-04T04:47:54 | 34,927,428 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 11,373 | cpp | /////////////////////////////////////////////////////////////////
// By Eugene Khodakovsky //
// April,2002 //
// [email protected] //
// Last Update: April, 2002 //
/////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "WebPage.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define CHECK_POINTER(p)\
ATLASSERT(p != NULL);\
if(p == NULL)\
{\
ShowError(_T("NULL pointer"));\
return false;\
}
const CString GetSystemErrorMessage(DWORD dwError)
{
CString strError;
LPTSTR lpBuffer;
if(!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT),
(LPTSTR) &lpBuffer, 0, NULL))
{
strError = "FormatMessage Netive Error" ;
}
else
{
strError = lpBuffer;
LocalFree(lpBuffer);
}
return strError;
}
CString GetNextToken(CString& strSrc, const CString strDelim,bool bTrim, bool bFindOneOf)
{
CString strToken;
int idx = bFindOneOf? strSrc.FindOneOf(strDelim) : strSrc.Find(strDelim);
if(idx != -1)
{
strToken = strSrc.Left(idx);
strSrc = strSrc.Right(strSrc.GetLength() - (idx + 1));
}
else
{
strToken = strSrc;
strSrc.Empty();
}
if(bTrim)
{
strToken.TrimLeft();
strToken.TrimRight();
}
return strToken;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CWebPage::CWebPage()
{
}
CWebPage::~CWebPage()
{
}
bool CWebPage::SetDocument(IDispatch* pDisp)
{
CHECK_POINTER(pDisp);
m_spDoc = NULL;
CComPtr<IDispatch> spDisp = pDisp;
HRESULT hr = spDisp->QueryInterface(IID_IHTMLDocument2,(void**)&m_spDoc);
if(FAILED(hr))
{
ShowError(_T("Failed to get HTML document COM object"));
return false;
}
return true;
}
bool CWebPage::GetJScript(CComPtr<IDispatch>& spDisp)
{
CHECK_POINTER(m_spDoc);
HRESULT hr = m_spDoc->get_Script(&spDisp);
ATLASSERT(SUCCEEDED(hr));
return SUCCEEDED(hr);
}
bool CWebPage::GetJScripts(CComPtr<IHTMLElementCollection>& spColl)
{
CHECK_POINTER(m_spDoc);
HRESULT hr = m_spDoc->get_scripts(&spColl);
ATLASSERT(SUCCEEDED(hr));
return SUCCEEDED(hr);
}
bool CWebPage::InsertJScript(CString src)
{
CHECK_POINTER(m_spDoc);
/*
// The value of bstrScript should from HTC file,which represents the script function you want to invoke.
//Here for the simplicity's sake, I set this value directly.
BSTR bstrScript = SysAllocString(OLESTR("function fun1(){alert(\"My Script\");}"));
BSTR bstrInsertWhere = SysAllocString(OLESTR("afterBegin"));
CComPtr<IHTMLElement> spElement;
CComPtr<IHTMLElement2> spElement2;
CComPtr<IHTMLElement> spScriptElement;
CComPtr<IHTMLScriptElement > spScript;
//Create the script element, which will be inserted into HTMLDocument
m_spDoc->get_body(&spElement);
m_spDoc->createElement(CComBSTR(_T("script")), &spScriptElement);
//Set text and attribute of this script element
spScriptElement->QueryInterface(IID_IHTMLScriptElement,(void**)&spScript );
spScript->put_defer(VARIANT_TRUE);
spScript->put_text(bstrScript);
//Insert this element into HTMLDocument
spElement->QueryInterface(IID_IHTMLElement2, (void**)&spElement2);
spElement2->insertAdjacentElement(bstrInsertWhere, spScriptElement, NULL);
//Free resource
SysFreeString(bstrScript);
SysFreeString(bstrInsertWhere);
*/
///////////////////////////////////////////
CComPtr<IHTMLElementCollection> pColl;
HRESULT hr = m_spDoc->get_all(&pColl);
if(FAILED(hr)){
return false;
}
long l;
if(S_OK == pColl->get_length(&l))
{
for(long i=0; i<l; i++)
{
VARIANT vt;
vt.vt = VT_I4;
vt.lVal = i;
CComPtr<IDispatch> pDis;
if(S_OK == pColl->item(vt, vt, &pDis))
{
CComBSTR str;
CComPtr<IHTMLDOMNode> pNode = NULL;
hr = pDis->QueryInterface(IID_IHTMLDOMNode, (void **)&pNode);
if(SUCCEEDED(hr) && pNode)
{
if(S_OK == pNode->get_nodeName(&str))
{
CComPtr<IHTMLElement> pEle;
//获取body element
if(str == CComBSTR("HEAD") || str == CComBSTR("head"))
{
//CComPtr<IHTMLElement> spElement;
CComPtr<IHTMLElement> spScriptElement;
CComPtr<IHTMLScriptElement > spScript;
//创建一个script关键字的element
if(S_OK == m_spDoc->createElement(CComBSTR(_T("SCRIPT")), &spScriptElement))
{
if(S_OK == spScriptElement->QueryInterface(IID_IHTMLScriptElement,(void**)&spScript )){
spScript->put_defer(VARIANT_TRUE);
spScript->put_src(CComBSTR(src));
spScript->put_type(CComBSTR(_T("text/javascript")));
}
CComPtr<IHTMLDOMNode> pNodeScript = NULL;
hr = spScriptElement->QueryInterface(IID_IHTMLDOMNode, (void **)&pNodeScript);
if(SUCCEEDED(hr) && pNodeScript) {
CComPtr<IHTMLDOMNode> pReturn;
//将新的element插入到body最后
if(S_OK == pNode->appendChild(pNodeScript, &pReturn) && pReturn)
{
return true;
}
}
}
return false;
}
}
}
}
}
}
return false;
}
CString CWebPage::GetHTMLContent()
{
CHECK_POINTER(m_spDoc);
CComPtr<IHTMLElement> pBody;
VERIFY(SUCCEEDED(m_spDoc->get_body(&pBody)));
CComBSTR content;
VERIFY(SUCCEEDED(pBody->get_innerHTML(&content)));
return CString(content);
}
/*
bool CWebPage::InsertJScript(CString src)
{
CHECK_POINTER(m_spDoc);
CComPtr<IHTMLElementCollection> spColl;
if(!GetJScripts(spColl)){
return false;
}
// Make sure there are items in the collection
long lCount;
if(SUCCEEDED(spColl->get_length(&lCount)) && lCount > 0)
{
CComPtr<IDispatch> pDisp;
CComVariant varName,varIndex(lCount);
spColl->item(varName, varIndex, &pDisp);
// Get the element returned above and insert the text
// before the end of it
CComQIPtr<IHTMLElement> pElement(pDisp);
if(pElement){
CString s;
s.Format(_T("<script DEFER src=\"%s\" type=\"text/javascript\"></script>"), src);
HRESULT hr = pElement->insertAdjacentHTML(_T("beforeEnd"), CComBSTR(src));
if(SUCCEEDED(hr)){
return true;
}
GetSystemErrorMessage(hr);
}
}
return false;
}
*/
bool CWebPage::CallJScript(const CString strFunc,CComVariant* pVarResult)
{
CStringArray paramArray;
return CallJScript(strFunc,paramArray,pVarResult);
}
bool CWebPage::CallJScript(const CString strFunc,const CString strArg1,CComVariant* pVarResult)
{
CStringArray paramArray;
paramArray.Add(strArg1);
return CallJScript(strFunc,paramArray,pVarResult);
}
bool CWebPage::CallJScript(const CString strFunc,const CString strArg1,const CString strArg2,CComVariant* pVarResult)
{
CStringArray paramArray;
paramArray.Add(strArg1);
paramArray.Add(strArg2);
return CallJScript(strFunc,paramArray,pVarResult);
}
bool CWebPage::CallJScript(const CString strFunc,const CString strArg1,const CString strArg2,const CString strArg3,CComVariant* pVarResult)
{
CStringArray paramArray;
paramArray.Add(strArg1);
paramArray.Add(strArg2);
paramArray.Add(strArg3);
return CallJScript(strFunc,paramArray,pVarResult);
}
bool CWebPage::CallJScript(const CString strFunc, const CStringArray& paramArray,CComVariant* pVarResult)
{
CComPtr<IDispatch> spScript;
if(!GetJScript(spScript))
{
ShowError(_T("Cannot GetScript"));
return false;
}
CComBSTR bstrMember(strFunc);
DISPID dispid = NULL;
HRESULT hr = spScript->GetIDsOfNames(IID_NULL,&bstrMember,1,
LOCALE_SYSTEM_DEFAULT,&dispid);
if(FAILED(hr))
{
ShowError(GetSystemErrorMessage(hr));
return false;
}
const int arraySize = paramArray.GetSize();
DISPPARAMS dispparams;
memset(&dispparams, 0, sizeof dispparams);
dispparams.cArgs = arraySize;
dispparams.rgvarg = new VARIANT[dispparams.cArgs];
for(int i = 0; i < arraySize; i++)
{
CComBSTR bstr = paramArray.GetAt(arraySize - 1 - i); // back reading
bstr.CopyTo(&dispparams.rgvarg[i].bstrVal);
dispparams.rgvarg[i].vt = VT_BSTR;
}
dispparams.cNamedArgs = 0;
EXCEPINFO excepInfo;
memset(&excepInfo, 0, sizeof excepInfo);
CComVariant vaResult;
UINT nArgErr = (UINT)-1; // initialize to invalid arg
hr = spScript->Invoke(dispid,IID_NULL,0,
DISPATCH_METHOD,&dispparams,&vaResult,&excepInfo,&nArgErr);
delete [] dispparams.rgvarg;
if(FAILED(hr))
{
ShowError(GetSystemErrorMessage(hr));
return false;
}
if(pVarResult)
{
*pVarResult = vaResult;
}
return true;
}
// returned java script function name, input string is truncating
CString CWebPage::ScanJScript(CString& strAText, CStringArray& args)
{
args.RemoveAll();
CString strDelim(" \n\r\t"),strSrc(strAText);
bool bFound = false;
while(!strSrc.IsEmpty())
{
CString strStart = GetNextToken(strSrc,strDelim);
if(strStart == "function")
{
bFound = true;
break;
}
if(strStart == "/*")
{
// Skip comments
while(!strSrc.IsEmpty())
{
CString strStop = GetNextToken(strSrc,strDelim);
if(strStop == "*/")
{
break;
}
}
}
}
if(!bFound){
return _T("");
}
CString strFunc = GetNextToken(strSrc, _T("("),true);
CString strArgs = GetNextToken(strSrc, _T(")"),true);
// Parse arguments
CString strArg;
while(!(strArg = GetNextToken(strArgs, _T(","))).IsEmpty())
args.Add(strArg);
strAText= strSrc;
return strFunc;
}
| [
"netnchen@631d5421-cb3f-0410-96e9-8590a48607ad"
] | [
[
[
1,
392
]
]
] |
2500e196b7fd9b9c198651df00dfe309d48f4205 | a0155e192c9dc2029b231829e3db9ba90861f956 | /Libs/mwnlm/Libraries/MSL C++/Include/functional.h | 36b8e5ad73d604e752f3a4b3cd419fe5ce451a4a | [] | no_license | zeha/mailfilter | d2de4aaa79bed2073cec76c93768a42068cfab17 | 898dd4d4cba226edec566f4b15c6bb97e79f8001 | refs/heads/master | 2021-01-22T02:03:31.470739 | 2010-08-12T23:51:35 | 2010-08-12T23:51:35 | 81,022,257 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,931 | h | /* Metrowerks Standard Library
* Copyright © 1995-2002 Metrowerks Corporation. All rights reserved.
*
* $Date: 2002/07/01 21:13:32 $
* $Revision: 1.3 $
*/
// functional.h // hh 971207 Changed filename from functional to functional.h
#ifndef _FUNCTIONAL_H // hh 971207 added standard include guards
#define _FUNCTIONAL_H
#include <functional>
#ifndef _MSL_NO_CPP_NAMESPACE // hh 971207 Added backward compatibility
using std::unary_function;
using std::binary_function;
using std::plus;
using std::minus;
using std::multiplies;
using std::divides;
using std::modulus;
using std::negate;
using std::equal_to;
using std::not_equal_to;
using std::greater;
using std::less;
using std::greater_equal;
using std::less_equal;
using std::logical_and;
using std::logical_or;
using std::logical_not;
using std::unary_negate;
using std::not1;
using std::binary_negate;
using std::not2;
using std::binder1st;
using std::bind1st;
using std::binder2nd;
using std::bind2nd;
using std::pointer_to_unary_function;
using std::pointer_to_binary_function;
using std::ptr_fun;
using std::mem_fun_t;
using std::mem_fun1_t;
using std::mem_fun;
using std::mem_fun_ref_t;
using std::mem_fun1_ref_t;
using std::mem_fun_ref;
#if !defined(__MWERKS__) || (defined(__MWERKS__) && __MWERKS__ >= 0x2400)
using std::const_mem_fun_t;
using std::const_mem_fun1_t;
using std::const_mem_fun_ref_t;
using std::const_mem_fun1_ref_t;
#endif
#endif
#endif // _FUNCTIONAL_H
// hh 971207 Changed filename from functional to functional.h
// hh 971207 added standard include guards
// hh 971207 Added backward compatibility
// hh 990120 changed name of MSIPL flags
// hh 991112 modified using policy
// hh 020102 Removed pointer_to_binary_function_with_const_args
// and pointer_to_unary_function_with_const_args.
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
d2289c9817b8ac31740b912b6979b6e12a63f037 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/Qt/qtestevent.h | 1bf25a243d3c07a679cfdac97b9c61f6cae1fc9a | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,376 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtTest module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QTESTEVENT_H
#define QTESTEVENT_H
#if 0
// inform syncqt
#pragma qt_no_master_include
#endif
#include <QtTest/qtest_global.h>
#include <QtTest/qtestkeyboard.h>
#include <QtTest/qtestmouse.h>
#include <QtTest/qtestsystem.h>
#include <QtCore/qlist.h>
#include <stdlib.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Test)
class QTestEvent
{
public:
virtual void simulate(QWidget *w) = 0;
virtual QTestEvent *clone() const = 0;
virtual ~QTestEvent() {}
};
class QTestKeyEvent: public QTestEvent
{
public:
inline QTestKeyEvent(QTest::KeyAction action, Qt::Key key, Qt::KeyboardModifiers modifiers, int delay)
: _action(action), _delay(delay), _modifiers(modifiers), _ascii(0), _key(key) {}
inline QTestKeyEvent(QTest::KeyAction action, char ascii, Qt::KeyboardModifiers modifiers, int delay)
: _action(action), _delay(delay), _modifiers(modifiers),
_ascii(ascii), _key(Qt::Key_unknown) {}
inline QTestEvent *clone() const { return new QTestKeyEvent(*this); }
inline void simulate(QWidget *w)
{
if (_ascii == 0)
QTest::keyEvent(_action, w, _key, _modifiers, _delay);
else
QTest::keyEvent(_action, w, _ascii, _modifiers, _delay);
}
protected:
QTest::KeyAction _action;
int _delay;
Qt::KeyboardModifiers _modifiers;
char _ascii;
Qt::Key _key;
};
class QTestKeyClicksEvent: public QTestEvent
{
public:
inline QTestKeyClicksEvent(const QString &keys, Qt::KeyboardModifiers modifiers, int delay)
: _keys(keys), _modifiers(modifiers), _delay(delay) {}
inline QTestEvent *clone() const { return new QTestKeyClicksEvent(*this); }
inline void simulate(QWidget *w)
{
QTest::keyClicks(w, _keys, _modifiers, _delay);
}
private:
QString _keys;
Qt::KeyboardModifiers _modifiers;
int _delay;
};
class QTestMouseEvent: public QTestEvent
{
public:
inline QTestMouseEvent(QTest::MouseAction action, Qt::MouseButton button,
Qt::KeyboardModifiers modifiers, QPoint position, int delay)
: _action(action), _button(button), _modifiers(modifiers), _pos(position), _delay(delay) {}
inline QTestEvent *clone() const { return new QTestMouseEvent(*this); }
inline void simulate(QWidget *w)
{
QTest::mouseEvent(_action, w, _button, _modifiers, _pos, _delay);
}
private:
QTest::MouseAction _action;
Qt::MouseButton _button;
Qt::KeyboardModifiers _modifiers;
QPoint _pos;
int _delay;
};
class QTestDelayEvent: public QTestEvent
{
public:
inline QTestDelayEvent(int msecs): _delay(msecs) {}
inline QTestEvent *clone() const { return new QTestDelayEvent(*this); }
inline void simulate(QWidget * /*w*/) { QTest::qWait(_delay); }
private:
int _delay;
};
class QTestEventList: public QList<QTestEvent *>
{
public:
inline QTestEventList() {}
inline QTestEventList(const QTestEventList &other): QList<QTestEvent *>()
{ for (int i = 0; i < other.count(); ++i) append(other.at(i)->clone()); }
inline ~QTestEventList()
{ clear(); }
inline void clear()
{ qDeleteAll(*this); QList<QTestEvent *>::clear(); }
inline void addKeyClick(Qt::Key qtKey, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ addKeyEvent(QTest::Click, qtKey, modifiers, msecs); }
inline void addKeyPress(Qt::Key qtKey, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ addKeyEvent(QTest::Press, qtKey, modifiers, msecs); }
inline void addKeyRelease(Qt::Key qtKey, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ addKeyEvent(QTest::Release, qtKey, modifiers, msecs); }
inline void addKeyEvent(QTest::KeyAction action, Qt::Key qtKey,
Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ append(new QTestKeyEvent(action, qtKey, modifiers, msecs)); }
inline void addKeyClick(char ascii, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ addKeyEvent(QTest::Click, ascii, modifiers, msecs); }
inline void addKeyPress(char ascii, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ addKeyEvent(QTest::Press, ascii, modifiers, msecs); }
inline void addKeyRelease(char ascii, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ addKeyEvent(QTest::Release, ascii, modifiers, msecs); }
inline void addKeyClicks(const QString &keys, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ append(new QTestKeyClicksEvent(keys, modifiers, msecs)); }
inline void addKeyEvent(QTest::KeyAction action, char ascii, Qt::KeyboardModifiers modifiers = Qt::NoModifier, int msecs = -1)
{ append(new QTestKeyEvent(action, ascii, modifiers, msecs)); }
inline void addMousePress(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MousePress, button, stateKey, pos, delay)); }
inline void addMouseRelease(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MouseRelease, button, stateKey, pos, delay)); }
inline void addMouseClick(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MouseClick, button, stateKey, pos, delay)); }
inline void addMouseDClick(Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0,
QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MouseDClick, button, stateKey, pos, delay)); }
inline void addMouseMove(QPoint pos = QPoint(), int delay=-1)
{ append(new QTestMouseEvent(QTest::MouseMove, Qt::NoButton, 0, pos, delay)); }
inline void addDelay(int msecs)
{ append(new QTestDelayEvent(msecs)); }
inline void simulate(QWidget *w)
{
for (int i = 0; i < count(); ++i)
at(i)->simulate(w);
}
};
QT_END_NAMESPACE
Q_DECLARE_METATYPE(QTestEventList)
QT_END_HEADER
#endif
| [
"alon@rogue.(none)"
] | [
[
[
1,
214
]
]
] |
c03e269395b3141a1677d652774d5776fbe91e4b | b5ab57edece8c14a67cc98e745c7d51449defcff | /Captain's Log/MainGame/Source/States/CHelpState.cpp | d6d04a877a149ddd99aaf3acc6551f3f930a6d5b | [] | no_license | tabu34/tht-captainslog | c648c6515424a6fcdb628320bc28fc7e5f23baba | 72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2 | refs/heads/master | 2020-05-30T15:09:24.514919 | 2010-07-30T17:05:11 | 2010-07-30T17:05:11 | 32,187,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | cpp | #include "precompiled_header.h"
#include "CHelpState.h"
#include "..\CGame.h"
#include "..\SGD Wrappers\CSGD_TextureManager.h"
#include "..\SGD Wrappers\CSGD_DirectInput.h"
#include "..\Managers\\MovementControl.h"
CHelpState::CHelpState()
{
}
CHelpState::~CHelpState()
{
}
CHelpState* CHelpState::GetInstance()
{
static CHelpState instance;
return &instance;
}
void CHelpState::Enter()
{
m_nBGImage[0] = CSGD_TextureManager::GetInstance()->LoadTexture(CGame::GetInstance()->GraphicsPath("howToPlayScreen.png").c_str());
m_nBGImage[1] = CSGD_TextureManager::GetInstance()->LoadTexture(CGame::GetInstance()->GraphicsPath("howToPlayScreen2.png").c_str());
curPage = 0;
}
void CHelpState::Exit()
{
CSGD_TextureManager::GetInstance()->UnloadTexture(m_nBGImage[0]);
CSGD_TextureManager::GetInstance()->UnloadTexture(m_nBGImage[1]);
}
bool CHelpState::Input()
{
if(CSGD_DirectInput::GetInstance()->KeyPressedEx(DIK_SPACE))
curPage++;
if(CSGD_DirectInput::GetInstance()->KeyPressedEx(DIK_TAB))
curPage--;
if(curPage == 2)
CGame::GetInstance()->PopState();
if(curPage == -1)
curPage = 1;
CMovementControl::GetInstance()->Input();
return true;
}
void CHelpState::Update(float fElapsedTime)
{
}
void CHelpState::Render()
{
CSGD_TextureManager::GetInstance()->Draw(m_nBGImage[curPage], 0, 0);
CMovementControl::GetInstance()->RenderCursor();
} | [
"[email protected]@34577012-8437-c882-6fb8-056151eb068d",
"notserp007@34577012-8437-c882-6fb8-056151eb068d"
] | [
[
[
1,
5
],
[
7,
25
],
[
29,
32
],
[
35,
38
],
[
46,
46
],
[
52,
56
],
[
58,
61
],
[
64,
64
]
],
[
[
6,
6
],
[
26,
28
],
[
33,
34
],
[
39,
45
],
[
47,
51
],
[
57,
57
],
[
62,
63
]
]
] |
43fb6a210da69538a9d03975bb89266df6f71594 | b67f9fa50b816d0c8a0d6328cafe711c8c21f75e | /trunk/wdg_serialtab.cpp | db8c80ffb6185658a3372bceaba886aa39991516 | [] | no_license | BackupTheBerlios/osibs-svn | d46db4e3f78fe872f3dad81d2767d8d8e530e831 | 151911e8fb044c183fca251d226a21cfbf4c6c8f | refs/heads/master | 2021-01-20T12:42:52.308488 | 2011-08-17T19:51:02 | 2011-08-17T19:51:02 | 40,800,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 198 | cpp | #include "wdg_serialtab.h"
#include "ui_wdg_serialtab.h"
wdg_serialtab::wdg_serialtab(QWidget *parent) :
QWidget(parent)
{
setupUi(this);
}
wdg_serialtab::~wdg_serialtab()
{
}
| [
"osiair@cc7348f7-d3be-4701-adbb-128cb98a0978"
] | [
[
[
1,
12
]
]
] |
a4da1f4b9ebe0bd81bf47265dd6795a02de08bf3 | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/ch06/Fig06_21/fig06_21.cpp | 4340d1a4f2be0ddcca674978ed9f6efc21d7bb36 | [] | no_license | tecmilenio/computacion2 | 728ac47299c1a4066b6140cebc9668bf1121053a | a1387e0f7f11c767574fcba608d94e5d61b7f36c | refs/heads/master | 2016-09-06T19:17:29.842053 | 2008-09-28T04:27:56 | 2008-09-28T04:27:56 | 50,540 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,470 | cpp | // Fig. 6.21: fig06_21.cpp
// References must be initialized.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int x = 3;
int &y; // Error: y must be initialized
cout << "x = " << x << endl << "y = " << y << endl;
y = 7;
cout << "x = " << x << endl << "y = " << y << endl;
return 0; // indicates successful termination
} // end main
/**************************************************************************
* (C) Copyright 1992-2008 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
| [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
b48fde8ed62de54d20eac6fc89217ea12a3b50ee | a37df219b4a30e684db85b00dd76d4c36140f3c2 | /1.7.1/dbloader/frame.h | d44ecd7a1f18d4007224cef8e377545b8bee82ce | [] | no_license | BlackMoon/bm-net | 0f79278f8709cd5d0738a6c3a27369726b0bb793 | eb6414bc412a8cfc5c24622977e7fa7203618269 | refs/heads/master | 2020-12-25T20:20:44.843483 | 2011-11-29T10:33:17 | 2011-11-29T10:33:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 920 | h | // frame.h : interface of the CMainFrame class
//
#pragma once
#include "view.h"
class CMainFrame : public CFrameWnd
{
DECLARE_DYNAMIC(CMainFrame)
public:
CMainFrame();
protected:
// Attributes
public:
// Operations
public:
// Overrides
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo);
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CStatusBar m_wndStatusBar;
CToolBar m_wndToolBar;
CChildView m_wndView;
// Generated message map functions
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSetFocus(CWnd *pOldWnd);
afx_msg void OnClick();
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]@b6168ec3-97fc-df6f-cbe5-288b4f99fbbd"
] | [
[
[
1,
47
]
]
] |
614ca0f924740b2d30070c6c2cda9c33ba085529 | 94c1c7459eb5b2826e81ad2750019939f334afc8 | /source/picture2.cpp | 5df6c78fde52f13678d3b4490b42cf8f9dc7b566 | [] | no_license | wgwang/yinhustock | 1c57275b4bca093e344a430eeef59386e7439d15 | 382ed2c324a0a657ddef269ebfcd84634bd03c3a | refs/heads/master | 2021-01-15T17:07:15.833611 | 2010-11-27T07:06:40 | 2010-11-27T07:06:40 | 37,531,026 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,131 | cpp | // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
#include "stdafx.h"
#include "picture2.h"
/////////////////////////////////////////////////////////////////////////////
//tel:13366898744
long CPicture1::GetHandle()
{
long result;
GetProperty(0x0, VT_I4, (void*)&result);
return result;
}
long CPicture1::GetHPal()
{
long result;
GetProperty(0x2, VT_I4, (void*)&result);
return result;
}
void CPicture1::SetHPal(long propVal)
{
SetProperty(0x2, VT_I4, propVal);
}
short CPicture1::GetType()
{
short result;
GetProperty(0x3, VT_I2, (void*)&result);
return result;
}
long CPicture1::GetWidth()
{
long result;
GetProperty(0x4, VT_I4, (void*)&result);
return result;
}
long CPicture1::GetHeight()
{
long result;
GetProperty(0x5, VT_I4, (void*)&result);
return result;
}
/////////////////////////////////////////////////////////////////////////////
// CPicture1 operations
| [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
c16635a4b0e381ffb0e6d9e50a985067208b1441 | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/src/OpenGL/Texture3DGL.cpp | a1ff099c2fe9006f601215c1cf9e75b1bef06db5 | [] | no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,202 | cpp | /*******************************************************************************/
/**
* @file Texture3DGL.cpp.
*
* @brief OpenGL 3Dテクスチャクラスソースファイル.
*
* @date 2008/07/20.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#include "Ngl/OpenGL/Texture3DGL.h"
using namespace Ngl;
using namespace Ngl::OpenGL;
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] desc テクスチャ作成記述子.
* @param[in] data テクスチャイメージデータ配列.
*/
Texture3DGL::Texture3DGL( const TextureDesc& desc, const void* data ):
TextureGL( desc, data )
{
initialize( data );
}
/*=========================================================================*/
/**
* @brief イメージを設定
*
* @param[in] data 設定するイメージの配列.
* @param[in] mipLevel 設定先のミップマップレベル.
* @param[in] index 設定先のインデックス番号.
* @return なし.
*/
void Texture3DGL::texImage( const void* data, unsigned int mipLevel, unsigned int index )
{
// 無圧縮イメージ
glTexImage3D(
target(index),
mipLevel,
pixel().internalFormat,
mipSize( desc().width, mipLevel ),
mipSize( desc().height, mipLevel ),
mipSize( desc().depth, mipLevel ),
0,
pixel().format, pixel().type, data
);
}
/*=========================================================================*/
/**
* @brief イメージの更新
*
* @param[in] data 更新するイメージデータの配列.
* @param[in] mipLevel 更新先のミップマップレベル.
* @param[in] index 更新先のインデックス番号.
* @return OpenGLターゲットフラグ.
*/
void Texture3DGL::texSubImage( const void* data, unsigned int mipLevel, unsigned int index )
{
if( pixel().complessedFormat ){
// 圧縮イメージ
glCompressedTexSubImage3DARB(
target( index ),
mipLevel,
0, 0, 0,
mipSize( desc().width, mipLevel ),
mipSize( desc().height, mipLevel ),
mipSize( desc().depth, mipLevel ),
pixel().format,
imageSize( mipLevel ),
data
);
}
else{
// 無圧縮イメージ
glTexSubImage3D(
target( index ),
mipLevel,
0, 0, 0,
mipSize( desc().width, mipLevel ),
mipSize( desc().height, mipLevel ),
mipSize( desc().depth, mipLevel ),
pixel().format, pixel().type, data
);
}
}
/*=========================================================================*/
/**
* @brief フレームバッファオブジェクトへのアタッチ
*
* @param[in] drawBuffer 描画バッファ番号.
* @param[in] index インデックス番号.
* @return なし.
*/
void Texture3DGL::framebufferTexture( GLuint drawBuffer, unsigned int index )
{
(void)index;
glFramebufferTexture3DEXT(
GL_FRAMEBUFFER_EXT,
GL_COLOR_ATTACHMENT0_EXT + drawBuffer,
GL_TEXTURE_3D,
texture(),
0,
index
);
}
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
] | [
[
[
1,
124
]
]
] |
a2a914ac88b21fe366b971ed36fc6a8d6670239b | 33cdd09e352529963fe8b28b04e0d2e33483777b | /trunk/ReportAsistent/AttributeLinkTableDialog.cpp | 0d98f9c5aa0c6c59a605d381ad92f6e05eb6e27a | [] | no_license | BackupTheBerlios/reportasistent-svn | 20e386c86b6990abafb679eeb9205f2aef1af1ac | 209650c8cbb0c72a6e8489b0346327374356b57c | refs/heads/master | 2020-06-04T16:28:21.972009 | 2010-05-18T12:06:48 | 2010-05-18T12:06:48 | 40,804,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,389 | cpp | // AttributeLinkTableDialog.cpp : implementation file
//
//
// This file is part of LM Report Asistent. (http://reportasistent.berlios.de, [email protected])
//
// Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova
//
// LM Report Asistent 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.
//
// LM Report Asistent 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 LM Report Asistent; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "stdafx.h"
#include "ReportAsistent.h"
#include "AttributeLinkTableDialog.h"
#include "CSkeletonDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAttributeLinkTableDialog dialog
CAttributeLinkTableDialog::CAttributeLinkTableDialog(MSXML2::IXMLDOMElementPtr & edited_element, CWnd* pParent, BOOL show_target)
: CDialog(CAttributeLinkTableDialog::IDD, pParent), CAttributeLinkDialogBase(edited_element),
m_bShowTarget(show_target)
{
ASSERT(edited_element != NULL);
//{{AFX_DATA_INIT(CAttributeLinkTableDialog)
m_AttrLinkTable_IdEdit = _T("");
//}}AFX_DATA_INIT
//Iva: Initialisation of variables of the dialog
//Id
_variant_t varAtr=m_SelXMLElm->getAttribute("id");
m_OldID=(LPCTSTR) (_bstr_t) varAtr;
if (varAtr.vt!=VT_NULL)
m_AttrLinkTable_IdEdit = m_OldID;
}
void CAttributeLinkTableDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAttributeLinkTableDialog)
DDX_Control(pDX, IDC_STYLE_COMBO, m_StyleCombo);
DDX_Control(pDX, IDC_CAPTIONS_LIST, m_CaptionsList);
DDX_Control(pDX, IDC_TARGET_COMBO, m_TargetCombo);
DDX_Control(pDX, IDC_ATTRIBUTES_LIST, m_AttributesList);
DDX_Text(pDX, IDC_ATTRLINKTABLE_ID_EDIT, m_AttrLinkTable_IdEdit);
DDV_MaxChars(pDX, m_AttrLinkTable_IdEdit, 50);
//}}AFX_DATA_MAP
DDV_NonDuplicateID(pDX,IDC_ATTRLINKTABLE_ID_EDIT, m_AttrLinkTable_IdEdit);
}
BEGIN_MESSAGE_MAP(CAttributeLinkTableDialog, CDialog)
//{{AFX_MSG_MAP(CAttributeLinkTableDialog)
ON_CBN_SELCHANGE(IDC_TARGET_COMBO, OnSelchangeTargetCombo)
ON_BN_CLICKED(IDC_REFRESH_BUTTON, OnRefreshButton)
ON_BN_CLICKED(IDC_ADD_BUTTON, OnAddButton)
ON_NOTIFY(LVN_ENDLABELEDIT, IDC_CAPTIONS_LIST, OnEndlabeleditCaptionsList)
ON_BN_CLICKED(IDC_REMOVE_BUTTON, OnRemoveButton)
ON_BN_CLICKED(IDC_EDIT_CAPTION_BUTTON, OnEditCaptionButton)
ON_BN_CLICKED(IDC_MOVE_UP_BUTTON, OnMoveUpButton)
ON_BN_CLICKED(IDC_MOVE_DOWN_BUTTON2, OnMoveDownButton)
ON_NOTIFY(NM_DBLCLK, IDC_ATTRIBUTES_LIST, OnDblclkAttributesList)
//}}AFX_MSG_MAP
ON_NOTIFY(LVN_DELETEITEM, IDC_ATTRIBUTES_LIST, OnLvnDeleteitemAttributesList)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAttributeLinkTableDialog message handlers
#define CAPTLIST_CL_CAPTION 0
#define CAPTLIST_CL_VALUE 1
#define CAPTLIST_CL_NAME 2
BOOL CAttributeLinkTableDialog::OnInitDialog()
{
CDialog::OnInitDialog();
if (! m_bShowTarget) m_TargetCombo.EnableWindow(FALSE);
InitBaseDialog(m_AttributesList, m_TargetCombo);
//dedek: inicializuj CaptionsList
CRect r;
m_CaptionsList.GetWindowRect(& r);
m_CaptionsList.InsertColumn(CAPTLIST_CL_CAPTION, "caption", LVCFMT_LEFT, r.Width()/3 -3);
m_CaptionsList.InsertColumn(CAPTLIST_CL_VALUE, "value", LVCFMT_LEFT, r.Width()/3 -3);
m_CaptionsList.InsertColumn(CAPTLIST_CL_NAME, "name", LVCFMT_LEFT, r.Width()/3 -3);
//napln CaptionsList hodnotami
m_CaptionsList.SetExtendedStyle(LVS_EX_FULLROWSELECT);
MSXML2::IXMLDOMNodeListPtr links = m_SelXMLElm->selectNodes("link");
CString target_id;
m_TargetCombo.GetWindowText(target_id);
int a;
for (a=0; a < links->length; a++)
{
MSXML2::IXMLDOMElementPtr link = links->item[a];
//caption
int item = m_CaptionsList.InsertItem(a, (_bstr_t) link->getAttribute("caption"));
//attr_name
CString attr_name = (LPCTSTR) (_bstr_t) link->getAttribute("attr_name");
m_CaptionsList.SetItemText(item, CAPTLIST_CL_NAME, attr_name);
//value
CString query_str;
query_str.Format("id(\"%s\")/attributes/element_attributes/attribute[@name=\"%s\"]/@value", target_id, attr_name);
MSXML2::IXMLDOMNodePtr value_attr = m_SelXMLElm->ownerDocument->selectSingleNode((LPCTSTR) query_str);
if (value_attr != NULL)
{
m_CaptionsList.SetItemText(item, CAPTLIST_CL_VALUE, value_attr->text);
value_attr.Release();
}
link.Release();
}
//napln style combo
CElementManager & m = ((CReportAsistentApp *) AfxGetApp())->m_pGeneralManager->ElementManager;
int item = CB_ERR;
for (a=0; a < m.getAttrLinkTableStylesCount(); a++)
{
item = m_StyleCombo.AddString(m.getAttrLinkTableStyleName(a));
}
//vyber style
int sel = m_StyleCombo.SelectString(-1, (_bstr_t) m_SelXMLElm->getAttribute("style"));
//vyber se nezdaril => kdyz exituje nejaky styl vyber prvni
if ((sel == CB_ERR) && (item != CB_ERR))
{
m_StyleCombo.SelectString(-1, m.getAttrLinkTableStyleName(0));
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CAttributeLinkTableDialog::OnSelchangeTargetCombo()
{
CString target_id;
m_TargetCombo.GetWindowText(target_id);
FillAttributesList(m_AttributesList, target_id);
m_CaptionsList.DeleteAllItems();
}
void CAttributeLinkTableDialog::OnRefreshButton()
{
CString target_id;
m_TargetCombo.GetWindowText(target_id);
OnRefresh(m_AttributesList, target_id);
//refresh pro captions list
for (int a=0; a < m_CaptionsList.GetItemCount(); a++)
{
CString attr_name = m_CaptionsList.GetItemText(a, CAPTLIST_CL_NAME);
CString query_str;
query_str.Format("id(\"%s\")/attributes/element_attributes/attribute[@name=\"%s\"]/@value", target_id, attr_name);
MSXML2::IXMLDOMNodePtr attr_value = m_SelXMLElm->ownerDocument->selectSingleNode((LPCTSTR) query_str);
if (attr_value != NULL)
{
m_CaptionsList.SetItemText(a, CAPTLIST_CL_VALUE, attr_value->text);
attr_value.Release();
}
}
}
void CAttributeLinkTableDialog::OnAddButton()
{
int selected_item;
//najdi vybranou polozku v attribues listu
POSITION pos = m_AttributesList.GetFirstSelectedItemPosition();
while (pos != NULL)
{
selected_item = m_AttributesList.GetNextSelectedItem(pos);
if (!AddAttribute(selected_item)) return;
}
}
void CAttributeLinkTableDialog::OnEndlabeleditCaptionsList(NMHDR* pNMHDR, LRESULT* pResult)
{
LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR;
*pResult = FALSE;
if (pDispInfo->item.pszText != NULL)
{
*pResult = TRUE;
}
}
void CAttributeLinkTableDialog::OnRemoveButton()
{
int selected_item[MAX_CHOSEN_ATTRIBUTES_COUNT];
int I=0;
POSITION pos = m_CaptionsList.GetFirstSelectedItemPosition();
while (pos != NULL )
{
selected_item[I] = m_CaptionsList.GetNextSelectedItem(pos);
I++;
}
while (I>=0)
{
RemoveAttribute(selected_item[I]);
I--;
}
}
void CAttributeLinkTableDialog::OnEditCaptionButton()
{
POSITION pos = m_CaptionsList.GetFirstSelectedItemPosition();
if (pos == NULL) return;
int nItem = m_CaptionsList.GetNextSelectedItem(pos);
//edituj caption
m_CaptionsList.SetFocus();
m_CaptionsList.EditLabel(nItem);
}
void CAttributeLinkTableDialog::OnMoveUpButton()
{
POSITION pos = m_CaptionsList.GetFirstSelectedItemPosition();
if (pos == NULL) return;
int nItem = m_CaptionsList.GetNextSelectedItem(pos);
if (nItem <= 0) return;
CString name = m_CaptionsList.GetItemText(nItem, CAPTLIST_CL_NAME);
CString value = m_CaptionsList.GetItemText(nItem, CAPTLIST_CL_VALUE);
CString caption = m_CaptionsList.GetItemText(nItem, CAPTLIST_CL_CAPTION);
m_CaptionsList.DeleteItem(nItem);
nItem = m_CaptionsList.InsertItem(--nItem, caption);
m_CaptionsList.SetItemText(nItem, CAPTLIST_CL_NAME, name);
m_CaptionsList.SetItemText(nItem, CAPTLIST_CL_VALUE, value);
m_CaptionsList.SetItemState(nItem, LVIS_SELECTED, LVIS_SELECTED);
}
void CAttributeLinkTableDialog::OnMoveDownButton()
{
POSITION pos = m_CaptionsList.GetFirstSelectedItemPosition();
if (pos == NULL) return;
int nItem = m_CaptionsList.GetNextSelectedItem(pos);
if (nItem >= m_CaptionsList.GetItemCount()) return;
CString name = m_CaptionsList.GetItemText(nItem, CAPTLIST_CL_NAME);
CString value = m_CaptionsList.GetItemText(nItem, CAPTLIST_CL_VALUE);
CString caption = m_CaptionsList.GetItemText(nItem, CAPTLIST_CL_CAPTION);
m_CaptionsList.DeleteItem(nItem);
nItem = m_CaptionsList.InsertItem(++nItem, caption);
m_CaptionsList.SetItemText(nItem, CAPTLIST_CL_NAME, name);
m_CaptionsList.SetItemText(nItem, CAPTLIST_CL_VALUE, value);
m_CaptionsList.SetItemState(nItem, LVIS_SELECTED, LVIS_SELECTED);
}
void CAttributeLinkTableDialog::OnOK()
{
SaveTarget(m_TargetCombo);
//smaz vsecky link elementy
MSXML2::IXMLDOMSelectionPtr sel = m_SelXMLElm->selectNodes("link");
sel->removeAll();
sel.Release();
//vytvor vzorovy element
MSXML2::IXMLDOMElementPtr link_elenet = m_SelXMLElm->ownerDocument->createElement("link");
link_elenet->setAttributeNode(m_SelXMLElm->ownerDocument->createAttribute("attr_name"));
link_elenet->setAttributeNode(m_SelXMLElm->ownerDocument->createAttribute("caption"));
//pridej elementy podle listu
for (int a=0; a < m_CaptionsList.GetItemCount(); a++)
{
link_elenet->setAttribute("attr_name", (LPCTSTR) m_CaptionsList.GetItemText(a, CAPTLIST_CL_NAME));
link_elenet->setAttribute("caption", (LPCTSTR) m_CaptionsList.GetItemText(a, CAPTLIST_CL_CAPTION));
m_SelXMLElm->appendChild(link_elenet->cloneNode(VARIANT_FALSE));
}
link_elenet.Release();
//uloz style
CString style_str;
m_StyleCombo.GetWindowText(style_str);
m_SelXMLElm->setAttribute("style", (LPCTSTR) style_str);
CDialog::OnOK();
}
void CAttributeLinkTableDialog::OnLvnDeleteitemAttributesList(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
delete (CString *) pNMLV->lParam;
*pResult = 0;
}
void CAttributeLinkTableDialog::DDV_NonDuplicateID(CDataExchange *pDX, int nId, CString csIDEditValue)
{
if (0!=pDX->m_bSaveAndValidate) //Iva: if it's end of dialog, not beginning
{
if (""==csIDEditValue) //Iva: ID can't be empty string
{
SetDlgItemText(nId, m_OldID );
CReportAsistentApp::ReportError(IDS_INVALID_ELEMENT_ID);
pDX->Fail();
}
CSkeletonDoc * Doc = ((CReportAsistentApp *) AfxGetApp())->FirstDocumentInFirstTemplate();
if (m_OldID!=csIDEditValue) //Iva: if "==", then ID is in tree, but it's OK
{
if (Doc->IsIDInTree(csIDEditValue))
{
SetDlgItemText(nId, m_OldID ); //Iva: return old value to edit box
CReportAsistentApp::ReportError(IDS_DUPLICATE_ELEMENT_ID);
pDX->Fail();
}
else
{
//Iva: I try to set ID to new value
try
{
m_SelXMLElm->setAttribute("id", (LPCTSTR)csIDEditValue);
}
catch(_com_error &e)
{
SetDlgItemText(nId, m_OldID ); //Iva: return old value to edit box
m_SelXMLElm->setAttribute("id", (LPCTSTR)m_OldID);
CReportAsistentApp::ReportError(IDS_INVALID_ELEMENT_ID,e.Description() );
pDX->Fail();
}
m_SelXMLElm->setAttribute("id", (LPCTSTR)m_OldID);
}
}
}
}
BOOL CAttributeLinkTableDialog::AddAttribute(int selected_item)
{
CString Pom;
if (m_CaptionsList.GetItemCount() >= MAX_CHOSEN_ATTRIBUTES_COUNT)
{
Pom.Format("%d", MAX_CHOSEN_ATTRIBUTES_COUNT);
CReportAsistentApp::ReportError(IDS_TOO_MANY_SELECTED_ITEMS, Pom);
return FALSE;
}
CString label = m_AttributesList.GetItemText(selected_item, ATTRLIST_CL_NAME);
CString value = m_AttributesList.GetItemText(selected_item, ATTRLIST_CL_VALUE);
CString name = * (CString*) m_AttributesList.GetItemData(selected_item);
//vloz polozku na konec captions listu
int item = m_CaptionsList.InsertItem(m_CaptionsList.GetItemCount(), label);
m_CaptionsList.SetItemText(item, CAPTLIST_CL_NAME, name);
m_CaptionsList.SetItemText(item, CAPTLIST_CL_VALUE, value);
//edituj caption
m_CaptionsList.SetFocus();
m_CaptionsList.EditLabel(item);
return TRUE;
}
void CAttributeLinkTableDialog::RemoveAttribute(int selected_item)
{
m_CaptionsList.DeleteItem(selected_item);
}
void CAttributeLinkTableDialog::OnDblclkAttributesList(NMHDR* pNMHDR, LRESULT* pResult)
{
POSITION pos = m_AttributesList.GetFirstSelectedItemPosition();
if (pos != NULL)
{
int selected_item = m_AttributesList.GetNextSelectedItem(pos);
AddAttribute(selected_item);
}
*pResult = 0;
}
| [
"dedej1am@fded5620-0c03-0410-a24c-85322fa64ba0",
"ibart@fded5620-0c03-0410-a24c-85322fa64ba0"
] | [
[
[
1,
24
],
[
26,
43
],
[
45,
45
],
[
53,
63
],
[
66,
66
],
[
68,
80
],
[
82,
110
],
[
114,
133
],
[
135,
156
],
[
158,
194
],
[
196,
210
],
[
212,
213
],
[
219,
236
],
[
239,
239
],
[
250,
316
],
[
318,
321
],
[
325,
331
],
[
333,
339
],
[
341,
353
],
[
404,
404
],
[
421,
421
],
[
426,
426
]
],
[
[
25,
25
],
[
44,
44
],
[
46,
52
],
[
64,
65
],
[
67,
67
],
[
81,
81
],
[
111,
113
],
[
134,
134
],
[
157,
157
],
[
195,
195
],
[
211,
211
],
[
214,
218
],
[
237,
238
],
[
240,
249
],
[
317,
317
],
[
322,
324
],
[
332,
332
],
[
340,
340
],
[
354,
403
],
[
405,
420
],
[
422,
425
],
[
427,
441
]
]
] |
7a3dafc48dbc57df1ed1b23a9406e86855b2d98e | 3eae8bea68fd2eb7965cca5afca717b86700adb5 | /Engine/Project/Core/GnMesh/Source/GFireAttack.cpp | ed24ad8254a5420f4d9d070ee6e7631089c4b56a | [] | no_license | mujige77/WebGame | c0a218ee7d23609076859e634e10e29c92bb595b | 73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd | refs/heads/master | 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,091 | cpp | #include "GnGamePCH.h"
#include "GFireAttack.h"
GnImplementCreateAttack(GFireAttack, eIndexItemFire);
GFarAttack* GFireAttack::CreateAttack(guint32 uIndex)
{
GFireAttack* attck = GnNew GFireAttack();
attck->SetAttackCount( 10 );
attck->CreateAttackMesh( 2 );
attck->SetOriginalAttackRect( GnFRect(-90.0f, -5.0f, 50.0f, 5.0f ) );
attck->SetStartAttackTime( 0.2f );
attck->GetAttackDamageInfo()->SetAttackType( uIndex );
GnTimeController::SetCycleType( GnTimeController::ONCE, attck->GetAttackMesh() );
guint32 level = GUserAbility::GetAbilityLevel( eIndexSkillUp );
attck->GetAttackDamageInfo()->SetDamage( 10 + level * 10 );
return attck;
}
void GFireAttack::Update(float fTime)
{
GFarAttack::Update( fTime );
if( IsStopAnimation() )
{
SetIsDestory( true );
}
}
void GFireAttack::SetPosition(GnVector2 cPos)
{
GFarAttack::SetPosition( cPos );
if( GetFilpX() )
cPos.x += 50.0f;
GnFRect originalRect = GetOriginalAttackRect();
originalRect.MoveX( cPos.x );
originalRect.MoveY( cPos.y );
SetAttackRect( originalRect );
} | [
"[email protected]"
] | [
[
[
1,
41
]
]
] |
d4a91bf01eef3cd4138ce0951c0eccd5d9adaddc | fcdddf0f27e52ece3f594c14fd47d1123f4ac863 | /TeCom/src/Graphics/Source Files/TdkGdiPolygon.cpp | d214ee081767487372f1b2cccf14781add728121 | [] | no_license | radtek/terra-printer | 32a2568b1e92cb5a0495c651d7048db6b2bbc8e5 | 959241e52562128d196ccb806b51fda17d7342ae | refs/heads/master | 2020-06-11T01:49:15.043478 | 2011-12-12T13:31:19 | 2011-12-12T13:31:19 | null | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 9,162 | cpp | #include <TdkGdiPoint.h>
#include <TdkGdiLine.h>
#include <TdkGdiPolygon.h>
///////////////////////////////////////////////////////////////////////////////
//Constructor
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
TdkGdiPolygon::TdkGdiPolygon()
{
_lineStyle=new TdkGdiLine();
_polygonDecorator=NULL;
_brush=new SolidBrush(Color(255,0,0));
}
///////////////////////////////////////////////////////////////////////////////
//Constructor
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
TdkGdiPolygon::TdkGdiPolygon(TdkGdiLine *line)
{
_lineStyle=line;
_polygonDecorator=NULL;
_brush=new SolidBrush(Color(255,0,0));
}
///////////////////////////////////////////////////////////////////////////////
//Destructor
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
TdkGdiPolygon::~TdkGdiPolygon()
{
if(_lineStyle) delete _lineStyle;
if(_polygonDecorator) delete _polygonDecorator;
if(_brush) delete _brush;
}
///////////////////////////////////////////////////////////////////////////////
//draw a polygon
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::draw(GraphicsPath* polygon, Graphics* graphic)
{
if(graphic!=NULL)
{
if(_brush) graphic->FillPath(_brush,polygon);
if(_lineStyle!=NULL)
{
_lineStyle->draw(polygon,graphic);
}
}
}
///////////////////////////////////////////////////////////////////////////////
//Sets the back color
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::setColor(const Color &color)
{
BrushType type;
HatchStyle style;
if(!_brush) return;
style=((HatchBrush*)_brush)->GetHatchStyle();
type=_brush->GetType();
if(_brush) delete _brush;
if(type == BrushTypeSolidColor)
{
_brush=new SolidBrush(color);
}else
{
_brush=new HatchBrush(style,color,Color(0,0,0,0));
}
}
///////////////////////////////////////////////////////////////////////////////
//Sets the alpha color
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::setAlpha(const int &alpha)
{
Color color;
if(_brush)
{
((SolidBrush*)_brush)->GetColor(&color);
((SolidBrush*)_brush)->SetColor(Color(alpha,color.GetR(),color.GetG(),color.GetB()));
}
}
///////////////////////////////////////////////////////////////////////////////
//Sets the border color
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::setBorderColor(const Color &color)
{
if(_lineStyle)
{
_lineStyle->setColor(color);
}
}
///////////////////////////////////////////////////////////////////////////////
//Sets the border alpha color
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::setBorderAlpha(const int &alpha)
{
if(_lineStyle)
{
_lineStyle->setAlpha(alpha);
}
}
///////////////////////////////////////////////////////////////////////////////
//Sets the border type
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::setBorderType(const LineSettings::DashStyle &type)
{
if(_lineStyle)
{
_lineStyle->setType(type);
}
}
///////////////////////////////////////////////////////////////////////////////
//Sets the border width
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::setBorderWidth(const int &width)
{
if(_lineStyle)
{
_lineStyle->setWidth((REAL)width);
}
}
///////////////////////////////////////////////////////////////////////////////
//Sets line style
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::setLine(TdkGdiLine* line)
{
if(_lineStyle) delete _lineStyle;
_lineStyle=line;
}
///////////////////////////////////////////////////////////////////////////////
//Clear Line Style
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::clearLine()
{
if(_lineStyle) delete _lineStyle;
_lineStyle=NULL;
}
///////////////////////////////////////////////////////////////////////////////
//Clear Decorator
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::clearDecorator()
{
if(_polygonDecorator) delete _polygonDecorator;
_polygonDecorator=NULL;
}
///////////////////////////////////////////////////////////////////////////////
//Adding a new TdkGdiPolygon Decorator
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::add(TdkGdiPolygon* dec)
{
if(_polygonDecorator) delete _polygonDecorator;
_polygonDecorator=dec;
}
///////////////////////////////////////////////////////////////////////////////
//Sets the back ground type
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::setType(const backgroundStyle &type)
{
Color color;
if(_brush)
{
if(_brush->GetType()==BrushTypeHatchFill)
{
((HatchBrush*)_brush)->GetForegroundColor(&color);
}
else
{
((SolidBrush*)_brush)->GetColor(&color);
}
}
if(_brush) delete _brush;
if(type == Solid)
{
_brush=new SolidBrush(color);
}else if(type == Transparent)
{
_brush=NULL;
}else
{
_brush=new HatchBrush((HatchStyle)type,color,Color(0,0,0,0));
}
}
///////////////////////////////////////////////////////////////////////////////
//Returns the current brush
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
Brush* TdkGdiPolygon::getBrush()
{
return _brush;
}
///////////////////////////////////////////////////////////////////////////////
//Return the current Pen
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
Pen* TdkGdiPolygon::getPen()
{
if(!_lineStyle)
{
_lineStyle=new TdkGdiLine();
}
return _lineStyle->getPen();
}
///////////////////////////////////////////////////////////////////////////////
//drawRectangle
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::drawRectangle(Graphics* graphic, const RectF &rect, const bool &xorOption)
{
if(graphic)
{
if(!xorOption) graphic->DrawRectangle(getPen(),rect);
else drawXorRectangle(graphic,rect);
}
}
///////////////////////////////////////////////////////////////////////////////
//drawXorRectangle
//Author : Rui Mauricio Gregório
//Date : 08/2009
///////////////////////////////////////////////////////////////////////////////
void TdkGdiPolygon::drawXorRectangle(Graphics* graphic, const RectF &rect)
{
Gdiplus::Region region;
HRGN rgn;
graphic->GetClip(®ion);
rgn = region.GetHRGN(graphic);
// Extract the Win32 HDC from the Graphics object supplied.
HDC hdc = graphic->GetHDC();
// Create a pen with a dotted style to draw the border of the
// rectangle.
HPEN gdiPen = CreatePen(PS_SOLID,1,RGB(128,128,128));
SelectClipRgn(hdc,rgn);
// Set the ROP cdrawint mode to XOR.
SetROP2( hdc, R2_XORPEN );
// Select the pen into the device context.
HPEN oldPen =(HPEN) SelectObject( hdc, gdiPen );
// Create a stock NULL_BRUSH brush and select it into the device
// context so that the rectangle isn't filled.
HBRUSH oldBrush =(HBRUSH) SelectObject( hdc, GetStockObject( NULL_BRUSH ) );
// Now XOR the hollow rectangle on the Graphics object with
// a dotted outline.
Rectangle( hdc,(int) rect.X, (int) rect.Y, (int)(rect.X + rect.Width),(int)(rect.Y + rect.Height));
// Put the old stuff back where it was.
SelectObject( hdc, oldBrush ); // no need to delete a stock object
SelectObject( hdc, oldPen );
DeleteObject( gdiPen ); // but we do need to delete the pen
DeleteObject(rgn);
SelectClipRgn(hdc,0);
// Return the device context to Windows.
graphic->ReleaseHDC(hdc);
} | [
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
] | [
[
[
1,
315
]
]
] |
460d4e0c38b84ec1d78bc2a07e76a0f36daa0763 | 5b2b0e9131a27043573107bf42d8ca7641ba511a | /PropsNetwork.h | 565b0903111c40b1fdb40bb8566700c3d13660ae | [
"MIT"
] | permissive | acastroy/pumpkin | 0b1932e9c1fe7672a707cc04f092d98cfcecbd4e | 6e7e413ca364d79673e523c09767c18e7cff1bec | refs/heads/master | 2023-03-15T20:43:59.544227 | 2011-04-27T16:24:42 | 2011-04-27T16:24:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | h | // PropsNetwork.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CPropsNetwork dialog
class CPropsNetwork : public CPropertyPage
{
DECLARE_DYNCREATE(CPropsNetwork)
// Construction
public:
CPropsNetwork();
~CPropsNetwork();
// Dialog Data
//{{AFX_DATA(CPropsNetwork)
enum { IDD = IDD_PROPS_NETWORK };
CSpinButtonCtrl m_BSizeSpinCtl;
CSpinButtonCtrl m_TimeSpinCtl;
CSpinButtonCtrl m_SpeakSpinCtl;
CSpinButtonCtrl m_ListenSpinCtl;
UINT m_ListenPort;
UINT m_SpeakPort;
UINT m_TimeOut;
UINT m_BlockSize;
CString m_ListenAddress;
//}}AFX_DATA
// Overrides
// ClassWizard generate virtual function overrides
//{{AFX_VIRTUAL(CPropsNetwork)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CPropsNetwork)
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
1cb552e27794bbcd7a7a34d40db9a3e4db8ccd06 | 44890f9b95a8c77492bf38514d26c0da51d2fae5 | /Gif/Gif/GifEncoder.cpp | e931a73ac527d66c8dd787b2780b83c9ec197699 | [] | no_license | winnison/huang-cpp | fd9cd57bd0b97870ae1ca6427d2fc8191cf58a77 | 989fe1d3fdc1c9eae33e0f11fcd6d790e866e4c5 | refs/heads/master | 2021-01-19T18:07:38.882211 | 2008-04-14T16:42:48 | 2008-04-14T16:42:48 | 34,250,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,146 | cpp | #include "GifEncoder.h"
#include "NeuQuant.h"
#include "LZWEncoder.h"
CGifEncoder::CGifEncoder()
:
width(0),
height(0),
transparent(EMPTYCOLOR),
transIndex(0),
repeat(-1),
delay(0),
started(false),
fs(NULL),
hBitmap(0),
pixels(NULL),
indexedPixels(NULL),
colorDepth(0),
//colorTab(NULL),
palSize(7),
dispose(-1),
closeStream(false),
firstFrame(true),
sizeSet(false),
sample(10)
{
}
CGifEncoder::~CGifEncoder()
{
SAVEDEL(pixels)
SAVEDEL(indexedPixels)
//SAVEDEL(colorTab)
}
/**
* Analyzes image colors and creates color map.
*/
void CGifEncoder::AnalyzePixels()
{
int nPix = width*height;
int len = 3*nPix;
SAVEDEL(indexedPixels)
indexedPixels = new byte[nPix];
CNeuQuant nq(pixels, len, sample);
// initialize quantizer
//SAVEDEL(colorTab)
nq.Process(colorTab); // create reduced palette
// convert map from BGR to RGB
//for (int i = 0; i < NETSIZE*3; i += 3)
//{
// byte temp = colorTab[i];
// colorTab[i] = colorTab[i + 2];
// colorTab[i + 2] = temp;
//}
memset(usedEntry,0,sizeof(usedEntry));
// map image pixels to new palette
int k = 0;
for (int i = 0; i < nPix; i++)
{
int index =
nq.Map(pixels[k],
pixels[k+1],
pixels[k+2]);
k+=3;
usedEntry[index] = true;
indexedPixels[i] = (byte)(index);
}
SAVEDEL(pixels);
pixels = NULL;
colorDepth = 8;
palSize = 7;
// get closest match to transparent color if specified
if (transparent != EMPTYCOLOR )
{
transIndex = FindClosest(transparent);
}
}
/**
* Returns index of palette color closest to c
*
*/
int CGifEncoder::FindClosest(COLORREF c)
{
if (colorTab == NULL) return -1;
int r = GetRValue(c);
int g = GetGValue(c);
int b = GetBValue(c);
int minpos = 0;
int dmin = 256 * 256 * 256;
int len = 3 * NETSIZE;
for (int i = 0; i < len;)
{
int dr = r - (colorTab[i++] & 0xff);
int dg = g - (colorTab[i++] & 0xff);
int db = b - (colorTab[i] & 0xff);
int d = dr * dr + dg * dg + db * db;
int index = i / 3;
if (usedEntry[index] && (d < dmin))
{
dmin = d;
minpos = index;
}
i++;
}
return minpos;
}
/**
* Extracts image pixels into byte array "pixels"
*/
void CGifEncoder::GetImagePixels()
{
HBITMAP hBm = NULL;
BITMAP bmpInfo;
::GetObject(hBitmap,sizeof(BITMAP),&bmpInfo);
if ((bmpInfo.bmWidth != width)
|| (bmpInfo.bmHeight != height)
)
{
hBm = StretchBitmap(hBitmap, width, height);
hBitmap = hBm;
}
/*
ToDo:
improve performance:
*/
SAVEDEL(pixels)
byte* pch;
pixels = pch = new byte [ 3 * width * height + 1 ];
int count =0;
CDCHandle dcScreen = GetDC(NULL);
CDC dcTemp;
dcTemp.CreateCompatibleDC(dcScreen);
HBITMAP hBmpOldSrc = dcTemp.SelectBitmap(hBitmap);
for (int th = 0; th < height; th++)
{
for (int tw = 0; tw < width; tw++)
{
*((COLORREF*)pch) = dcTemp.GetPixel(tw, th);
pch+=3;
//COLORREF color = dcTemp.GetPixel(tw, th);
//pixels[count] = GetRValue(color);
//count++;
//pixels[count] = GetGValue(color);
//count++;
//pixels[count] = GetBValue(color);
//count++;
}
}
dcTemp.SelectBitmap(hBmpOldSrc);
::ReleaseDC(NULL,dcScreen.m_hDC);
if (hBm != NULL)
{
::DeleteObject(hBm);
}
// pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
}
/**
* Writes Graphic Control Extension
*/
void CGifEncoder::WriteGraphicCtrlExt()
{
fs->put(0x21); // extension introducer
fs->put(0xf9); // GCE label
fs->put(4); // data block size
int transp, disp;
if (transparent == EMPTYCOLOR )
{
transp = 0;
disp = 0; // dispose = no action
}
else
{
transp = 1;
disp = 2; // force clear if using transparent color
}
if (dispose >= 0)
{
disp = dispose & 7; // user override
}
disp <<= 2;
// packed fields
fs->put((char) ( 0 | // 1:3 reserved
disp | // 4:6 disposal
0 | // 7 user input - 0 = none
transp )); // 8 transparency flag
WriteShort(delay); // delay x 1/100 sec
fs->put((char)transIndex); // transparent color index
fs->put(0); // block terminator
}
/**
* Writes Image Descriptor
*/
void CGifEncoder::WriteImageDesc()
{
fs->put(0x2c);// image separator
WriteShort(0); // image position x,y = 0,0
WriteShort(0);
WriteShort(width); // image size
WriteShort(height);
// packed fields
if (firstFrame)
{
// no LCT - GCT is used for first (or only) frame
fs->put(0);
}
else
{
// specify normal LCT
fs->put((char) (0x80 | // 1 local color table 1=yes
0 | // 2 interlace - 0=no
0 | // 3 sorted - 0=no
0 | // 4-5 reserved
palSize) ); // 6-8 size of color table
}
}
/**
* Writes Logical Screen Descriptor
*/
void CGifEncoder::WriteLSD()
{
// logical screen size
WriteShort(width);
WriteShort(height);
// packed fields
fs->put((char) (0x80 | // 1 : global color table flag = 1 (gct used)
0x70 | // 2-4 : color resolution = 7
0x00 | // 5 : gct sort flag = 0
palSize) ); // 6-8 : gct size
WriteShort(0);
//fs<<(byte)(0); // background color index
//fs<<(byte)(0); // pixel aspect ratio - assume 1:1
}
/**
* Writes Netscape application extension to define
* repeat count.
*/
void CGifEncoder::WriteNetscapeExt()
{
int a = 0x000b;
WriteShort(0xff21);
fs->put(0x0b);
//fs<<(byte)0x21; // extension introducer
//fs<<(byte)0xff; // app extension label
//fs<<(byte)0x0b; // block size
WriteString("NETSCAPE2.0"); // app id + auth code
a = 0x0103;
WriteShort(a);
//fs<<(byte)3; // sub-block size
//fs<<(byte)1; // loop sub-block id
WriteShort(repeat); // loop count (extra iterations, 0=repeat forever)
fs->put(0); // block terminator
}
/**
* Writes color table
*/
void CGifEncoder::WritePalette()
{
fs->write((char*)colorTab, (3 * NETSIZE));
/*int n = (3 * 256) - (3 * NETSIZE);
for (int i = 0; i < n; i++)
{
fs<<(byte)(0);
}*/
}
/**
* Encodes and writes pixel data
*/
void CGifEncoder::WritePixels()
{
CLZWEncoder encoder(width, height, indexedPixels, colorDepth);
encoder.Encode( fs );
}
void CGifEncoder::WriteInt(int value)
{
fs->write((char*)&value, 4);
}
/**
* Write 16-bit value to output stream, LSB first
*/
void CGifEncoder::WriteShort(int value)
{
fs->write((char*)&value, 2);
}
/**
* Writes string to output stream
*/
void CGifEncoder::WriteString(string s)
{
fs->write(s.c_str(), s.length());
}
/**
* Adds next GIF frame. The frame is not written immediately, but is
* actually deferred until the next frame is received so that timing
* data can be inserted. Invoking <code>finish()</code> flushes all
* frames. If <code>setSize</code> was not invoked, the size of the
* first image is used for all subsequent frames.
*
* @param im BufferedImage containing frame to write.
* @return true if successful.
*/
bool CGifEncoder::AddFrame(HBITMAP hBm)
{
if ((hBm == 0) || !started)
{
return false;
}
hBitmap = hBm;
BITMAP bmpInfo;
::GetObject(hBitmap,sizeof(BITMAP),&bmpInfo);
bool ok = true;
try
{
if (!sizeSet)
{
// use first frame's size
SetSize(bmpInfo.bmWidth, bmpInfo.bmHeight);
}
GetImagePixels(); // convert to correct format if necessary
AnalyzePixels(); // build color table & map pixels
if (firstFrame)
{
WriteLSD(); // logical screen descriptior
WritePalette(); // global color table
if (repeat >= 0)
{
// use NS app extension to indicate reps
WriteNetscapeExt();
}
}
WriteGraphicCtrlExt(); // write graphic control extension
WriteImageDesc(); // image descriptor
if (!firstFrame)
{
WritePalette(); // local color table
}
WritePixels(); // encode and write pixel data
firstFrame = false;
}
catch (...)
{
ok = false;
}
//DeleteObject(hBitmap);
return ok;
}
/**
* Flushes any pending data and closes output file.
* If writing to an OutputStream, the stream is not
* closed.
*/
bool CGifEncoder::Finish()
{
if (!started) return false;
bool ok = true;
started = false;
try
{
fs->put( 0x3b ); // gif trailer
fs->flush();
if (closeStream)
{
fs->close();
SAVEDEL(fs)
}
}
catch (...)
{
ok = false;
}
SAVEDEL(pixels)
SAVEDEL(indexedPixels)
// reset for subsequent use
transIndex = 0;
fs = NULL;
hBitmap = NULL;
pixels = NULL;
indexedPixels = NULL;
//colorTab = NULL;
closeStream = false;
firstFrame = true;
return ok;
}
/**
* Initiates GIF file creation on the given stream. The stream
* is not closed automatically.
*
* @param os OutputStream on which GIF images are written.
* @return false if initial write failed.
*/
bool CGifEncoder::Start( fstream* os)
{
if (os == NULL || started) return false;
bool ok = true;
closeStream = false;
SAVEDEL(fs)
fs = os;
try
{
WriteString("GIF89a"); // header
}
catch (...)
{
ok = false;
}
return started = ok;
}
/**
* Initiates writing of a GIF file with the specified name.
*
* @param file string containing output file name.
* @return false if open or initial write failed.
*/
bool CGifEncoder::Start(string file)
{
if (started) return false;
bool ok = true;
try
{
// bw = new BinaryWriter( new FileStream( file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None ) );
ok = Start(new fstream( file.c_str(), ios_base::out | ios_base::binary ));
closeStream = true;
}
catch (...)
{
ok = false;
}
return started = ok;
}
/**
* Sets the delay time between each frame, or changes it
* for subsequent frames (applies to last frame added).
*
* @param ms int delay time in milliseconds
*/
void CGifEncoder::SetDelay(int ms)
{
delay = ( int ) ((ms+5) / 10.0f);
}
/**
* Sets the GIF frame disposal code for the last added frame
* and any subsequent frames. Default is 0 if no transparent
* color has been set, otherwise 2.
* @param code int disposal code.
*/
void CGifEncoder::SetDispose(int code)
{
if (code >= 0)
{
dispose = code;
}
}
/**
* Sets the number of times the set of GIF frames
* should be played. Default is 1; 0 means play
* indefinitely. Must be invoked before the first
* image is added.
*
* @param iter int number of iterations.
* @return
*/
void CGifEncoder::SetRepeat(int iter)
{
if (iter >= 0)
{
repeat = iter;
}
}
/**
* Sets the transparent color for the last added frame
* and any subsequent frames.
* Since all colors are subject to modification
* in the quantization process, the color in the final
* palette for each frame closest to the given color
* becomes the transparent color for that frame.
* May be set to NULL to indicate no transparent color.
*
* @param c COLOR to be treated as transparent on display.
*/
void CGifEncoder::SetTransparent(COLORREF c)
{
transparent = c & 0x00ffffff;
}
/**
* Sets frame rate in frames per second. Equivalent to
* <code>setDelay(1000/fps)</code>.
*
* @param fps float frame rate (frames per second)
*/
void CGifEncoder::SetFrameRate(float fps)
{
if (fps != 0)
{
delay = ( int ) ((100 / fps)+0.5);
}
}
/**
* Sets quality of color quantization (conversion of images
* to the maximum 256 colors allowed by the GIF specification).
* Lower values (minimum = 1) produce better colors, but slow
* processing significantly. 10 is the default, and produces
* good color mapping at reasonable speeds. Values greater
* than 20 do not yield significant improvements in speed.
*
* @param quality int greater than 0.
* @return
*/
void CGifEncoder::SetQuality(int quality)
{
if (quality < 1) quality = 1;
sample = quality;
}
/**
* Sets the GIF frame size. The default size is the
* size of the first frame added if this method is
* not invoked.
*
* @param w int frame width.
* @param h int frame width.
*/
void CGifEncoder::SetSize(int w, int h)
{
if (started && !firstFrame) return;
width = w;
height = h;
if (width < 1) width = 320;
if (height < 1) height = 240;
sizeSet = true;
}
| [
"mr.huanghuan@48bf5850-ed27-0410-9317-b938f814dc16"
] | [
[
[
1,
569
]
]
] |
e83f6ac374ff4c9bc9c5dc8a1746f6eea8226937 | 83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c | /test/unit/utRemoveRedundantMaterials.h | b0b310669caacad86f296e756914879ee842096d | [
"BSD-3-Clause"
] | permissive | spring/assimp | fb53b91228843f7677fe8ec18b61d7b5886a6fd3 | db29c9a20d0dfa9f98c8fd473824bba5a895ae9e | refs/heads/master | 2021-01-17T23:19:56.511185 | 2011-11-08T12:15:18 | 2011-11-08T12:15:18 | 2,017,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 876 | h | #ifndef TESTRRM_H
#define TESTRRM_H
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <aiTypes.h>
#include <aiMesh.h>
#include <aiScene.h>
#include <RemoveRedundantMaterials.h>
#include <MaterialSystem.h>
using namespace std;
using namespace Assimp;
class RemoveRedundantMatsTest : public CPPUNIT_NS :: TestFixture
{
CPPUNIT_TEST_SUITE (RemoveRedundantMatsTest);
CPPUNIT_TEST (testRedundantMaterials);
CPPUNIT_TEST (testRedundantMaterialsWithExcludeList);
CPPUNIT_TEST_SUITE_END ();
public:
void setUp (void);
void tearDown (void);
protected:
void testRedundantMaterials (void);
void testRedundantMaterialsWithExcludeList (void);
private:
RemoveRedundantMatsProcess* piProcess;
aiScene* pcScene1;
aiScene* pcScene2;
};
#endif
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
] | [
[
[
1,
40
]
]
] |
c1c5036619aed70bc0c94a8eff77e6122c8183a0 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /Ed2kLoader/Ed2kLoader/Collector.cpp | 1287df6e2f7e491e411ed16a1a55880c76732b8f | [] | no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,587 | cpp | #include "stdafx.h"
#include "Ed2kLoader.h"
#include ".\collector.h"
#include "EmuleMgr.h"
#include "CollectorWaitInitThread.h"
#include <strsafe.h>
extern CEmuleMgr theEmuleMgr;
CCollector* CCollector::ms_instance = NULL;
CCollector* CCollector::GetInstance()
{
if (NULL == ms_instance)
ms_instance = new CCollector;
return ms_instance;
}
void CCollector::FreeInstance()
{
if (NULL != ms_instance)
delete ms_instance;
}
CCollector::CCollector(void)
{
m_hHelperWnd = NULL;
}
CCollector::~CCollector(void)
{
CleanupList();
}
BOOL CCollector::Proc(LPCTSTR lpszEd2kLink)
{
if (!CreateHelperWnd())
{
theEmuleMgr.OpenEmuleWithParam(lpszEd2kLink);
return FALSE;
}
CreateThread(NULL, 0, CCollectorWaitInitThread::ThreadProc, (LPVOID)m_hHelperWnd, 0, NULL);
AddEd2kToList(lpszEd2kLink);
theLoaderSingleInst.InitCompleted(&m_hHelperWnd, sizeof(HWND));
bool bCanSendEd2k;
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if (UM_STOP_MESSAGE == msg.message)
{
bCanSendEd2k = (0 == msg.wParam) ? false : true;
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
theLoaderSingleInst.AppEnd();
::DestroyWindow(m_hHelperWnd);
m_hHelperWnd = NULL;
BOOL result = TRUE;
if (bCanSendEd2k)
{
TCHAR szEd2kLink[1024];
while (RemoveEd2kFromList(szEd2kLink, 1024))
{
result = result & theEmuleMgr.SendEd2kToEmule(szEd2kLink);
}
}
return result;
}
bool CCollector::CreateHelperWnd(void)
{
MyRegisterClass();
m_hHelperWnd = CreateWindow(LOADERHELPERWND_CLASSNAME, NULL, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, GetModuleHandle(NULL), NULL);
if (!m_hHelperWnd)
{
return false;
}
return true;
}
ATOM CCollector::MyRegisterClass(void)
{
WNDCLASSEX wcex;
ZeroMemory(&wcex, sizeof(wcex));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.lpfnWndProc = (WNDPROC)CCollector::HelperWndProc;
wcex.hInstance = GetModuleHandle(NULL);
wcex.lpszClassName = LOADERHELPERWND_CLASSNAME;
return RegisterClassEx(&wcex);
}
LRESULT CALLBACK CCollector::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (UWM_ARE_YOU_LOADER == message)
return (LRESULT) UWM_ARE_YOU_LOADER;
switch (message)
{
case WM_COPYDATA:
{
COPYDATASTRUCT *pcds = (COPYDATASTRUCT*) lParam;
if (UM_COPYDATACODE_ED2KLINK == pcds->dwData)
{
LPCTSTR pLink = (LPCTSTR) pcds->lpData;
AddEd2kToList(pLink);
}
return 1;
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
LRESULT CALLBACK CCollector::HelperWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return CCollector::GetInstance()->WndProc(hWnd, message, wParam, lParam);
}
void CCollector::AddEd2kToList(LPCTSTR lpszEd2kLink)
{
if (NULL == lpszEd2kLink)
return;
UINT uLen = (UINT) _tcslen(lpszEd2kLink);
LPTSTR pLink = new TCHAR[uLen + 1];
StringCchCopy(pLink, uLen + 1, lpszEd2kLink);
m_listLinks.push_back(pLink);
}
bool CCollector::RemoveEd2kFromList(LPTSTR lpszEd2kLink, UINT uCch)
{
if (m_listLinks.size() <= 0)
return false;
LPTSTR pLink;
pLink = m_listLinks.front();
m_listLinks.pop_front();
if (NULL != lpszEd2kLink)
StringCchCopy(lpszEd2kLink, uCch, pLink);
return true;
}
void CCollector::CleanupList()
{
LPTSTR pLink;
while (m_listLinks.size() > 0)
{
pLink = m_listLinks.front();
delete pLink;
pLink = NULL;
m_listLinks.pop_front();
}
}
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
] | [
[
[
1,
177
]
]
] |
9358451ebeae48b21b3ad06d3fd9e36108a147bc | 14d51a21038a3d46f2fc019bbb161022a9f4854f | /DocHostSite.cpp | 764acd7843d08be99a6e76c958f94f8c7ff5bd01 | [] | no_license | toraleap/w3plus | 44246d8e7373c07ac430ebc66409ba8aae4be59f | a34a9e4fad93f763ea8423f684f04a4e5b466a98 | refs/heads/master | 2021-01-01T15:50:08.091393 | 2011-02-18T05:38:32 | 2011-02-18T05:38:32 | 32,132,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,706 | cpp | #include "stdafx.h"
#if _MFC_VER >= 0x0700
#include <afxocc.h>
#else
#ifdef _AFXDLL
#undef AFX_DATA
#define AFX_DATA AFX_DATA_IMPORT
#endif
#include <..\src\occimpl.h>
#ifdef _AFXDLL
#undef AFX_DATA
#define AFX_DATA AFX_DATA_EXPORT
#endif
#endif
#include <mshtmhst.h>
#include "DocHostSite.h"
#include "LhpHtmlView.h"
BEGIN_INTERFACE_MAP(CDocHostSite, COleControlSite)
INTERFACE_PART(CDocHostSite, IID_IDocHostShowUI, DocHostShowUI)
INTERFACE_PART(CDocHostSite, IID_IDocHostUIHandler, DocHostUIHandler)
#if (_WIN32_IE >= 0x0501) // IE 5.5 and higher
INTERFACE_PART(CDocHostSite, IID_IDocHostUIHandler2, DocHostUIHandler2)
#endif
INTERFACE_PART(CDocHostSite, IID_IInternetSecurityManager, InternetSecurityManager)
INTERFACE_PART(CDocHostSite, IID_IServiceProvider, ServiceProvider)
END_INTERFACE_MAP()
CDocHostSite::CDocHostSite(COleControlContainer * pOcc, CLhpHtmlView* pView)
: COleControlSite( pOcc )
{
m_pView = pView;
}
CDocHostSite::~CDocHostSite()
{
}
ULONG CDocHostSite::XDocHostShowUI::AddRef()
{
METHOD_PROLOGUE(CDocHostSite, DocHostShowUI);
return pThis->ExternalAddRef();
}
ULONG CDocHostSite::XDocHostShowUI::Release()
{
METHOD_PROLOGUE(CDocHostSite, DocHostShowUI);
return pThis->ExternalRelease();
}
HRESULT CDocHostSite::XDocHostShowUI::QueryInterface(REFIID riid, void ** ppvObj)
{
METHOD_PROLOGUE(CDocHostSite, DocHostShowUI);
return pThis->ExternalQueryInterface( &riid, ppvObj );
}
HRESULT CDocHostSite::XDocHostShowUI::ShowHelp(HWND hwnd,
LPOLESTR pszHelpFile,
UINT nCommand,
DWORD dwData,
POINT ptMouse,
IDispatch * pDispatchObjectHit)
{
METHOD_PROLOGUE(CDocHostSite, DocHostShowUI);
return E_NOTIMPL;
}
HRESULT CDocHostSite::XDocHostShowUI::ShowMessage(HWND hwnd,
LPOLESTR lpstrText,
LPOLESTR lpstrCaption,
DWORD dwType,
LPOLESTR lpstrHelpFile,
DWORD dwHelpContext,
LRESULT * plResult)
{
METHOD_PROLOGUE(CDocHostSite, DocHostShowUI);
return E_NOTIMPL;
}
ULONG CDocHostSite::XDocHostUIHandler::AddRef()
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->ExternalAddRef();
}
ULONG CDocHostSite::XDocHostUIHandler::Release()
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->ExternalRelease();
}
HRESULT CDocHostSite::XDocHostUIHandler::QueryInterface(REFIID riid, void ** ppvObj)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->ExternalQueryInterface( &riid, ppvObj );
}
HRESULT CDocHostSite::XDocHostUIHandler::GetHostInfo(DOCHOSTUIINFO * pInfo)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnGetHostInfo( pInfo );
}
HRESULT CDocHostSite::XDocHostUIHandler::ShowUI(DWORD dwID,
IOleInPlaceActiveObject * pActiveObject,
IOleCommandTarget * pCommandTarget,
IOleInPlaceFrame * pFrame,
IOleInPlaceUIWindow * pDoc)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnShowUI( dwID, pActiveObject, pCommandTarget,
pFrame, pDoc );
}
HRESULT CDocHostSite::XDocHostUIHandler::HideUI()
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnHideUI();
}
HRESULT CDocHostSite::XDocHostUIHandler::UpdateUI()
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnUpdateUI();
}
HRESULT CDocHostSite::XDocHostUIHandler::EnableModeless(BOOL fEnable)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnEnableModeless( fEnable );
}
HRESULT CDocHostSite::XDocHostUIHandler::OnDocWindowActivate(BOOL fEnable)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnDocWindowActivate( fEnable );
}
HRESULT CDocHostSite::XDocHostUIHandler::OnFrameWindowActivate(BOOL fEnable)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnFrameWindowActivate( fEnable );
}
HRESULT CDocHostSite::XDocHostUIHandler::ResizeBorder(LPCRECT prcBorder,
IOleInPlaceUIWindow * pUIWindow,
BOOL fFrameWindow)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnResizeBorder( prcBorder, pUIWindow, fFrameWindow );
}
HRESULT CDocHostSite::XDocHostUIHandler::ShowContextMenu(DWORD dwID,
POINT * ppt,
IUnknown * pcmdtReserved,
IDispatch * pdispReserved)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnShowContextMenu( dwID, ppt, pcmdtReserved,
pdispReserved );
}
HRESULT CDocHostSite::XDocHostUIHandler::TranslateAccelerator(LPMSG lpMsg,
const GUID * pguidCmdGroup,
DWORD nCmdID)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return E_NOTIMPL;
return pThis->m_pView->OnTranslateAccelerator( lpMsg,
pguidCmdGroup, nCmdID );
}
HRESULT CDocHostSite::XDocHostUIHandler::GetOptionKeyPath(LPOLESTR * pchKey,
DWORD dw)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnGetOptionKeyPath( pchKey, dw );
}
HRESULT CDocHostSite::XDocHostUIHandler::GetDropTarget(IDropTarget * pDropTarget,
IDropTarget ** ppDropTarget)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnGetDropTarget( pDropTarget, ppDropTarget );
}
HRESULT CDocHostSite::XDocHostUIHandler::GetExternal(IDispatch ** ppDispatch)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnGetExternal( ppDispatch );
}
HRESULT CDocHostSite::XDocHostUIHandler::TranslateUrl(DWORD dwTranslate,
OLECHAR * pchURLIn,
OLECHAR ** ppchURLOut)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnTranslateUrl( dwTranslate, pchURLIn, ppchURLOut );
}
HRESULT CDocHostSite::XDocHostUIHandler::FilterDataObject(IDataObject * pDO,
IDataObject ** ppDORet)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler);
return pThis->m_pView->OnFilterDataObject( pDO, ppDORet );
}
#if (_WIN32_IE >= 0x0501) // IE 5.5 and higher
ULONG CDocHostSite::XDocHostUIHandler2::AddRef()
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler2);
return pThis->ExternalAddRef();
}
ULONG CDocHostSite::XDocHostUIHandler2::Release()
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler2);
return pThis->ExternalRelease();
}
HRESULT CDocHostSite::XDocHostUIHandler2::QueryInterface(REFIID riid, void ** ppvObj)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler2);
return pThis->ExternalQueryInterface( &riid, ppvObj );
}
HRESULT CDocHostSite::XDocHostUIHandler2::GetHostInfo(DOCHOSTUIINFO *)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::ShowUI(DWORD /*dwID*/,
IOleInPlaceActiveObject * /*pActiveObject*/,
IOleCommandTarget * /*pCommandTarget*/,
IOleInPlaceFrame * /*pFrame*/,
IOleInPlaceUIWindow * /*pDoc*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::HideUI()
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::UpdateUI()
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::EnableModeless(BOOL /*fEnable*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::OnDocWindowActivate(BOOL /*fActivate*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::OnFrameWindowActivate(BOOL /*fActivate*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::ResizeBorder(LPCRECT /*prcBorder*/,
IOleInPlaceUIWindow* /*pUIWindow*/,
BOOL /*fRameWindow*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::ShowContextMenu(DWORD /*dwID*/,
POINT* /*pptPosition*/,
IUnknown* /*pCommandTarget*/,
IDispatch* /*pDispatchObjectHit*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::TranslateAccelerator(LPMSG /*lpMsg*/,
const GUID * /*pguidCmdGroup*/,
DWORD /*nCmdID*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::GetOptionKeyPath(BSTR* /*pbstrKey*/, DWORD)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::GetDropTarget(IDropTarget * /*pDropTarget*/,
IDropTarget ** /*ppDropTarget*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::GetExternal(IDispatch ** /*ppDispatch*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::TranslateUrl(DWORD /*dwTranslate*/,
OLECHAR * /*pchURLIn*/,
OLECHAR ** /*ppchURLOut*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::FilterDataObject(IDataObject * /*pDO*/,
IDataObject ** /*ppDORet*/)
{
ASSERT(FALSE);
return S_FALSE;
}
HRESULT CDocHostSite::XDocHostUIHandler2::GetOverrideKeyPath(LPOLESTR * pchKey, DWORD dw)
{
METHOD_PROLOGUE(CDocHostSite, DocHostUIHandler2);
return pThis->m_pView->OnGetOverrideKeyPath( pchKey, dw );
}
#endif
// InternetSecurityManager Methods
HRESULT FAR EXPORT CDocHostSite::XInternetSecurityManager
::QueryInterface(REFIID riid, void** ppvObj)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
HRESULT hr = (HRESULT)pThis->ExternalQueryInterface(&riid, ppvObj);
return hr;
}
ULONG FAR EXPORT CDocHostSite::XInternetSecurityManager::AddRef()
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return pThis->ExternalAddRef();
}
ULONG FAR EXPORT CDocHostSite::XInternetSecurityManager::Release()
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return pThis->ExternalRelease();
}
HRESULT CDocHostSite::XInternetSecurityManager
::SetSecuritySite (IInternetSecurityMgrSite *pSite)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return INET_E_DEFAULT_ACTION;
}
HRESULT CDocHostSite::XInternetSecurityManager
::GetSecuritySite(IInternetSecurityMgrSite **ppSite)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return INET_E_DEFAULT_ACTION;
}
HRESULT CDocHostSite::XInternetSecurityManager
::MapUrlToZone(LPCWSTR pwszUrl,DWORD *pdwZone,DWORD dwFlags)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return INET_E_DEFAULT_ACTION;
}
HRESULT FAR EXPORT CDocHostSite::XInternetSecurityManager
::GetSecurityId(LPCWSTR pwszUrl,
BYTE *pbSecurityId,
DWORD *pcbSecurityId,
DWORD dwReserved)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return INET_E_DEFAULT_ACTION;
}
STDMETHODIMP CDocHostSite::XInternetSecurityManager
::ProcessUrlAction( /* [in] */ LPCWSTR pwszUrl,
/* [in] */ DWORD dwAction,
/* [size_is][out] */ BYTE __RPC_FAR *pPolicy,
/* [in] */ DWORD cbPolicy,
/* [in] */ BYTE __RPC_FAR *pContext,
/* [in] */ DWORD cbContext,
/* [in] */ DWORD dwFlags,
/* [in] */ DWORD dwReserved)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
DWORD dwPolicy=URLPOLICY_ALLOW;
BOOL bNoActiveX=FALSE;
BOOL bNoJava=FALSE;
BOOL bNoScript=FALSE;
BOOL bCrossData=FALSE;
if (dwAction <= URLACTION_ACTIVEX_MAX && dwAction >= URLACTION_ACTIVEX_MIN)
dwPolicy = bNoActiveX ? URLPOLICY_DISALLOW : URLPOLICY_ALLOW;
else if ((dwAction <= URLACTION_JAVA_MAX && dwAction >= URLACTION_JAVA_MIN) ||
URLACTION_HTML_JAVA_RUN == dwAction)
if (bNoJava)
dwPolicy = URLPOLICY_JAVA_PROHIBIT;
else
return INET_E_DEFAULT_ACTION;
else if (dwAction <= URLACTION_SCRIPT_MAX && dwAction >= URLACTION_SCRIPT_MIN)
dwPolicy = bNoScript ? URLPOLICY_DISALLOW : URLPOLICY_ALLOW;
// !! If the compiler can't find URLACTION_CROSS_DOMAIN_DATA, make sure you are building with
// !! the latest version of the IE headers -- URLMON.H specifically -- from MSDN Downloads for the
// !! Web Workshop or the Platform SDK
else if (URLACTION_CROSS_DOMAIN_DATA == dwAction)
dwPolicy = bCrossData ? URLPOLICY_ALLOW : URLPOLICY_DISALLOW;
else
return INET_E_DEFAULT_ACTION;
if ( cbPolicy >= sizeof (DWORD))
{
*(DWORD*) pPolicy = dwPolicy;
return S_OK;
}
else
{
return S_FALSE;
}
}
HRESULT CDocHostSite::XInternetSecurityManager
::QueryCustomPolicy(LPCWSTR pwszUrl,
REFGUID guidKey,
BYTE **ppPolicy,
DWORD *pcbPolicy,
BYTE *pContext,
DWORD cbContext,
DWORD dwReserved)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return INET_E_DEFAULT_ACTION;
}
HRESULT CDocHostSite::XInternetSecurityManager
::SetZoneMapping(DWORD dwZone,
LPCWSTR lpszPattern,
DWORD dwFlags)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return INET_E_DEFAULT_ACTION;
}
HRESULT CDocHostSite::XInternetSecurityManager
::GetZoneMappings(DWORD dwZone,
IEnumString **ppenumString,
DWORD dwFlags)
{
METHOD_PROLOGUE(CDocHostSite, InternetSecurityManager)
return INET_E_DEFAULT_ACTION;
}
// ServiceProvider Methods
ULONG FAR EXPORT CDocHostSite::XServiceProvider::AddRef()
{
METHOD_PROLOGUE(CDocHostSite, ServiceProvider)
return pThis->ExternalAddRef();
}
ULONG FAR EXPORT CDocHostSite::XServiceProvider::Release()
{
METHOD_PROLOGUE(CDocHostSite, ServiceProvider)
return pThis->ExternalRelease();
}
HRESULT FAR EXPORT CDocHostSite::XServiceProvider
::QueryInterface(REFIID riid,
void** ppvObj)
{
METHOD_PROLOGUE(CDocHostSite, ServiceProvider)
HRESULT hr = (HRESULT)pThis->ExternalQueryInterface(&riid, ppvObj);
return hr;
}
STDMETHODIMP CDocHostSite::XServiceProvider
::QueryService(REFGUID guidService,
REFIID riid,
void** ppvObject)
{
if (guidService == SID_SInternetSecurityManager &&
riid == IID_IInternetSecurityManager)
{
METHOD_PROLOGUE(CDocHostSite, ServiceProvider)
HRESULT hr = (HRESULT)pThis->ExternalQueryInterface(&riid, ppvObject);
return hr;
}
else
{
*ppvObject = NULL;
}
return E_NOINTERFACE;
} | [
"[email protected]@00efcefc-f4bc-333f-9454-5c8bce538679"
] | [
[
[
1,
546
]
]
] |
6353e2510cd19da9633e0bf9377109eb40b249ef | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/TPLayer_IOCP/TPBroadcast.h | 0942546f4ef1367980d7e36f412ab8a9999d405f | [] | no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 798 | h | // TPBroadcast.h: interface for the TPBroadcast class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TPBROADCAST_H__2543F871_771C_4286_A2D5_F03047DA80B6__INCLUDED_)
#define AFX_TPBROADCAST_H__2543F871_771C_4286_A2D5_F03047DA80B6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "TPUDPClient.h"
class TPBroadcast : public TPUDPClient
{
public:
TPBroadcast(ITPListener *callback, int engineId = 0);
virtual ~TPBroadcast();
public:/*½Ó¿Ú*/
virtual int Connect(const char* szIp, int nPort);
virtual int Connect(const char* szLocalIp, int nLocalPort, const char* szRemoteIp, int nRemotePort);
};
#endif // !defined(AFX_TPBROADCAST_H__2543F871_771C_4286_A2D5_F03047DA80B6__INCLUDED_)
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
] | [
[
[
1,
27
]
]
] |
0612fb8d1612b8ebeaa306e613f23b3bf5bc3328 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/nebula2/src/microtcl/tclExecute.cc | b05811ed7a7200a8a3c6a3ce3a2c39ddb9c8aa19 | [] | 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 | 202,596 | cc | /*
* tclExecute.c --
*
* This file contains procedures that execute byte-compiled Tcl
* commands.
*
* Copyright (c) 1996-1997 Sun Microsystems, Inc.
* Copyright (c) 1998-2000 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/tclCompile.h"
#ifdef NO_FLOAT_H
# include "../compat/float.h"
#else
# include <float.h>
#endif
#ifndef TCL_NO_MATH
#include "microtcl/tclMath.h"
#endif
/*
* The stuff below is a bit of a hack so that this file can be used
* in environments that include no UNIX, i.e. no errno. Just define
* errno here.
*/
#ifndef TCL_GENERIC_ONLY
#include "microtcl/tclPort.h"
#else
#define NO_ERRNO_H
#endif
#ifdef NO_ERRNO_H
int errno;
#define EDOM 33
#define ERANGE 34
#endif
/*
* Boolean flag indicating whether the Tcl bytecode interpreter has been
* initialized.
*/
static int execInitialized = 0;
TCL_DECLARE_MUTEX(execMutex)
/*
* Variable that controls whether execution tracing is enabled and, if so,
* what level of tracing is desired:
* 0: no execution tracing
* 1: trace invocations of Tcl procs only
* 2: trace invocations of all (not compiled away) commands
* 3: display each instruction executed
* This variable is linked to the Tcl variable "tcl_traceExec".
*/
int tclTraceExec = 0;
#if 0
typedef struct ThreadSpecificData {
/*
* The following global variable is use to signal matherr that Tcl
* is responsible for the arithmetic, so errors can be handled in a
* fashion appropriate for Tcl. Zero means no Tcl math is in
* progress; non-zero means Tcl is doing math.
*/
int mathInProgress;
} ThreadSpecificData;
static Tcl_ThreadDataKey dataKey;
#endif
/*
* The variable below serves no useful purpose except to generate
* a reference to matherr, so that the Tcl version of matherr is
* linked in rather than the system version. Without this reference
* the need for matherr won't be discovered during linking until after
* libtcl.a has been processed, so Tcl's version won't be used.
*/
#ifdef NEED_MATHERR
extern int matherr();
int (*tclMatherrPtr)() = matherr;
#endif
/*
* Mapping from expression instruction opcodes to strings; used for error
* messages. Note that these entries must match the order and number of the
* expression opcodes (e.g., INST_LOR) in tclCompile.h.
*/
static char *operatorStrings[] = {
"||", "&&", "|", "^", "&", "==", "!=", "<", ">", "<=", ">=", "<<", ">>",
"+", "-", "*", "/", "%", "+", "-", "~", "!",
"BUILTIN FUNCTION", "FUNCTION",
"", "", "", "", "", "", "", "", "eq", "ne",
};
/*
* Mapping from Tcl result codes to strings; used for error and debugging
* messages.
*/
#ifdef TCL_COMPILE_DEBUG
static char *resultStrings[] = {
"TCL_OK", "TCL_ERROR", "TCL_RETURN", "TCL_BREAK", "TCL_CONTINUE"
};
#endif
/*
* These are used by evalstats to monitor object usage in Tcl.
*/
#ifdef TCL_COMPILE_STATS
long tclObjsAlloced = 0;
long tclObjsFreed = 0;
#define TCL_MAX_SHARED_OBJ_STATS 5
long tclObjsShared[TCL_MAX_SHARED_OBJ_STATS] = { 0, 0, 0, 0, 0 };
#endif /* TCL_COMPILE_STATS */
/*
* Macros for testing floating-point values for certain special cases. Test
* for not-a-number by comparing a value against itself; test for infinity
* by comparing against the largest floating-point value.
*/
#define IS_NAN(v) ((v) != (v))
#ifdef DBL_MAX
# define IS_INF(v) (((v) > DBL_MAX) || ((v) < -DBL_MAX))
#else
# define IS_INF(v) 0
#endif
/*
* Macro to adjust the program counter and restart the instruction execution
* loop after each instruction is executed.
*/
#define ADJUST_PC(instBytes) \
pc += (instBytes); \
continue
/*
* Macros used to cache often-referenced Tcl evaluation stack information
* in local variables. Note that a DECACHE_STACK_INFO()-CACHE_STACK_INFO()
* pair must surround any call inside TclExecuteByteCode (and a few other
* procedures that use this scheme) that could result in a recursive call
* to TclExecuteByteCode.
*/
#define CACHE_STACK_INFO() \
stackPtr = eePtr->stackPtr; \
stackTop = eePtr->stackTop
#define DECACHE_STACK_INFO() \
eePtr->stackTop = stackTop
/*
* Macros used to access items on the Tcl evaluation stack. PUSH_OBJECT
* increments the object's ref count since it makes the stack have another
* reference pointing to the object. However, POP_OBJECT does not decrement
* the ref count. This is because the stack may hold the only reference to
* the object, so the object would be destroyed if its ref count were
* decremented before the caller had a chance to, e.g., store it in a
* variable. It is the caller's responsibility to decrement the ref count
* when it is finished with an object.
*
* WARNING! It is essential that objPtr only appear once in the PUSH_OBJECT
* macro. The actual parameter might be an expression with side effects,
* and this ensures that it will be executed only once.
*/
#define PUSH_OBJECT(objPtr) \
Tcl_IncrRefCount(stackPtr[++stackTop] = (objPtr))
#define POP_OBJECT() \
(stackPtr[stackTop--])
/*
* Macros used to trace instruction execution. The macros TRACE,
* TRACE_WITH_OBJ, and O2S are only used inside TclExecuteByteCode.
* O2S is only used in TRACE* calls to get a string from an object.
*/
#ifdef TCL_COMPILE_DEBUG
#define TRACE(a) \
if (traceInstructions) { \
fprintf(stdout, "%2d: %2d (%u) %s ", iPtr->numLevels, stackTop, \
(unsigned int)(pc - codePtr->codeStart), \
GetOpcodeName(pc)); \
printf a; \
}
#define TRACE_WITH_OBJ(a, objPtr) \
if (traceInstructions) { \
fprintf(stdout, "%2d: %2d (%u) %s ", iPtr->numLevels, stackTop, \
(unsigned int)(pc - codePtr->codeStart), \
GetOpcodeName(pc)); \
printf a; \
TclPrintObject(stdout, (objPtr), 30); \
fprintf(stdout, "\n"); \
}
#define O2S(objPtr) \
Tcl_GetString(objPtr)
#else
#define TRACE(a)
#define TRACE_WITH_OBJ(a, objPtr)
#define O2S(objPtr)
#endif /* TCL_COMPILE_DEBUG */
/*
* Declarations for local procedures to this file:
*/
static void CallTraceProcedure _ANSI_ARGS_((Tcl_Interp *interp,
Trace *tracePtr, Command *cmdPtr,
char *command, int numChars,
int objc, Tcl_Obj *objv[]));
static void DupCmdNameInternalRep _ANSI_ARGS_((Tcl_Obj *objPtr,
Tcl_Obj *copyPtr));
static int ExprAbsFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, ClientData clientData));
static int ExprBinaryFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, ClientData clientData));
static int ExprCallMathFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, int objc, Tcl_Obj **objv));
static int ExprDoubleFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, ClientData clientData));
static int ExprIntFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, ClientData clientData));
static int ExprRandFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, ClientData clientData));
static int ExprRoundFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, ClientData clientData));
static int ExprSrandFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, ClientData clientData));
static int ExprUnaryFunc _ANSI_ARGS_((Tcl_Interp *interp,
ExecEnv *eePtr, ClientData clientData));
#ifdef TCL_COMPILE_STATS
static int EvalStatsCmd _ANSI_ARGS_((ClientData clientData,
Tcl_Interp *interp, int argc, char **argv));
#endif
static void FreeCmdNameInternalRep _ANSI_ARGS_((
Tcl_Obj *objPtr));
#ifdef TCL_COMPILE_DEBUG
static char * GetOpcodeName _ANSI_ARGS_((unsigned char *pc));
#endif
static ExceptionRange * GetExceptRangeForPc _ANSI_ARGS_((unsigned char *pc,
int catchOnly, ByteCode* codePtr));
static char * GetSrcInfoForPc _ANSI_ARGS_((unsigned char *pc,
ByteCode* codePtr, int *lengthPtr));
static void GrowEvaluationStack _ANSI_ARGS_((ExecEnv *eePtr));
static void IllegalExprOperandType _ANSI_ARGS_((
Tcl_Interp *interp, unsigned char *pc,
Tcl_Obj *opndPtr));
static void InitByteCodeExecution _ANSI_ARGS_((
Tcl_Interp *interp));
#ifdef TCL_COMPILE_DEBUG
static void PrintByteCodeInfo _ANSI_ARGS_((ByteCode *codePtr));
#endif
static int SetCmdNameFromAny _ANSI_ARGS_((Tcl_Interp *interp,
Tcl_Obj *objPtr));
#ifdef TCL_COMPILE_DEBUG
static char * StringForResultCode _ANSI_ARGS_((int result));
static void ValidatePcAndStackTop _ANSI_ARGS_((
ByteCode *codePtr, unsigned char *pc,
int stackTop, int stackLowerBound,
int stackUpperBound));
#endif
static int VerifyExprObjType _ANSI_ARGS_((Tcl_Interp *interp,
Tcl_Obj *objPtr));
/*
* Table describing the built-in math functions. Entries in this table are
* indexed by the values of the INST_CALL_BUILTIN_FUNC instruction's
* operand byte.
*/
BuiltinFunc builtinFuncTable[] = {
#ifndef TCL_NO_MATH
{"acos", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) acos},
{"asin", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) asin},
{"atan", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) atan},
{"atan2", 2, {TCL_DOUBLE, TCL_DOUBLE}, ExprBinaryFunc, (ClientData) atan2},
{"ceil", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) ceil},
{"cos", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) cos},
{"cosh", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) cosh},
{"exp", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) exp},
{"floor", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) floor},
{"fmod", 2, {TCL_DOUBLE, TCL_DOUBLE}, ExprBinaryFunc, (ClientData) fmod},
{"hypot", 2, {TCL_DOUBLE, TCL_DOUBLE}, ExprBinaryFunc, (ClientData) hypot},
{"log", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) log},
{"log10", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) log10},
{"pow", 2, {TCL_DOUBLE, TCL_DOUBLE}, ExprBinaryFunc, (ClientData) pow},
{"sin", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) sin},
{"sinh", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) sinh},
{"sqrt", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) sqrt},
{"tan", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) tan},
{"tanh", 1, {TCL_DOUBLE}, ExprUnaryFunc, (ClientData) tanh},
#endif
{"abs", 1, {TCL_EITHER}, ExprAbsFunc, 0},
{"double", 1, {TCL_EITHER}, ExprDoubleFunc, 0},
{"int", 1, {TCL_EITHER}, ExprIntFunc, 0},
{"rand", 0, {TCL_EITHER}, ExprRandFunc, 0}, /* NOTE: rand takes no args. */
{"round", 1, {TCL_EITHER}, ExprRoundFunc, 0},
{"srand", 1, {TCL_INT}, ExprSrandFunc, 0},
{0},
};
/*
* The structure below defines the command name Tcl object type by means of
* procedures that can be invoked by generic object code. Objects of this
* type cache the Command pointer that results from looking up command names
* in the command hashtable. Such objects appear as the zeroth ("command
* name") argument in a Tcl command.
*/
Tcl_ObjType tclCmdNameType = {
"cmdName", /* name */
FreeCmdNameInternalRep, /* freeIntRepProc */
DupCmdNameInternalRep, /* dupIntRepProc */
(Tcl_UpdateStringProc *) NULL, /* updateStringProc */
SetCmdNameFromAny /* setFromAnyProc */
};
/*
*----------------------------------------------------------------------
*
* InitByteCodeExecution --
*
* This procedure is called once to initialize the Tcl bytecode
* interpreter.
*
* Results:
* None.
*
* Side effects:
* This procedure initializes the array of instruction names. If
* compiling with the TCL_COMPILE_STATS flag, it initializes the
* array that counts the executions of each instruction and it
* creates the "evalstats" command. It also registers the command name
* Tcl_ObjType. It also establishes the link between the Tcl
* "tcl_traceExec" and C "tclTraceExec" variables.
*
*----------------------------------------------------------------------
*/
static void
InitByteCodeExecution(interp)
Tcl_Interp *interp; /* Interpreter for which the Tcl variable
* "tcl_traceExec" is linked to control
* instruction tracing. */
{
Tcl_RegisterObjType(&tclCmdNameType);
if (Tcl_LinkVar(interp, "tcl_traceExec", (char *) &tclTraceExec,
TCL_LINK_INT) != TCL_OK) {
panic("InitByteCodeExecution: can't create link for tcl_traceExec variable");
}
#ifdef TCL_COMPILE_STATS
Tcl_CreateCommand(interp, "evalstats", EvalStatsCmd,
(ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
#endif /* TCL_COMPILE_STATS */
}
/*
*----------------------------------------------------------------------
*
* TclCreateExecEnv --
*
* This procedure creates a new execution environment for Tcl bytecode
* execution. An ExecEnv points to a Tcl evaluation stack. An ExecEnv
* is typically created once for each Tcl interpreter (Interp
* structure) and recursively passed to TclExecuteByteCode to execute
* ByteCode sequences for nested commands.
*
* Results:
* A newly allocated ExecEnv is returned. This points to an empty
* evaluation stack of the standard initial size.
*
* Side effects:
* The bytecode interpreter is also initialized here, as this
* procedure will be called before any call to TclExecuteByteCode.
*
*----------------------------------------------------------------------
*/
#define TCL_STACK_INITIAL_SIZE 2000
ExecEnv *
TclCreateExecEnv(interp)
Tcl_Interp *interp; /* Interpreter for which the execution
* environment is being created. */
{
ExecEnv *eePtr = (ExecEnv *) ckalloc(sizeof(ExecEnv));
eePtr->stackPtr = (Tcl_Obj **)
ckalloc((unsigned) (TCL_STACK_INITIAL_SIZE * sizeof(Tcl_Obj *)));
eePtr->stackTop = -1;
eePtr->stackEnd = (TCL_STACK_INITIAL_SIZE - 1);
Tcl_MutexLock(&execMutex);
if (!execInitialized) {
TclInitAuxDataTypeTable();
InitByteCodeExecution(interp);
execInitialized = 1;
}
Tcl_MutexUnlock(&execMutex);
return eePtr;
}
#undef TCL_STACK_INITIAL_SIZE
/*
*----------------------------------------------------------------------
*
* TclDeleteExecEnv --
*
* Frees the storage for an ExecEnv.
*
* Results:
* None.
*
* Side effects:
* Storage for an ExecEnv and its contained storage (e.g. the
* evaluation stack) is freed.
*
*----------------------------------------------------------------------
*/
void
TclDeleteExecEnv(eePtr)
ExecEnv *eePtr; /* Execution environment to free. */
{
ckfree((char *) eePtr->stackPtr);
ckfree((char *) eePtr);
}
/*
*----------------------------------------------------------------------
*
* TclFinalizeExecution --
*
* Finalizes the execution environment setup so that it can be
* later reinitialized.
*
* Results:
* None.
*
* Side effects:
* After this call, the next time TclCreateExecEnv will be called
* it will call InitByteCodeExecution.
*
*----------------------------------------------------------------------
*/
void
TclFinalizeExecution()
{
Tcl_MutexLock(&execMutex);
execInitialized = 0;
Tcl_MutexUnlock(&execMutex);
TclFinalizeAuxDataTypeTable();
}
/*
*----------------------------------------------------------------------
*
* GrowEvaluationStack --
*
* This procedure grows a Tcl evaluation stack stored in an ExecEnv.
*
* Results:
* None.
*
* Side effects:
* The size of the evaluation stack is doubled.
*
*----------------------------------------------------------------------
*/
static void
GrowEvaluationStack(eePtr)
register ExecEnv *eePtr; /* Points to the ExecEnv with an evaluation
* stack to enlarge. */
{
/*
* The current Tcl stack elements are stored from eePtr->stackPtr[0]
* to eePtr->stackPtr[eePtr->stackEnd] (inclusive).
*/
int currElems = (eePtr->stackEnd + 1);
int newElems = 2*currElems;
int currBytes = currElems * sizeof(Tcl_Obj *);
int newBytes = 2*currBytes;
Tcl_Obj **newStackPtr = (Tcl_Obj **) ckalloc((unsigned) newBytes);
/*
* Copy the existing stack items to the new stack space, free the old
* storage if appropriate, and mark new space as malloc'ed.
*/
memcpy((VOID *) newStackPtr, (VOID *) eePtr->stackPtr,
(size_t) currBytes);
ckfree((char *) eePtr->stackPtr);
eePtr->stackPtr = newStackPtr;
eePtr->stackEnd = (newElems - 1); /* i.e. index of last usable item */
}
/*
*----------------------------------------------------------------------
*
* TclExecuteByteCode --
*
* This procedure executes the instructions of a ByteCode structure.
* It returns when a "done" instruction is executed or an error occurs.
*
* Results:
* The return value is one of the return codes defined in tcl.h
* (such as TCL_OK), and interp->objResultPtr refers to a Tcl object
* that either contains the result of executing the code or an
* error message.
*
* Side effects:
* Almost certainly, depending on the ByteCode's instructions.
*
*----------------------------------------------------------------------
*/
int
TclExecuteByteCode(interp, codePtr)
Tcl_Interp *interp; /* Token for command interpreter. */
ByteCode *codePtr; /* The bytecode sequence to interpret. */
{
Interp *iPtr = (Interp *) interp;
ExecEnv *eePtr = iPtr->execEnvPtr;
/* Points to the execution environment. */
register Tcl_Obj **stackPtr = eePtr->stackPtr;
/* Cached evaluation stack base pointer. */
register int stackTop = eePtr->stackTop;
/* Cached top index of evaluation stack. */
register unsigned char *pc = codePtr->codeStart;
/* The current program counter. */
int opnd; /* Current instruction's operand byte. */
int pcAdjustment; /* Hold pc adjustment after instruction. */
int initStackTop = stackTop;/* Stack top at start of execution. */
ExceptionRange *rangePtr; /* Points to closest loop or catch exception
* range enclosing the pc. Used by various
* instructions and processCatch to
* process break, continue, and errors. */
int result = TCL_OK; /* Return code returned after execution. */
int traceInstructions = (tclTraceExec == 3);
Tcl_Obj *valuePtr, *value2Ptr, *objPtr;
char *bytes;
int length;
long i;
/*
* This procedure uses a stack to hold information about catch commands.
* This information is the current operand stack top when starting to
* execute the code for each catch command. It starts out with stack-
* allocated space but uses dynamically-allocated storage if needed.
*/
#define STATIC_CATCH_STACK_SIZE 4
int (catchStackStorage[STATIC_CATCH_STACK_SIZE]);
int *catchStackPtr = catchStackStorage;
int catchTop = -1;
#ifdef TCL_COMPILE_DEBUG
if (tclTraceExec >= 2) {
PrintByteCodeInfo(codePtr);
fprintf(stdout, " Starting stack top=%d\n", eePtr->stackTop);
fflush(stdout);
}
#endif
#ifdef TCL_COMPILE_STATS
iPtr->stats.numExecutions++;
#endif
/*
* Make sure the catch stack is large enough to hold the maximum number
* of catch commands that could ever be executing at the same time. This
* will be no more than the exception range array's depth.
*/
if (codePtr->maxExceptDepth > STATIC_CATCH_STACK_SIZE) {
catchStackPtr = (int *)
ckalloc(codePtr->maxExceptDepth * sizeof(int));
}
/*
* Make sure the stack has enough room to execute this ByteCode.
*/
while ((stackTop + codePtr->maxStackDepth) > eePtr->stackEnd) {
GrowEvaluationStack(eePtr);
stackPtr = eePtr->stackPtr;
}
/*
* Loop executing instructions until a "done" instruction, a TCL_RETURN,
* or some error.
*/
for (;;) {
#ifdef TCL_COMPILE_DEBUG
ValidatePcAndStackTop(codePtr, pc, stackTop, initStackTop,
eePtr->stackEnd);
#else /* not TCL_COMPILE_DEBUG */
if (traceInstructions) {
fprintf(stdout, "%2d: %2d ", iPtr->numLevels, stackTop);
TclPrintInstruction(codePtr, pc);
fflush(stdout);
}
#endif /* TCL_COMPILE_DEBUG */
#ifdef TCL_COMPILE_STATS
iPtr->stats.instructionCount[*pc]++;
#endif
switch (*pc) {
case INST_DONE:
/*
* Pop the topmost object from the stack, set the interpreter's
* object result to point to it, and return.
*/
valuePtr = POP_OBJECT();
Tcl_SetObjResult(interp, valuePtr);
TclDecrRefCount(valuePtr);
if (stackTop != initStackTop) {
fprintf(stderr, "\nTclExecuteByteCode: done instruction at pc %u: stack top %d != entry stack top %d\n",
(unsigned int)(pc - codePtr->codeStart),
(unsigned int) stackTop,
(unsigned int) initStackTop);
panic("TclExecuteByteCode execution failure: end stack top != start stack top");
}
TRACE_WITH_OBJ(("=> return code=%d, result=", result),
iPtr->objResultPtr);
#ifdef TCL_COMPILE_DEBUG
if (traceInstructions) {
fprintf(stdout, "\n");
}
#endif
goto done;
case INST_PUSH1:
#ifdef TCL_COMPILE_DEBUG
valuePtr = codePtr->objArrayPtr[TclGetUInt1AtPtr(pc+1)];
PUSH_OBJECT(valuePtr);
TRACE_WITH_OBJ(("%u => ", TclGetInt1AtPtr(pc+1)), valuePtr);
#else
PUSH_OBJECT(codePtr->objArrayPtr[TclGetUInt1AtPtr(pc+1)]);
#endif /* TCL_COMPILE_DEBUG */
ADJUST_PC(2);
case INST_PUSH4:
valuePtr = codePtr->objArrayPtr[TclGetUInt4AtPtr(pc+1)];
PUSH_OBJECT(valuePtr);
TRACE_WITH_OBJ(("%u => ", TclGetUInt4AtPtr(pc+1)), valuePtr);
ADJUST_PC(5);
case INST_POP:
valuePtr = POP_OBJECT();
TRACE_WITH_OBJ(("=> discarding "), valuePtr);
TclDecrRefCount(valuePtr); /* finished with pop'ed object. */
ADJUST_PC(1);
case INST_DUP:
valuePtr = stackPtr[stackTop];
PUSH_OBJECT(Tcl_DuplicateObj(valuePtr));
TRACE_WITH_OBJ(("=> "), valuePtr);
ADJUST_PC(1);
case INST_CONCAT1:
opnd = TclGetUInt1AtPtr(pc+1);
{
Tcl_Obj *concatObjPtr;
int totalLen = 0;
/*
* Concatenate strings (with no separators) from the top
* opnd items on the stack starting with the deepest item.
* First, determine how many characters are needed.
*/
for (i = (stackTop - (opnd-1)); i <= stackTop; i++) {
bytes = Tcl_GetStringFromObj(stackPtr[i], &length);
if (bytes != NULL) {
totalLen += length;
}
}
/*
* Initialize the new append string object by appending the
* strings of the opnd stack objects. Also pop the objects.
*/
TclNewObj(concatObjPtr);
if (totalLen > 0) {
char *p = (char *) ckalloc((unsigned) (totalLen + 1));
concatObjPtr->bytes = p;
concatObjPtr->length = totalLen;
for (i = (stackTop - (opnd-1)); i <= stackTop; i++) {
valuePtr = stackPtr[i];
bytes = Tcl_GetStringFromObj(valuePtr, &length);
if (bytes != NULL) {
memcpy((VOID *) p, (VOID *) bytes,
(size_t) length);
p += length;
}
TclDecrRefCount(valuePtr);
}
*p = '\0';
} else {
for (i = (stackTop - (opnd-1)); i <= stackTop; i++) {
Tcl_DecrRefCount(stackPtr[i]);
}
}
stackTop -= opnd;
PUSH_OBJECT(concatObjPtr);
TRACE_WITH_OBJ(("%u => ", opnd), concatObjPtr);
ADJUST_PC(2);
}
case INST_INVOKE_STK4:
opnd = TclGetUInt4AtPtr(pc+1);
pcAdjustment = 5;
goto doInvocation;
case INST_INVOKE_STK1:
opnd = TclGetUInt1AtPtr(pc+1);
pcAdjustment = 2;
doInvocation:
{
int objc = opnd; /* The number of arguments. */
Tcl_Obj **objv; /* The array of argument objects. */
Command *cmdPtr; /* Points to command's Command struct. */
int newPcOffset; /* New inst offset for break, continue. */
#ifdef TCL_COMPILE_DEBUG
int isUnknownCmd = 0;
char cmdNameBuf[21];
#endif /* TCL_COMPILE_DEBUG */
/*
* If the interpreter was deleted, return an error.
*/
if (iPtr->flags & DELETED) {
Tcl_ResetResult(interp);
Tcl_AppendToObj(Tcl_GetObjResult(interp),
"attempt to call eval in deleted interpreter", -1);
Tcl_SetErrorCode(interp, "CORE", "IDELETE",
"attempt to call eval in deleted interpreter",
(char *) NULL);
result = TCL_ERROR;
goto checkForCatch;
}
/*
* Find the procedure to execute this command. If the
* command is not found, handle it with the "unknown" proc.
*/
objv = &(stackPtr[stackTop - (objc-1)]);
cmdPtr = (Command *) Tcl_GetCommandFromObj(interp, objv[0]);
if (cmdPtr == NULL) {
cmdPtr = (Command *) Tcl_FindCommand(interp, "unknown",
(Tcl_Namespace *) NULL, TCL_GLOBAL_ONLY);
if (cmdPtr == NULL) {
Tcl_ResetResult(interp);
Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
"invalid command name \"",
Tcl_GetString(objv[0]), "\"",
(char *) NULL);
TRACE(("%u => unknown proc not found: ", objc));
result = TCL_ERROR;
goto checkForCatch;
}
#ifdef TCL_COMPILE_DEBUG
isUnknownCmd = 1;
#endif /*TCL_COMPILE_DEBUG*/
stackTop++; /* need room for new inserted objv[0] */
for (i = objc-1; i >= 0; i--) {
objv[i+1] = objv[i];
}
objc++;
objv[0] = Tcl_NewStringObj("unknown", -1);
Tcl_IncrRefCount(objv[0]);
}
/*
* Call any trace procedures.
*/
if (iPtr->tracePtr != NULL) {
Trace *tracePtr, *nextTracePtr;
for (tracePtr = iPtr->tracePtr; tracePtr != NULL;
tracePtr = nextTracePtr) {
nextTracePtr = tracePtr->nextPtr;
if (iPtr->numLevels <= tracePtr->level) {
int numChars;
char *cmd = GetSrcInfoForPc(pc, codePtr,
&numChars);
if (cmd != NULL) {
DECACHE_STACK_INFO();
CallTraceProcedure(interp, tracePtr, cmdPtr,
cmd, numChars, objc, objv);
CACHE_STACK_INFO();
}
}
}
}
/*
* Finally, invoke the command's Tcl_ObjCmdProc. First reset
* the interpreter's string and object results to their
* default empty values since they could have gotten changed
* by earlier invocations.
*/
Tcl_ResetResult(interp);
if (tclTraceExec >= 2) {
#ifdef TCL_COMPILE_DEBUG
if (traceInstructions) {
strncpy(cmdNameBuf, Tcl_GetString(objv[0]), 20);
TRACE(("%u => call ", (isUnknownCmd? objc-1:objc)));
} else {
fprintf(stdout, "%d: (%u) invoking ",
iPtr->numLevels,
(unsigned int)(pc - codePtr->codeStart));
}
for (i = 0; i < objc; i++) {
TclPrintObject(stdout, objv[i], 15);
fprintf(stdout, " ");
}
fprintf(stdout, "\n");
fflush(stdout);
#else /* TCL_COMPILE_DEBUG */
fprintf(stdout, "%d: (%u) invoking %s\n",
iPtr->numLevels,
(unsigned int)(pc - codePtr->codeStart),
Tcl_GetString(objv[0]));
#endif /*TCL_COMPILE_DEBUG*/
}
iPtr->cmdCount++;
DECACHE_STACK_INFO();
result = (*cmdPtr->objProc)(cmdPtr->objClientData, interp, objc, objv);
// FIXME FLOH
/*
if (Tcl_AsyncReady()) {
result = Tcl_AsyncInvoke(interp, result);
}
*/
CACHE_STACK_INFO();
/*
* If the interpreter has a non-empty string result, the
* result object is either empty or stale because some
* procedure set interp->result directly. If so, move the
* string result to the result object, then reset the
* string result.
*/
if (*(iPtr->result) != 0) {
(void) Tcl_GetObjResult(interp);
}
/*
* Pop the objc top stack elements and decrement their ref
* counts.
*/
for (i = 0; i < objc; i++) {
valuePtr = stackPtr[stackTop];
TclDecrRefCount(valuePtr);
stackTop--;
}
/*
* Process the result of the Tcl_ObjCmdProc call.
*/
switch (result) {
case TCL_OK:
/*
* Push the call's object result and continue execution
* with the next instruction.
*/
PUSH_OBJECT(Tcl_GetObjResult(interp));
TRACE_WITH_OBJ(("%u => ...after \"%.20s\", result=",
objc, cmdNameBuf), Tcl_GetObjResult(interp));
ADJUST_PC(pcAdjustment);
case TCL_BREAK:
case TCL_CONTINUE:
/*
* The invoked command requested a break or continue.
* Find the closest enclosing loop or catch exception
* range, if any. If a loop is found, terminate its
* execution or skip to its next iteration. If the
* closest is a catch exception range, jump to its
* catchOffset. If no enclosing range is found, stop
* execution and return the TCL_BREAK or TCL_CONTINUE.
*/
rangePtr = GetExceptRangeForPc(pc, /*catchOnly*/ 0,
codePtr);
if (rangePtr == NULL) {
TRACE(("%u => ... after \"%.20s\", no encl. loop or catch, returning %s\n",
objc, cmdNameBuf,
StringForResultCode(result)));
goto abnormalReturn; /* no catch exists to check */
}
newPcOffset = 0;
switch (rangePtr->type) {
case LOOP_EXCEPTION_RANGE:
if (result == TCL_BREAK) {
newPcOffset = rangePtr->breakOffset;
} else if (rangePtr->continueOffset == -1) {
TRACE(("%u => ... after \"%.20s\", %s, loop w/o continue, checking for catch\n",
objc, cmdNameBuf,
StringForResultCode(result)));
goto checkForCatch;
} else {
newPcOffset = rangePtr->continueOffset;
}
TRACE(("%u => ... after \"%.20s\", %s, range at %d, new pc %d\n",
objc, cmdNameBuf,
StringForResultCode(result),
rangePtr->codeOffset, newPcOffset));
break;
case CATCH_EXCEPTION_RANGE:
TRACE(("%u => ... after \"%.20s\", %s...\n",
objc, cmdNameBuf,
StringForResultCode(result)));
goto processCatch; /* it will use rangePtr */
default:
panic("TclExecuteByteCode: bad ExceptionRange type\n");
}
result = TCL_OK;
pc = (codePtr->codeStart + newPcOffset);
continue; /* restart outer instruction loop at pc */
case TCL_ERROR:
/*
* The invoked command returned an error. Look for an
* enclosing catch exception range, if any.
*/
TRACE_WITH_OBJ(("%u => ... after \"%.20s\", TCL_ERROR ",
objc, cmdNameBuf), Tcl_GetObjResult(interp));
goto checkForCatch;
case TCL_RETURN:
/*
* The invoked command requested that the current
* procedure stop execution and return. First check
* for an enclosing catch exception range, if any.
*/
TRACE(("%u => ... after \"%.20s\", TCL_RETURN\n",
objc, cmdNameBuf));
goto checkForCatch;
default:
TRACE_WITH_OBJ(("%u => ... after \"%.20s\", OTHER RETURN CODE %d ",
objc, cmdNameBuf, result),
Tcl_GetObjResult(interp));
goto checkForCatch;
}
}
case INST_EVAL_STK:
objPtr = POP_OBJECT();
DECACHE_STACK_INFO();
result = Tcl_EvalObjEx(interp, objPtr, 0);
CACHE_STACK_INFO();
if (result == TCL_OK) {
/*
* Normal return; push the eval's object result.
*/
PUSH_OBJECT(Tcl_GetObjResult(interp));
TRACE_WITH_OBJ(("\"%.30s\" => ", O2S(objPtr)),
Tcl_GetObjResult(interp));
TclDecrRefCount(objPtr);
ADJUST_PC(1);
} else if ((result == TCL_BREAK) || (result == TCL_CONTINUE)) {
/*
* Find the closest enclosing loop or catch exception range,
* if any. If a loop is found, terminate its execution or
* skip to its next iteration. If the closest is a catch
* exception range, jump to its catchOffset. If no enclosing
* range is found, stop execution and return that same
* TCL_BREAK or TCL_CONTINUE.
*/
int newPcOffset = 0; /* Pc offset computed during break,
* continue, error processing. Init.
* to avoid compiler warning. */
rangePtr = GetExceptRangeForPc(pc, /*catchOnly*/ 0,
codePtr);
if (rangePtr == NULL) {
TRACE(("\"%.30s\" => no encl. loop or catch, returning %s\n",
O2S(objPtr), StringForResultCode(result)));
Tcl_DecrRefCount(objPtr);
goto abnormalReturn; /* no catch exists to check */
}
switch (rangePtr->type) {
case LOOP_EXCEPTION_RANGE:
if (result == TCL_BREAK) {
newPcOffset = rangePtr->breakOffset;
} else if (rangePtr->continueOffset == -1) {
TRACE(("\"%.30s\" => %s, loop w/o continue, checking for catch\n",
O2S(objPtr), StringForResultCode(result)));
Tcl_DecrRefCount(objPtr);
goto checkForCatch;
} else {
newPcOffset = rangePtr->continueOffset;
}
result = TCL_OK;
TRACE_WITH_OBJ(("\"%.30s\" => %s, range at %d, new pc %d ",
O2S(objPtr), StringForResultCode(result),
rangePtr->codeOffset, newPcOffset), valuePtr);
break;
case CATCH_EXCEPTION_RANGE:
TRACE_WITH_OBJ(("\"%.30s\" => %s ",
O2S(objPtr), StringForResultCode(result)),
valuePtr);
Tcl_DecrRefCount(objPtr);
goto processCatch; /* it will use rangePtr */
default:
panic("TclExecuteByteCode: unrecognized ExceptionRange type %d\n", rangePtr->type);
}
Tcl_DecrRefCount(objPtr);
pc = (codePtr->codeStart + newPcOffset);
continue; /* restart outer instruction loop at pc */
} else { /* eval returned TCL_ERROR, TCL_RETURN, unknown code */
TRACE_WITH_OBJ(("\"%.30s\" => ERROR: ", O2S(objPtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
goto checkForCatch;
}
case INST_EXPR_STK:
objPtr = POP_OBJECT();
Tcl_ResetResult(interp);
DECACHE_STACK_INFO();
result = Tcl_ExprObj(interp, objPtr, &valuePtr);
CACHE_STACK_INFO();
if (result != TCL_OK) {
TRACE_WITH_OBJ(("\"%.30s\" => ERROR: ",
O2S(objPtr)), Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
goto checkForCatch;
}
stackPtr[++stackTop] = valuePtr; /* already has right refct */
TRACE_WITH_OBJ(("\"%.30s\" => ", O2S(objPtr)), valuePtr);
TclDecrRefCount(objPtr);
ADJUST_PC(1);
case INST_LOAD_SCALAR1:
#ifdef TCL_COMPILE_DEBUG
opnd = TclGetUInt1AtPtr(pc+1);
DECACHE_STACK_INFO();
valuePtr = TclGetIndexedScalar(interp, opnd,
/*leaveErrorMsg*/ 1);
CACHE_STACK_INFO();
if (valuePtr == NULL) {
TRACE_WITH_OBJ(("%u => ERROR: ", opnd),
Tcl_GetObjResult(interp));
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(valuePtr);
TRACE_WITH_OBJ(("%u => ", opnd), valuePtr);
#else /* TCL_COMPILE_DEBUG */
DECACHE_STACK_INFO();
opnd = TclGetUInt1AtPtr(pc+1);
valuePtr = TclGetIndexedScalar(interp, opnd, /*leaveErrorMsg*/ 1);
CACHE_STACK_INFO();
if (valuePtr == NULL) {
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(valuePtr);
#endif /* TCL_COMPILE_DEBUG */
ADJUST_PC(2);
case INST_LOAD_SCALAR4:
opnd = TclGetUInt4AtPtr(pc+1);
DECACHE_STACK_INFO();
valuePtr = TclGetIndexedScalar(interp, opnd,
/*leaveErrorMsg*/ 1);
CACHE_STACK_INFO();
if (valuePtr == NULL) {
TRACE_WITH_OBJ(("%u => ERROR: ", opnd),
Tcl_GetObjResult(interp));
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(valuePtr);
TRACE_WITH_OBJ(("%u => ", opnd), valuePtr);
ADJUST_PC(5);
case INST_LOAD_SCALAR_STK:
objPtr = POP_OBJECT(); /* scalar name */
DECACHE_STACK_INFO();
valuePtr = Tcl_ObjGetVar2(interp, objPtr, NULL, TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (valuePtr == NULL) {
TRACE_WITH_OBJ(("\"%.30s\" => ERROR: ", O2S(objPtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(valuePtr);
TRACE_WITH_OBJ(("\"%.30s\" => ", O2S(objPtr)), valuePtr);
TclDecrRefCount(objPtr);
ADJUST_PC(1);
case INST_LOAD_ARRAY4:
opnd = TclGetUInt4AtPtr(pc+1);
pcAdjustment = 5;
goto doLoadArray;
case INST_LOAD_ARRAY1:
opnd = TclGetUInt1AtPtr(pc+1);
pcAdjustment = 2;
doLoadArray:
{
Tcl_Obj *elemPtr = POP_OBJECT();
DECACHE_STACK_INFO();
valuePtr = TclGetElementOfIndexedArray(interp, opnd,
elemPtr, /*leaveErrorMsg*/ 1);
CACHE_STACK_INFO();
if (valuePtr == NULL) {
TRACE_WITH_OBJ(("%u \"%.30s\" => ERROR: ",
opnd, O2S(elemPtr)), Tcl_GetObjResult(interp));
Tcl_DecrRefCount(elemPtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(valuePtr);
TRACE_WITH_OBJ(("%u \"%.30s\" => ",
opnd, O2S(elemPtr)),valuePtr);
TclDecrRefCount(elemPtr);
}
ADJUST_PC(pcAdjustment);
case INST_LOAD_ARRAY_STK:
{
Tcl_Obj *elemPtr = POP_OBJECT();
objPtr = POP_OBJECT(); /* array name */
DECACHE_STACK_INFO();
valuePtr = Tcl_ObjGetVar2(interp, objPtr, elemPtr,
TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (valuePtr == NULL) {
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" => ERROR: ",
O2S(objPtr), O2S(elemPtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(elemPtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(valuePtr);
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" => ",
O2S(objPtr), O2S(elemPtr)), valuePtr);
TclDecrRefCount(objPtr);
TclDecrRefCount(elemPtr);
}
ADJUST_PC(1);
case INST_LOAD_STK:
objPtr = POP_OBJECT(); /* variable name */
DECACHE_STACK_INFO();
valuePtr = Tcl_ObjGetVar2(interp, objPtr, NULL, TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (valuePtr == NULL) {
TRACE_WITH_OBJ(("\"%.30s\" => ERROR: ",
O2S(objPtr)), Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(valuePtr);
TRACE_WITH_OBJ(("\"%.30s\" => ", O2S(objPtr)), valuePtr);
TclDecrRefCount(objPtr);
ADJUST_PC(1);
case INST_STORE_SCALAR4:
opnd = TclGetUInt4AtPtr(pc+1);
pcAdjustment = 5;
goto doStoreScalar;
case INST_STORE_SCALAR1:
opnd = TclGetUInt1AtPtr(pc+1);
pcAdjustment = 2;
doStoreScalar:
valuePtr = POP_OBJECT();
DECACHE_STACK_INFO();
value2Ptr = TclSetIndexedScalar(interp, opnd, valuePtr,
/*leaveErrorMsg*/ 1);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("%u <- \"%.30s\" => ERROR: ",
opnd, O2S(valuePtr)), Tcl_GetObjResult(interp));
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("%u <- \"%.30s\" => ",
opnd, O2S(valuePtr)), value2Ptr);
TclDecrRefCount(valuePtr);
ADJUST_PC(pcAdjustment);
case INST_STORE_SCALAR_STK:
valuePtr = POP_OBJECT();
objPtr = POP_OBJECT(); /* scalar name */
DECACHE_STACK_INFO();
value2Ptr = Tcl_ObjSetVar2(interp, objPtr, NULL, valuePtr,
TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("\"%.30s\" <- \"%.30s\" => ERROR: ",
O2S(objPtr), O2S(valuePtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("\"%.30s\" <- \"%.30s\" => ",
O2S(objPtr), O2S(valuePtr)), value2Ptr);
TclDecrRefCount(objPtr);
TclDecrRefCount(valuePtr);
ADJUST_PC(1);
case INST_STORE_ARRAY4:
opnd = TclGetUInt4AtPtr(pc+1);
pcAdjustment = 5;
goto doStoreArray;
case INST_STORE_ARRAY1:
opnd = TclGetUInt1AtPtr(pc+1);
pcAdjustment = 2;
doStoreArray:
{
Tcl_Obj *elemPtr;
valuePtr = POP_OBJECT();
elemPtr = POP_OBJECT();
DECACHE_STACK_INFO();
value2Ptr = TclSetElementOfIndexedArray(interp, opnd,
elemPtr, valuePtr, TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("%u \"%.30s\" <- \"%.30s\" => ERROR: ",
opnd, O2S(elemPtr), O2S(valuePtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(elemPtr);
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("%u \"%.30s\" <- \"%.30s\" => ",
opnd, O2S(elemPtr), O2S(valuePtr)), value2Ptr);
TclDecrRefCount(elemPtr);
TclDecrRefCount(valuePtr);
}
ADJUST_PC(pcAdjustment);
case INST_STORE_ARRAY_STK:
{
Tcl_Obj *elemPtr;
valuePtr = POP_OBJECT();
elemPtr = POP_OBJECT();
objPtr = POP_OBJECT(); /* array name */
DECACHE_STACK_INFO();
value2Ptr = Tcl_ObjSetVar2(interp, objPtr, elemPtr, valuePtr,
TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" <- \"%.30s\" => ERROR: ",
O2S(objPtr), O2S(elemPtr), O2S(valuePtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(elemPtr);
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" <- \"%.30s\" => ",
O2S(objPtr), O2S(elemPtr), O2S(valuePtr)),
value2Ptr);
TclDecrRefCount(objPtr);
TclDecrRefCount(elemPtr);
TclDecrRefCount(valuePtr);
}
ADJUST_PC(1);
case INST_STORE_STK:
valuePtr = POP_OBJECT();
objPtr = POP_OBJECT(); /* variable name */
DECACHE_STACK_INFO();
value2Ptr = Tcl_ObjSetVar2(interp, objPtr, NULL, valuePtr,
TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("\"%.30s\" <- \"%.30s\" => ERROR: ",
O2S(objPtr), O2S(valuePtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("\"%.30s\" <- \"%.30s\" => ",
O2S(objPtr), O2S(valuePtr)), value2Ptr);
TclDecrRefCount(objPtr);
TclDecrRefCount(valuePtr);
ADJUST_PC(1);
case INST_INCR_SCALAR1:
opnd = TclGetUInt1AtPtr(pc+1);
valuePtr = POP_OBJECT();
if (valuePtr->typePtr != &tclIntType) {
result = tclIntType.setFromAnyProc(interp, valuePtr);
if (result != TCL_OK) {
TRACE_WITH_OBJ(("%u (by %s) => ERROR converting increment amount to int: ",
opnd, O2S(valuePtr)), Tcl_GetObjResult(interp));
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
}
i = valuePtr->internalRep.longValue;
DECACHE_STACK_INFO();
value2Ptr = TclIncrIndexedScalar(interp, opnd, i);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("%u (by %ld) => ERROR: ", opnd, i),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("%u (by %ld) => ", opnd, i), value2Ptr);
TclDecrRefCount(valuePtr);
ADJUST_PC(2);
case INST_INCR_SCALAR_STK:
case INST_INCR_STK:
valuePtr = POP_OBJECT();
objPtr = POP_OBJECT(); /* scalar name */
if (valuePtr->typePtr != &tclIntType) {
result = tclIntType.setFromAnyProc(interp, valuePtr);
if (result != TCL_OK) {
TRACE_WITH_OBJ(("\"%.30s\" (by %s) => ERROR converting increment amount to int: ",
O2S(objPtr), O2S(valuePtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
}
i = valuePtr->internalRep.longValue;
DECACHE_STACK_INFO();
value2Ptr = TclIncrVar2(interp, objPtr, (Tcl_Obj *) NULL, i,
TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("\"%.30s\" (by %ld) => ERROR: ",
O2S(objPtr), i), Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("\"%.30s\" (by %ld) => ", O2S(objPtr), i),
value2Ptr);
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(valuePtr);
ADJUST_PC(1);
case INST_INCR_ARRAY1:
{
Tcl_Obj *elemPtr;
opnd = TclGetUInt1AtPtr(pc+1);
valuePtr = POP_OBJECT();
elemPtr = POP_OBJECT();
if (valuePtr->typePtr != &tclIntType) {
result = tclIntType.setFromAnyProc(interp, valuePtr);
if (result != TCL_OK) {
TRACE_WITH_OBJ(("%u \"%.30s\" (by %s) => ERROR converting increment amount to int: ",
opnd, O2S(elemPtr), O2S(valuePtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(elemPtr);
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
}
i = valuePtr->internalRep.longValue;
DECACHE_STACK_INFO();
value2Ptr = TclIncrElementOfIndexedArray(interp, opnd,
elemPtr, i);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("%u \"%.30s\" (by %ld) => ERROR: ",
opnd, O2S(elemPtr), i),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(elemPtr);
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("%u \"%.30s\" (by %ld) => ",
opnd, O2S(elemPtr), i), value2Ptr);
Tcl_DecrRefCount(elemPtr);
Tcl_DecrRefCount(valuePtr);
}
ADJUST_PC(2);
case INST_INCR_ARRAY_STK:
{
Tcl_Obj *elemPtr;
valuePtr = POP_OBJECT();
elemPtr = POP_OBJECT();
objPtr = POP_OBJECT(); /* array name */
if (valuePtr->typePtr != &tclIntType) {
result = tclIntType.setFromAnyProc(interp, valuePtr);
if (result != TCL_OK) {
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" (by %s) => ERROR converting increment amount to int: ",
O2S(objPtr), O2S(elemPtr), O2S(valuePtr)),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(elemPtr);
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
}
i = valuePtr->internalRep.longValue;
DECACHE_STACK_INFO();
value2Ptr = TclIncrVar2(interp, objPtr, elemPtr, i,
TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" (by %ld) => ERROR: ",
O2S(objPtr), O2S(elemPtr), i),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(elemPtr);
Tcl_DecrRefCount(valuePtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" (by %ld) => ",
O2S(objPtr), O2S(elemPtr), i), value2Ptr);
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(elemPtr);
Tcl_DecrRefCount(valuePtr);
}
ADJUST_PC(1);
case INST_INCR_SCALAR1_IMM:
opnd = TclGetUInt1AtPtr(pc+1);
i = TclGetInt1AtPtr(pc+2);
DECACHE_STACK_INFO();
value2Ptr = TclIncrIndexedScalar(interp, opnd, i);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("%u %ld => ERROR: ", opnd, i),
Tcl_GetObjResult(interp));
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("%u %ld => ", opnd, i), value2Ptr);
ADJUST_PC(3);
case INST_INCR_SCALAR_STK_IMM:
case INST_INCR_STK_IMM:
objPtr = POP_OBJECT(); /* variable name */
i = TclGetInt1AtPtr(pc+1);
DECACHE_STACK_INFO();
value2Ptr = TclIncrVar2(interp, objPtr, (Tcl_Obj *) NULL, i,
TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("\"%.30s\" %ld => ERROR: ",
O2S(objPtr), i), Tcl_GetObjResult(interp));
result = TCL_ERROR;
Tcl_DecrRefCount(objPtr);
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("\"%.30s\" %ld => ", O2S(objPtr), i),
value2Ptr);
TclDecrRefCount(objPtr);
ADJUST_PC(2);
case INST_INCR_ARRAY1_IMM:
{
Tcl_Obj *elemPtr;
opnd = TclGetUInt1AtPtr(pc+1);
i = TclGetInt1AtPtr(pc+2);
elemPtr = POP_OBJECT();
DECACHE_STACK_INFO();
value2Ptr = TclIncrElementOfIndexedArray(interp, opnd,
elemPtr, i);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("%u \"%.30s\" (by %ld) => ERROR: ",
opnd, O2S(elemPtr), i),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(elemPtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("%u \"%.30s\" (by %ld) => ",
opnd, O2S(elemPtr), i), value2Ptr);
Tcl_DecrRefCount(elemPtr);
}
ADJUST_PC(3);
case INST_INCR_ARRAY_STK_IMM:
{
Tcl_Obj *elemPtr;
i = TclGetInt1AtPtr(pc+1);
elemPtr = POP_OBJECT();
objPtr = POP_OBJECT(); /* array name */
DECACHE_STACK_INFO();
value2Ptr = TclIncrVar2(interp, objPtr, elemPtr, i,
TCL_LEAVE_ERR_MSG);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" (by %ld) => ERROR: ",
O2S(objPtr), O2S(elemPtr), i),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(elemPtr);
result = TCL_ERROR;
goto checkForCatch;
}
PUSH_OBJECT(value2Ptr);
TRACE_WITH_OBJ(("\"%.30s(%.30s)\" (by %ld) => ",
O2S(objPtr), O2S(elemPtr), i), value2Ptr);
Tcl_DecrRefCount(objPtr);
Tcl_DecrRefCount(elemPtr);
}
ADJUST_PC(2);
case INST_JUMP1:
#ifdef TCL_COMPILE_DEBUG
opnd = TclGetInt1AtPtr(pc+1);
TRACE(("%d => new pc %u\n", opnd,
(unsigned int)(pc + opnd - codePtr->codeStart)));
pc += opnd;
#else
pc += TclGetInt1AtPtr(pc+1);
#endif /* TCL_COMPILE_DEBUG */
continue;
case INST_JUMP4:
opnd = TclGetInt4AtPtr(pc+1);
TRACE(("%d => new pc %u\n", opnd,
(unsigned int)(pc + opnd - codePtr->codeStart)));
ADJUST_PC(opnd);
case INST_JUMP_TRUE4:
opnd = TclGetInt4AtPtr(pc+1);
pcAdjustment = 5;
goto doJumpTrue;
case INST_JUMP_TRUE1:
opnd = TclGetInt1AtPtr(pc+1);
pcAdjustment = 2;
doJumpTrue:
{
int b;
valuePtr = POP_OBJECT();
if (valuePtr->typePtr == &tclIntType) {
b = (valuePtr->internalRep.longValue != 0);
} else if (valuePtr->typePtr == &tclDoubleType) {
b = (valuePtr->internalRep.doubleValue != 0.0);
} else {
result = Tcl_GetBooleanFromObj(interp, valuePtr, &b);
if (result != TCL_OK) {
TRACE_WITH_OBJ(("%d => ERROR: ", opnd),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
}
if (b) {
TRACE(("%d => %.20s true, new pc %u\n",
opnd, O2S(valuePtr),
(unsigned int)(pc+opnd - codePtr->codeStart)));
TclDecrRefCount(valuePtr);
ADJUST_PC(opnd);
} else {
TRACE(("%d => %.20s false\n", opnd, O2S(valuePtr)));
TclDecrRefCount(valuePtr);
ADJUST_PC(pcAdjustment);
}
}
case INST_JUMP_FALSE4:
opnd = TclGetInt4AtPtr(pc+1);
pcAdjustment = 5;
goto doJumpFalse;
case INST_JUMP_FALSE1:
opnd = TclGetInt1AtPtr(pc+1);
pcAdjustment = 2;
doJumpFalse:
{
int b;
valuePtr = POP_OBJECT();
if (valuePtr->typePtr == &tclIntType) {
b = (valuePtr->internalRep.longValue != 0);
} else if (valuePtr->typePtr == &tclDoubleType) {
b = (valuePtr->internalRep.doubleValue != 0.0);
} else {
result = Tcl_GetBooleanFromObj(interp, valuePtr, &b);
if (result != TCL_OK) {
TRACE_WITH_OBJ(("%d => ERROR: ", opnd),
Tcl_GetObjResult(interp));
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
}
if (b) {
TRACE(("%d => %.20s true\n", opnd, O2S(valuePtr)));
TclDecrRefCount(valuePtr);
ADJUST_PC(pcAdjustment);
} else {
TRACE(("%d => %.20s false, new pc %u\n",
opnd, O2S(valuePtr),
(unsigned int)(pc + opnd - codePtr->codeStart)));
TclDecrRefCount(valuePtr);
ADJUST_PC(opnd);
}
}
case INST_LOR:
case INST_LAND:
{
/*
* Operands must be boolean or numeric. No int->double
* conversions are performed.
*/
int i1, i2;
int iResult;
char *s;
Tcl_ObjType *t1Ptr, *t2Ptr;
value2Ptr = POP_OBJECT();
valuePtr = POP_OBJECT();
t1Ptr = valuePtr->typePtr;
t2Ptr = value2Ptr->typePtr;
if ((t1Ptr == &tclIntType) || (t1Ptr == &tclBooleanType)) {
i1 = (valuePtr->internalRep.longValue != 0);
} else if (t1Ptr == &tclDoubleType) {
i1 = (valuePtr->internalRep.doubleValue != 0.0);
} else {
s = Tcl_GetStringFromObj(valuePtr, &length);
if (TclLooksLikeInt(s, length)) {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
valuePtr, &i);
i1 = (i != 0);
} else {
result = Tcl_GetBooleanFromObj((Tcl_Interp *) NULL,
valuePtr, &i1);
i1 = (i1 != 0);
}
if (result != TCL_OK) {
TRACE(("\"%.20s\" => ILLEGAL TYPE %s \n",
O2S(valuePtr),
(t1Ptr? t1Ptr->name : "null")));
IllegalExprOperandType(interp, pc, valuePtr);
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto checkForCatch;
}
}
if ((t2Ptr == &tclIntType) || (t2Ptr == &tclBooleanType)) {
i2 = (value2Ptr->internalRep.longValue != 0);
} else if (t2Ptr == &tclDoubleType) {
i2 = (value2Ptr->internalRep.doubleValue != 0.0);
} else {
s = Tcl_GetStringFromObj(value2Ptr, &length);
if (TclLooksLikeInt(s, length)) {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
value2Ptr, &i);
i2 = (i != 0);
} else {
result = Tcl_GetBooleanFromObj((Tcl_Interp *) NULL,
value2Ptr, &i2);
}
if (result != TCL_OK) {
TRACE(("\"%.20s\" => ILLEGAL TYPE %s \n",
O2S(value2Ptr),
(t2Ptr? t2Ptr->name : "null")));
IllegalExprOperandType(interp, pc, value2Ptr);
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto checkForCatch;
}
}
/*
* Reuse the valuePtr object already on stack if possible.
*/
if (*pc == INST_LOR) {
iResult = (i1 || i2);
} else {
iResult = (i1 && i2);
}
if (Tcl_IsShared(valuePtr)) {
PUSH_OBJECT(Tcl_NewLongObj(iResult));
TRACE(("%.20s %.20s => %d\n",
O2S(valuePtr), O2S(value2Ptr), iResult));
TclDecrRefCount(valuePtr);
} else { /* reuse the valuePtr object */
TRACE(("%.20s %.20s => %d\n",
O2S(valuePtr), O2S(value2Ptr), iResult));
Tcl_SetLongObj(valuePtr, iResult);
++stackTop; /* valuePtr now on stk top has right r.c. */
}
TclDecrRefCount(value2Ptr);
}
ADJUST_PC(1);
case INST_STR_EQ:
case INST_STR_NEQ:
{
/*
* String (in)equality check
*/
char *s1, *s2;
int s1len, s2len, iResult;
value2Ptr = POP_OBJECT();
valuePtr = POP_OBJECT();
if (valuePtr == value2Ptr) {
/*
* On the off-chance that the objects are the same,
* we don't really have to think hard about equality.
*/
iResult = (*pc == INST_STR_EQ);
} else {
s1 = Tcl_GetStringFromObj(valuePtr, &s1len);
s2 = Tcl_GetStringFromObj(value2Ptr, &s2len);
if (s1len == s2len) {
/*
* We only need to check (in)equality when
* we have equal length strings.
*/
if (*pc == INST_STR_NEQ) {
iResult = (strcmp(s1, s2) != 0);
} else {
/* INST_STR_EQ */
iResult = (strcmp(s1, s2) == 0);
}
} else {
iResult = (*pc == INST_STR_NEQ);
}
}
PUSH_OBJECT(Tcl_NewIntObj(iResult));
TRACE(("%.20s %.20s => %d\n",
O2S(valuePtr), O2S(value2Ptr), iResult));
TclDecrRefCount(valuePtr);
TclDecrRefCount(value2Ptr);
}
ADJUST_PC(1);
case INST_STR_CMP:
{
/*
* String compare
*/
char *s1, *s2;
int s1len, s2len, iResult;
value2Ptr = POP_OBJECT();
valuePtr = POP_OBJECT();
s1 = Tcl_GetStringFromObj(valuePtr, &s1len);
s2 = Tcl_GetStringFromObj(value2Ptr, &s2len);
/*
* Compare up to the minimum byte length
*/
iResult = memcmp(s1, s2,
(size_t) ((s1len < s2len) ? s1len : s2len));
if (iResult == 0) {
iResult = s1len - s2len;
} else if (iResult < 0) {
iResult = -1;
} else {
iResult = 1;
}
PUSH_OBJECT(Tcl_NewIntObj(iResult));
TRACE(("%.20s %.20s => %d\n",
O2S(valuePtr), O2S(value2Ptr), iResult));
TclDecrRefCount(valuePtr);
TclDecrRefCount(value2Ptr);
}
ADJUST_PC(1);
case INST_STR_LEN:
{
int length1;
valuePtr = POP_OBJECT();
if (valuePtr->typePtr == &tclByteArrayType) {
(void) Tcl_GetByteArrayFromObj(valuePtr, &length1);
} else {
length1 = Tcl_GetCharLength(valuePtr);
}
PUSH_OBJECT(Tcl_NewIntObj(length1));
TRACE(("%.20s => %d\n", O2S(valuePtr), length1));
TclDecrRefCount(valuePtr);
}
ADJUST_PC(1);
case INST_STR_INDEX:
{
/*
* String compare
*/
int index;
bytes = NULL; /* lint */
value2Ptr = POP_OBJECT();
valuePtr = POP_OBJECT();
/*
* If we have a ByteArray object, avoid indexing in the
* Utf string since the byte array contains one byte per
* character. Otherwise, use the Unicode string rep to
* get the index'th char.
*/
if (valuePtr->typePtr == &tclByteArrayType) {
bytes = (char *)Tcl_GetByteArrayFromObj(valuePtr, &length);
} else {
/*
* Get Unicode char length to calulate what 'end' means.
*/
length = Tcl_GetCharLength(valuePtr);
}
result = TclGetIntForIndex(interp, value2Ptr, length - 1,
&index);
if (result != TCL_OK) {
Tcl_DecrRefCount(value2Ptr);
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
if ((index >= 0) && (index < length)) {
if (valuePtr->typePtr == &tclByteArrayType) {
objPtr = Tcl_NewByteArrayObj((unsigned char *)
(&bytes[index]), 1);
} else {
char buf[TCL_UTF_MAX];
Tcl_UniChar ch;
ch = Tcl_GetUniChar(valuePtr, index);
length = Tcl_UniCharToUtf(ch, buf);
objPtr = Tcl_NewStringObj(buf, length);
}
} else {
objPtr = Tcl_NewObj();
}
PUSH_OBJECT(objPtr);
TRACE(("%.20s %.20s => %s\n",
O2S(valuePtr), O2S(value2Ptr), O2S(objPtr)));
TclDecrRefCount(valuePtr);
TclDecrRefCount(value2Ptr);
}
ADJUST_PC(1);
case INST_STR_MATCH:
{
int nocase, match;
valuePtr = POP_OBJECT(); /* String */
value2Ptr = POP_OBJECT(); /* Pattern */
objPtr = POP_OBJECT(); /* Case Sensitivity */
Tcl_GetBooleanFromObj(interp, objPtr, &nocase);
match = Tcl_UniCharCaseMatch(Tcl_GetUnicode(valuePtr),
Tcl_GetUnicode(value2Ptr), nocase);
/*
* Reuse the casePtr object already on stack if possible.
*/
TRACE(("%.20s %.20s => %d\n",
O2S(valuePtr), O2S(value2Ptr), match));
if (Tcl_IsShared(objPtr)) {
PUSH_OBJECT(Tcl_NewIntObj(match));
TclDecrRefCount(objPtr);
} else { /* reuse the valuePtr object */
Tcl_SetIntObj(objPtr, match);
++stackTop; /* valuePtr now on stk top has right r.c. */
}
TclDecrRefCount(valuePtr);
TclDecrRefCount(value2Ptr);
}
ADJUST_PC(1);
case INST_EQ:
case INST_NEQ:
case INST_LT:
case INST_GT:
case INST_LE:
case INST_GE:
{
/*
* Any type is allowed but the two operands must have the
* same type. We will compute value op value2.
*/
Tcl_ObjType *t1Ptr, *t2Ptr;
char *s1 = NULL; /* Init. avoids compiler warning. */
char *s2 = NULL; /* Init. avoids compiler warning. */
long i2 = 0; /* Init. avoids compiler warning. */
double d1 = 0.0; /* Init. avoids compiler warning. */
double d2 = 0.0; /* Init. avoids compiler warning. */
long iResult = 0; /* Init. avoids compiler warning. */
value2Ptr = POP_OBJECT();
valuePtr = POP_OBJECT();
t1Ptr = valuePtr->typePtr;
t2Ptr = value2Ptr->typePtr;
/*
* We only want to coerce numeric validation if
* neither type is NULL. A NULL type means the arg is
* essentially an empty object ("", {} or [list]).
*/
if (!((((t1Ptr == NULL) && (valuePtr->bytes == NULL))
|| (valuePtr->bytes && (valuePtr->length == 0)))
|| (((t2Ptr == NULL) && (value2Ptr->bytes == NULL))
|| (value2Ptr->bytes && (value2Ptr->length == 0))))) {
if ((t1Ptr != &tclIntType) && (t1Ptr != &tclDoubleType)) {
s1 = Tcl_GetStringFromObj(valuePtr, &length);
if (TclLooksLikeInt(s1, length)) {
(void) Tcl_GetLongFromObj((Tcl_Interp *) NULL,
valuePtr, &i);
} else {
(void) Tcl_GetDoubleFromObj((Tcl_Interp *) NULL,
valuePtr, &d1);
}
t1Ptr = valuePtr->typePtr;
}
if ((t2Ptr != &tclIntType) && (t2Ptr != &tclDoubleType)) {
s2 = Tcl_GetStringFromObj(value2Ptr, &length);
if (TclLooksLikeInt(s2, length)) {
(void) Tcl_GetLongFromObj((Tcl_Interp *) NULL,
value2Ptr, &i2);
} else {
(void) Tcl_GetDoubleFromObj((Tcl_Interp *) NULL,
value2Ptr, &d2);
}
t2Ptr = value2Ptr->typePtr;
}
}
if (((t1Ptr != &tclIntType) && (t1Ptr != &tclDoubleType))
|| ((t2Ptr != &tclIntType) && (t2Ptr != &tclDoubleType))) {
/*
* One operand is not numeric. Compare as strings.
*/
int cmpValue;
s1 = Tcl_GetString(valuePtr);
s2 = Tcl_GetString(value2Ptr);
cmpValue = strcmp(s1, s2);
switch (*pc) {
case INST_EQ:
iResult = (cmpValue == 0);
break;
case INST_NEQ:
iResult = (cmpValue != 0);
break;
case INST_LT:
iResult = (cmpValue < 0);
break;
case INST_GT:
iResult = (cmpValue > 0);
break;
case INST_LE:
iResult = (cmpValue <= 0);
break;
case INST_GE:
iResult = (cmpValue >= 0);
break;
}
} else if ((t1Ptr == &tclDoubleType)
|| (t2Ptr == &tclDoubleType)) {
/*
* Compare as doubles.
*/
if (t1Ptr == &tclDoubleType) {
d1 = valuePtr->internalRep.doubleValue;
if (t2Ptr == &tclIntType) {
d2 = value2Ptr->internalRep.longValue;
} else {
d2 = value2Ptr->internalRep.doubleValue;
}
} else { /* t1Ptr is int, t2Ptr is double */
d1 = valuePtr->internalRep.longValue;
d2 = value2Ptr->internalRep.doubleValue;
}
switch (*pc) {
case INST_EQ:
iResult = d1 == d2;
break;
case INST_NEQ:
iResult = d1 != d2;
break;
case INST_LT:
iResult = d1 < d2;
break;
case INST_GT:
iResult = d1 > d2;
break;
case INST_LE:
iResult = d1 <= d2;
break;
case INST_GE:
iResult = d1 >= d2;
break;
}
} else {
/*
* Compare as ints.
*/
i = valuePtr->internalRep.longValue;
i2 = value2Ptr->internalRep.longValue;
switch (*pc) {
case INST_EQ:
iResult = i == i2;
break;
case INST_NEQ:
iResult = i != i2;
break;
case INST_LT:
iResult = i < i2;
break;
case INST_GT:
iResult = i > i2;
break;
case INST_LE:
iResult = i <= i2;
break;
case INST_GE:
iResult = i >= i2;
break;
}
}
/*
* Reuse the valuePtr object already on stack if possible.
*/
if (Tcl_IsShared(valuePtr)) {
PUSH_OBJECT(Tcl_NewLongObj(iResult));
TRACE(("%.20s %.20s => %ld\n",
O2S(valuePtr), O2S(value2Ptr), iResult));
TclDecrRefCount(valuePtr);
} else { /* reuse the valuePtr object */
TRACE(("%.20s %.20s => %ld\n",
O2S(valuePtr), O2S(value2Ptr), iResult));
Tcl_SetLongObj(valuePtr, iResult);
++stackTop; /* valuePtr now on stk top has right r.c. */
}
TclDecrRefCount(value2Ptr);
}
ADJUST_PC(1);
case INST_MOD:
case INST_LSHIFT:
case INST_RSHIFT:
case INST_BITOR:
case INST_BITXOR:
case INST_BITAND:
{
/*
* Only integers are allowed. We compute value op value2.
*/
long i2, rem, negative;
long iResult = 0; /* Init. avoids compiler warning. */
value2Ptr = POP_OBJECT();
valuePtr = POP_OBJECT();
if (valuePtr->typePtr == &tclIntType) {
i = valuePtr->internalRep.longValue;
} else { /* try to convert to int */
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
valuePtr, &i);
if (result != TCL_OK) {
TRACE(("%.20s %.20s => ILLEGAL 1st TYPE %s\n",
O2S(valuePtr), O2S(value2Ptr),
(valuePtr->typePtr?
valuePtr->typePtr->name : "null")));
IllegalExprOperandType(interp, pc, valuePtr);
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto checkForCatch;
}
}
if (value2Ptr->typePtr == &tclIntType) {
i2 = value2Ptr->internalRep.longValue;
} else {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
value2Ptr, &i2);
if (result != TCL_OK) {
TRACE(("%.20s %.20s => ILLEGAL 2nd TYPE %s\n",
O2S(valuePtr), O2S(value2Ptr),
(value2Ptr->typePtr?
value2Ptr->typePtr->name : "null")));
IllegalExprOperandType(interp, pc, value2Ptr);
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto checkForCatch;
}
}
switch (*pc) {
case INST_MOD:
/*
* This code is tricky: C doesn't guarantee much about
* the quotient or remainder, but Tcl does. The
* remainder always has the same sign as the divisor and
* a smaller absolute value.
*/
if (i2 == 0) {
TRACE(("%ld %ld => DIVIDE BY ZERO\n", i, i2));
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto divideByZero;
}
negative = 0;
if (i2 < 0) {
i2 = -i2;
i = -i;
negative = 1;
}
rem = i % i2;
if (rem < 0) {
rem += i2;
}
if (negative) {
rem = -rem;
}
iResult = rem;
break;
case INST_LSHIFT:
iResult = i << i2;
break;
case INST_RSHIFT:
/*
* The following code is a bit tricky: it ensures that
* right shifts propagate the sign bit even on machines
* where ">>" won't do it by default.
*/
if (i < 0) {
iResult = ~((~i) >> i2);
} else {
iResult = i >> i2;
}
break;
case INST_BITOR:
iResult = i | i2;
break;
case INST_BITXOR:
iResult = i ^ i2;
break;
case INST_BITAND:
iResult = i & i2;
break;
}
/*
* Reuse the valuePtr object already on stack if possible.
*/
if (Tcl_IsShared(valuePtr)) {
PUSH_OBJECT(Tcl_NewLongObj(iResult));
TRACE(("%ld %ld => %ld\n", i, i2, iResult));
TclDecrRefCount(valuePtr);
} else { /* reuse the valuePtr object */
TRACE(("%ld %ld => %ld\n", i, i2, iResult));
Tcl_SetLongObj(valuePtr, iResult);
++stackTop; /* valuePtr now on stk top has right r.c. */
}
TclDecrRefCount(value2Ptr);
}
ADJUST_PC(1);
case INST_ADD:
case INST_SUB:
case INST_MULT:
case INST_DIV:
{
/*
* Operands must be numeric and ints get converted to floats
* if necessary. We compute value op value2.
*/
Tcl_ObjType *t1Ptr, *t2Ptr;
long i2, quot, rem;
double d1, d2;
long iResult = 0; /* Init. avoids compiler warning. */
double dResult = 0.0; /* Init. avoids compiler warning. */
int doDouble = 0; /* 1 if doing floating arithmetic */
value2Ptr = POP_OBJECT();
valuePtr = POP_OBJECT();
t1Ptr = valuePtr->typePtr;
t2Ptr = value2Ptr->typePtr;
if (t1Ptr == &tclIntType) {
i = valuePtr->internalRep.longValue;
} else if ((t1Ptr == &tclDoubleType)
&& (valuePtr->bytes == NULL)) {
/*
* We can only use the internal rep directly if there is
* no string rep. Otherwise the string rep might actually
* look like an integer, which is preferred.
*/
d1 = valuePtr->internalRep.doubleValue;
} else {
char *s = Tcl_GetStringFromObj(valuePtr, &length);
if (TclLooksLikeInt(s, length)) {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
valuePtr, &i);
} else {
result = Tcl_GetDoubleFromObj((Tcl_Interp *) NULL,
valuePtr, &d1);
}
if (result != TCL_OK) {
TRACE(("%.20s %.20s => ILLEGAL 1st TYPE %s\n",
s, O2S(valuePtr),
(valuePtr->typePtr?
valuePtr->typePtr->name : "null")));
IllegalExprOperandType(interp, pc, valuePtr);
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto checkForCatch;
}
t1Ptr = valuePtr->typePtr;
}
if (t2Ptr == &tclIntType) {
i2 = value2Ptr->internalRep.longValue;
} else if ((t2Ptr == &tclDoubleType)
&& (value2Ptr->bytes == NULL)) {
/*
* We can only use the internal rep directly if there is
* no string rep. Otherwise the string rep might actually
* look like an integer, which is preferred.
*/
d2 = value2Ptr->internalRep.doubleValue;
} else {
char *s = Tcl_GetStringFromObj(value2Ptr, &length);
if (TclLooksLikeInt(s, length)) {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
value2Ptr, &i2);
} else {
result = Tcl_GetDoubleFromObj((Tcl_Interp *) NULL,
value2Ptr, &d2);
}
if (result != TCL_OK) {
TRACE(("%.20s %.20s => ILLEGAL 2nd TYPE %s\n",
O2S(value2Ptr), s,
(value2Ptr->typePtr?
value2Ptr->typePtr->name : "null")));
IllegalExprOperandType(interp, pc, value2Ptr);
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto checkForCatch;
}
t2Ptr = value2Ptr->typePtr;
}
if ((t1Ptr == &tclDoubleType) || (t2Ptr == &tclDoubleType)) {
/*
* Do double arithmetic.
*/
doDouble = 1;
if (t1Ptr == &tclIntType) {
d1 = i; /* promote value 1 to double */
} else if (t2Ptr == &tclIntType) {
d2 = i2; /* promote value 2 to double */
}
switch (*pc) {
case INST_ADD:
dResult = d1 + d2;
break;
case INST_SUB:
dResult = d1 - d2;
break;
case INST_MULT:
dResult = d1 * d2;
break;
case INST_DIV:
if (d2 == 0.0) {
TRACE(("%.6g %.6g => DIVIDE BY ZERO\n", d1, d2));
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto divideByZero;
}
dResult = d1 / d2;
break;
}
/*
* Check now for IEEE floating-point error.
*/
if (IS_NAN(dResult) || IS_INF(dResult)) {
TRACE(("%.20s %.20s => IEEE FLOATING PT ERROR\n",
O2S(valuePtr), O2S(value2Ptr)));
TclExprFloatError(interp, dResult);
result = TCL_ERROR;
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto checkForCatch;
}
} else {
/*
* Do integer arithmetic.
*/
switch (*pc) {
case INST_ADD:
iResult = i + i2;
break;
case INST_SUB:
iResult = i - i2;
break;
case INST_MULT:
iResult = i * i2;
break;
case INST_DIV:
/*
* This code is tricky: C doesn't guarantee much
* about the quotient or remainder, but Tcl does.
* The remainder always has the same sign as the
* divisor and a smaller absolute value.
*/
if (i2 == 0) {
TRACE(("%ld %ld => DIVIDE BY ZERO\n", i, i2));
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
goto divideByZero;
}
if (i2 < 0) {
i2 = -i2;
i = -i;
}
quot = i / i2;
rem = i % i2;
if (rem < 0) {
quot -= 1;
}
iResult = quot;
break;
}
}
/*
* Reuse the valuePtr object already on stack if possible.
*/
if (Tcl_IsShared(valuePtr)) {
if (doDouble) {
PUSH_OBJECT(Tcl_NewDoubleObj(dResult));
TRACE(("%.6g %.6g => %.6g\n", d1, d2, dResult));
} else {
PUSH_OBJECT(Tcl_NewLongObj(iResult));
TRACE(("%ld %ld => %ld\n", i, i2, iResult));
}
TclDecrRefCount(valuePtr);
} else { /* reuse the valuePtr object */
if (doDouble) { /* NB: stack top is off by 1 */
TRACE(("%.6g %.6g => %.6g\n", d1, d2, dResult));
Tcl_SetDoubleObj(valuePtr, dResult);
} else {
TRACE(("%ld %ld => %ld\n", i, i2, iResult));
Tcl_SetLongObj(valuePtr, iResult);
}
++stackTop; /* valuePtr now on stk top has right r.c. */
}
TclDecrRefCount(value2Ptr);
}
ADJUST_PC(1);
case INST_UPLUS:
{
/*
* Operand must be numeric.
*/
double d;
Tcl_ObjType *tPtr;
valuePtr = stackPtr[stackTop];
tPtr = valuePtr->typePtr;
if ((tPtr != &tclIntType) && ((tPtr != &tclDoubleType)
|| (valuePtr->bytes != NULL))) {
char *s = Tcl_GetStringFromObj(valuePtr, &length);
if (TclLooksLikeInt(s, length)) {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
valuePtr, &i);
} else {
result = Tcl_GetDoubleFromObj((Tcl_Interp *) NULL,
valuePtr, &d);
}
if (result != TCL_OK) {
TRACE(("\"%.20s\" => ILLEGAL TYPE %s \n",
s, (tPtr? tPtr->name : "null")));
IllegalExprOperandType(interp, pc, valuePtr);
goto checkForCatch;
}
tPtr = valuePtr->typePtr;
}
/*
* Ensure that the operand's string rep is the same as the
* formatted version of its internal rep. This makes sure
* that "expr +000123" yields "83", not "000123". We
* implement this by _discarding_ the string rep since we
* know it will be regenerated, if needed later, by
* formatting the internal rep's value.
*/
if (Tcl_IsShared(valuePtr)) {
if (tPtr == &tclIntType) {
i = valuePtr->internalRep.longValue;
objPtr = Tcl_NewLongObj(i);
} else {
d = valuePtr->internalRep.doubleValue;
objPtr = Tcl_NewDoubleObj(d);
}
Tcl_IncrRefCount(objPtr);
Tcl_DecrRefCount(valuePtr);
valuePtr = objPtr;
stackPtr[stackTop] = valuePtr;
} else {
Tcl_InvalidateStringRep(valuePtr);
}
TRACE_WITH_OBJ(("%s => ", O2S(valuePtr)), valuePtr);
}
ADJUST_PC(1);
case INST_UMINUS:
case INST_LNOT:
{
/*
* The operand must be numeric. If the operand object is
* unshared modify it directly, otherwise create a copy to
* modify: this is "copy on write". free any old string
* representation since it is now invalid.
*/
double d;
Tcl_ObjType *tPtr;
valuePtr = POP_OBJECT();
tPtr = valuePtr->typePtr;
if ((tPtr != &tclIntType) && ((tPtr != &tclDoubleType)
|| (valuePtr->bytes != NULL))) {
if ((tPtr == &tclBooleanType)
&& (valuePtr->bytes == NULL)) {
valuePtr->typePtr = &tclIntType;
} else {
char *s = Tcl_GetStringFromObj(valuePtr, &length);
if (TclLooksLikeInt(s, length)) {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
valuePtr, &i);
} else {
result = Tcl_GetDoubleFromObj((Tcl_Interp *) NULL,
valuePtr, &d);
}
if (result != TCL_OK) {
TRACE(("\"%.20s\" => ILLEGAL TYPE %s\n",
s, (tPtr? tPtr->name : "null")));
IllegalExprOperandType(interp, pc, valuePtr);
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
}
tPtr = valuePtr->typePtr;
}
if (Tcl_IsShared(valuePtr)) {
/*
* Create a new object.
*/
if (tPtr == &tclIntType) {
i = valuePtr->internalRep.longValue;
objPtr = Tcl_NewLongObj(
(*pc == INST_UMINUS)? -i : !i);
TRACE_WITH_OBJ(("%ld => ", i), objPtr);
} else {
d = valuePtr->internalRep.doubleValue;
if (*pc == INST_UMINUS) {
objPtr = Tcl_NewDoubleObj(-d);
} else {
/*
* Should be able to use "!d", but apparently
* some compilers can't handle it.
*/
objPtr = Tcl_NewLongObj((d==0.0)? 1 : 0);
}
TRACE_WITH_OBJ(("%.6g => ", d), objPtr);
}
PUSH_OBJECT(objPtr);
TclDecrRefCount(valuePtr);
} else {
/*
* valuePtr is unshared. Modify it directly.
*/
if (tPtr == &tclIntType) {
i = valuePtr->internalRep.longValue;
Tcl_SetLongObj(valuePtr,
(*pc == INST_UMINUS)? -i : !i);
TRACE_WITH_OBJ(("%ld => ", i), valuePtr);
} else {
d = valuePtr->internalRep.doubleValue;
if (*pc == INST_UMINUS) {
Tcl_SetDoubleObj(valuePtr, -d);
} else {
/*
* Should be able to use "!d", but apparently
* some compilers can't handle it.
*/
Tcl_SetLongObj(valuePtr, (d==0.0)? 1 : 0);
}
TRACE_WITH_OBJ(("%.6g => ", d), valuePtr);
}
++stackTop; /* valuePtr now on stk top has right r.c. */
}
}
ADJUST_PC(1);
case INST_BITNOT:
{
/*
* The operand must be an integer. If the operand object is
* unshared modify it directly, otherwise modify a copy.
* Free any old string representation since it is now
* invalid.
*/
Tcl_ObjType *tPtr;
valuePtr = POP_OBJECT();
tPtr = valuePtr->typePtr;
if (tPtr != &tclIntType) {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
valuePtr, &i);
if (result != TCL_OK) { /* try to convert to double */
TRACE(("\"%.20s\" => ILLEGAL TYPE %s\n",
O2S(valuePtr), (tPtr? tPtr->name : "null")));
IllegalExprOperandType(interp, pc, valuePtr);
Tcl_DecrRefCount(valuePtr);
goto checkForCatch;
}
}
i = valuePtr->internalRep.longValue;
if (Tcl_IsShared(valuePtr)) {
PUSH_OBJECT(Tcl_NewLongObj(~i));
TRACE(("0x%lx => (%lu)\n", i, ~i));
TclDecrRefCount(valuePtr);
} else {
/*
* valuePtr is unshared. Modify it directly.
*/
Tcl_SetLongObj(valuePtr, ~i);
++stackTop; /* valuePtr now on stk top has right r.c. */
TRACE(("0x%lx => (%lu)\n", i, ~i));
}
}
ADJUST_PC(1);
case INST_CALL_BUILTIN_FUNC1:
opnd = TclGetUInt1AtPtr(pc+1);
{
/*
* Call one of the built-in Tcl math functions.
*/
BuiltinFunc *mathFuncPtr;
if ((opnd < 0) || (opnd > LAST_BUILTIN_FUNC)) {
TRACE(("UNRECOGNIZED BUILTIN FUNC CODE %d\n", opnd));
panic("TclExecuteByteCode: unrecognized builtin function code %d", opnd);
}
mathFuncPtr = &(builtinFuncTable[opnd]);
DECACHE_STACK_INFO();
result = (*mathFuncPtr->proc)(interp, eePtr, mathFuncPtr->clientData);
CACHE_STACK_INFO();
if (result != TCL_OK) {
goto checkForCatch;
}
TRACE_WITH_OBJ(("%d => ", opnd), stackPtr[stackTop]);
}
ADJUST_PC(2);
case INST_CALL_FUNC1:
opnd = TclGetUInt1AtPtr(pc+1);
{
/*
* Call a non-builtin Tcl math function previously
* registered by a call to Tcl_CreateMathFunc.
*/
int objc = opnd; /* Number of arguments. The function name
* is the 0-th argument. */
Tcl_Obj **objv; /* The array of arguments. The function
* name is objv[0]. */
objv = &(stackPtr[stackTop - (objc-1)]); /* "objv[0]" */
DECACHE_STACK_INFO();
result = ExprCallMathFunc(interp, eePtr, objc, objv);
CACHE_STACK_INFO();
if (result != TCL_OK) {
goto checkForCatch;
}
TRACE_WITH_OBJ(("%d => ", objc), stackPtr[stackTop]);
ADJUST_PC(2);
}
case INST_TRY_CVT_TO_NUMERIC:
{
/*
* Try to convert the topmost stack object to an int or
* double object. This is done in order to support Tcl's
* policy of interpreting operands if at all possible as
* first integers, else floating-point numbers.
*/
double d;
char *s;
Tcl_ObjType *tPtr;
int converted, shared;
valuePtr = stackPtr[stackTop];
tPtr = valuePtr->typePtr;
converted = 0;
if ((tPtr != &tclIntType) && ((tPtr != &tclDoubleType)
|| (valuePtr->bytes != NULL))) {
if ((tPtr == &tclBooleanType)
&& (valuePtr->bytes == NULL)) {
valuePtr->typePtr = &tclIntType;
converted = 1;
} else {
s = Tcl_GetStringFromObj(valuePtr, &length);
if (TclLooksLikeInt(s, length)) {
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL,
valuePtr, &i);
} else {
result = Tcl_GetDoubleFromObj((Tcl_Interp *) NULL,
valuePtr, &d);
}
if (result == TCL_OK) {
converted = 1;
}
result = TCL_OK; /* reset the result variable */
}
tPtr = valuePtr->typePtr;
}
/*
* Ensure that the topmost stack object, if numeric, has a
* string rep the same as the formatted version of its
* internal rep. This is used, e.g., to make sure that "expr
* {0001}" yields "1", not "0001". We implement this by
* _discarding_ the string rep since we know it will be
* regenerated, if needed later, by formatting the internal
* rep's value. Also check if there has been an IEEE
* floating point error.
*/
if ((tPtr == &tclIntType) || (tPtr == &tclDoubleType)) {
shared = 0;
if (Tcl_IsShared(valuePtr)) {
shared = 1;
if (valuePtr->bytes != NULL) {
/*
* We only need to make a copy of the object
* when it already had a string rep
*/
if (tPtr == &tclIntType) {
i = valuePtr->internalRep.longValue;
objPtr = Tcl_NewLongObj(i);
} else {
d = valuePtr->internalRep.doubleValue;
objPtr = Tcl_NewDoubleObj(d);
}
Tcl_IncrRefCount(objPtr);
TclDecrRefCount(valuePtr);
valuePtr = objPtr;
stackPtr[stackTop] = valuePtr;
tPtr = valuePtr->typePtr;
}
} else {
Tcl_InvalidateStringRep(valuePtr);
}
if (tPtr == &tclDoubleType) {
d = valuePtr->internalRep.doubleValue;
if (IS_NAN(d) || IS_INF(d)) {
TRACE(("\"%.20s\" => IEEE FLOATING PT ERROR\n",
O2S(valuePtr)));
TclExprFloatError(interp, d);
result = TCL_ERROR;
goto checkForCatch;
}
}
shared = shared; /* lint, shared not used. */
converted = converted; /* lint, converted not used. */
TRACE(("\"%.20s\" => numeric, %s, %s\n", O2S(valuePtr),
(converted? "converted" : "not converted"),
(shared? "shared" : "not shared")));
} else {
TRACE(("\"%.20s\" => not numeric\n", O2S(valuePtr)));
}
}
ADJUST_PC(1);
case INST_BREAK:
/*
* First reset the interpreter's result. Then find the closest
* enclosing loop or catch exception range, if any. If a loop is
* found, terminate its execution. If the closest is a catch
* exception range, jump to its catchOffset. If no enclosing
* range is found, stop execution and return TCL_BREAK.
*/
Tcl_ResetResult(interp);
rangePtr = GetExceptRangeForPc(pc, /*catchOnly*/ 0, codePtr);
if (rangePtr == NULL) {
TRACE(("=> no encl. loop or catch, returning TCL_BREAK\n"));
result = TCL_BREAK;
goto abnormalReturn; /* no catch exists to check */
}
switch (rangePtr->type) {
case LOOP_EXCEPTION_RANGE:
result = TCL_OK;
TRACE(("=> range at %d, new pc %d\n",
rangePtr->codeOffset, rangePtr->breakOffset));
break;
case CATCH_EXCEPTION_RANGE:
result = TCL_BREAK;
TRACE(("=> ...\n"));
goto processCatch; /* it will use rangePtr */
default:
panic("TclExecuteByteCode: unrecognized ExceptionRange type %d\n", rangePtr->type);
}
pc = (codePtr->codeStart + rangePtr->breakOffset);
continue; /* restart outer instruction loop at pc */
case INST_CONTINUE:
/*
* Find the closest enclosing loop or catch exception range,
* if any. If a loop is found, skip to its next iteration.
* If the closest is a catch exception range, jump to its
* catchOffset. If no enclosing range is found, stop
* execution and return TCL_CONTINUE.
*/
Tcl_ResetResult(interp);
rangePtr = GetExceptRangeForPc(pc, /*catchOnly*/ 0, codePtr);
if (rangePtr == NULL) {
TRACE(("=> no encl. loop or catch, returning TCL_CONTINUE\n"));
result = TCL_CONTINUE;
goto abnormalReturn;
}
switch (rangePtr->type) {
case LOOP_EXCEPTION_RANGE:
if (rangePtr->continueOffset == -1) {
TRACE(("=> loop w/o continue, checking for catch\n"));
goto checkForCatch;
} else {
result = TCL_OK;
TRACE(("=> range at %d, new pc %d\n",
rangePtr->codeOffset, rangePtr->continueOffset));
}
break;
case CATCH_EXCEPTION_RANGE:
result = TCL_CONTINUE;
TRACE(("=> ...\n"));
goto processCatch; /* it will use rangePtr */
default:
panic("TclExecuteByteCode: unrecognized ExceptionRange type %d\n", rangePtr->type);
}
pc = (codePtr->codeStart + rangePtr->continueOffset);
continue; /* restart outer instruction loop at pc */
case INST_FOREACH_START4:
opnd = TclGetUInt4AtPtr(pc+1);
{
/*
* Initialize the temporary local var that holds the count
* of the number of iterations of the loop body to -1.
*/
ForeachInfo *infoPtr = (ForeachInfo *)
codePtr->auxDataArrayPtr[opnd].clientData;
int iterTmpIndex = infoPtr->loopCtTemp;
Var *compiledLocals = iPtr->varFramePtr->compiledLocals;
Var *iterVarPtr = &(compiledLocals[iterTmpIndex]);
Tcl_Obj *oldValuePtr = iterVarPtr->value.objPtr;
if (oldValuePtr == NULL) {
iterVarPtr->value.objPtr = Tcl_NewLongObj(-1);
Tcl_IncrRefCount(iterVarPtr->value.objPtr);
} else {
Tcl_SetLongObj(oldValuePtr, -1);
}
TclSetVarScalar(iterVarPtr);
TclClearVarUndefined(iterVarPtr);
TRACE(("%u => loop iter count temp %d\n",
opnd, iterTmpIndex));
}
ADJUST_PC(5);
case INST_FOREACH_STEP4:
opnd = TclGetUInt4AtPtr(pc+1);
{
/*
* "Step" a foreach loop (i.e., begin its next iteration) by
* assigning the next value list element to each loop var.
*/
ForeachInfo *infoPtr = (ForeachInfo *)
codePtr->auxDataArrayPtr[opnd].clientData;
ForeachVarList *varListPtr;
int numLists = infoPtr->numLists;
Var *compiledLocals = iPtr->varFramePtr->compiledLocals;
Tcl_Obj *listPtr;
List *listRepPtr;
Var *iterVarPtr, *listVarPtr;
int iterNum, listTmpIndex, listLen, numVars;
int varIndex, valIndex, continueLoop, j;
/*
* Increment the temp holding the loop iteration number.
*/
iterVarPtr = &(compiledLocals[infoPtr->loopCtTemp]);
valuePtr = iterVarPtr->value.objPtr;
iterNum = (valuePtr->internalRep.longValue + 1);
Tcl_SetLongObj(valuePtr, iterNum);
/*
* Check whether all value lists are exhausted and we should
* stop the loop.
*/
continueLoop = 0;
listTmpIndex = infoPtr->firstValueTemp;
for (i = 0; i < numLists; i++) {
varListPtr = infoPtr->varLists[i];
numVars = varListPtr->numVars;
listVarPtr = &(compiledLocals[listTmpIndex]);
listPtr = listVarPtr->value.objPtr;
result = Tcl_ListObjLength(interp, listPtr, &listLen);
if (result != TCL_OK) {
TRACE_WITH_OBJ(("%u => ERROR converting list %ld, \"%s\": ",
opnd, i, O2S(listPtr)),
Tcl_GetObjResult(interp));
goto checkForCatch;
}
if (listLen > (iterNum * numVars)) {
continueLoop = 1;
}
listTmpIndex++;
}
/*
* If some var in some var list still has a remaining list
* element iterate one more time. Assign to var the next
* element from its value list. We already checked above
* that each list temp holds a valid list object.
*/
if (continueLoop) {
listTmpIndex = infoPtr->firstValueTemp;
for (i = 0; i < numLists; i++) {
varListPtr = infoPtr->varLists[i];
numVars = varListPtr->numVars;
listVarPtr = &(compiledLocals[listTmpIndex]);
listPtr = listVarPtr->value.objPtr;
listRepPtr = (List *) listPtr->internalRep.otherValuePtr;
listLen = listRepPtr->elemCount;
valIndex = (iterNum * numVars);
for (j = 0; j < numVars; j++) {
int setEmptyStr = 0;
if (valIndex >= listLen) {
setEmptyStr = 1;
valuePtr = Tcl_NewObj();
} else {
valuePtr = listRepPtr->elements[valIndex];
}
varIndex = varListPtr->varIndexes[j];
DECACHE_STACK_INFO();
value2Ptr = TclSetIndexedScalar(interp,
varIndex, valuePtr, /*leaveErrorMsg*/ 1);
CACHE_STACK_INFO();
if (value2Ptr == NULL) {
TRACE_WITH_OBJ(("%u => ERROR init. index temp %d: ",
opnd, varIndex),
Tcl_GetObjResult(interp));
if (setEmptyStr) {
Tcl_DecrRefCount(valuePtr);
}
result = TCL_ERROR;
goto checkForCatch;
}
valIndex++;
}
listTmpIndex++;
}
}
/*
* Push 1 if at least one value list had a remaining element
* and the loop should continue. Otherwise push 0.
*/
PUSH_OBJECT(Tcl_NewLongObj(continueLoop));
TRACE(("%u => %d lists, iter %d, %s loop\n",
opnd, numLists, iterNum,
(continueLoop? "continue" : "exit")));
}
ADJUST_PC(5);
case INST_BEGIN_CATCH4:
/*
* Record start of the catch command with exception range index
* equal to the operand. Push the current stack depth onto the
* special catch stack.
*/
catchStackPtr[++catchTop] = stackTop;
TRACE(("%u => catchTop=%d, stackTop=%d\n",
TclGetUInt4AtPtr(pc+1), catchTop, stackTop));
ADJUST_PC(5);
case INST_END_CATCH:
catchTop--;
result = TCL_OK;
TRACE(("=> catchTop=%d\n", catchTop));
ADJUST_PC(1);
case INST_PUSH_RESULT:
PUSH_OBJECT(Tcl_GetObjResult(interp));
TRACE_WITH_OBJ(("=> "), Tcl_GetObjResult(interp));
ADJUST_PC(1);
case INST_PUSH_RETURN_CODE:
PUSH_OBJECT(Tcl_NewLongObj(result));
TRACE(("=> %u\n", result));
ADJUST_PC(1);
default:
panic("TclExecuteByteCode: unrecognized opCode %u", *pc);
} /* end of switch on opCode */
/*
* Division by zero in an expression. Control only reaches this
* point by "goto divideByZero".
*/
divideByZero:
Tcl_ResetResult(interp);
Tcl_AppendToObj(Tcl_GetObjResult(interp), "divide by zero", -1);
Tcl_SetErrorCode(interp, "ARITH", "DIVZERO", "divide by zero",
(char *) NULL);
result = TCL_ERROR;
/*
* Execution has generated an "exception" such as TCL_ERROR. If the
* exception is an error, record information about what was being
* executed when the error occurred. Find the closest enclosing
* catch range, if any. If no enclosing catch range is found, stop
* execution and return the "exception" code.
*/
checkForCatch:
if ((result == TCL_ERROR) && !(iPtr->flags & ERR_ALREADY_LOGGED)) {
bytes = GetSrcInfoForPc(pc, codePtr, &length);
if (bytes != NULL) {
Tcl_LogCommandInfo(interp, codePtr->source, bytes, length);
iPtr->flags |= ERR_ALREADY_LOGGED;
}
}
rangePtr = GetExceptRangeForPc(pc, /*catchOnly*/ 1, codePtr);
if (rangePtr == NULL) {
#ifdef TCL_COMPILE_DEBUG
if (traceInstructions) {
fprintf(stdout, " ... no enclosing catch, returning %s\n",
StringForResultCode(result));
}
#endif
goto abnormalReturn;
}
/*
* A catch exception range (rangePtr) was found to handle an
* "exception". It was found either by checkForCatch just above or
* by an instruction during break, continue, or error processing.
* Jump to its catchOffset after unwinding the operand stack to
* the depth it had when starting to execute the range's catch
* command.
*/
processCatch:
while (stackTop > catchStackPtr[catchTop]) {
valuePtr = POP_OBJECT();
TclDecrRefCount(valuePtr);
}
#ifdef TCL_COMPILE_DEBUG
if (traceInstructions) {
fprintf(stdout, " ... found catch at %d, catchTop=%d, unwound to %d, new pc %u\n",
rangePtr->codeOffset, catchTop, catchStackPtr[catchTop],
(unsigned int)(rangePtr->catchOffset));
}
#endif
pc = (codePtr->codeStart + rangePtr->catchOffset);
continue; /* restart the execution loop at pc */
} /* end of infinite loop dispatching on instructions */
/*
* Abnormal return code. Restore the stack to state it had when starting
* to execute the ByteCode.
*/
abnormalReturn:
while (stackTop > initStackTop) {
valuePtr = POP_OBJECT();
Tcl_DecrRefCount(valuePtr);
}
/*
* Free the catch stack array if malloc'ed storage was used.
*/
done:
if (catchStackPtr != catchStackStorage) {
ckfree((char *) catchStackPtr);
}
eePtr->stackTop = initStackTop;
return result;
#undef STATIC_CATCH_STACK_SIZE
}
#ifdef TCL_COMPILE_DEBUG
/*
*----------------------------------------------------------------------
*
* PrintByteCodeInfo --
*
* This procedure prints a summary about a bytecode object to stdout.
* It is called by TclExecuteByteCode when starting to execute the
* bytecode object if tclTraceExec has the value 2 or more.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
PrintByteCodeInfo(codePtr)
register ByteCode *codePtr; /* The bytecode whose summary is printed
* to stdout. */
{
Proc *procPtr = codePtr->procPtr;
Interp *iPtr = (Interp *) *codePtr->interpHandle;
fprintf(stdout, "\nExecuting ByteCode 0x%x, refCt %u, epoch %u, interp 0x%x (epoch %u)\n",
(unsigned int) codePtr, codePtr->refCount,
codePtr->compileEpoch, (unsigned int) iPtr,
iPtr->compileEpoch);
fprintf(stdout, " Source: ");
TclPrintSource(stdout, codePtr->source, 60);
fprintf(stdout, "\n Cmds %d, src %d, inst %u, litObjs %u, aux %d, stkDepth %u, code/src %.2f\n",
codePtr->numCommands, codePtr->numSrcBytes,
codePtr->numCodeBytes, codePtr->numLitObjects,
codePtr->numAuxDataItems, codePtr->maxStackDepth,
#ifdef TCL_COMPILE_STATS
(codePtr->numSrcBytes?
((float)codePtr->structureSize)/((float)codePtr->numSrcBytes) : 0.0));
#else
0.0);
#endif
#ifdef TCL_COMPILE_STATS
fprintf(stdout, " Code %d = header %d+inst %d+litObj %d+exc %d+aux %d+cmdMap %d\n",
codePtr->structureSize,
(sizeof(ByteCode) - (sizeof(size_t) + sizeof(Tcl_Time))),
codePtr->numCodeBytes,
(codePtr->numLitObjects * sizeof(Tcl_Obj *)),
(codePtr->numExceptRanges * sizeof(ExceptionRange)),
(codePtr->numAuxDataItems * sizeof(AuxData)),
codePtr->numCmdLocBytes);
#endif /* TCL_COMPILE_STATS */
if (procPtr != NULL) {
fprintf(stdout,
" Proc 0x%x, refCt %d, args %d, compiled locals %d\n",
(unsigned int) procPtr, procPtr->refCount,
procPtr->numArgs, procPtr->numCompiledLocals);
}
}
#endif /* TCL_COMPILE_DEBUG */
/*
*----------------------------------------------------------------------
*
* ValidatePcAndStackTop --
*
* This procedure is called by TclExecuteByteCode when debugging to
* verify that the program counter and stack top are valid during
* execution.
*
* Results:
* None.
*
* Side effects:
* Prints a message to stderr and panics if either the pc or stack
* top are invalid.
*
*----------------------------------------------------------------------
*/
#ifdef TCL_COMPILE_DEBUG
static void
ValidatePcAndStackTop(codePtr, pc, stackTop, stackLowerBound,
stackUpperBound)
register ByteCode *codePtr; /* The bytecode whose summary is printed
* to stdout. */
unsigned char *pc; /* Points to first byte of a bytecode
* instruction. The program counter. */
int stackTop; /* Current stack top. Must be between
* stackLowerBound and stackUpperBound
* (inclusive). */
int stackLowerBound; /* Smallest legal value for stackTop. */
int stackUpperBound; /* Greatest legal value for stackTop. */
{
unsigned int relativePc = (unsigned int) (pc - codePtr->codeStart);
unsigned int codeStart = (unsigned int) codePtr->codeStart;
unsigned int codeEnd = (unsigned int)
(codePtr->codeStart + codePtr->numCodeBytes);
unsigned char opCode = *pc;
if (((unsigned int) pc < codeStart) || ((unsigned int) pc > codeEnd)) {
fprintf(stderr, "\nBad instruction pc 0x%x in TclExecuteByteCode\n",
(unsigned int) pc);
panic("TclExecuteByteCode execution failure: bad pc");
}
if ((unsigned int) opCode > LAST_INST_OPCODE) {
fprintf(stderr, "\nBad opcode %d at pc %u in TclExecuteByteCode\n",
(unsigned int) opCode, relativePc);
panic("TclExecuteByteCode execution failure: bad opcode");
}
if ((stackTop < stackLowerBound) || (stackTop > stackUpperBound)) {
int numChars;
char *cmd = GetSrcInfoForPc(pc, codePtr, &numChars);
char *ellipsis = "";
fprintf(stderr, "\nBad stack top %d at pc %u in TclExecuteByteCode",
stackTop, relativePc);
if (cmd != NULL) {
if (numChars > 100) {
numChars = 100;
ellipsis = "...";
}
fprintf(stderr, "\n executing %.*s%s\n", numChars, cmd,
ellipsis);
} else {
fprintf(stderr, "\n");
}
panic("TclExecuteByteCode execution failure: bad stack top");
}
}
#endif /* TCL_COMPILE_DEBUG */
/*
*----------------------------------------------------------------------
*
* IllegalExprOperandType --
*
* Used by TclExecuteByteCode to add an error message to errorInfo
* when an illegal operand type is detected by an expression
* instruction. The argument opndPtr holds the operand object in error.
*
* Results:
* None.
*
* Side effects:
* An error message is appended to errorInfo.
*
*----------------------------------------------------------------------
*/
static void
IllegalExprOperandType(interp, pc, opndPtr)
Tcl_Interp *interp; /* Interpreter to which error information
* pertains. */
unsigned char *pc; /* Points to the instruction being executed
* when the illegal type was found. */
Tcl_Obj *opndPtr; /* Points to the operand holding the value
* with the illegal type. */
{
unsigned char opCode = *pc;
Tcl_ResetResult(interp);
if ((opndPtr->bytes == NULL) || (opndPtr->length == 0)) {
Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
"can't use empty string as operand of \"",
operatorStrings[opCode - INST_LOR], "\"", (char *) NULL);
} else {
char *msg = "non-numeric string";
if (opndPtr->typePtr != &tclDoubleType) {
/*
* See if the operand can be interpreted as a double in order to
* improve the error message.
*/
char *s = Tcl_GetString(opndPtr);
double d;
if (Tcl_GetDouble((Tcl_Interp *) NULL, s, &d) == TCL_OK) {
/*
* Make sure that what appears to be a double
* (ie 08) isn't really a bad octal
*/
if (TclCheckBadOctal(NULL, Tcl_GetString(opndPtr))) {
msg = "invalid octal number";
} else {
msg = "floating-point value";
}
}
}
Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "can't use ",
msg, " as operand of \"", operatorStrings[opCode - INST_LOR],
"\"", (char *) NULL);
}
}
/*
*----------------------------------------------------------------------
*
* CallTraceProcedure --
*
* Invokes a trace procedure registered with an interpreter. These
* procedures trace command execution. Currently this trace procedure
* is called with the address of the string-based Tcl_CmdProc for the
* command, not the Tcl_ObjCmdProc.
*
* Results:
* None.
*
* Side effects:
* Those side effects made by the trace procedure.
*
*----------------------------------------------------------------------
*/
static void
CallTraceProcedure(interp, tracePtr, cmdPtr, command, numChars, objc, objv)
Tcl_Interp *interp; /* The current interpreter. */
register Trace *tracePtr; /* Describes the trace procedure to call. */
Command *cmdPtr; /* Points to command's Command struct. */
char *command; /* Points to the first character of the
* command's source before substitutions. */
int numChars; /* The number of characters in the
* command's source. */
register int objc; /* Number of arguments for the command. */
Tcl_Obj *objv[]; /* Pointers to Tcl_Obj of each argument. */
{
Interp *iPtr = (Interp *) interp;
register char **argv;
register int i;
int length;
char *p;
/*
* Get the string rep from the objv argument objects and place their
* pointers in argv. First make sure argv is large enough to hold the
* objc args plus 1 extra word for the zero end-of-argv word.
*/
argv = (char **) ckalloc((unsigned)(objc + 1) * sizeof(char *));
for (i = 0; i < objc; i++) {
argv[i] = Tcl_GetStringFromObj(objv[i], &length);
}
argv[objc] = 0;
/*
* Copy the command characters into a new string.
*/
p = (char *) ckalloc((unsigned) (numChars + 1));
memcpy((VOID *) p, (VOID *) command, (size_t) numChars);
p[numChars] = '\0';
/*
* Call the trace procedure then free allocated storage.
*/
(*tracePtr->proc)(tracePtr->clientData, interp, iPtr->numLevels,
p, cmdPtr->proc, cmdPtr->clientData, objc, argv);
ckfree((char *) argv);
ckfree((char *) p);
}
/*
*----------------------------------------------------------------------
*
* GetSrcInfoForPc --
*
* Given a program counter value, finds the closest command in the
* bytecode code unit's CmdLocation array and returns information about
* that command's source: a pointer to its first byte and the number of
* characters.
*
* Results:
* If a command is found that encloses the program counter value, a
* pointer to the command's source is returned and the length of the
* source is stored at *lengthPtr. If multiple commands resulted in
* code at pc, information about the closest enclosing command is
* returned. If no matching command is found, NULL is returned and
* *lengthPtr is unchanged.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static char *
GetSrcInfoForPc(pc, codePtr, lengthPtr)
unsigned char *pc; /* The program counter value for which to
* return the closest command's source info.
* This points to a bytecode instruction
* in codePtr's code. */
ByteCode *codePtr; /* The bytecode sequence in which to look
* up the command source for the pc. */
int *lengthPtr; /* If non-NULL, the location where the
* length of the command's source should be
* stored. If NULL, no length is stored. */
{
register int pcOffset = (pc - codePtr->codeStart);
int numCmds = codePtr->numCommands;
unsigned char *codeDeltaNext, *codeLengthNext;
unsigned char *srcDeltaNext, *srcLengthNext;
int codeOffset, codeLen, codeEnd, srcOffset, srcLen, delta, i;
int bestDist = INT_MAX; /* Distance of pc to best cmd's start pc. */
int bestSrcOffset = -1; /* Initialized to avoid compiler warning. */
int bestSrcLength = -1; /* Initialized to avoid compiler warning. */
if ((pcOffset < 0) || (pcOffset >= codePtr->numCodeBytes)) {
return NULL;
}
/*
* Decode the code and source offset and length for each command. The
* closest enclosing command is the last one whose code started before
* pcOffset.
*/
codeDeltaNext = codePtr->codeDeltaStart;
codeLengthNext = codePtr->codeLengthStart;
srcDeltaNext = codePtr->srcDeltaStart;
srcLengthNext = codePtr->srcLengthStart;
codeOffset = srcOffset = 0;
for (i = 0; i < numCmds; i++) {
if ((unsigned int) (*codeDeltaNext) == (unsigned int) 0xFF) {
codeDeltaNext++;
delta = TclGetInt4AtPtr(codeDeltaNext);
codeDeltaNext += 4;
} else {
delta = TclGetInt1AtPtr(codeDeltaNext);
codeDeltaNext++;
}
codeOffset += delta;
if ((unsigned int) (*codeLengthNext) == (unsigned int) 0xFF) {
codeLengthNext++;
codeLen = TclGetInt4AtPtr(codeLengthNext);
codeLengthNext += 4;
} else {
codeLen = TclGetInt1AtPtr(codeLengthNext);
codeLengthNext++;
}
codeEnd = (codeOffset + codeLen - 1);
if ((unsigned int) (*srcDeltaNext) == (unsigned int) 0xFF) {
srcDeltaNext++;
delta = TclGetInt4AtPtr(srcDeltaNext);
srcDeltaNext += 4;
} else {
delta = TclGetInt1AtPtr(srcDeltaNext);
srcDeltaNext++;
}
srcOffset += delta;
if ((unsigned int) (*srcLengthNext) == (unsigned int) 0xFF) {
srcLengthNext++;
srcLen = TclGetInt4AtPtr(srcLengthNext);
srcLengthNext += 4;
} else {
srcLen = TclGetInt1AtPtr(srcLengthNext);
srcLengthNext++;
}
if (codeOffset > pcOffset) { /* best cmd already found */
break;
} else if (pcOffset <= codeEnd) { /* this cmd's code encloses pc */
int dist = (pcOffset - codeOffset);
if (dist <= bestDist) {
bestDist = dist;
bestSrcOffset = srcOffset;
bestSrcLength = srcLen;
}
}
}
if (bestDist == INT_MAX) {
return NULL;
}
if (lengthPtr != NULL) {
*lengthPtr = bestSrcLength;
}
return (codePtr->source + bestSrcOffset);
}
/*
*----------------------------------------------------------------------
*
* GetExceptRangeForPc --
*
* Given a program counter value, return the closest enclosing
* ExceptionRange.
*
* Results:
* In the normal case, catchOnly is 0 (false) and this procedure
* returns a pointer to the most closely enclosing ExceptionRange
* structure regardless of whether it is a loop or catch exception
* range. This is appropriate when processing a TCL_BREAK or
* TCL_CONTINUE, which will be "handled" either by a loop exception
* range or a closer catch range. If catchOnly is nonzero, this
* procedure ignores loop exception ranges and returns a pointer to the
* closest catch range. If no matching ExceptionRange is found that
* encloses pc, a NULL is returned.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static ExceptionRange *
GetExceptRangeForPc(pc, catchOnly, codePtr)
unsigned char *pc; /* The program counter value for which to
* search for a closest enclosing exception
* range. This points to a bytecode
* instruction in codePtr's code. */
int catchOnly; /* If 0, consider either loop or catch
* ExceptionRanges in search. If nonzero
* consider only catch ranges (and ignore
* any closer loop ranges). */
ByteCode* codePtr; /* Points to the ByteCode in which to search
* for the enclosing ExceptionRange. */
{
ExceptionRange *rangeArrayPtr;
int numRanges = codePtr->numExceptRanges;
register ExceptionRange *rangePtr;
int pcOffset = (pc - codePtr->codeStart);
register int i, level;
if (numRanges == 0) {
return NULL;
}
rangeArrayPtr = codePtr->exceptArrayPtr;
for (level = codePtr->maxExceptDepth; level >= 0; level--) {
for (i = 0; i < numRanges; i++) {
rangePtr = &(rangeArrayPtr[i]);
if (rangePtr->nestingLevel == level) {
int start = rangePtr->codeOffset;
int end = (start + rangePtr->numCodeBytes);
if ((start <= pcOffset) && (pcOffset < end)) {
if ((!catchOnly)
|| (rangePtr->type == CATCH_EXCEPTION_RANGE)) {
return rangePtr;
}
}
}
}
}
return NULL;
}
/*
*----------------------------------------------------------------------
*
* GetOpcodeName --
*
* This procedure is called by the TRACE and TRACE_WITH_OBJ macros
* used in TclExecuteByteCode when debugging. It returns the name of
* the bytecode instruction at a specified instruction pc.
*
* Results:
* A character string for the instruction.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
#ifdef TCL_COMPILE_DEBUG
static char *
GetOpcodeName(pc)
unsigned char *pc; /* Points to the instruction whose name
* should be returned. */
{
unsigned char opCode = *pc;
return instructionTable[opCode].name;
}
#endif /* TCL_COMPILE_DEBUG */
/*
*----------------------------------------------------------------------
*
* VerifyExprObjType --
*
* This procedure is called by the math functions to verify that
* the object is either an int or double, coercing it if necessary.
* If an error occurs during conversion, an error message is left
* in the interpreter's result unless "interp" is NULL.
*
* Results:
* TCL_OK if it was int or double, TCL_ERROR otherwise
*
* Side effects:
* objPtr is ensured to be either tclIntType of tclDoubleType.
*
*----------------------------------------------------------------------
*/
static int
VerifyExprObjType(interp, objPtr)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
Tcl_Obj *objPtr; /* Points to the object to type check. */
{
if ((objPtr->typePtr == &tclIntType) ||
(objPtr->typePtr == &tclDoubleType)) {
return TCL_OK;
} else {
int length, result = TCL_OK;
char *s = Tcl_GetStringFromObj(objPtr, &length);
if (TclLooksLikeInt(s, length)) {
long i;
result = Tcl_GetLongFromObj((Tcl_Interp *) NULL, objPtr, &i);
} else {
double d;
result = Tcl_GetDoubleFromObj((Tcl_Interp *) NULL, objPtr, &d);
}
if ((result != TCL_OK) && (interp != NULL)) {
Tcl_ResetResult(interp);
if (TclCheckBadOctal((Tcl_Interp *) NULL, s)) {
Tcl_AppendToObj(Tcl_GetObjResult(interp),
"argument to math function was an invalid octal number",
-1);
} else {
Tcl_AppendToObj(Tcl_GetObjResult(interp),
"argument to math function didn't have numeric value",
-1);
}
}
return result;
}
}
/*
*----------------------------------------------------------------------
*
* Math Functions --
*
* This page contains the procedures that implement all of the
* built-in math functions for expressions.
*
* Results:
* Each procedure returns TCL_OK if it succeeds and pushes an
* Tcl object holding the result. If it fails it returns TCL_ERROR
* and leaves an error message in the interpreter's result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ExprUnaryFunc(interp, eePtr, clientData)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
ClientData clientData; /* Contains the address of a procedure that
* takes one double argument and returns a
* double result. */
{
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
register Tcl_Obj *valuePtr;
double d, dResult;
int result;
double (*func) _ANSI_ARGS_((double)) =
(double (*)_ANSI_ARGS_((double))) clientData;
/*
* Set stackPtr and stackTop from eePtr.
*/
result = TCL_OK;
CACHE_STACK_INFO();
/*
* Pop the function's argument from the evaluation stack. Convert it
* to a double if necessary.
*/
valuePtr = POP_OBJECT();
if (VerifyExprObjType(interp, valuePtr) != TCL_OK) {
result = TCL_ERROR;
goto done;
}
if (valuePtr->typePtr == &tclIntType) {
d = (double) valuePtr->internalRep.longValue;
} else {
d = valuePtr->internalRep.doubleValue;
}
errno = 0;
dResult = (*func)(d);
if ((errno != 0) || IS_NAN(dResult) || IS_INF(dResult)) {
TclExprFloatError(interp, dResult);
result = TCL_ERROR;
goto done;
}
/*
* Push a Tcl object holding the result.
*/
PUSH_OBJECT(Tcl_NewDoubleObj(dResult));
/*
* Reflect the change to stackTop back in eePtr.
*/
done:
Tcl_DecrRefCount(valuePtr);
DECACHE_STACK_INFO();
return result;
}
static int
ExprBinaryFunc(interp, eePtr, clientData)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
ClientData clientData; /* Contains the address of a procedure that
* takes two double arguments and
* returns a double result. */
{
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
register Tcl_Obj *valuePtr, *value2Ptr;
double d1, d2, dResult;
int result;
double (*func) _ANSI_ARGS_((double, double))
= (double (*)_ANSI_ARGS_((double, double))) clientData;
/*
* Set stackPtr and stackTop from eePtr.
*/
result = TCL_OK;
CACHE_STACK_INFO();
/*
* Pop the function's two arguments from the evaluation stack. Convert
* them to doubles if necessary.
*/
value2Ptr = POP_OBJECT();
valuePtr = POP_OBJECT();
if ((VerifyExprObjType(interp, valuePtr) != TCL_OK) ||
(VerifyExprObjType(interp, value2Ptr) != TCL_OK)) {
result = TCL_ERROR;
goto done;
}
if (valuePtr->typePtr == &tclIntType) {
d1 = (double) valuePtr->internalRep.longValue;
} else {
d1 = valuePtr->internalRep.doubleValue;
}
if (value2Ptr->typePtr == &tclIntType) {
d2 = (double) value2Ptr->internalRep.longValue;
} else {
d2 = value2Ptr->internalRep.doubleValue;
}
errno = 0;
dResult = (*func)(d1, d2);
if ((errno != 0) || IS_NAN(dResult) || IS_INF(dResult)) {
TclExprFloatError(interp, dResult);
result = TCL_ERROR;
goto done;
}
/*
* Push a Tcl object holding the result.
*/
PUSH_OBJECT(Tcl_NewDoubleObj(dResult));
/*
* Reflect the change to stackTop back in eePtr.
*/
done:
Tcl_DecrRefCount(valuePtr);
Tcl_DecrRefCount(value2Ptr);
DECACHE_STACK_INFO();
return result;
}
static int
ExprAbsFunc(interp, eePtr, clientData)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
ClientData clientData; /* Ignored. */
{
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
register Tcl_Obj *valuePtr;
long i, iResult;
double d, dResult;
int result;
/*
* Set stackPtr and stackTop from eePtr.
*/
result = TCL_OK;
CACHE_STACK_INFO();
/*
* Pop the argument from the evaluation stack.
*/
valuePtr = POP_OBJECT();
if (VerifyExprObjType(interp, valuePtr) != TCL_OK) {
result = TCL_ERROR;
goto done;
}
/*
* Push a Tcl object with the result.
*/
if (valuePtr->typePtr == &tclIntType) {
i = valuePtr->internalRep.longValue;
if (i < 0) {
iResult = -i;
if (iResult < 0) {
Tcl_ResetResult(interp);
Tcl_AppendToObj(Tcl_GetObjResult(interp),
"integer value too large to represent", -1);
Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW",
"integer value too large to represent", (char *) NULL);
result = TCL_ERROR;
goto done;
}
} else {
iResult = i;
}
PUSH_OBJECT(Tcl_NewLongObj(iResult));
} else {
d = valuePtr->internalRep.doubleValue;
if (d < 0.0) {
dResult = -d;
} else {
dResult = d;
}
if (IS_NAN(dResult) || IS_INF(dResult)) {
TclExprFloatError(interp, dResult);
result = TCL_ERROR;
goto done;
}
PUSH_OBJECT(Tcl_NewDoubleObj(dResult));
}
/*
* Reflect the change to stackTop back in eePtr.
*/
done:
Tcl_DecrRefCount(valuePtr);
DECACHE_STACK_INFO();
return result;
}
static int
ExprDoubleFunc(interp, eePtr, clientData)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
ClientData clientData; /* Ignored. */
{
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
register Tcl_Obj *valuePtr;
double dResult;
int result;
/*
* Set stackPtr and stackTop from eePtr.
*/
result = TCL_OK;
CACHE_STACK_INFO();
/*
* Pop the argument from the evaluation stack.
*/
valuePtr = POP_OBJECT();
if (VerifyExprObjType(interp, valuePtr) != TCL_OK) {
result = TCL_ERROR;
goto done;
}
if (valuePtr->typePtr == &tclIntType) {
dResult = (double) valuePtr->internalRep.longValue;
} else {
dResult = valuePtr->internalRep.doubleValue;
}
/*
* Push a Tcl object with the result.
*/
PUSH_OBJECT(Tcl_NewDoubleObj(dResult));
/*
* Reflect the change to stackTop back in eePtr.
*/
done:
Tcl_DecrRefCount(valuePtr);
DECACHE_STACK_INFO();
return result;
}
static int
ExprIntFunc(interp, eePtr, clientData)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
ClientData clientData; /* Ignored. */
{
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
register Tcl_Obj *valuePtr;
long iResult;
double d;
int result;
/*
* Set stackPtr and stackTop from eePtr.
*/
result = TCL_OK;
CACHE_STACK_INFO();
/*
* Pop the argument from the evaluation stack.
*/
valuePtr = POP_OBJECT();
if (VerifyExprObjType(interp, valuePtr) != TCL_OK) {
result = TCL_ERROR;
goto done;
}
if (valuePtr->typePtr == &tclIntType) {
iResult = valuePtr->internalRep.longValue;
} else {
d = valuePtr->internalRep.doubleValue;
if (d < 0.0) {
if (d < (double) (long) LONG_MIN) {
tooLarge:
Tcl_ResetResult(interp);
Tcl_AppendToObj(Tcl_GetObjResult(interp),
"integer value too large to represent", -1);
Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW",
"integer value too large to represent", (char *) NULL);
result = TCL_ERROR;
goto done;
}
} else {
if (d > (double) LONG_MAX) {
goto tooLarge;
}
}
if (IS_NAN(d) || IS_INF(d)) {
TclExprFloatError(interp, d);
result = TCL_ERROR;
goto done;
}
iResult = (long) d;
}
/*
* Push a Tcl object with the result.
*/
PUSH_OBJECT(Tcl_NewLongObj(iResult));
/*
* Reflect the change to stackTop back in eePtr.
*/
done:
Tcl_DecrRefCount(valuePtr);
DECACHE_STACK_INFO();
return result;
}
static int
ExprRandFunc(interp, eePtr, clientData)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
ClientData clientData; /* Ignored. */
{
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
Interp *iPtr = (Interp *) interp;
double dResult;
int tmp;
if (!(iPtr->flags & RAND_SEED_INITIALIZED)) {
iPtr->flags |= RAND_SEED_INITIALIZED;
// FIXME FLOH
// iPtr->randSeed = TclpGetClicks();
iPtr->randSeed = 123459876;
}
/*
* Set stackPtr and stackTop from eePtr.
*/
CACHE_STACK_INFO();
/*
* Generate the random number using the linear congruential
* generator defined by the following recurrence:
* seed = (IA * seed) mod IM
* where IA is 16807 and IM is (2^31) - 1. In order to avoid
* potential problems with integer overflow, the code uses
* additional constants IQ and IR such that
* IM = IA*IQ + IR
* For details on how this algorithm works, refer to the following
* papers:
*
* S.K. Park & K.W. Miller, "Random number generators: good ones
* are hard to find," Comm ACM 31(10):1192-1201, Oct 1988
*
* W.H. Press & S.A. Teukolsky, "Portable random number
* generators," Computers in Physics 6(5):522-524, Sep/Oct 1992.
*/
#define RAND_IA 16807
#define RAND_IM 2147483647
#define RAND_IQ 127773
#define RAND_IR 2836
#define RAND_MASK 123459876
if (iPtr->randSeed == 0) {
/*
* Don't allow a 0 seed, since it breaks the generator. Shift
* it to some other value.
*/
iPtr->randSeed = 123459876;
}
tmp = iPtr->randSeed/RAND_IQ;
iPtr->randSeed = RAND_IA*(iPtr->randSeed - tmp*RAND_IQ) - RAND_IR*tmp;
if (iPtr->randSeed < 0) {
iPtr->randSeed += RAND_IM;
}
/*
* On 64-bit architectures we need to mask off the upper bits to
* ensure we only have a 32-bit range. The constant has the
* bizarre form below in order to make sure that it doesn't
* get sign-extended (the rules for sign extension are very
* concat, particularly on 64-bit machines).
*/
iPtr->randSeed &= ((((unsigned long) 0xfffffff) << 4) | 0xf);
dResult = iPtr->randSeed * (1.0/RAND_IM);
/*
* Push a Tcl object with the result.
*/
PUSH_OBJECT(Tcl_NewDoubleObj(dResult));
/*
* Reflect the change to stackTop back in eePtr.
*/
DECACHE_STACK_INFO();
return TCL_OK;
}
static int
ExprRoundFunc(interp, eePtr, clientData)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
ClientData clientData; /* Ignored. */
{
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
Tcl_Obj *valuePtr;
long iResult;
double d, temp;
int result;
/*
* Set stackPtr and stackTop from eePtr.
*/
result = TCL_OK;
CACHE_STACK_INFO();
/*
* Pop the argument from the evaluation stack.
*/
valuePtr = POP_OBJECT();
if (VerifyExprObjType(interp, valuePtr) != TCL_OK) {
result = TCL_ERROR;
goto done;
}
if (valuePtr->typePtr == &tclIntType) {
iResult = valuePtr->internalRep.longValue;
} else {
d = valuePtr->internalRep.doubleValue;
if (d < 0.0) {
if (d <= (((double) (long) LONG_MIN) - 0.5)) {
tooLarge:
Tcl_ResetResult(interp);
Tcl_AppendToObj(Tcl_GetObjResult(interp),
"integer value too large to represent", -1);
Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW",
"integer value too large to represent",
(char *) NULL);
result = TCL_ERROR;
goto done;
}
temp = (long) (d - 0.5);
} else {
if (d >= (((double) LONG_MAX + 0.5))) {
goto tooLarge;
}
temp = (long) (d + 0.5);
}
if (IS_NAN(temp) || IS_INF(temp)) {
TclExprFloatError(interp, temp);
result = TCL_ERROR;
goto done;
}
iResult = (long) temp;
}
/*
* Push a Tcl object with the result.
*/
PUSH_OBJECT(Tcl_NewLongObj(iResult));
/*
* Reflect the change to stackTop back in eePtr.
*/
done:
Tcl_DecrRefCount(valuePtr);
DECACHE_STACK_INFO();
return result;
}
static int
ExprSrandFunc(interp, eePtr, clientData)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
ClientData clientData; /* Ignored. */
{
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
Interp *iPtr = (Interp *) interp;
Tcl_Obj *valuePtr;
long i = 0; /* Initialized to avoid compiler warning. */
int result;
/*
* Set stackPtr and stackTop from eePtr.
*/
CACHE_STACK_INFO();
/*
* Pop the argument from the evaluation stack. Use the value
* to reset the random number seed.
*/
valuePtr = POP_OBJECT();
if (VerifyExprObjType(interp, valuePtr) != TCL_OK) {
result = TCL_ERROR;
goto badValue;
}
if (valuePtr->typePtr == &tclIntType) {
i = valuePtr->internalRep.longValue;
} else {
/*
* At this point, the only other possible type is double
*/
Tcl_ResetResult(interp);
Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
"can't use floating-point value as argument to srand",
(char *) NULL);
badValue:
Tcl_DecrRefCount(valuePtr);
DECACHE_STACK_INFO();
return TCL_ERROR;
}
/*
* Reset the seed.
*/
iPtr->flags |= RAND_SEED_INITIALIZED;
iPtr->randSeed = i;
/*
* To avoid duplicating the random number generation code we simply
* clean up our state and call the real random number function. That
* function will always succeed.
*/
Tcl_DecrRefCount(valuePtr);
DECACHE_STACK_INFO();
ExprRandFunc(interp, eePtr, clientData);
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* ExprCallMathFunc --
*
* This procedure is invoked to call a non-builtin math function
* during the execution of an expression.
*
* Results:
* TCL_OK is returned if all went well and the function's value
* was computed successfully. If an error occurred, TCL_ERROR
* is returned and an error message is left in the interpreter's
* result. After a successful return this procedure pushes a Tcl object
* holding the result.
*
* Side effects:
* None, unless the called math function has side effects.
*
*----------------------------------------------------------------------
*/
static int
ExprCallMathFunc(interp, eePtr, objc, objv)
Tcl_Interp *interp; /* The interpreter in which to execute the
* function. */
ExecEnv *eePtr; /* Points to the environment for executing
* the function. */
int objc; /* Number of arguments. The function name is
* the 0-th argument. */
Tcl_Obj **objv; /* The array of arguments. The function name
* is objv[0]. */
{
Interp *iPtr = (Interp *) interp;
Tcl_Obj **stackPtr; /* Cached evaluation stack base pointer. */
register int stackTop; /* Cached top index of evaluation stack. */
char *funcName;
Tcl_HashEntry *hPtr;
MathFunc *mathFuncPtr; /* Information about math function. */
Tcl_Value args[MAX_MATH_ARGS]; /* Arguments for function call. */
Tcl_Value funcResult; /* Result of function call as Tcl_Value. */
register Tcl_Obj *valuePtr;
long i;
double d;
int j, k, result;
Tcl_ResetResult(interp);
/*
* Set stackPtr and stackTop from eePtr.
*/
CACHE_STACK_INFO();
/*
* Look up the MathFunc record for the function.
*/
funcName = Tcl_GetString(objv[0]);
hPtr = Tcl_FindHashEntry(&iPtr->mathFuncTable, funcName);
if (hPtr == NULL) {
Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
"unknown math function \"", funcName, "\"", (char *) NULL);
result = TCL_ERROR;
goto done;
}
mathFuncPtr = (MathFunc *) Tcl_GetHashValue(hPtr);
if (mathFuncPtr->numArgs != (objc-1)) {
panic("ExprCallMathFunc: expected number of args %d != actual number %d",
mathFuncPtr->numArgs, objc);
result = TCL_ERROR;
goto done;
}
/*
* Collect the arguments for the function, if there are any, into the
* array "args". Note that args[0] will have the Tcl_Value that
* corresponds to objv[1].
*/
for (j = 1, k = 0; j < objc; j++, k++) {
valuePtr = objv[j];
if (VerifyExprObjType(interp, valuePtr) != TCL_OK) {
result = TCL_ERROR;
goto done;
}
/*
* Copy the object's numeric value to the argument record,
* converting it if necessary.
*/
if (valuePtr->typePtr == &tclIntType) {
i = valuePtr->internalRep.longValue;
if (mathFuncPtr->argTypes[k] == TCL_DOUBLE) {
args[k].type = TCL_DOUBLE;
args[k].doubleValue = i;
} else {
args[k].type = TCL_INT;
args[k].intValue = i;
}
} else {
d = valuePtr->internalRep.doubleValue;
if (mathFuncPtr->argTypes[k] == TCL_INT) {
args[k].type = TCL_INT;
args[k].intValue = (long) d;
} else {
args[k].type = TCL_DOUBLE;
args[k].doubleValue = d;
}
}
}
/*
* Invoke the function and copy its result back into valuePtr.
*/
result = (*mathFuncPtr->proc)(mathFuncPtr->clientData, interp, args,
&funcResult);
if (result != TCL_OK) {
goto done;
}
/*
* Pop the objc top stack elements and decrement their ref counts.
*/
i = (stackTop - (objc-1));
while (i <= stackTop) {
valuePtr = stackPtr[i];
Tcl_DecrRefCount(valuePtr);
i++;
}
stackTop -= objc;
/*
* Push the call's object result.
*/
if (funcResult.type == TCL_INT) {
PUSH_OBJECT(Tcl_NewLongObj(funcResult.intValue));
} else {
d = funcResult.doubleValue;
if (IS_NAN(d) || IS_INF(d)) {
TclExprFloatError(interp, d);
result = TCL_ERROR;
goto done;
}
PUSH_OBJECT(Tcl_NewDoubleObj(d));
}
/*
* Reflect the change to stackTop back in eePtr.
*/
done:
DECACHE_STACK_INFO();
return result;
}
/*
*----------------------------------------------------------------------
*
* TclExprFloatError --
*
* This procedure is called when an error occurs during a
* floating-point operation. It reads errno and sets
* interp->objResultPtr accordingly.
*
* Results:
* interp->objResultPtr is set to hold an error message.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
TclExprFloatError(interp, value)
Tcl_Interp *interp; /* Where to store error message. */
double value; /* Value returned after error; used to
* distinguish underflows from overflows. */
{
char *s;
Tcl_ResetResult(interp);
if ((errno == EDOM) || (value != value)) {
s = "domain error: argument not in valid range";
Tcl_AppendToObj(Tcl_GetObjResult(interp), s, -1);
Tcl_SetErrorCode(interp, "ARITH", "DOMAIN", s, (char *) NULL);
} else if ((errno == ERANGE) || IS_INF(value)) {
if (value == 0.0) {
s = "floating-point value too small to represent";
Tcl_AppendToObj(Tcl_GetObjResult(interp), s, -1);
Tcl_SetErrorCode(interp, "ARITH", "UNDERFLOW", s, (char *) NULL);
} else {
s = "floating-point value too large to represent";
Tcl_AppendToObj(Tcl_GetObjResult(interp), s, -1);
Tcl_SetErrorCode(interp, "ARITH", "OVERFLOW", s, (char *) NULL);
}
} else {
char msg[64 + TCL_INTEGER_SPACE];
sprintf(msg, "unknown floating-point error, errno = %d", errno);
Tcl_AppendToObj(Tcl_GetObjResult(interp), msg, -1);
Tcl_SetErrorCode(interp, "ARITH", "UNKNOWN", msg, (char *) NULL);
}
}
/*
*----------------------------------------------------------------------
*
* TclMathInProgress --
*
* This procedure is called to find out if Tcl is doing math
* in this thread.
*
* Results:
* 0 or 1.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
#if 0
int
TclMathInProgress()
{
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
return tsdPtr->mathInProgress;
}
#endif
#ifdef TCL_COMPILE_STATS
/*
*----------------------------------------------------------------------
*
* TclLog2 --
*
* Procedure used while collecting compilation statistics to determine
* the log base 2 of an integer.
*
* Results:
* Returns the log base 2 of the operand. If the argument is less
* than or equal to zero, a zero is returned.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TclLog2(value)
register int value; /* The integer for which to compute the
* log base 2. */
{
register int n = value;
register int result = 0;
while (n > 1) {
n = n >> 1;
result++;
}
return result;
}
/*
*----------------------------------------------------------------------
*
* EvalStatsCmd --
*
* Implements the "evalstats" command that prints instruction execution
* counts to stdout.
*
* Results:
* Standard Tcl results.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
EvalStatsCmd(unused, interp, argc, argv)
ClientData unused; /* Unused. */
Tcl_Interp *interp; /* The current interpreter. */
int argc; /* The number of arguments. */
char **argv; /* The argument strings. */
{
Interp *iPtr = (Interp *) interp;
LiteralTable *globalTablePtr = &(iPtr->literalTable);
ByteCodeStats *statsPtr = &(iPtr->stats);
double totalCodeBytes, currentCodeBytes;
double totalLiteralBytes, currentLiteralBytes;
double objBytesIfUnshared, strBytesIfUnshared, sharingBytesSaved;
double strBytesSharedMultX, strBytesSharedOnce;
double numInstructions, currentHeaderBytes;
long numCurrentByteCodes, numByteCodeLits;
long refCountSum, literalMgmtBytes, sum;
int numSharedMultX, numSharedOnce;
int decadeHigh, minSizeDecade, maxSizeDecade, length, i;
char *litTableStats;
LiteralEntry *entryPtr;
numInstructions = 0.0;
for (i = 0; i < 256; i++) {
if (statsPtr->instructionCount[i] != 0) {
numInstructions += statsPtr->instructionCount[i];
}
}
totalLiteralBytes = sizeof(LiteralTable)
+ iPtr->literalTable.numBuckets * sizeof(LiteralEntry *)
+ (statsPtr->numLiteralsCreated * sizeof(LiteralEntry))
+ (statsPtr->numLiteralsCreated * sizeof(Tcl_Obj))
+ statsPtr->totalLitStringBytes;
totalCodeBytes = statsPtr->totalByteCodeBytes + totalLiteralBytes;
numCurrentByteCodes =
statsPtr->numCompilations - statsPtr->numByteCodesFreed;
currentHeaderBytes = numCurrentByteCodes
* (sizeof(ByteCode) - (sizeof(size_t) + sizeof(Tcl_Time)));
literalMgmtBytes = sizeof(LiteralTable)
+ (iPtr->literalTable.numBuckets * sizeof(LiteralEntry *))
+ (iPtr->literalTable.numEntries * sizeof(LiteralEntry));
currentLiteralBytes = literalMgmtBytes
+ iPtr->literalTable.numEntries * sizeof(Tcl_Obj)
+ statsPtr->currentLitStringBytes;
currentCodeBytes = statsPtr->currentByteCodeBytes + currentLiteralBytes;
/*
* Summary statistics, total and current source and ByteCode sizes.
*/
fprintf(stdout, "\n----------------------------------------------------------------\n");
fprintf(stdout,
"Compilation and execution statistics for interpreter 0x%x\n",
(unsigned int) iPtr);
fprintf(stdout, "\nNumber ByteCodes executed %ld\n",
statsPtr->numExecutions);
fprintf(stdout, "Number ByteCodes compiled %ld\n",
statsPtr->numCompilations);
fprintf(stdout, " Mean executions/compile %.1f\n",
((float)statsPtr->numExecutions) / ((float)statsPtr->numCompilations));
fprintf(stdout, "\nInstructions executed %.0f\n",
numInstructions);
fprintf(stdout, " Mean inst/compile %.0f\n",
numInstructions / statsPtr->numCompilations);
fprintf(stdout, " Mean inst/execution %.0f\n",
numInstructions / statsPtr->numExecutions);
fprintf(stdout, "\nTotal ByteCodes %ld\n",
statsPtr->numCompilations);
fprintf(stdout, " Source bytes %.6g\n",
statsPtr->totalSrcBytes);
fprintf(stdout, " Code bytes %.6g\n",
totalCodeBytes);
fprintf(stdout, " ByteCode bytes %.6g\n",
statsPtr->totalByteCodeBytes);
fprintf(stdout, " Literal bytes %.6g\n",
totalLiteralBytes);
fprintf(stdout, " table %d + bkts %d + entries %ld + objects %ld + strings %.6g\n",
sizeof(LiteralTable),
iPtr->literalTable.numBuckets * sizeof(LiteralEntry *),
statsPtr->numLiteralsCreated * sizeof(LiteralEntry),
statsPtr->numLiteralsCreated * sizeof(Tcl_Obj),
statsPtr->totalLitStringBytes);
fprintf(stdout, " Mean code/compile %.1f\n",
totalCodeBytes / statsPtr->numCompilations);
fprintf(stdout, " Mean code/source %.1f\n",
totalCodeBytes / statsPtr->totalSrcBytes);
fprintf(stdout, "\nCurrent (active) ByteCodes %ld\n",
numCurrentByteCodes);
fprintf(stdout, " Source bytes %.6g\n",
statsPtr->currentSrcBytes);
fprintf(stdout, " Code bytes %.6g\n",
currentCodeBytes);
fprintf(stdout, " ByteCode bytes %.6g\n",
statsPtr->currentByteCodeBytes);
fprintf(stdout, " Literal bytes %.6g\n",
currentLiteralBytes);
fprintf(stdout, " table %d + bkts %d + entries %d + objects %d + strings %.6g\n",
sizeof(LiteralTable),
iPtr->literalTable.numBuckets * sizeof(LiteralEntry *),
iPtr->literalTable.numEntries * sizeof(LiteralEntry),
iPtr->literalTable.numEntries * sizeof(Tcl_Obj),
statsPtr->currentLitStringBytes);
fprintf(stdout, " Mean code/source %.1f\n",
currentCodeBytes / statsPtr->currentSrcBytes);
fprintf(stdout, " Code + source bytes %.6g (%0.1f mean code/src)\n",
(currentCodeBytes + statsPtr->currentSrcBytes),
(currentCodeBytes / statsPtr->currentSrcBytes) + 1.0);
/*
* Tcl_IsShared statistics check
*
* This gives the refcount of each obj as Tcl_IsShared was called
* for it. Shared objects must be duplicated before they can be
* modified.
*/
numSharedMultX = 0;
fprintf(stdout, "\nTcl_IsShared object check (all objects):\n");
fprintf(stdout, " Object had refcount <=1 (not shared) %ld\n",
tclObjsShared[1]);
for (i = 2; i < TCL_MAX_SHARED_OBJ_STATS; i++) {
fprintf(stdout, " refcount ==%d %ld\n",
i, tclObjsShared[i]);
numSharedMultX += tclObjsShared[i];
}
fprintf(stdout, " refcount >=%d %ld\n",
i, tclObjsShared[0]);
numSharedMultX += tclObjsShared[0];
fprintf(stdout, " Total shared objects %d\n",
numSharedMultX);
/*
* Literal table statistics.
*/
numByteCodeLits = 0;
refCountSum = 0;
numSharedMultX = 0;
numSharedOnce = 0;
objBytesIfUnshared = 0.0;
strBytesIfUnshared = 0.0;
strBytesSharedMultX = 0.0;
strBytesSharedOnce = 0.0;
for (i = 0; i < globalTablePtr->numBuckets; i++) {
for (entryPtr = globalTablePtr->buckets[i]; entryPtr != NULL;
entryPtr = entryPtr->nextPtr) {
if (entryPtr->objPtr->typePtr == &tclByteCodeType) {
numByteCodeLits++;
}
(void) Tcl_GetStringFromObj(entryPtr->objPtr, &length);
refCountSum += entryPtr->refCount;
objBytesIfUnshared += (entryPtr->refCount * sizeof(Tcl_Obj));
strBytesIfUnshared += (entryPtr->refCount * (length+1));
if (entryPtr->refCount > 1) {
numSharedMultX++;
strBytesSharedMultX += (length+1);
} else {
numSharedOnce++;
strBytesSharedOnce += (length+1);
}
}
}
sharingBytesSaved = (objBytesIfUnshared + strBytesIfUnshared)
- currentLiteralBytes;
fprintf(stdout, "\nTotal objects (all interps) %ld\n",
tclObjsAlloced);
fprintf(stdout, "Current objects %ld\n",
(tclObjsAlloced - tclObjsFreed));
fprintf(stdout, "Total literal objects %ld\n",
statsPtr->numLiteralsCreated);
fprintf(stdout, "\nCurrent literal objects %d (%0.1f%% of current objects)\n",
globalTablePtr->numEntries,
(globalTablePtr->numEntries * 100.0) / (tclObjsAlloced-tclObjsFreed));
fprintf(stdout, " ByteCode literals %ld (%0.1f%% of current literals)\n",
numByteCodeLits,
(numByteCodeLits * 100.0) / globalTablePtr->numEntries);
fprintf(stdout, " Literals reused > 1x %d\n",
numSharedMultX);
fprintf(stdout, " Mean reference count %.2f\n",
((double) refCountSum) / globalTablePtr->numEntries);
fprintf(stdout, " Mean len, str reused >1x %.2f\n",
(numSharedMultX? (strBytesSharedMultX/numSharedMultX) : 0.0));
fprintf(stdout, " Mean len, str used 1x %.2f\n",
(numSharedOnce? (strBytesSharedOnce/numSharedOnce) : 0.0));
fprintf(stdout, " Total sharing savings %.6g (%0.1f%% of bytes if no sharing)\n",
sharingBytesSaved,
(sharingBytesSaved * 100.0) / (objBytesIfUnshared + strBytesIfUnshared));
fprintf(stdout, " Bytes with sharing %.6g\n",
currentLiteralBytes);
fprintf(stdout, " table %d + bkts %d + entries %d + objects %d + strings %.6g\n",
sizeof(LiteralTable),
iPtr->literalTable.numBuckets * sizeof(LiteralEntry *),
iPtr->literalTable.numEntries * sizeof(LiteralEntry),
iPtr->literalTable.numEntries * sizeof(Tcl_Obj),
statsPtr->currentLitStringBytes);
fprintf(stdout, " Bytes if no sharing %.6g = objects %.6g + strings %.6g\n",
(objBytesIfUnshared + strBytesIfUnshared),
objBytesIfUnshared, strBytesIfUnshared);
fprintf(stdout, " String sharing savings %.6g = unshared %.6g - shared %.6g\n",
(strBytesIfUnshared - statsPtr->currentLitStringBytes),
strBytesIfUnshared, statsPtr->currentLitStringBytes);
fprintf(stdout, " Literal mgmt overhead %ld (%0.1f%% of bytes with sharing)\n",
literalMgmtBytes,
(literalMgmtBytes * 100.0) / currentLiteralBytes);
fprintf(stdout, " table %d + buckets %d + entries %d\n",
sizeof(LiteralTable),
iPtr->literalTable.numBuckets * sizeof(LiteralEntry *),
iPtr->literalTable.numEntries * sizeof(LiteralEntry));
/*
* Breakdown of current ByteCode space requirements.
*/
fprintf(stdout, "\nBreakdown of current ByteCode requirements:\n");
fprintf(stdout, " Bytes Pct of Avg per\n");
fprintf(stdout, " total ByteCode\n");
fprintf(stdout, "Total %12.6g 100.00%% %8.1f\n",
statsPtr->currentByteCodeBytes,
statsPtr->currentByteCodeBytes / numCurrentByteCodes);
fprintf(stdout, "Header %12.6g %8.1f%% %8.1f\n",
currentHeaderBytes,
((currentHeaderBytes * 100.0) / statsPtr->currentByteCodeBytes),
currentHeaderBytes / numCurrentByteCodes);
fprintf(stdout, "Instructions %12.6g %8.1f%% %8.1f\n",
statsPtr->currentInstBytes,
((statsPtr->currentInstBytes * 100.0) / statsPtr->currentByteCodeBytes),
statsPtr->currentInstBytes / numCurrentByteCodes);
fprintf(stdout, "Literal ptr array %12.6g %8.1f%% %8.1f\n",
statsPtr->currentLitBytes,
((statsPtr->currentLitBytes * 100.0) / statsPtr->currentByteCodeBytes),
statsPtr->currentLitBytes / numCurrentByteCodes);
fprintf(stdout, "Exception table %12.6g %8.1f%% %8.1f\n",
statsPtr->currentExceptBytes,
((statsPtr->currentExceptBytes * 100.0) / statsPtr->currentByteCodeBytes),
statsPtr->currentExceptBytes / numCurrentByteCodes);
fprintf(stdout, "Auxiliary data %12.6g %8.1f%% %8.1f\n",
statsPtr->currentAuxBytes,
((statsPtr->currentAuxBytes * 100.0) / statsPtr->currentByteCodeBytes),
statsPtr->currentAuxBytes / numCurrentByteCodes);
fprintf(stdout, "Command map %12.6g %8.1f%% %8.1f\n",
statsPtr->currentCmdMapBytes,
((statsPtr->currentCmdMapBytes * 100.0) / statsPtr->currentByteCodeBytes),
statsPtr->currentCmdMapBytes / numCurrentByteCodes);
/*
* Detailed literal statistics.
*/
fprintf(stdout, "\nLiteral string sizes:\n");
fprintf(stdout, " Up to length Percentage\n");
maxSizeDecade = 0;
for (i = 31; i >= 0; i--) {
if (statsPtr->literalCount[i] > 0) {
maxSizeDecade = i;
break;
}
}
sum = 0;
for (i = 0; i <= maxSizeDecade; i++) {
decadeHigh = (1 << (i+1)) - 1;
sum += statsPtr->literalCount[i];
fprintf(stdout, " %10d %8.0f%%\n",
decadeHigh, (sum * 100.0) / statsPtr->numLiteralsCreated);
}
litTableStats = TclLiteralStats(globalTablePtr);
fprintf(stdout, "\nCurrent literal table statistics:\n%s\n",
litTableStats);
ckfree((char *) litTableStats);
/*
* Source and ByteCode size distributions.
*/
fprintf(stdout, "\nSource sizes:\n");
fprintf(stdout, " Up to size Percentage\n");
minSizeDecade = maxSizeDecade = 0;
for (i = 0; i < 31; i++) {
if (statsPtr->srcCount[i] > 0) {
minSizeDecade = i;
break;
}
}
for (i = 31; i >= 0; i--) {
if (statsPtr->srcCount[i] > 0) {
maxSizeDecade = i;
break;
}
}
sum = 0;
for (i = minSizeDecade; i <= maxSizeDecade; i++) {
decadeHigh = (1 << (i+1)) - 1;
sum += statsPtr->srcCount[i];
fprintf(stdout, " %10d %8.0f%%\n",
decadeHigh, (sum * 100.0) / statsPtr->numCompilations);
}
fprintf(stdout, "\nByteCode sizes:\n");
fprintf(stdout, " Up to size Percentage\n");
minSizeDecade = maxSizeDecade = 0;
for (i = 0; i < 31; i++) {
if (statsPtr->byteCodeCount[i] > 0) {
minSizeDecade = i;
break;
}
}
for (i = 31; i >= 0; i--) {
if (statsPtr->byteCodeCount[i] > 0) {
maxSizeDecade = i;
break;
}
}
sum = 0;
for (i = minSizeDecade; i <= maxSizeDecade; i++) {
decadeHigh = (1 << (i+1)) - 1;
sum += statsPtr->byteCodeCount[i];
fprintf(stdout, " %10d %8.0f%%\n",
decadeHigh, (sum * 100.0) / statsPtr->numCompilations);
}
fprintf(stdout, "\nByteCode longevity (excludes Current ByteCodes):\n");
fprintf(stdout, " Up to ms Percentage\n");
minSizeDecade = maxSizeDecade = 0;
for (i = 0; i < 31; i++) {
if (statsPtr->lifetimeCount[i] > 0) {
minSizeDecade = i;
break;
}
}
for (i = 31; i >= 0; i--) {
if (statsPtr->lifetimeCount[i] > 0) {
maxSizeDecade = i;
break;
}
}
sum = 0;
for (i = minSizeDecade; i <= maxSizeDecade; i++) {
decadeHigh = (1 << (i+1)) - 1;
sum += statsPtr->lifetimeCount[i];
fprintf(stdout, " %12.3f %8.0f%%\n",
decadeHigh / 1000.0,
(sum * 100.0) / statsPtr->numByteCodesFreed);
}
/*
* Instruction counts.
*/
fprintf(stdout, "\nInstruction counts:\n");
for (i = 0; i <= LAST_INST_OPCODE; i++) {
if (statsPtr->instructionCount[i]) {
fprintf(stdout, "%20s %8ld %6.1f%%\n",
instructionTable[i].name,
statsPtr->instructionCount[i],
(statsPtr->instructionCount[i]*100.0) / numInstructions);
}
}
fprintf(stdout, "\nInstructions NEVER executed:\n");
for (i = 0; i <= LAST_INST_OPCODE; i++) {
if (statsPtr->instructionCount[i] == 0) {
fprintf(stdout, "%20s\n",
instructionTable[i].name);
}
}
#ifdef TCL_MEM_DEBUG
fprintf(stdout, "\nHeap Statistics:\n");
TclDumpMemoryInfo(stdout);
#endif
fprintf(stdout, "\n----------------------------------------------------------------\n");
return TCL_OK;
}
#endif /* TCL_COMPILE_STATS */
/*
*----------------------------------------------------------------------
*
* Tcl_GetCommandFromObj --
*
* Returns the command specified by the name in a Tcl_Obj.
*
* Results:
* Returns a token for the command if it is found. Otherwise, if it
* can't be found or there is an error, returns NULL.
*
* Side effects:
* May update the internal representation for the object, caching
* the command reference so that the next time this procedure is
* called with the same object, the command can be found quickly.
*
*----------------------------------------------------------------------
*/
Tcl_Command
Tcl_GetCommandFromObj(interp, objPtr)
Tcl_Interp *interp; /* The interpreter in which to resolve the
* command and to report errors. */
register Tcl_Obj *objPtr; /* The object containing the command's
* name. If the name starts with "::", will
* be looked up in global namespace. Else,
* looked up first in the current namespace
* if contextNsPtr is NULL, then in global
* namespace. */
{
Interp *iPtr = (Interp *) interp;
register ResolvedCmdName *resPtr;
register Command *cmdPtr;
Namespace *currNsPtr;
int result;
/*
* Get the internal representation, converting to a command type if
* needed. The internal representation is a ResolvedCmdName that points
* to the actual command.
*/
if (objPtr->typePtr != &tclCmdNameType) {
result = tclCmdNameType.setFromAnyProc(interp, objPtr);
if (result != TCL_OK) {
return (Tcl_Command) NULL;
}
}
resPtr = (ResolvedCmdName *) objPtr->internalRep.otherValuePtr;
/*
* Get the current namespace.
*/
if (iPtr->varFramePtr != NULL) {
currNsPtr = iPtr->varFramePtr->nsPtr;
} else {
currNsPtr = iPtr->globalNsPtr;
}
/*
* Check the context namespace and the namespace epoch of the resolved
* symbol to make sure that it is fresh. If not, then force another
* conversion to the command type, to discard the old rep and create a
* new one. Note that we verify that the namespace id of the context
* namespace is the same as the one we cached; this insures that the
* namespace wasn't deleted and a new one created at the same address
* with the same command epoch.
*/
cmdPtr = NULL;
if ((resPtr != NULL)
&& (resPtr->refNsPtr == currNsPtr)
&& (resPtr->refNsId == currNsPtr->nsId)
&& (resPtr->refNsCmdEpoch == currNsPtr->cmdRefEpoch)) {
cmdPtr = resPtr->cmdPtr;
if (cmdPtr->cmdEpoch != resPtr->cmdEpoch) {
cmdPtr = NULL;
}
}
if (cmdPtr == NULL) {
result = tclCmdNameType.setFromAnyProc(interp, objPtr);
if (result != TCL_OK) {
return (Tcl_Command) NULL;
}
resPtr = (ResolvedCmdName *) objPtr->internalRep.otherValuePtr;
if (resPtr != NULL) {
cmdPtr = resPtr->cmdPtr;
}
}
return (Tcl_Command) cmdPtr;
}
/*
*----------------------------------------------------------------------
*
* TclSetCmdNameObj --
*
* Modify an object to be an CmdName object that refers to the argument
* Command structure.
*
* Results:
* None.
*
* Side effects:
* The object's old internal rep is freed. It's string rep is not
* changed. The refcount in the Command structure is incremented to
* keep it from being freed if the command is later deleted until
* TclExecuteByteCode has a chance to recognize that it was deleted.
*
*----------------------------------------------------------------------
*/
void
TclSetCmdNameObj(interp, objPtr, cmdPtr)
Tcl_Interp *interp; /* Points to interpreter containing command
* that should be cached in objPtr. */
register Tcl_Obj *objPtr; /* Points to Tcl object to be changed to
* a CmdName object. */
Command *cmdPtr; /* Points to Command structure that the
* CmdName object should refer to. */
{
Interp *iPtr = (Interp *) interp;
register ResolvedCmdName *resPtr;
Tcl_ObjType *oldTypePtr = objPtr->typePtr;
register Namespace *currNsPtr;
if (oldTypePtr == &tclCmdNameType) {
return;
}
/*
* Get the current namespace.
*/
if (iPtr->varFramePtr != NULL) {
currNsPtr = iPtr->varFramePtr->nsPtr;
} else {
currNsPtr = iPtr->globalNsPtr;
}
cmdPtr->refCount++;
resPtr = (ResolvedCmdName *) ckalloc(sizeof(ResolvedCmdName));
resPtr->cmdPtr = cmdPtr;
resPtr->refNsPtr = currNsPtr;
resPtr->refNsId = currNsPtr->nsId;
resPtr->refNsCmdEpoch = currNsPtr->cmdRefEpoch;
resPtr->cmdEpoch = cmdPtr->cmdEpoch;
resPtr->refCount = 1;
if ((oldTypePtr != NULL) && (oldTypePtr->freeIntRepProc != NULL)) {
oldTypePtr->freeIntRepProc(objPtr);
}
objPtr->internalRep.twoPtrValue.ptr1 = (VOID *) resPtr;
objPtr->internalRep.twoPtrValue.ptr2 = NULL;
objPtr->typePtr = &tclCmdNameType;
}
/*
*----------------------------------------------------------------------
*
* FreeCmdNameInternalRep --
*
* Frees the resources associated with a cmdName object's internal
* representation.
*
* Results:
* None.
*
* Side effects:
* Decrements the ref count of any cached ResolvedCmdName structure
* pointed to by the cmdName's internal representation. If this is
* the last use of the ResolvedCmdName, it is freed. This in turn
* decrements the ref count of the Command structure pointed to by
* the ResolvedSymbol, which may free the Command structure.
*
*----------------------------------------------------------------------
*/
static void
FreeCmdNameInternalRep(objPtr)
register Tcl_Obj *objPtr; /* CmdName object with internal
* representation to free. */
{
register ResolvedCmdName *resPtr =
(ResolvedCmdName *) objPtr->internalRep.otherValuePtr;
if (resPtr != NULL) {
/*
* Decrement the reference count of the ResolvedCmdName structure.
* If there are no more uses, free the ResolvedCmdName structure.
*/
resPtr->refCount--;
if (resPtr->refCount == 0) {
/*
* Now free the cached command, unless it is still in its
* hash table or if there are other references to it
* from other cmdName objects.
*/
Command *cmdPtr = resPtr->cmdPtr;
TclCleanupCommand(cmdPtr);
ckfree((char *) resPtr);
}
}
}
/*
*----------------------------------------------------------------------
*
* DupCmdNameInternalRep --
*
* Initialize the internal representation of an cmdName Tcl_Obj to a
* copy of the internal representation of an existing cmdName object.
*
* Results:
* None.
*
* Side effects:
* "copyPtr"s internal rep is set to point to the ResolvedCmdName
* structure corresponding to "srcPtr"s internal rep. Increments the
* ref count of the ResolvedCmdName structure pointed to by the
* cmdName's internal representation.
*
*----------------------------------------------------------------------
*/
static void
DupCmdNameInternalRep(srcPtr, copyPtr)
Tcl_Obj *srcPtr; /* Object with internal rep to copy. */
register Tcl_Obj *copyPtr; /* Object with internal rep to set. */
{
register ResolvedCmdName *resPtr =
(ResolvedCmdName *) srcPtr->internalRep.otherValuePtr;
copyPtr->internalRep.twoPtrValue.ptr1 = (VOID *) resPtr;
copyPtr->internalRep.twoPtrValue.ptr2 = NULL;
if (resPtr != NULL) {
resPtr->refCount++;
}
copyPtr->typePtr = &tclCmdNameType;
}
/*
*----------------------------------------------------------------------
*
* SetCmdNameFromAny --
*
* Generate an cmdName internal form for the Tcl object "objPtr".
*
* Results:
* The return value is a standard Tcl result. The conversion always
* succeeds and TCL_OK is returned.
*
* Side effects:
* A pointer to a ResolvedCmdName structure that holds a cached pointer
* to the command with a name that matches objPtr's string rep is
* stored as objPtr's internal representation. This ResolvedCmdName
* pointer will be NULL if no matching command was found. The ref count
* of the cached Command's structure (if any) is also incremented.
*
*----------------------------------------------------------------------
*/
static int
SetCmdNameFromAny(interp, objPtr)
Tcl_Interp *interp; /* Used for error reporting if not NULL. */
register Tcl_Obj *objPtr; /* The object to convert. */
{
Interp *iPtr = (Interp *) interp;
char *name;
Tcl_Command cmd;
register Command *cmdPtr;
Namespace *currNsPtr;
register ResolvedCmdName *resPtr;
/*
* Get "objPtr"s string representation. Make it up-to-date if necessary.
*/
name = objPtr->bytes;
if (name == NULL) {
name = Tcl_GetString(objPtr);
}
/*
* Find the Command structure, if any, that describes the command called
* "name". Build a ResolvedCmdName that holds a cached pointer to this
* Command, and bump the reference count in the referenced Command
* structure. A Command structure will not be deleted as long as it is
* referenced from a CmdName object.
*/
cmd = Tcl_FindCommand(interp, name, (Tcl_Namespace *) NULL,
/*flags*/ 0);
cmdPtr = (Command *) cmd;
if (cmdPtr != NULL) {
/*
* Get the current namespace.
*/
if (iPtr->varFramePtr != NULL) {
currNsPtr = iPtr->varFramePtr->nsPtr;
} else {
currNsPtr = iPtr->globalNsPtr;
}
cmdPtr->refCount++;
resPtr = (ResolvedCmdName *) ckalloc(sizeof(ResolvedCmdName));
resPtr->cmdPtr = cmdPtr;
resPtr->refNsPtr = currNsPtr;
resPtr->refNsId = currNsPtr->nsId;
resPtr->refNsCmdEpoch = currNsPtr->cmdRefEpoch;
resPtr->cmdEpoch = cmdPtr->cmdEpoch;
resPtr->refCount = 1;
} else {
resPtr = NULL; /* no command named "name" was found */
}
/*
* Free the old internalRep before setting the new one. We do this as
* late as possible to allow the conversion code, in particular
* GetStringFromObj, to use that old internalRep. If no Command
* structure was found, leave NULL as the cached value.
*/
if ((objPtr->typePtr != NULL)
&& (objPtr->typePtr->freeIntRepProc != NULL)) {
objPtr->typePtr->freeIntRepProc(objPtr);
}
objPtr->internalRep.twoPtrValue.ptr1 = (VOID *) resPtr;
objPtr->internalRep.twoPtrValue.ptr2 = NULL;
objPtr->typePtr = &tclCmdNameType;
return TCL_OK;
}
#ifdef TCL_COMPILE_DEBUG
/*
*----------------------------------------------------------------------
*
* StringForResultCode --
*
* Procedure that returns a human-readable string representing a
* Tcl result code such as TCL_ERROR.
*
* Results:
* If the result code is one of the standard Tcl return codes, the
* result is a string representing that code such as "TCL_ERROR".
* Otherwise, the result string is that code formatted as a
* sequence of decimal digit characters. Note that the resulting
* string must not be modified by the caller.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static char *
StringForResultCode(result)
int result; /* The Tcl result code for which to
* generate a string. */
{
static char buf[TCL_INTEGER_SPACE];
if ((result >= TCL_OK) && (result <= TCL_CONTINUE)) {
return resultStrings[result];
}
TclFormatInt(buf, result);
return buf;
}
#endif /* TCL_COMPILE_DEBUG */
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
5314
]
]
] |
3ec8909e8c34bf0b60f3691fe6a27b75426e81b4 | b7c073dfd73823cf85fcc5467644a307b52b90db | /projekt/projects/BCompressor/source/BCompressor.h | 60af0d2d87a68ac02d97220b66f37a56008b50ec | [] | no_license | eriser/bfoozrocnikovy | dc0272cfd2869b611c76ee8859f961d6b3151f64 | 49244511e5fe15ce3dbd92f932fccec5df7f6bf1 | refs/heads/master | 2021-01-18T20:08:45.364014 | 2010-05-23T10:48:01 | 2010-05-23T10:48:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,247 | h | #ifndef __BCompressor__
#define __BCompressor__
#include "libraries/vst/audioeffectx.h"
enum {
kInput,
kLimiter,
kAttack,
kRelease,
kRatio,
kTresh,
kAutoMakeUp,
kOutput,
kNumParams
};
///\brief Implementovany efekt kompresor ako VST efekt.
///
///Dokumentacia k metodam je uvedena v dokumentacii k VST SDK.
class BCompressor : public AudioEffectX
{
public:
BCompressor (audioMasterCallback audioMaster);
~BCompressor ();
// Processing
virtual void processReplacing (float** inputs, float** outputs, VstInt32 sampleFrames);
//virtual void processDoubleReplacing (double** inputs, double** outputs, VstInt32 sampleFrames);
// Program
virtual void setProgramName (char* name);
virtual void getProgramName (char* name);
// Parameters
virtual void setParameter (VstInt32 index, float value);
virtual float getParameter (VstInt32 index);
virtual void getParameterLabel (VstInt32 index, char* label);
virtual void getParameterDisplay (VstInt32 index, char* text);
virtual void getParameterName (VstInt32 index, char* text);
virtual bool getEffectName (char* name);
virtual bool getVendorString (char* text);
virtual bool getProductString (char* text);
virtual VstInt32 getVendorVersion ();
private:
void setInput(float input);
void setLimiter(float limiter);
void setAttack(float attack);
void setRelease(float release);
void setRatio(float ratio);
void setTresh(float tresh);
void setAutoMakeUp(float automakeup);
void setOutput(float Output);
float funLimiter(float in);
float funBCompressor(float in);
long sr;
float iInput, iLimiter, iAttack, iRelease, iRatio, iTresh, iAutoMakeUp, iOutput; //(input) vstupna hodnota z vst ovladaca ([0,1])
float oInput, oAttack, oRelease, oRatio, oTresh, oOutput; //(output) vystupna hodnota, ktora je zobrazovana na ovladaci
float uInput, uRatio, uTresh, uOutput; //(used) hodnota, ktora sa pouziva
long uAttack, uRelease; //hodnota prepocitana na sample
long att_counter, att_counter_old, rel_counter; //odpocitavanie pre attack a release, v samploch
float oldOutput;
bool uAutoMakeUp, oAutoMakeUp, uLimiter, oLimiter, komprimuj;
char programName[kVstMaxProgNameLen + 1];
};
#endif | [
"fabry.brano@7dde01ba-876c-11de-b48b-8f0b266c3b3d"
] | [
[
[
1,
74
]
]
] |
3f46b6abbaa40c90f947997c8e1b73a65ddf157e | 2aa37ad4e32d8208f4b116fe32a723690b0d9502 | /rubystuff/rubywin-0.0.4.3/u2s.cpp | 57d6e01ca5effa7be0a0cac406c942b788b8a6e8 | [] | no_license | srirammca53/update_status | 213070d809629971302192444dd48c0f8d245fdc | a5bf9d16d9f3a81329f1a7801274ad716b40c3e8 | refs/heads/master | 2020-04-05T23:40:26.156836 | 2011-08-02T13:35:17 | 2011-08-02T13:35:17 | 2,142,552 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,128 | cpp | /*
* Unicode Conversion Library (UCS2 to Shift_JIS)
* 1999 by yoshidam
*
*/
/*
* Modified for RubyWin by Masaki Suketa
*/
#include <windows.h>
#include <string.h>
#include <stdlib.h>
#include "rwuconv.h"
#include "u2s.h"
#include "u8tou16.h"
#include "ustring.h"
int u8tosjis(const unsigned char* u, UString *s) {
UString out;
u8tou16(u, &out);
int len = u2s_conv2(out.str, out.len, s);
UStr_free(&out);
return len;
}
int
u2s_conv2(const unsigned char* u, int len, UString* s)
{
int i;
UStr_alloc(s);
for (i = 0; i < len; i+=2) {
unsigned char str[3];
int slen = WideCharToMultiByte(SJIS_CODEPAGE, 0,
(LPCWSTR)(u + i), 1,
reinterpret_cast<CHAR*>(str), 3,
"\xff", NULL);
if (slen == 1 && str[0] == (unsigned char)'\xff') { /* Unknown char */
UStr_addChar(s, '?');
}
else if (slen == 1) {
UStr_addChar(s, str[0]);
}
else if (slen == 2) {
UStr_addChar2(s, str[0], str[1]);
}
else {
UStr_addChar(s, '?');
}
}
return s->len;
}
| [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
4864f53834c20f08d4616084ebe30008224e6369 | 6c5cd70473dceee91751a9ae9f1fecda20fa60d0 | /src/Replay.cpp | bf8b7053a954866a5f23d2576e09bb978714ccb5 | [] | no_license | jncraton/rep2ai | 27da3316f365ae2518b361a8186fd6fc8a53804f | c0ce7de68bb110e6f11cf1c3a29d32fec2d0694a | refs/heads/master | 2020-04-29T02:57:57.288273 | 2010-07-20T18:41:44 | 2010-07-20T18:41:44 | 441,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | cpp | #include "Replay.h"
Replay::Replay(char * filename) {
/**
* Replay
*/
int repID ,cmdSize = 0;
char * cmd;
FILE * replayFile;
const char raceList[3] = {'Z','T','P'};
replayFile = fopen(filename, "rb");
if(replayFile) {
unpack_section(replayFile, (byte*)&repID, 4);
unpack_section(replayFile, (byte*)&header, 0x279);
unpack_section(replayFile, (byte*)&cmdSize, 4);
cmd = (char *)malloc(cmdSize * sizeof(char));
unpack_section(replayFile, (byte*)cmd, cmdSize);
} else {
printf("Failed to open file %s\n",filename);
exit(0);
}
fclose(replayFile);
memcpy(&gameName, &header[24], 28);
gameName[28] = 0x00;
for(int i = 0; i < 8; i++) {
memcpy(playerName[i], &header[0xA1+11 + i*36], 28);
playerName[i][26] = 0x00;
playerID[i] = header[0xA1+4 + i*36];
if((unsigned int)header[0xA1+9 + i*36] > 3) {
playerRace[i] = 'N';
} else {
playerRace[i] = raceList[(int)header[0xA1+9 + i*36]];
}
}
actionList.build(cmd, cmdSize);
// count how many players we have
numPlayers = 0;
for(int i = 0; i < 8; i++) {
if(playerID[i] > -1) {
numPlayers++;
}
}
}
Replay::~Replay() {
/**
* ~Replay
*/
}
| [
"jncraton@.(none)",
"[email protected]"
] | [
[
[
1,
3
],
[
7,
31
],
[
33,
36
],
[
45,
47
]
],
[
[
4,
6
],
[
32,
32
],
[
37,
44
],
[
48,
51
]
]
] |
d6eba3cf6cff10e0ece36e2f3ae25bd1216596fc | 52db451b6b354993000a4a808e9d046dff4c956f | /include/Player.h | dcbb34ce0cc797ffdc03a8921de94da159671946 | [] | no_license | PuffNSting/Poker | a4b0263c27911291c6ce7148d22c1c137af457d3 | b1c606980af32b325fdf7398f30d6364c0097034 | refs/heads/master | 2021-01-15T22:29:18.718588 | 2011-12-23T03:02:07 | 2011-12-23T03:02:07 | 3,032,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | h | #ifndef PLAYER_H
#define PLAYER_H
#include <vector>
#include <iostream>
#include "../include/Card.h"
#include "../include/Board.h"
#include "../include/win_state.h"
#include <string>
using namespace std;
class Player
{
public:
Player() {};
void print_hand();
int calc_win_level(Board);
string win_level_to_string(int);
void add_card(Card c) {
hand.push_back(c);
}
void new_hand() {
hand.resize(0);
}
vector<Card> get_hand() {
return hand;
}
int get_win_level() {
return win_level;
}
int get_high_card() {
return high_card;
}
private:
vector<Card> hand;
int win_level, high_card;
};
#endif // PLAYER_H
| [
"[email protected]"
] | [
[
[
1,
42
]
]
] |
2e068fd0611a649c6ab823e428598a02d2ed1242 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/jsapi/third_party/gecko-1.9.0.11/win32/include/nsIDOMStyleSheet.h | f85757fc9dc1355a845bc46fd22a1fc6ced3556e | [
"Apache-2.0"
] | permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,756 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/xr19rel/WINNT_5.2_Depend/mozilla/dom/public/idl/stylesheets/nsIDOMStyleSheet.idl
*/
#ifndef __gen_nsIDOMStyleSheet_h__
#define __gen_nsIDOMStyleSheet_h__
#ifndef __gen_domstubs_h__
#include "domstubs.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMStyleSheet */
#define NS_IDOMSTYLESHEET_IID_STR "a6cf9080-15b3-11d2-932e-00805f8add32"
#define NS_IDOMSTYLESHEET_IID \
{0xa6cf9080, 0x15b3, 0x11d2, \
{ 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMStyleSheet : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSTYLESHEET_IID)
/**
* The nsIDOMStyleSheet interface is a datatype for a style sheet in
* the Document Object Model.
*
* For more information on this interface please see
* http://www.w3.org/TR/DOM-Level-2-Style
*
* @status FROZEN
*/
/* readonly attribute DOMString type; */
NS_SCRIPTABLE NS_IMETHOD GetType(nsAString & aType) = 0;
/* attribute boolean disabled; */
NS_SCRIPTABLE NS_IMETHOD GetDisabled(PRBool *aDisabled) = 0;
NS_SCRIPTABLE NS_IMETHOD SetDisabled(PRBool aDisabled) = 0;
/* readonly attribute nsIDOMNode ownerNode; */
NS_SCRIPTABLE NS_IMETHOD GetOwnerNode(nsIDOMNode * *aOwnerNode) = 0;
/* readonly attribute nsIDOMStyleSheet parentStyleSheet; */
NS_SCRIPTABLE NS_IMETHOD GetParentStyleSheet(nsIDOMStyleSheet * *aParentStyleSheet) = 0;
/* readonly attribute DOMString href; */
NS_SCRIPTABLE NS_IMETHOD GetHref(nsAString & aHref) = 0;
/* readonly attribute DOMString title; */
NS_SCRIPTABLE NS_IMETHOD GetTitle(nsAString & aTitle) = 0;
/* readonly attribute nsIDOMMediaList media; */
NS_SCRIPTABLE NS_IMETHOD GetMedia(nsIDOMMediaList * *aMedia) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMStyleSheet, NS_IDOMSTYLESHEET_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMSTYLESHEET \
NS_SCRIPTABLE NS_IMETHOD GetType(nsAString & aType); \
NS_SCRIPTABLE NS_IMETHOD GetDisabled(PRBool *aDisabled); \
NS_SCRIPTABLE NS_IMETHOD SetDisabled(PRBool aDisabled); \
NS_SCRIPTABLE NS_IMETHOD GetOwnerNode(nsIDOMNode * *aOwnerNode); \
NS_SCRIPTABLE NS_IMETHOD GetParentStyleSheet(nsIDOMStyleSheet * *aParentStyleSheet); \
NS_SCRIPTABLE NS_IMETHOD GetHref(nsAString & aHref); \
NS_SCRIPTABLE NS_IMETHOD GetTitle(nsAString & aTitle); \
NS_SCRIPTABLE NS_IMETHOD GetMedia(nsIDOMMediaList * *aMedia);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMSTYLESHEET(_to) \
NS_SCRIPTABLE NS_IMETHOD GetType(nsAString & aType) { return _to GetType(aType); } \
NS_SCRIPTABLE NS_IMETHOD GetDisabled(PRBool *aDisabled) { return _to GetDisabled(aDisabled); } \
NS_SCRIPTABLE NS_IMETHOD SetDisabled(PRBool aDisabled) { return _to SetDisabled(aDisabled); } \
NS_SCRIPTABLE NS_IMETHOD GetOwnerNode(nsIDOMNode * *aOwnerNode) { return _to GetOwnerNode(aOwnerNode); } \
NS_SCRIPTABLE NS_IMETHOD GetParentStyleSheet(nsIDOMStyleSheet * *aParentStyleSheet) { return _to GetParentStyleSheet(aParentStyleSheet); } \
NS_SCRIPTABLE NS_IMETHOD GetHref(nsAString & aHref) { return _to GetHref(aHref); } \
NS_SCRIPTABLE NS_IMETHOD GetTitle(nsAString & aTitle) { return _to GetTitle(aTitle); } \
NS_SCRIPTABLE NS_IMETHOD GetMedia(nsIDOMMediaList * *aMedia) { return _to GetMedia(aMedia); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMSTYLESHEET(_to) \
NS_SCRIPTABLE NS_IMETHOD GetType(nsAString & aType) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetType(aType); } \
NS_SCRIPTABLE NS_IMETHOD GetDisabled(PRBool *aDisabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDisabled(aDisabled); } \
NS_SCRIPTABLE NS_IMETHOD SetDisabled(PRBool aDisabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetDisabled(aDisabled); } \
NS_SCRIPTABLE NS_IMETHOD GetOwnerNode(nsIDOMNode * *aOwnerNode) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOwnerNode(aOwnerNode); } \
NS_SCRIPTABLE NS_IMETHOD GetParentStyleSheet(nsIDOMStyleSheet * *aParentStyleSheet) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetParentStyleSheet(aParentStyleSheet); } \
NS_SCRIPTABLE NS_IMETHOD GetHref(nsAString & aHref) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetHref(aHref); } \
NS_SCRIPTABLE NS_IMETHOD GetTitle(nsAString & aTitle) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTitle(aTitle); } \
NS_SCRIPTABLE NS_IMETHOD GetMedia(nsIDOMMediaList * *aMedia) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMedia(aMedia); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMStyleSheet : public nsIDOMStyleSheet
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMSTYLESHEET
nsDOMStyleSheet();
private:
~nsDOMStyleSheet();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMStyleSheet, nsIDOMStyleSheet)
nsDOMStyleSheet::nsDOMStyleSheet()
{
/* member initializers and constructor code */
}
nsDOMStyleSheet::~nsDOMStyleSheet()
{
/* destructor code */
}
/* readonly attribute DOMString type; */
NS_IMETHODIMP nsDOMStyleSheet::GetType(nsAString & aType)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute boolean disabled; */
NS_IMETHODIMP nsDOMStyleSheet::GetDisabled(PRBool *aDisabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsDOMStyleSheet::SetDisabled(PRBool aDisabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIDOMNode ownerNode; */
NS_IMETHODIMP nsDOMStyleSheet::GetOwnerNode(nsIDOMNode * *aOwnerNode)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIDOMStyleSheet parentStyleSheet; */
NS_IMETHODIMP nsDOMStyleSheet::GetParentStyleSheet(nsIDOMStyleSheet * *aParentStyleSheet)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString href; */
NS_IMETHODIMP nsDOMStyleSheet::GetHref(nsAString & aHref)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString title; */
NS_IMETHODIMP nsDOMStyleSheet::GetTitle(nsAString & aTitle)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIDOMMediaList media; */
NS_IMETHODIMP nsDOMStyleSheet::GetMedia(nsIDOMMediaList * *aMedia)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMStyleSheet_h__ */
| [
"simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9"
] | [
[
[
1,
180
]
]
] |
b18c670692f597418e678fb5cc9f8dd403f4e2f5 | 7d839db100b924a37f7974d49247ddaea605dafa | /include/Exil/ExilDocument.h | 8194003e38f1390275415f10d1ce9ddd59621de4 | [] | no_license | pabloarista/libexil | ac841fc38ad8dba1fb92b8cb2bc945821596027f | d4b4ae82eef6ad5d507ec3b37765ad190a042a7f | refs/heads/master | 2020-05-17T15:31:26.367578 | 2009-05-29T14:30:06 | 2009-05-29T14:30:06 | 39,530,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,157 | h | /**
Exil library. Simply compose objects from xml and serialize back.
@author James Wynn
@date 4/15/2009
Copyright (c) 2009 James Wynn ([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.
*/
#ifndef _EXIL_DOCUMENT_H_
#define _EXIL_DOCUMENT_H_
#pragma once
#include "Exil.h"
namespace Exil
{
///
/// @class Document
class EXIL_API Document
{
public:
Document();
Document(const String& filename);
~Document();
Element getFirstChild();
void addChild(Element el);
void print();
void save(const String& filename = BLANK_STRING);
void load(const String& filename = BLANK_STRING);
private:
TiXmlDocument* mDoc;
String mFilename;
friend std::ostream EXIL_API &operator<<(std::ostream& os, const Document& doc);
};
/// Output function for Document objects.
/// @param os The stream to which the Document is to be written
/// @param doc The document object being written
/// @return A reference to the stream being passed in
std::ostream EXIL_API &operator<<(std::ostream& os, const Document& doc);
};//namespace Exil
#endif//_EXIL_DOCUMENT_H_
| [
"saintonfire@localhost"
] | [
[
[
1,
66
]
]
] |
4c0ef2ca732c5aecb131350743077120768299f1 | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/refactor/src_root/include/ireon_client/Ogre/paging_landscape/OgrePagingLandScapeTileManager.h | 25f46486ebf50c1a954544c38f9410a0fbb1af65 | [] | no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,234 | h | /***************************************************************************
OgrePagingLandScapeTileManager.h - description
-------------------
begin : Mon Jun 16 2003
copyright : (C) 2003-2005 by Jose A. Milan and Tuan Kuranes
email : [email protected] && [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
#ifndef PAGINGLANDSCAPETILEMANAGER_H
#define PAGINGLANDSCAPETILEMANAGER_H
#include "OgrePagingLandScapePrerequisites.h"
#include "OgreSingleton.h"
#include "OgrePagingLandScapeQueue.h"
namespace Ogre
{
class PagingLandScapeTileManager : public Singleton< PagingLandScapeTileManager >
{
public:
PagingLandScapeTileManager( void );
virtual ~PagingLandScapeTileManager( void );
/** Retrieve a free tile.
*/
PagingLandScapeTile* getTile( void );
/** Make a tile free.
*/
void freeTile( PagingLandScapeTile* tile );
void reset( void );
uint numTiles( void ) const;
int numFree( void ) const;
static PagingLandScapeTileManager& getSingleton( void );
static PagingLandScapeTileManager* getSingletonPtr( void );
void load( void );
void clear( void );
protected:
void _addBatch( const uint num );
PagingLandScapeTileRow mTiles;
PagingLandScapeQueue< PagingLandScapeTile > mQueue;
uint mNumTiles;
};
} //namespace
#endif
| [
"[email protected]"
] | [
[
[
1,
72
]
]
] |
6fd10c2c9c5cb1a078408cd9e1ef02f233cdea92 | 310a6e92333860268302ed1a24163f47211358b4 | /GuiContext.cpp | 45eecb7b731dd55780c56936efc098dd30f69c61 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | bramstein/ui-demo | fde0b03d955146f940ee263281a36f40edce5f15 | 102757bdc3ca99bdda9e7390a67a21a53a04cf1f | refs/heads/master | 2021-01-10T19:23:22.526035 | 2009-11-18T22:11:41 | 2009-11-18T22:11:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,063 | cpp | #include ".\GuiContext.h"
#include ".\includes.h"
namespace demo
{
GuiContext::GuiContext()
: guiInstance(new ui::Gui()),
mainGui(0),
fontFactory(0)
{
// SDL specific stuff
SDL_EnableUNICODE(1);
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
SDL_PumpEvents();
thisFrameIndex = SDL_GetTicks();
lastFrameIndex = thisFrameIndex = 0;
deltaTime = 0;
// OpenGL initialization
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH_TEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glViewport(0,0,800,600);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// create a font factory
fontFactory = new BitmapFontFactory();
// and add it to our Gui instance before anything else..
guiInstance->setFontFactory(fontFactory);
// here we create the main Frame and set it to be visible..
mainGui = new MainGui();
mainGui->show();
// and finally add it to the Gui instance
guiInstance->addFrame(mainGui);
}
GuiContext::~GuiContext()
{
// don't forget to delete our frame and font factory..
delete mainGui;
delete fontFactory;
}
bool GuiContext::isRunning()
{
if(gatherInput())
{
update();
paint();
return true;
}
else
{
return false;
}
}
void GuiContext::paint() const
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// go to ortho
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0,800,600,0);
glMatrixMode(GL_MODELVIEW);
// paint the Gui
guiInstance->paint();
// switch back
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
void GuiContext::update()
{
lastFrameIndex = thisFrameIndex;
thisFrameIndex = SDL_GetTicks();
deltaTime = ((float)(thisFrameIndex-lastFrameIndex))/1000.0f;
// print FPS counter...
char s[8];
sprintf(s,"%3.0ffps", 1/deltaTime);
SDL_WM_SetCaption(s,0);
guiInstance->importUpdate(deltaTime);
}
bool GuiContext::gatherInput() const
{
bool isRunning = true;
SDL_Event event;
int mx, my;
SDL_GetMouseState(&mx,&my);
guiInstance->importMouseMotion(mx,my);
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
{
isRunning = false;
break;
}
case SDL_MOUSEBUTTONUP:
{
guiInstance->importMouseReleased(1);
break;
}
case SDL_MOUSEBUTTONDOWN:
{
guiInstance->importMousePressed(1);
break;
}
case SDL_KEYDOWN:
{
guiInstance->importKeyPressed(event.key.keysym.unicode,event.key.keysym.mod);
break;
}
case SDL_KEYUP:
{
guiInstance->importKeyReleased(event.key.keysym.sym,event.key.keysym.mod);
break;
}
}
}
return isRunning;
}
} | [
"[email protected]"
] | [
[
[
1,
151
]
]
] |
6902bd3bde83f6cfa775ca82dc6d3b406f6de5f9 | 3c582e3e95dc0c4a9613477e7ae1c5307a93ace0 | /cpp/include/Homemade.h | 0c08d64fe6d6edf105456744ab82f774e44a209f | [] | no_license | anat/b429befdb28b97946c1f5f34cf64110f | b4483d718773525009a58dc53c10a00e2c7d00fd | eff1032dbaaa10a486bdf1ac3bccbb7f1001fe87 | refs/heads/master | 2016-09-06T18:06:46.750071 | 2010-12-18T02:08:39 | 2010-12-18T02:08:39 | 32,614,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | h | #ifndef _HOMEMADE_H_
#define _HOMEMADE_H_
#include "IHeuristic.h"
#include <map>
class Homemade : public IHeuristic
{
private:
char _size;
std::map<unsigned char, std::pair<unsigned char, unsigned char> > _helper;
public:
Homemade();
~Homemade(void);
double getH(Node * beforeState, Node* currentState);
void setSolution(Node *solution);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
19
]
]
] |
c2449a9998592a26ba31076c6aabd104c9b10eac | 89d2197ed4531892f005d7ee3804774202b1cb8d | /GWEN/include/Gwen/Controls/ListBox.h | db932c7bc157c178c2396bef687817e5e772ed35 | [
"MIT",
"Zlib"
] | permissive | hpidcock/gbsfml | ef8172b6c62b1c17d71d59aec9a7ff2da0131d23 | e3aa990dff8c6b95aef92bab3e94affb978409f2 | refs/heads/master | 2020-05-30T15:01:19.182234 | 2010-09-29T06:53:53 | 2010-09-29T06:53:53 | 35,650,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | h | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#pragma once
#include "Gwen/Gwen.h"
#include "Gwen/Controls/Layout/Table.h"
#include "Gwen/Controls/ScrollControl.h"
namespace Gwen
{
namespace Controls
{
class ScrollControl;
class GWEN_EXPORT ListBox : public Base
{
public:
GWEN_CONTROL( ListBox, Base );
typedef std::list<Layout::TableRow*> Rows;
Layout::TableRow* AddItem( const String& strLabel, const String& strName = "" );
Layout::TableRow* AddItem( const UnicodeString& strLabel, const String& strName = "" );
void Render( Skin::Base* skin );
void UnselectAll();
void SetColumnCount( int iCount ) { m_Table->SetColumnCount( iCount ); }
void SetAllowMultiSelect( bool bMultiSelect ){ m_bMultiSelect = bMultiSelect; }
bool AllowMultiSelect() const { return m_bMultiSelect; }
const ListBox::Rows& GetSelectedRows(){ return m_SelectedRows; }
Layout::TableRow* GetSelectedRow();
Gwen::Controls::ScrollControl* Scroller() { return m_ScrollControl; }
void OnChildBoundsChanged( Rect oldChildBounds, Base* pChild );
Gwen::Event::Caller onRowSelected;
Controls::Layout::Table* GetTable() { return m_Table; }
virtual void Clear();
protected:
void OnRowSelected( Base* pControl );
Controls::Layout::Table* m_Table;
ListBox::Rows m_SelectedRows;
Controls::ScrollControl* m_ScrollControl;
bool m_bMultiSelect;
};
}
} | [
"haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793"
] | [
[
[
1,
64
]
]
] |
3f7583a8c369b41fd3bc87889eb777b82d35cf83 | 6b55bfd8b659523d1d6b0e25ed12d2f85ea3c4a4 | /mainwidget.h | 7f05157d5921f304e9d05b6412d778640e9d7a2a | [] | no_license | DanielSkalski/majotranslator | 6081f582a7be78ddd4eb6c19c7fd761c20945eda | 8bae420f141beee6d61328c9b5a95947f11f2dd4 | refs/heads/master | 2016-08-13T01:17:39.149053 | 2010-03-13T13:22:25 | 2010-03-13T13:22:25 | 36,719,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | h | #ifndef MAINWIDGET_H
#define MAINWIDGET_H
#include <QWidget>
#include <QTextEdit>
#include <QPushButton>
#include <QCheckBox>
#include "braillewidget.h"
#include "morsewidget.h"
class MainWidget : public QWidget
{
Q_OBJECT
public:
BrailleWidget * brailleWidget;
MorseWidget * morseWidget;
QTextEdit * brailleCode;
QTextEdit * morseCode;
QTextEdit * normalText;
QPushButton * translate;
QCheckBox * morseMode;
MainWidget(QWidget * parent = 0);
public slots:
void updateText( const QString& str );
void changeMorseRep();
void updateText();
};
#endif // MAINWIDGET_H
| [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
9ab014a7bf3cff4509d107223a606e6c759f56d7 | 3464482d0516fe967133bce6e374b4993d426f35 | /CedeCrypt/CedeCrypt/Diagnostics.h | b1111dd8c91e4408b20fa58ea5cd7b2d7b9870e8 | [] | no_license | dannydraper/CedeCryptPortable | 75fc2cc0b17546469b9da7d0e82dcc150c6e24ab | e848915107597d1ada0c7de18a8ede46e9a44de1 | refs/heads/master | 2021-01-09T20:03:52.722661 | 2010-09-27T18:49:42 | 2010-09-27T18:49:42 | 63,583,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,169 | h | #pragma once
#include <windows.h>
#include <io.h>
#include <commctrl.h>
#include "UIWindow.h"
#include "UIHandler.h"
#include "UIBanner.h"
class Diagnostics : public UIWindow
{
public:
Diagnostics ();
~Diagnostics ();
void Initialise (HWND hWnd, LPSTR lpCmdLine);
void ParseCommandLine (char *pszCmdline);
void OutputInt (LPCSTR lpszText, int iValue);
void OutputText (LPCSTR lpszText);
void OutputText (LPCSTR lpszName, LPCSTR lpszValue);
HWND m_hwnddiaglist;
private:
// Private Member Variables & objects
// The UI Handler required for multiple handling of custom controls.
UIHandler m_uihandler;
// The header bitmap image
UIBanner m_header;
// Window controls
bool m_bUsingdiagnostics;
// event notification from base class
void OnCreate (HWND hWnd);
void OnCommand (HWND hWnd, WPARAM wParam, LPARAM lParam);
void OnUICommand (HWND hWnd, WPARAM wParam, LPARAM lParam);
void OnPaint (HWND hWnd);
void OnTimer (WPARAM wParam);
void OnMouseMove (HWND hWnd, int mouseXPos, int mouseYPos);
void OnLButtonDown (HWND hWnd);
void OnLButtonUp (HWND hWnd);
};
| [
"ddraper@06f4e086-0d69-e349-ad0a-cc76533d4475"
] | [
[
[
1,
46
]
]
] |
b255c47b8ec55e3ea28cbd7682c1ec2791992752 | 216ae2fd7cba505c3690eaae33f62882102bd14a | /source/GameMap.h | 9e58c87180743996d65326470d05c1f7bbaa1837 | [] | no_license | TimelineX/balyoz | c154d4de9129a8a366c1b8257169472dc02c5b19 | 5a0f2ee7402a827bbca210d7c7212a2eb698c109 | refs/heads/master | 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | h | #pragma once
#include <OgreVector3.h>
#include <list>
namespace Balyoz
{
class GameObject;
typedef struct _MapGameObject{
public:
_MapGameObject(const std::string &name, const Ogre::Vector3& orient, const Ogre::Vector3& pos )
{
m_GameUnitName = name;
m_Orientation = orient;
m_Position = pos;
}
std::string m_GameUnitName;
Ogre::Vector3 m_Orientation;
Ogre::Vector3 m_Position;
bool operator < (const _MapGameObject& rhs)
{
return m_Position.z < rhs.m_Position.z;
}
}MapGameObject;
class GameMap{
public:
GameMap(const std::string& name = std::string(""));
~GameMap();
std::string m_MapName;
//MapGameObject* getMapObjectByName (const std::string& objName) ;
//MapGameObject* getMapObjectByPosition (const Ogre::Vector3& position) ;
std::list<MapGameObject*>* getAllMapObjects();
public:
std::list<MapGameObject*> *m_pGameObjectList;
};
} | [
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
] | [
[
[
1,
44
]
]
] |
13d30a98bfdad30f3f6eb7709ceddc169b5781d5 | 12203ea9fe0801d613bbb2159d4f69cab3c84816 | /Export/cpp/windows/obj/src/nme/display/MovieClip.cpp | b285f98e4203bc1f1488f82d14ba4bac9b1977ac | [] | no_license | alecmce/haxe_game_of_life | 91b5557132043c6e9526254d17fdd9bcea9c5086 | 35ceb1565e06d12c89481451a7bedbbce20fa871 | refs/heads/master | 2016-09-16T00:47:24.032302 | 2011-10-10T12:38:14 | 2011-10-10T12:38:14 | 2,547,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,971 | cpp | #include <hxcpp.h>
#ifndef INCLUDED_nme_display_DisplayObject
#include <nme/display/DisplayObject.h>
#endif
#ifndef INCLUDED_nme_display_DisplayObjectContainer
#include <nme/display/DisplayObjectContainer.h>
#endif
#ifndef INCLUDED_nme_display_IBitmapDrawable
#include <nme/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_nme_display_InteractiveObject
#include <nme/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_nme_display_MovieClip
#include <nme/display/MovieClip.h>
#endif
#ifndef INCLUDED_nme_display_Sprite
#include <nme/display/Sprite.h>
#endif
#ifndef INCLUDED_nme_events_EventDispatcher
#include <nme/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_nme_events_IEventDispatcher
#include <nme/events/IEventDispatcher.h>
#endif
namespace nme{
namespace display{
Void MovieClip_obj::__construct()
{
{
HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/display/MovieClip.hx",9)
super::__construct();
HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/display/MovieClip.hx",10)
this->mCurrentFrame = (int)0;
HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/display/MovieClip.hx",11)
this->mTotalFrames = (int)0;
}
;
return null();
}
MovieClip_obj::~MovieClip_obj() { }
Dynamic MovieClip_obj::__CreateEmpty() { return new MovieClip_obj; }
hx::ObjectPtr< MovieClip_obj > MovieClip_obj::__new()
{ hx::ObjectPtr< MovieClip_obj > result = new MovieClip_obj();
result->__construct();
return result;}
Dynamic MovieClip_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< MovieClip_obj > result = new MovieClip_obj();
result->__construct();
return result;}
::String MovieClip_obj::nmeGetType( ){
HX_SOURCE_PUSH("MovieClip_obj::nmeGetType")
HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/display/MovieClip.hx",14)
return HX_CSTRING("MovieClip");
}
HX_DEFINE_DYNAMIC_FUNC0(MovieClip_obj,nmeGetType,return )
int MovieClip_obj::GetTotalFrames( ){
HX_SOURCE_PUSH("MovieClip_obj::GetTotalFrames")
HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/display/MovieClip.hx",25)
return this->mTotalFrames;
}
HX_DEFINE_DYNAMIC_FUNC0(MovieClip_obj,GetTotalFrames,return )
int MovieClip_obj::GetCurrentFrame( ){
HX_SOURCE_PUSH("MovieClip_obj::GetCurrentFrame")
HX_SOURCE_POS("C:\\Motion-Twin\\haxe\\dev\\nme/nme/display/MovieClip.hx",26)
return this->mCurrentFrame;
}
HX_DEFINE_DYNAMIC_FUNC0(MovieClip_obj,GetCurrentFrame,return )
Void MovieClip_obj::gotoAndPlay( Dynamic frame,::String scene){
{
HX_SOURCE_PUSH("MovieClip_obj::gotoAndPlay")
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC2(MovieClip_obj,gotoAndPlay,(void))
Void MovieClip_obj::gotoAndStop( Dynamic frame,::String scene){
{
HX_SOURCE_PUSH("MovieClip_obj::gotoAndStop")
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC2(MovieClip_obj,gotoAndStop,(void))
Void MovieClip_obj::play( ){
{
HX_SOURCE_PUSH("MovieClip_obj::play")
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(MovieClip_obj,play,(void))
Void MovieClip_obj::stop( ){
{
HX_SOURCE_PUSH("MovieClip_obj::stop")
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(MovieClip_obj,stop,(void))
MovieClip_obj::MovieClip_obj()
{
}
void MovieClip_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(MovieClip);
HX_MARK_MEMBER_NAME(enabled,"enabled");
HX_MARK_MEMBER_NAME(currentFrame,"currentFrame");
HX_MARK_MEMBER_NAME(framesLoaded,"framesLoaded");
HX_MARK_MEMBER_NAME(totalFrames,"totalFrames");
HX_MARK_MEMBER_NAME(mCurrentFrame,"mCurrentFrame");
HX_MARK_MEMBER_NAME(mTotalFrames,"mTotalFrames");
super::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
Dynamic MovieClip_obj::__Field(const ::String &inName)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"play") ) { return play_dyn(); }
if (HX_FIELD_EQ(inName,"stop") ) { return stop_dyn(); }
break;
case 7:
if (HX_FIELD_EQ(inName,"enabled") ) { return enabled; }
break;
case 10:
if (HX_FIELD_EQ(inName,"nmeGetType") ) { return nmeGetType_dyn(); }
break;
case 11:
if (HX_FIELD_EQ(inName,"totalFrames") ) { return GetTotalFrames(); }
if (HX_FIELD_EQ(inName,"gotoAndPlay") ) { return gotoAndPlay_dyn(); }
if (HX_FIELD_EQ(inName,"gotoAndStop") ) { return gotoAndStop_dyn(); }
break;
case 12:
if (HX_FIELD_EQ(inName,"currentFrame") ) { return GetCurrentFrame(); }
if (HX_FIELD_EQ(inName,"framesLoaded") ) { return GetTotalFrames(); }
if (HX_FIELD_EQ(inName,"mTotalFrames") ) { return mTotalFrames; }
break;
case 13:
if (HX_FIELD_EQ(inName,"mCurrentFrame") ) { return mCurrentFrame; }
break;
case 14:
if (HX_FIELD_EQ(inName,"GetTotalFrames") ) { return GetTotalFrames_dyn(); }
break;
case 15:
if (HX_FIELD_EQ(inName,"GetCurrentFrame") ) { return GetCurrentFrame_dyn(); }
}
return super::__Field(inName);
}
Dynamic MovieClip_obj::__SetField(const ::String &inName,const Dynamic &inValue)
{
switch(inName.length) {
case 7:
if (HX_FIELD_EQ(inName,"enabled") ) { enabled=inValue.Cast< bool >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"totalFrames") ) { totalFrames=inValue.Cast< int >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"currentFrame") ) { currentFrame=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"framesLoaded") ) { framesLoaded=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"mTotalFrames") ) { mTotalFrames=inValue.Cast< int >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"mCurrentFrame") ) { mCurrentFrame=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue);
}
void MovieClip_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_CSTRING("enabled"));
outFields->push(HX_CSTRING("currentFrame"));
outFields->push(HX_CSTRING("framesLoaded"));
outFields->push(HX_CSTRING("totalFrames"));
outFields->push(HX_CSTRING("mCurrentFrame"));
outFields->push(HX_CSTRING("mTotalFrames"));
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
String(null()) };
static ::String sMemberFields[] = {
HX_CSTRING("nmeGetType"),
HX_CSTRING("enabled"),
HX_CSTRING("currentFrame"),
HX_CSTRING("framesLoaded"),
HX_CSTRING("totalFrames"),
HX_CSTRING("mCurrentFrame"),
HX_CSTRING("mTotalFrames"),
HX_CSTRING("GetTotalFrames"),
HX_CSTRING("GetCurrentFrame"),
HX_CSTRING("gotoAndPlay"),
HX_CSTRING("gotoAndStop"),
HX_CSTRING("play"),
HX_CSTRING("stop"),
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
};
Class MovieClip_obj::__mClass;
void MovieClip_obj::__register()
{
Static(__mClass) = hx::RegisterClass(HX_CSTRING("nme.display.MovieClip"), hx::TCanCast< MovieClip_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics);
}
void MovieClip_obj::__boot()
{
}
} // end namespace nme
} // end namespace display
| [
"[email protected]"
] | [
[
[
1,
244
]
]
] |
fa71654e0e99fba7023cfa113453a574d559c3ca | 58ef4939342d5253f6fcb372c56513055d589eb8 | /LemonTangram2/inc/YCSettingContainer.h | 63e1439b5705119e5f7f9ae30f7f13768f03e337 | [] | no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,676 | h | /*
============================================================================
Name : YCSettingContainer.h
Author : zengcity
Version : 1.0
Copyright : Your copyright notice
Description : CYCSettingContainer declaration
============================================================================
*/
#ifndef YCSETTINGCONTAINER_H
#define YCSETTINGCONTAINER_H
// INCLUDES
#include <e32std.h>
#include <e32base.h>
#include <coecntrl.h>
#include <aknsettingitemlist.h>
#include "LemonTangram.hrh"
// CLASS DECLARATION
class CSkinImageScan;
class CConfiguration;
/**
* CYCSettingContainer
*
*/
class CYCSettingContainer : public CCoeControl
{
public:
// Constructors and destructor
~CYCSettingContainer();
CYCSettingContainer();
void ConstructL(const TRect& aRect);
private: // Functions from base classes
//* From CCoeControl
void Draw(const TRect& aRect) const;
TInt CountComponentControls() const;
CCoeControl* ComponentControl(TInt aIndex) const;
TKeyResponse OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType );
private: // New Functions
void LoadListL();
void StoreSettingsL();
void CreateSkinFolderItem(TInt aSettingId);
void CreateSkinChooseItem(TInt aSettingId);
void CreateSaveFolderItem(TInt aSettingId);
void LoadConfigL();
void SaveL();
private: // Data members
CAknSettingItemList* iItemList;
TFileName iSkinFolder;
TInt iSkinChoose;
TFileName iFileSkinChoose;
TFileName iSaveFolder;
CSkinImageScan* iScaner;
CConfiguration* iConfig;
};
#endif // YCSETTINGCONTAINER_H
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] | [
[
[
1,
68
]
]
] |
019be19020ae0ecf72595c06639341e128d329b9 | 5e72c94a4ea92b1037217e31a66e9bfee67f71dd | /older/tptest5/src/ServerListDialog.h | 8e2e9a352bdc7f834f724ff01cfe5333f82ffcef | [] | no_license | stein1/bbk | 1070d2c145e43af02a6df14b6d06d9e8ed85fc8a | 2380fc7a2f5bcc9cb2b54f61e38411468e1a1aa8 | refs/heads/master | 2021-01-17T23:57:37.689787 | 2011-05-04T14:50:01 | 2011-05-04T14:50:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | h | #ifndef __SERVERLISTDIALOG_H
#define __SERVERLISTDIALOG_H
#include "main.h"
#include "AppConfig.h"
enum { wxID_BUTTON_REFRESH_SERVERLIST = wxID_HIGHEST, wxID_BUTTON_CLOSE };
class ServerListDialog : public wxDialog
{
public:
ServerListDialog( wxWindow *parent );
~ServerListDialog(void);
private:
ServerList *m_ServerList;
wxListCtrl *m_ListCtrl;
wxTextCtrl *m_TextCtrlHost;
wxTextCtrl *m_TextCtrlTCPPort;
wxTextCtrl *m_TextCtrlTPTestPort;
wxTextCtrl *m_TextCtrlFTP_Path;
wxTextCtrl *m_TextCtrlHTTP_Path;
wxCheckBox *m_CheckBoxICMP;
wxButton *m_ButtonAdd;
wxButton *m_ButtonUpdate;
wxButton *m_ButtonDelete;
wxButton *m_ButtonRefresh;
wxButton *m_ButtonClose;
wxBoxSizer *m_SizerMain;
wxGridBagSizer *m_SizerEdit;
int m_SelectedIndex;
DECLARE_EVENT_TABLE()
public:
void RefreshServerList(void);
void OnItemSelected(wxListEvent& event);
void OnButtonAdd(wxCommandEvent& event);
void OnButtonUpdate(wxCommandEvent& event);
void OnButtonDelete(wxCommandEvent& event);
void OnButtonRefresh(wxCommandEvent& event);
void OnButtonClose(wxCommandEvent& event);
void RefreshMainWindow(void);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
51
]
]
] |
9f953fc4de439b063355aeda71818ea7fb3120ee | 1b3a26845c00ede008ea66d26f370c3542641f45 | /pymfclib/pymwebprotocol.cpp | 959d63c03e53e02aaaeacd2a8a267721933271a8 | [] | no_license | atsuoishimoto/pymfc | 26617fac259ed0ffd685a038b47702db0bdccd5f | 1341ef3be6ca85ea1fa284689edbba1ac29c72cb | refs/heads/master | 2021-01-01T05:50:51.613190 | 2010-12-29T07:38:01 | 2010-12-29T07:38:01 | 33,760,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,106 | cpp | // Copyright (c) 2001- Atsuo Ishimoto
// See LICENSE for details.
#include "stdafx.h"
#include <urlmon.h>
#include "pymwndbase.h"
#include "pymwnd.h"
#include "pymutils.h"
#include "passthru_app/ProtocolCF.h"
#include "passthru_app/ProtocolImpl.h"
#include "PyMFC_CustomProtocol.h"
class PyMFC_WebProtocolApp;
class PyMFC_WebProtocolSink :
public PassthroughAPP::CInternetProtocolSinkWithSP<PyMFC_WebProtocolSink>
{
typedef PassthroughAPP::CInternetProtocolSinkWithSP<PyMFC_WebProtocolSink> BaseClass;
public:
};
class PyMFC_WebProtocolPolicy:public PassthroughAPP::CustomSinkStartPolicy<PyMFC_WebProtocolApp, PyMFC_WebProtocolSink> {
public:
HRESULT OnStart(LPCWSTR szUrl,
IInternetProtocolSink *pOIProtSink, IInternetBindInfo *pOIBindInfo,
DWORD grfPI, HANDLE_PTR dwReserved,
IInternetProtocol* pTargetProtocol) const;
HRESULT OnStartEx(IUri *pUri,
IInternetProtocolSink *pOIProtSink, IInternetBindInfo *pOIBindInfo,
DWORD grfPI, HANDLE_PTR dwReserved,
IInternetProtocolEx* pTargetProtocol) const;
bool callFilter(LPCWSTR url, std::wstring &newuri) const;
};
class PyMFC_WebProtocolApp:
public PassthroughAPP::CInternetProtocol<PyMFC_WebProtocolPolicy>
{
};
class PyMFCWebProtocol {
public:
struct TypeInstance {
PyObject_HEAD
PyObject *filterfunc;
PyObject *customprotocolfunc;
};
// static IClassFactory *cf_http;
// static IClassFactory *cf_https;
static TypeInstance *webprotocol;
typedef PyDTExtDef<PyMFCWebProtocol> EXTDEF;
static PyTypeObject *getBaseType() {
return NULL;
}
static void initMethods(EXTDEF &def) {
def.setGC(traverse, clear);
def.addKwdArgMethod("register", registerProtocol);
def.addKwdArgMethod("registerCustomProtocol", registerCustomProtocol);
def.addObjMember("filter", offsetof(TypeInstance, filterfunc));
def.addKwdArgMethod("customprotocolfunc", customprotocolfunc);
}
static int onInitObj(TypeInstance *obj, PyObject *args, PyObject *kwds) {
PyMFC_PROLOGUE("PyMFCWebProtocol::onInitObj");
if (webprotocol) {
throw PyDTExc_RuntimeError("WebProtocol instance already exists");
}
obj->filterfunc = NULL;
obj->customprotocolfunc = NULL;
webprotocol = obj;
CPyMFC_CustomProtocol::mapfunc = &(obj->customprotocolfunc);
return 0;
PyMFC_EPILOGUE(-1);
}
static void onDeallocObj(TypeInstance *obj) {
clear(obj);
}
static int traverse(TypeInstance *obj, visitproc visit, void *arg) {
int err = 0;
if (obj->filterfunc) {
err = visit(obj->filterfunc, arg);
if (err) {
return err;
}
}
if (obj->customprotocolfunc) {
err = visit(obj->customprotocolfunc, arg);
if (err) {
return err;
}
}
return err;
}
static int clear(TypeInstance *obj) {
if (obj->filterfunc) {
Py_XDECREF(obj->filterfunc);
obj->filterfunc = NULL;
}
if (obj->customprotocolfunc) {
Py_XDECREF(obj->customprotocolfunc);
obj->customprotocolfunc = NULL;
}
return 0;
}
typedef PassthroughAPP::CMetaFactory<PassthroughAPP::CComClassFactoryProtocol,
PyMFC_WebProtocolApp> MetaFactory;
static PyObject *registerProtocol(TypeInstance *obj, PyObject *args, PyObject *kwds) {
PyMFC_PROLOGUE(PyMFCWebCtrl_registerProtocol)
static char *kwlist[] = {"protocol", "http", "https", NULL};
PyDTUnicode protocol;
int http=0, https=0;
if (!PyArg_ParseTupleAndKeywords(args, kwds,
"O|ii", kwlist, protocol.getBuf(), &http, &https)) {
return NULL;
}
if (http == https) {
throw PyDTExc_InvalidValue("invalid target protocol");
}
CComPtr<IInternetSession> spSession;
HRESULT hr = CoInternetGetSession(0, &spSession, 0);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
CLSID dest;
if (http) {
dest = CLSID_HttpProtocol;
}
else {
dest = CLSID_HttpSProtocol;
}
IClassFactory *cf;
hr = MetaFactory::CreateInstance(dest, &cf);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
hr = spSession->RegisterNameSpace(cf, CLSID_NULL, protocol.asUnicode(), 0, 0, 0);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
PyMFC_RETNONE();
PyMFC_EPILOGUE(0);
}
static PyObject *customprotocolfunc(TypeInstance *obj, PyObject *args, PyObject *kwds) {
PyMFC_PROLOGUE(customprotocolfunc)
static char *kwlist[] = {"protocol", NULL};
PyDTObject f;
if (!PyArg_ParseTupleAndKeywords(args, kwds,
"O", kwlist, f.getBuf())) {
return NULL;
}
if (obj->customprotocolfunc) {
Py_XDECREF(obj->customprotocolfunc);
obj->customprotocolfunc = NULL;
}
if (f.get()) {
f.incRef();
obj->customprotocolfunc = f.detach();
}
PyMFC_RETNONE();
PyMFC_EPILOGUE(0);
}
static PyObject *registerCustomProtocol(TypeInstance *obj, PyObject *args, PyObject *kwds) {
PyMFC_PROLOGUE(registerCustomProtocol)
static char *kwlist[] = {"protocol", NULL};
const char *s;
if (!PyArg_ParseTupleAndKeywords(args, kwds,
"s", kwlist, &s)) {
return NULL;
}
CComPtr<IInternetSession> spSession;
HRESULT hr = CoInternetGetSession(0, &spSession, 0);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
UnicodeStr protocol(s);
/*
IClassFactory *p;
hr = CoGetClassObject(CLSID_PyMFC_CustomProtocol, CLSCTX_INPROC_SERVER, NULL, IID_IClassFactory, (void**)&p);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
*/
CComObject<CPyMFC_CustomProtocolFactory> *cf;
CComObject<CPyMFC_CustomProtocolFactory>::CreateInstance(&cf);
hr = spSession->RegisterNameSpace(cf, CLSID_NULL, protocol.get(), 0, 0, 0);
if (FAILED(hr)) {
throw PyMFC_WIN32ERRCODE(hr);
}
PyMFC_RETNONE();
PyMFC_EPILOGUE(0);
}
static EXTDEF def_webprotocol;
};
PyMFCWebProtocol::TypeInstance *PyMFCWebProtocol::webprotocol = NULL;
PyMFCWebProtocol::EXTDEF PyMFCWebProtocol::def_webprotocol;
HRESULT PyMFC_WebProtocolPolicy::OnStart(LPCWSTR szUrl,
IInternetProtocolSink *pOIProtSink, IInternetBindInfo *pOIBindInfo,
DWORD grfPI, HANDLE_PTR dwReserved,
IInternetProtocol* pTargetProtocol) const {
std::wstring newuri;
if (!callFilter(szUrl, newuri)) {
return INET_E_INVALID_URL;
}
if (newuri.size() && newuri != szUrl) {
szUrl = &(newuri[0]);
}
return PassthroughAPP::CustomSinkStartPolicy<PyMFC_WebProtocolApp, PyMFC_WebProtocolSink>::
OnStart(szUrl, pOIProtSink, pOIBindInfo, grfPI, dwReserved, pTargetProtocol);
}
/*
HRESULT PyMFC_WebProtocolPolicy::OnStartEx(IUri *pUri,
IInternetProtocolSink *pOIProtSink, IInternetBindInfo *pOIBindInfo,
DWORD grfPI, HANDLE_PTR dwReserved,
IInternetProtocolEx* pTargetProtocol) const {
BSTR uri;
HRESULT hr = pUri->GetAbsoluteUri(&uri);
if (FAILED(hr)) {
return hr;
}
std::wstring newuri;
bool ret = callFilter(uri, newuri);
if (uri != newuri) {
// pUri = CreateUri();
}
SysFreeString(uri);
if (!ret) {
return INET_E_INVALID_URL;
}
return PassthroughAPP::CustomSinkStartPolicy<PyMFC_WebProtocolApp, PyMFC_WebProtocolSink>::
OnStartEx(pUri, pOIProtSink, pOIBindInfo, grfPI, dwReserved, pTargetProtocol);
}
*/
bool PyMFC_WebProtocolPolicy::callFilter(LPCWSTR url, std::wstring &newuri) const {
{
PyMFCEnterPython e;
if (!PyMFCWebProtocol::webprotocol) {
return true;
}
if (!PyMFCWebProtocol::webprotocol->filterfunc) {
return true;
}
PyDTObject f(PyMFCWebProtocol::webprotocol->filterfunc, true);
f.incRef();
if (!f.isTrue())
return true;
PyDTUnicode s(url);
try {
PyDTObject ret = f.call("O", s.get());
if (ret.isTrue()) {
if (ret.isUnicode()) {
PyDTUnicode uriobj(ret);
newuri.assign(uriobj.asUnicode());
}
return true;
}
else {
return false;
}
}
catch (PyDTException &exc) {
exc.setError();
PyErr_Print();
return false;
}
}
}
void init_webprotocol(PyObject *module) {
PyDTModule m(module, false);
PyDTRegType(m, "_pymfclib.WebProtocol", "WebProtocol", PyMFCWebProtocol::def_webprotocol);
}
| [
"[email protected]"
] | [
[
[
1,
325
]
]
] |
095f94010c278fcfd1e9f216f04de0d13a5a46c3 | b3b0c727bbafdb33619dedb0b61b6419692e03d3 | /Source/WinHTTPTestUI/WinHTTPLW.h | ffbe462769dc85f5f7893f9ec6acc579d3e2487d | [] | no_license | testzzzz/hwccnet | 5b8fb8be799a42ef84d261e74ee6f91ecba96b1d | 4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113 | refs/heads/master | 2021-01-10T02:59:32.527961 | 2009-11-04T03:39:39 | 2009-11-04T03:39:39 | 45,688,112 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 6,164 | h | //////////////////////////////////////////////////////////
///
/// @file WinHTTPLW.h
///
/// @brief 封装了WinHTTP类、定义了一些错误代码
///
/// @version 1.0
///
/// @author 游枭
///
/// @date 2009-07-24
///
/// <修改日期> <修改者> <修改描述>\n
///
/// 2009-07-28 游枭 增加了UnInitialize,修改了Initialize
/// 2009-07-30 游枭 修改了GetData
///
////////////////////////////////////////////////////////////
#ifndef WINHTTPLW_H
#define WINHTTPLW_H
#include "stdafx.h"
#include <windows.h>
#include <winhttp.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "winhttp.lib")
/// @class WinHTTPLW
/// @brief 封装了WinHTTP,并支持IE代理设置
class WinHTTPLW
{
public:
/// @brief 初始化m_Connect和m_Request
WinHTTPLW();
/// @brief 关闭m_Connect、m_Request
~WinHTTPLW();
////////////////////////////////////////////////////////////
///
/// @brief 为应用程序创建一个会话对象、获取用户IE代理设置
///
/// @note 在应用程序开始时调用
///
/// @param void
///
/// @return HRESULT
///
/// @retval S_OK 正常返回
/// @retval 通过GetLastError()返回
///
////////////////////////////////////////////////////////////
static HRESULT Initialize();
////////////////////////////////////////////////////////////
///
/// @brief 关闭应用程序会话对象,释放一些资源
///
/// @note 在应用程序结束时调用
///
/// @param void
///
/// @return void
///
////////////////////////////////////////////////////////////
static void Uninitialize();
////////////////////////////////////////////////////////////
///
/// @brief 利用应用程序会话创建一个连接对象
///
/// @param __in LPCWSTR pswzServerName 连接的服务器名称
/// @param __in INTERNET_PORT nServerPort 连接的服务器端口号
///
/// @return HRESULT
///
/// @retval S_OK 正常返回
/// @retval E_NOSESSION 会话对象没有创建
/// @retval 通过GetLastError()返回
///
////////////////////////////////////////////////////////////
HRESULT Connect(
__in LPCWSTR pswzServerName,
__in INTERNET_PORT nServerPort = INTERNET_DEFAULT_PORT
);
////////////////////////////////////////////////////////////
///
/// @brief 利用连接对象创建请求对象,并发送请求
///
/// 所有参数均有默认实参,默认情况下能执行最简单的请求操作
///
/// @param __in LPCWSTR pswzVerb 指定HTTP协议动作(GET、POST)
/// @param __in LPCWSTR pswzObjectName 指定正在请求的资源名称和相对路径
/// @param __in_opt LPCWSTR pwszHeaders 包含其他标头
/// @param __in DWORD dwHeadersLength 指定标头的长度
/// @param __in_opt LPVOID lpOptional 包含用作请求的内容或正文的所有数据(通常用于POST请求)
/// @param __in DWORD dwOptionalLength 指定用作请求的内容或正文的所有数据的长度
/// @param __in DWORD dwTotalLength 指定请求内容的总长度。如果此值大于前面参数提供的数据的长度,则使用WinHttpWriteData函数编写其他数据来完成该请求。
///
/// @return HRESULT
///
/// @retval S_OK 正常返回
/// @retval E_NOCONNCET 连接对象没有创建
/// @retval 通过GetLastError()返回
///
////////////////////////////////////////////////////////////
HRESULT Request(
__in LPCWSTR pswzVerb = NULL,
__in LPCWSTR pswzObjectName = NULL,
__in_opt LPCWSTR pwszHeaders = WINHTTP_NO_ADDITIONAL_HEADERS,
__in DWORD dwHeadersLength = -1L,
__in_opt LPVOID lpOptional = WINHTTP_NO_REQUEST_DATA,
__in DWORD dwOptionalLength = 0,
__in DWORD dwTotalLength = 0
);
////////////////////////////////////////////////////////////
///
/// @brief 获取请求到的数据
///
/// @param __out char* buf 输出缓冲区
/// @param __in int bufSize 缓冲区大小
///
/// @return HRESULT
///
/// @retval S_OK 正常返回
/// @retval E_NOREQUEST 请求对象没有创建
/// @retval 通过GetLastError()返回
///
////////////////////////////////////////////////////////////
HRESULT GetData(
__out char* pBuf,
__in int bufSize
);
private:
static WINHTTP_CURRENT_USER_IE_PROXY_CONFIG m_ieProxyConfig; ///< 当前用户的IE代理设置
static WINHTTP_PROXY_INFO m_proxyInfo; ///< 当前代理设置信息
static HINTERNET m_hSession; ///< 会话对象(static保证了应用程序仅存在一个会话对象)
HINTERNET m_hConncet; ///< 连接对象
HINTERNET m_hRequest; ///< 请求对象
};
/// @def E_NOSESSION
/// m_hSession == NULL返回的错误代码
#define E_NOSESSION 0x80010001
/// @def E_NOCONNECT
/// m_hConncet == NULL返回的错误代码
#define E_NOCONNECT 0x80010002
/// @def E_NOREQUEST
/// m_hRequest == NULL返回的错误代码
#define E_NOREQUEST 0x80010003
/// @def E_NOBUFFER
/// 缓冲区没有内存空间返回的错误代码
#define E_NOBUFFER 0x80010004
#endif | [
"[email protected]"
] | [
[
[
1,
161
]
]
] |
90b63f43e1e9fc89af38676a62d89ea612ddfe34 | 04578bbb86e3d7bd68bc207fed2ae35935f21893 | /libXML.h | 2e59efc01e822a1a6085f3d284c2954dd4f67079 | [] | no_license | nicolasrn/pjtalghatnr | eb3e0d4d1c06db4ab01def007d649e9bf8ff4e5d | f9db0cd38e7e5430188fc4b5db3a5318ef430559 | refs/heads/master | 2016-09-05T19:47:15.274945 | 2011-05-13T13:12:22 | 2011-05-13T13:12:22 | 32,201,884 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,626 | h | /**
* \file libXML.h
* \brief librairie des fonctions XML de sauvegarde et chargement
*/
#ifndef LIBXML_H_INCLUDED
#define LIBXML_H_INCLUDED
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <vector>
#include "MyImage.hpp"
#include "tinyxml.h"
using namespace std;
/**
*@param index: index dans le vecteur pour sauvegarder l'image
*@param Balise: Balise mère de l'arborescence de l'image
*@param heightVector : hauteur pour chaque partie enregistrée
*@param widthVector : largeur pour chaque partie enregistrée
*/
void saveTailleImage(int index, TiXmlElement * &Balise, std::vector<int> heightVector, std::vector<int> widthVector);
/**
*@param index: index dans le vecteur pour sauvegarder l'image
*@param Balise: Balise mère de l'arborescence de l'image
*@param Y: quantification pour Y
*@param U: quantification pour U
*@param V : quantification pour V
*@param stratY : stratégie pour Y
*@param stratU : stratégie pour U
*@param stratV : stratégie pour V
*@param height : hauteur pour chaque partie enregistrée
*@param width : largeur pour chaque partie enregistrée
*/
void saveImage(int index, TiXmlElement * &Balise, std::vector<double **> Y, std::vector<double **> U, std::vector<double **> V , std::vector<int **> stratY, std::vector<int **> stratU, std::vector<int **> stratV, int height, int width);
/**
*@param name: Nom du Fichier qu'on enregistre
*@param Y: quantification pour Y
*@param U: quantification pour U
*@param V : quantification pour V
*@param stratY : stratégie pour Y
*@param stratU : stratégie pour U
*@param stratV : stratégie pour V
*@param heightVector : hauteur pour chaque partie enregistrée
*@param widthVector : largeur pour chaque partie enregistrée
*/
void saveXML(const char * name, std::vector<double **> Y, std::vector<double **> U, std::vector<double **> V , std::vector<int **> stratY, std::vector<int **> stratU, std::vector<int **> stratV, std::vector<int> heightVector, std::vector<int> widthVector, int QP);
/**
*@param width: largeur à instancier
*@param height: hauteur à instancier
*/
double ** instanciateTabQuantif(int width, int height);
/**
*@param width: largeur à instancier
*@param height: hauteur à instancier
*/
int ** instanciateTabStrat(int width, int height);
/**
*@param index: index dans le vecteur pour charger l'image
*@param Balise: Balise mère de l'arborescence de l'image
*@param Y: quantification pour Y
*@param U: quantification pour U
*@param V : quantification pour V
*@param stratY : stratégie pour Y
*@param stratU : stratégie pour U
*@param stratV : stratégie pour V
*/
void chargeImage(int index, TiXmlElement * &Balise, std::vector<double **> Y, std::vector<double **> U, std::vector<double **> V , std::vector<int **> stratY, std::vector<int **> stratU, std::vector<int **> stratV);
/**
*@param name: Nom du Fichier qu'on charge
*@param Y: quantification pour Y
*@param U: quantification pour U
*@param V : quantification pour V
*@param stratY : stratégie pour Y
*@param stratU : stratégie pour U
*@param stratV : stratégie pour V
*@param heightVector : hauteur pour chaque partie enregistrée
*@param widthVector : largeur pour chaque partie enregistrée
*/
void loadXML(const char* name, std::vector<double **> &Y, std::vector<double **> &U, std::vector<double **> &V , std::vector<int **> &stratY, std::vector<int **> &stratU, std::vector<int **> &stratV, std::vector<int> &heightVector, std::vector<int> &widthVector, int &QP);
#endif // LIBXML_H_INCLUDED
| [
"[email protected]@7bacfe4a-4d2d-2879-b5fa-80d0502c43e4",
"[email protected]@7bacfe4a-4d2d-2879-b5fa-80d0502c43e4",
"[email protected]@7bacfe4a-4d2d-2879-b5fa-80d0502c43e4"
] | [
[
[
1,
5
],
[
38,
38
],
[
51,
51
],
[
57,
57
],
[
75,
75
],
[
88,
88
]
],
[
[
6,
15
],
[
17,
37
],
[
39,
50
],
[
52,
56
],
[
58,
74
],
[
76,
87
],
[
90,
90
]
],
[
[
16,
16
],
[
89,
89
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.