blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ce7fd87318a671316ae5a7b80d1053af26912aa0
|
d1ce8db98d580f0f17f868ed408edf6d92f9208f
|
/QT/QtOgre/source/GameLogic.cpp
|
405a87eac9eac9675508e077bedd261701b84c7f
|
[] |
no_license
|
babochingu/andrew-phd
|
eed82e7bbd3e2b5b5403c1493e3d36b112b1b007
|
ba94c3961d9dfef041c974e7ed2d9da4eb7d4dd3
|
refs/heads/master
| 2016-09-06T07:18:39.627522 | 2010-10-04T23:54:06 | 2010-10-04T23:54:06 | 33,762,959 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 657 |
cpp
|
#include "GameLogic.h"
namespace QtOgre
{
GameLogic::GameLogic(void)
:mApplication(0)
{
}
void GameLogic::initialise(void)
{
}
void GameLogic::update(void)
{
}
void GameLogic::shutdown(void)
{
}
void GameLogic::onKeyPress(QKeyEvent* event)
{
}
void GameLogic::onKeyRelease(QKeyEvent* event)
{
}
void GameLogic::onMousePress(QMouseEvent* event)
{
}
void GameLogic::onMouseRelease(QMouseEvent* event)
{
}
void GameLogic::onMouseDoubleClick(QMouseEvent* event)
{
}
void GameLogic::onMouseMove(QMouseEvent* event)
{
}
void GameLogic::onWheel(QWheelEvent* event)
{
}
}
|
[
"evertech.andrew@2dccfce6-0550-11df-956f-01f849d29158"
] |
[
[
[
1,
49
]
]
] |
37ad9ba46acf874af2677588f1c35b97a7769d98
|
2982a765bb21c5396587c86ecef8ca5eb100811f
|
/util/wm5/LibCore/ObjectSystems/Wm5OutStream.inl
|
83eeed9b06728b0fa220331172b85a1b3101fbda
|
[] |
no_license
|
evanw/cs224final
|
1a68c6be4cf66a82c991c145bcf140d96af847aa
|
af2af32732535f2f58bf49ecb4615c80f141ea5b
|
refs/heads/master
| 2023-05-30T19:48:26.968407 | 2011-05-10T16:21:37 | 2011-05-10T16:21:37 | 1,653,696 | 27 | 9 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,948 |
inl
|
// Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::Write (T datum)
{
return mTarget.Write(sizeof(T), &datum);
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WriteW (int numElements, const T* data)
{
if (!mTarget.Write(sizeof(int), &numElements))
{
return false;
}
if (numElements > 0)
{
return mTarget.Write(sizeof(T), numElements, data);
}
return true;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WriteN (int numElements, const T* data)
{
if (numElements > 0)
{
return mTarget.Write(sizeof(T), numElements, data);
}
return true;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WriteEnum (const T datum)
{
int value = (int)datum;
return mTarget.Write(sizeof(int), &value);
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WriteEnumW (int numElements, const T* data)
{
if (!mTarget.Write(sizeof(T), &numElements))
{
return false;
}
if (numElements > 0)
{
for (int i = 0; i < numElements; ++i)
{
if (!WriteEnum(data[i]))
{
return false;
}
}
}
return true;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WriteEnumN (int numElements, const T* data)
{
if (numElements > 0)
{
for (int i = 0; i < numElements; ++i)
{
if (!WriteEnum(data[i]))
{
return false;
}
}
}
return true;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WritePointer (const T* object)
{
RegisterMap::iterator iter = mRegistered.find(object);
if (iter != mRegistered.end())
{
unsigned int uniqueID = iter->second;
mTarget.Write(sizeof(unsigned int), &uniqueID);
return true;
}
return false;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WritePointerW (int numElements, T* const* objects)
{
if (!mTarget.Write(sizeof(int), &numElements))
{
return false;
}
if (numElements > 0)
{
for (int i = 0; i < numElements; ++i)
{
if (!WritePointer(objects[i]))
{
return false;
}
}
}
return true;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WritePointerN (int numElements, T* const* objects)
{
if (numElements > 0)
{
for (int i = 0; i < numElements; ++i)
{
if (!WritePointer(objects[i]))
{
return false;
}
}
}
return true;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WritePointer (const Pointer0<T>& object)
{
RegisterMap::iterator iter = mRegistered.find(object);
if (iter != mRegistered.end())
{
unsigned int uniqueID = iter->second;
mTarget.Write(sizeof(unsigned int), &uniqueID);
return true;
}
return false;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WritePointerW (int numElements, const Pointer0<T>* objects)
{
if (!mTarget.Write(sizeof(int), &numElements))
{
return false;
}
if (numElements > 0)
{
for (int i = 0; i < numElements; ++i)
{
if (!WritePointer(objects[i]))
{
return false;
}
}
}
return true;
}
//----------------------------------------------------------------------------
template <typename T>
bool OutStream::WritePointerN (int numElements, const Pointer0<T>* objects)
{
if (numElements > 0)
{
for (int i = 0; i < numElements; ++i)
{
if (!WritePointer(objects[i]))
{
return false;
}
}
}
return true;
}
//----------------------------------------------------------------------------
template <typename T>
void OutStream::Register (const T* object)
{
if (object)
{
object->Register(*this);
}
}
//----------------------------------------------------------------------------
template <typename T>
void OutStream::Register (int numElements, T* const* objects)
{
for (int i = 0; i < numElements; ++i)
{
Register(objects[i]);
}
}
//----------------------------------------------------------------------------
template <typename T>
void OutStream::Register (const Pointer0<T>& object)
{
if (object)
{
object->Register(*this);
}
}
//----------------------------------------------------------------------------
template <typename T>
void OutStream::Register (int numElements, Pointer0<T> const* objects)
{
for (int i = 0; i < numElements; ++i)
{
Register(objects[i]);
}
}
//----------------------------------------------------------------------------
|
[
"[email protected]"
] |
[
[
[
1,
220
]
]
] |
e41272aad4bb566b06ccc25471e9d5c12492bda5
|
777399eafeb952743fcb973fbba392842c2e9b14
|
/CyberneticWarrior/CyberneticWarrior/source/CPickUp.cpp
|
a4b252c8b5f8dc10dbeafd5d8446709a3649b81f
|
[] |
no_license
|
Warbeleth/cyberneticwarrior
|
7c0af33ada4d461b90dc843c6a25cd5dc2ba056a
|
21959c93d638b5bc8a881f75119d33d5708a3ea9
|
refs/heads/master
| 2021-01-10T14:31:27.017284 | 2010-11-23T23:16:28 | 2010-11-23T23:16:28 | 53,352,209 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,272 |
cpp
|
#include "PrecompiledHeader.h"
#include "CPickUp.h"
CPickUp::CPickUp(void)
{
this->SetPosX(0.0f);
this->SetPosY(0.0f);
this->SetWidth(0);
this->SetHeight(0);
this->SetType(OBJ_PICKUP);
this->SetPickUpType(GRAPPLING_HOOK);
bOn = 1;
}
CPickUp::~CPickUp(void)
{
CSGD_TextureManager::GetInstance()->UnloadTexture(this->GetImageID());
}
void CPickUp::Update(float fElapsedTime)
{
CBase::Update(fElapsedTime);
}
void CPickUp::Render(void)
{
if(bOn)
CSGD_TextureManager::GetInstance()->Draw(this->GetImageID(),
(int)((this->GetPosX() - CCamera::GetInstance()->GetOffsetX()) * CCamera::GetInstance()->GetScale()),
(int)((this->GetPosY() - CCamera::GetInstance()->GetOffsetY()) * CCamera::GetInstance()->GetScale()),
1.0f * CCamera::GetInstance()->GetScale(), 1.0f * CCamera::GetInstance()->GetScale());
}
bool CPickUp::CheckCollision(CBase* pBase)
{
RECT rIntersect;
if(IntersectRect(&rIntersect, &this->GetRect(), &(pBase->GetRect())))
{
if(pBase->GetType() == OBJ_PLAYER)
{
bOn = 0;
//delete this;
}
return 1;
}
else
{
return 0;
}
return 0;
}
int CPickUp::GetPickUpType(void) {return this->m_nPickUpType;}
void CPickUp::SetPickUpType(int nType) {this->m_nPickUpType = nType;}
|
[
"atmuccio@d49f6b0b-9fae-41b6-31ce-67b77e794db9",
"[email protected]",
"[email protected]"
] |
[
[
[
1,
1
],
[
3,
3
]
],
[
[
2,
2
],
[
4,
28
],
[
33,
56
]
],
[
[
29,
32
]
]
] |
18efc4e44afeaa027dd7ef8595957d2dd58acb7d
|
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
|
/fbide-vs/Sdk/Version.cpp
|
51cff00c421a2f3ac24a5e53f83b262d0569aa97
|
[] |
no_license
|
albeva/fbide-old-svn
|
4add934982ce1ce95960c9b3859aeaf22477f10b
|
bde1e72e7e182fabc89452738f7655e3307296f4
|
refs/heads/master
| 2021-01-13T10:22:25.921182 | 2009-11-19T16:50:48 | 2009-11-19T16:50:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 802 |
cpp
|
/*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde 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 FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Albert Varaksin <[email protected]>
* Copyright (C) The FBIde development team
*/
#include "sdk_pch.h"
|
[
"vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7"
] |
[
[
[
1,
20
]
]
] |
ab49db8afb0d2d46f1e41fb3c37f513f6585b635
|
814b49df11675ac3664ac0198048961b5306e1c5
|
/Code/Engine/GUI/include/Button.h
|
280703c832616eef6603cc0822ddbee6675f767d
|
[] |
no_license
|
Atridas/biogame
|
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
|
3b8e95b215da4d51ab856b4701c12e077cbd2587
|
refs/heads/master
| 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,341 |
h
|
//----------------------------------------------------------------------------------
// CButton class
// Author: Enric Vergara
//
// Description:
// A button is typically used when you want an immediate action to occur when the user presses the button.
// An example might be a button to quit the application.
//----------------------------------------------------------------------------------
#pragma once
#ifndef INC_BUTTON_H
#define INC_BUTTON_H
#include <string>
#include "GuiElement.h"
#include "base.h"
//---Forward Declarations---
class CTexture;
//--------------------------
class CButton: public CGuiElement
{
private:
typedef enum EButtonState { BS_NORMAL, BS_OVER, BS_CLICKED };
public:
CButton( uint32 windowsHeight, uint32 windowsWidth, float height_precent, float witdh_percent,
const Vect2f position_percent, std::string lit="", uint32 textHeightOffset=0,
uint32 textWidthOffsetbool=0, bool isVisible = true, bool isActive = true);
virtual ~CButton() {/*NOTHING*/;}
//---------------CGuiElement Interface----------------------
virtual void Render (CRenderManager *renderManager, CFontManager* fm);
virtual void Update (CInputManager* intputManager, float elapsedTime);
virtual void OnClickedChild (const std::string& name) {/*NOTHING*/;}
//---------------CButton Interface----------------------
void SetTextures (CTexture* normal, CTexture* over, CTexture* clicked, CTexture* deactivated);
void SetLiteral (const std::string& lit) {m_sLiteral = lit;}
void SetColors (const CColor& normal, const CColor& over, const CColor& clicked, const CColor& deactivated, float alpha = 1.f);
void OnOverButton ();
void OnClickedButton ();
bool IsClicking () const {return (m_eState == BS_CLICKED);}
void SetOnClickedAction (std::string & inAction );
void SetOnOverAction (std::string & inAction );
private:
EButtonState m_eState;
std::string m_sLuaCode_OnClicked;
std::string m_sLuaCode_OnOver;
CTexture* m_pNormalTexture;
CTexture* m_pOverTexture;
CTexture* m_pClickedTexture;
CTexture* m_pDeactivatedTexture;
CColor m_NormalColor;
CColor m_OverColor;
CColor m_ClickedColor;
CColor m_DeactivatedColor;
};
#endif //INC_BUTTON_H
|
[
"atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
] |
[
[
[
1,
65
]
]
] |
202adbae38b879cb331697b6a28ba8a0f48e7e14
|
8a3fce9fb893696b8e408703b62fa452feec65c5
|
/业余时间学习笔记/type.cpp
|
bb928d56f9745b143056d7b643a9955dcece9c76
|
[] |
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 |
UTF-8
|
C++
| false | false | 621 |
cpp
|
#include <iostream>
#include <string>
using namespace std;
template < typename T>
struct Type2Type
{
typedef T type;
};
class Widget
{
public:
Widget(string str,int n)
{
std::cout << str.c_str() <<" " << n << std::endl;
}
};
template < typename U , typename T >
T* Create(const U& arg, Type2Type<T> )
{
std::cout << " arg "<< arg << std::endl;
return new T( arg );
}
template < typename U >
Widget* Create(const U& arg,Type2Type<Widget>)
{
return new Widget(arg,-1);
}
int main()
{
string* p = Create("string",Type2Type<string>());
getchar();
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
39
]
]
] |
38b403cd88f76027d16ad93684dc5a7b2ec475f6
|
c0306fde9637b5398f3d64c1564051f5bdca4f76
|
/屏幕取词程序VC源码/Demo/nhdemoDlg.cpp
|
d2ec40fd52ec11078635a5429afd892d19f655cb
|
[] |
no_license
|
zbbfreedom/uiafproject
|
45583e5f4f97888142f9e0bb07b89df2d1d32113
|
967bb9aadd88b9de14516b1abc2ade961ea94757
|
refs/heads/master
| 2021-01-20T13:47:20.456973 | 2009-12-02T04:27:59 | 2009-12-02T04:27:59 | 40,394,388 | 1 | 2 | null | null | null | null |
WINDOWS-1252
|
C++
| false | false | 4,782 |
cpp
|
// nhdemoDlg.cpp : implementation file
//
#include "stdafx.h"
#include "nhdemo.h"
#include "nhdemoDlg.h"
#include "getwords.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern POINT g_ptMousePos;
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CNhdemoDlg dialog
CNhdemoDlg::CNhdemoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CNhdemoDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CNhdemoDlg)
m_szWords = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CNhdemoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CNhdemoDlg)
DDX_Text(pDX, IDC_EDIT1, m_szWords);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CNhdemoDlg, CDialog)
//{{AFX_MSG_MAP(CNhdemoDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_MESSAGE(NHD_WM_GETWORD_OK, OnGetWordsOK)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CNhdemoDlg message handlers
BOOL CNhdemoDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
HINSTANCE hInst = AfxGetInstanceHandle();
HWND hWnd = GetSafeHwnd();
//¼ÓÔØNHW32.DLL£¬²¢³õʼ»¯
if (!NHD_InitGetWords(hInst, hWnd))
{
AfxMessageBox("Load DLL For Init NHD_InitGetWords error.");
return FALSE;
}
return TRUE; // return TRUE unless you set the focus to a control
}
void CNhdemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CNhdemoDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CNhdemoDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
BOOL CNhdemoDlg::DestroyWindow()
{
// TODO: Add your specialized code here and/or call the base class
NHD_ExitGetWords();
return CDialog::DestroyWindow();
}
LRESULT CNhdemoDlg::OnGetWordsOK(UINT wParam, LONG lParam)
{
char szBuffer[256];
if(NHD_CopyWordsTo(szBuffer, sizeof(szBuffer)))
{
m_szWords = CString(szBuffer);
UpdateData(FALSE);
}
return 0;
}
|
[
"lvjinming@f531bc94-ccfd-11de-b15d-2770122ffd34"
] |
[
[
[
1,
205
]
]
] |
c5e6f43048e512f222bf7e741e5bb9e4acbe271f
|
974a20e0f85d6ac74c6d7e16be463565c637d135
|
/trunk/coreLibrary_300/source/physics/dgWorldDynamicsParallelSolver.cpp
|
6fad32af789cdaf0abf536e55add3637fcc05c51
|
[] |
no_license
|
Naddiseo/Newton-Dynamics-fork
|
cb0b8429943b9faca9a83126280aa4f2e6944f7f
|
91ac59c9687258c3e653f592c32a57b61dc62fb6
|
refs/heads/master
| 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 27,190 |
cpp
|
/* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "dgPhysicsStdafx.h"
#include "dgBody.h"
#include "dgWorld.h"
#include "dgConstraint.h"
#include "dgWorldDynamicUpdate.h"
#define DG_MAX_PASSES 64
class dgCalculateForceLocks
{
public:
dgInt32 m_jointAccelerationSync;
dgInt32 m_bodyVelocityAtomicSync;
dgInt32 m_bodyVelocityAtomicIndex;
dgInt32 m_jointAccelerationAtomicIndex;
dgInt32 m_JointForceSync[DG_MAX_PASSES];
dgInt32 m_JointForceAtomicIndex[DG_MAX_PASSES];
};
class dgParallelSolverSyncData
{
public:
dgParallelSolverSyncData()
{
memset (this, 0, sizeof (dgParallelSolverSyncData));
}
dgWorld* m_world;
dgFloat32 m_timestep;
dgInt32 m_bodyCount;
dgInt32 m_jointCount;
dgInt32 m_initBodiesSync;
dgInt32 m_initBodiesCounter;
dgInt32 m_initJacobianMatrixSync;
dgInt32 m_initJacobianMatrixCounter;
dgInt32 m_jacobianMatrixRowIndexCounter;
dgInt32 m_initIntenalForceAccumulatorSync;
dgInt32 m_initIntenalForceAccumulatorCounter;
dgInt32 m_saveForcefeebackSync;
dgInt32 m_saveForcefeebackCounter;
dgInt32 m_updateForcefeebackSync;
dgInt32 m_updateForcefeebackCounter;
dgInt32 m_updateBodyVelocitySync;
dgInt32 m_updateBodyVelocityCounter;
dgInt32 m_subStepLocks;
dgInt32 m_calculateInternalForcesSync;
dgInt32* m_bodyInfoMap;
dgInt32* m_jointInfoMap;
dgFloat32 m_accNorm[DG_MAX_THREADS_HIVE_COUNT];
dgInt32 m_hasJointFeeback[DG_MAX_THREADS_HIVE_COUNT];
dgCalculateForceLocks m_calculateForcesLock[LINEAR_SOLVER_SUB_STEPS];
};
void dgWorldDynamicUpdate::CalculateReactionForcesParallel (const dgIsland* const islandArray, dgInt32 islandsCount, dgFloat32 timestep) const
{
// dgInt32 rowBase = BuildJacobianMatrix (island, threadID, timestep);
// CalculateReactionsForces (island, rowBase, threadID, timestep, DG_SOLVER_MAX_ERROR);
// IntegrateArray (island, DG_SOLVER_MAX_ERROR, timestep, threadID, true);
dgWorld* const world = (dgWorld*) this;
world->m_pairMemoryBuffer.ExpandCapacityIfNeessesary ((m_bodies + m_joints + 1024), sizeof (dgInt32));
dgInt32* const bodyInfoMap = (dgInt32*) &world->m_pairMemoryBuffer[0];
dgInt32* const jointInfoMap = &bodyInfoMap[(m_bodies + 15) & (-16)];
dgJacobian* const internalVeloc = &world->m_solverMemory.m_internalVeloc[0];
dgJacobian* const internalForces = &world->m_solverMemory.m_internalForces[0];
dgVector zero(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));
internalVeloc[0].m_linear = zero;
internalVeloc[0].m_angular = zero;
internalForces[0].m_linear = zero;
internalForces[0].m_angular = zero;
dgInt32 bodyCount = 0;
dgBodyInfo* const bodyArray = (dgBodyInfo*) &world->m_bodiesMemory[0];
for (dgInt32 i = 0; i < islandsCount; i ++) {
dgInt32 count = islandArray[i].m_bodyCount;
dgInt32 bodyStart = islandArray[i].m_bodyStart;
for (dgInt32 j = 1; j < count; j ++) {
dgInt32 index = bodyStart + j;
bodyInfoMap[bodyCount] = index;
dgBody* const body = bodyArray[index].m_body;
body->m_index = index;
_ASSERTE (bodyCount <= m_bodies);
bodyCount ++;
}
}
dgInt32 jointsCount = 0;
dgInt32 maxRowCount = islandsCount ? islandArray[0].m_jointCount : 0;
dgJointInfo* const constraintArray = (dgJointInfo*) &world->m_jointsMemory[0];
for (dgInt32 jointIndex = 0; jointIndex < maxRowCount; jointIndex ++) {
for (dgInt32 i = 0; (i < islandsCount) && (jointIndex < islandArray[i].m_jointCount); i ++) {
dgInt32 index = islandArray[i].m_jointStart + jointIndex;
jointInfoMap[jointsCount] = index;
dgConstraint* const joint = constraintArray[index].m_joint;
joint->m_index = dgUnsigned32 (jointsCount);
jointsCount ++;
_ASSERTE (jointsCount <= m_joints);
}
}
dgParallelSolverSyncData sincksPoints;
sincksPoints.m_world = world;
sincksPoints.m_timestep = timestep;
// void* userParamArray[DG_MAX_THREADS_HIVE_PARAMETERS];
// userParamArray[0] = &sincksPoints;
sincksPoints.m_bodyCount = bodyCount;
sincksPoints.m_jointCount = jointsCount;
sincksPoints.m_bodyInfoMap = bodyInfoMap;
sincksPoints.m_jointInfoMap = jointInfoMap;
dgInt32 threadCounts = world->GetThreadCount();
for (dgInt32 i = 0; i < threadCounts; i ++) {
//world->QueueJob (ParallelSolverDriver, &userParamArray[0], 1);
world->QueueJob (ParallelSolverDriver, &sincksPoints);
}
world->SynchronizationBarrier();
}
void dgWorldDynamicUpdate::ParallelSolverDriver (void* const userParamArray, dgInt32 threadID)
{
dgParallelSolverSyncData* const data = (dgParallelSolverSyncData*) userParamArray;
dgWorld* const world = data->m_world;
world->InitilizeBodyArrayParallel (data, threadID);
world->BuildJacobianMatrixParallel (data, threadID);
world->SolverInitInternalForcesParallel (data, threadID);
world->CalculateForcesGameModeParallel (data, threadID);
}
void dgWorldDynamicUpdate::GetJacobianDerivativesParallel (dgJointInfo* const jointInfo, dgInt32 threadIndex, bool bitMode, dgInt32 rowBase, dgFloat32 timestep) const
{
dgWorld* const world = (dgWorld*) this;
dgContraintDescritor constraintParams;
constraintParams.m_world = world;
constraintParams.m_threadIndex = threadIndex;
constraintParams.m_timestep = timestep;
constraintParams.m_invTimestep = dgFloat32 (1.0f / timestep);
dgJacobianMatrixElement* const matrixRow = &m_solverMemory.m_memory[rowBase];
dgConstraint* const constraint = jointInfo->m_joint;
dgInt32 dof = dgInt32 (constraint->m_maxDOF);
_ASSERTE (dof <= DG_CONSTRAINT_MAX_ROWS);
for (dgInt32 i = 0; i < dof; i ++) {
constraintParams.m_forceBounds[i].m_low = DG_MIN_BOUND;
constraintParams.m_forceBounds[i].m_upper = DG_MAX_BOUND;
constraintParams.m_forceBounds[i].m_jointForce = NULL;
constraintParams.m_forceBounds[i].m_normalIndex = DG_BILATERAL_CONSTRAINT;
}
_ASSERTE (constraint->m_body0);
_ASSERTE (constraint->m_body1);
constraint->m_body0->m_inCallback = true;
constraint->m_body1->m_inCallback = true;
dof = dgInt32 (constraint->JacobianDerivative (constraintParams));
constraint->m_body0->m_inCallback = false;
constraint->m_body1->m_inCallback = false;
dgInt32 m0 = (constraint->m_body0->m_invMass.m_w != dgFloat32(0.0f)) ? constraint->m_body0->m_index: 0;
dgInt32 m1 = (constraint->m_body1->m_invMass.m_w != dgFloat32(0.0f)) ? constraint->m_body1->m_index: 0;
//_ASSERTE (constraint->m_index == dgUnsigned32(j));
//constraint->m_index = j;
jointInfo->m_autoPairstart = rowBase;
jointInfo->m_autoPaircount = dof;
jointInfo->m_autoPairActiveCount = dof;
jointInfo->m_m0 = m0;
jointInfo->m_m1 = m1;
// dgInt32 fistForceOffset = -rowBase;
for (dgInt32 i = 0; i < dof; i ++) {
dgJacobianMatrixElement* const row = &matrixRow[i];
_ASSERTE (constraintParams.m_forceBounds[i].m_jointForce);
row->m_Jt = constraintParams.m_jacobian[i];
_ASSERTE (constraintParams.m_jointStiffness[i] >= dgFloat32(0.1f));
_ASSERTE (constraintParams.m_jointStiffness[i] <= dgFloat32(100.0f));
row->m_diagDamp = constraintParams.m_jointStiffness[i];
row->m_coordenateAccel = constraintParams.m_jointAccel[i];
row->m_accelIsMotor = constraintParams.m_isMotor[i];
row->m_restitution = constraintParams.m_restitution[i];
row->m_penetration = constraintParams.m_penetration[i];
row->m_penetrationStiffness = constraintParams.m_penetrationStiffness[i];
row->m_lowerBoundFrictionCoefficent = constraintParams.m_forceBounds[i].m_low;
row->m_upperBoundFrictionCoefficent = constraintParams.m_forceBounds[i].m_upper;
row->m_jointFeebackForce = constraintParams.m_forceBounds[i].m_jointForce;
dgInt32 index = constraintParams.m_forceBounds[i].m_normalIndex ;
//normalForceIndex[rowCount] = constraintParams.m_forceBounds[i].m_normalIndex + ((constraintParams.m_forceBounds[i].m_normalIndex >=0) ? (rowCount - i) : fistForceOffset);
//row->m_normalForceIndex = index + ((index >=0) ? (rowCount - i) : fistForceOffset);
row->m_normalForceIndex = (index >=0) ? (index + rowBase) : index;
// rowCount ++;
}
//#ifdef _DEBUG
#if 0
for (dgInt32 i = 0; i < ((rowCount + 3) & 0xfffc) - rowCount ; i ++) {
matrixRow[rowCount + i].m_diagDamp = dgFloat32 (0.0f);
matrixRow[rowCount + i].m_coordenateAccel = dgFloat32 (0.0f);
matrixRow[rowCount + i].m_restitution = dgFloat32 (0.0f);
matrixRow[rowCount + i].m_penetration = dgFloat32 (0.0f);
matrixRow[rowCount + i].m_penetrationStiffness = dgFloat32 (0.0f);
matrixRow[rowCount + i].m_lowerBoundFrictionCoefficent = dgFloat32 (0.0f);
matrixRow[rowCount + i].m_upperBoundFrictionCoefficent = dgFloat32 (0.0f);
matrixRow[rowCount + i].m_jointFeebackForce = 0;
matrixRow[rowCount + i].m_normalForceIndex = 0;
}
#endif
// rowCount = (rowCount & (DG_SIMD_WORD_SIZE - 1)) ? ((rowCount & (-DG_SIMD_WORD_SIZE)) + DG_SIMD_WORD_SIZE) : rowCount;
// _ASSERTE ((rowCount & (DG_SIMD_WORD_SIZE - 1)) == 0);
// return rowCount;
}
void dgWorldDynamicUpdate::InitilizeBodyArrayParallel (dgParallelSolverSyncData* const syncData, dgInt32 threadIndex) const
{
dgWorld* const world = (dgWorld*)this;
dgInt32* const atomicIndex = &syncData->m_initBodiesCounter;
const dgInt32* const bodyInfoIndexArray = syncData->m_bodyInfoMap;
dgBodyInfo* const bodyArray = (dgBodyInfo*) &world->m_bodiesMemory[0];
dgJacobian* const internalVeloc = &world->m_solverMemory.m_internalVeloc[0];
dgJacobian* const internalForces = &world->m_solverMemory.m_internalForces[0];
dgVector zero(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));
for (dgInt32 i = dgAtomicAdd(atomicIndex, 1); i < syncData->m_bodyCount; i = dgAtomicAdd(atomicIndex, 1)) {
_ASSERTE ((bodyArray[0].m_body->m_accel % bodyArray[0].m_body->m_accel) == dgFloat32 (0.0f));
_ASSERTE ((bodyArray[0].m_body->m_alpha % bodyArray[0].m_body->m_alpha) == dgFloat32 (0.0f));
dgInt32 index = bodyInfoIndexArray[i];
_ASSERTE (index);
dgBody* const body = bodyArray[index].m_body;
_ASSERTE (body->m_invMass.m_w > dgFloat32 (0.0f));
body->AddDamingAcceleration();
body->CalcInvInertiaMatrix ();
body->m_netForce = body->m_veloc;
body->m_netTorque = body->m_omega;
internalVeloc[index].m_linear = zero;
internalVeloc[index].m_angular = zero;
internalForces[index].m_linear = zero;
internalForces[index].m_angular = zero;
}
world->SyncThreads(&syncData->m_initBodiesSync);
}
void dgWorldDynamicUpdate::BuildJacobianMatrixParallel (dgParallelSolverSyncData* const syncData, dgInt32 threadIndex) const
{
dgWorld* const world = (dgWorld*) this;
const dgInt32* const jointInfoIndexArray = syncData->m_jointInfoMap;
dgInt32* const atomicIndex = &syncData->m_initJacobianMatrixCounter;
dgBodyInfo* const bodyArray = (dgBodyInfo*) &world->m_bodiesMemory[0];
dgJointInfo* const constraintArray = (dgJointInfo*) &world->m_jointsMemory[0];
dgJacobianMatrixElement* const matrixRow = &m_solverMemory.m_memory[0];
for (dgInt32 i = dgAtomicAdd(atomicIndex, 1); i < syncData->m_jointCount; i = dgAtomicAdd(atomicIndex, 1)) {
dgInt32 jointIndex = jointInfoIndexArray[i];
dgJointInfo* const jointInfo = &constraintArray[jointIndex];
_ASSERTE (dgInt32 (jointInfo->m_joint->m_index) == i);
dgInt32 rowBase = dgAtomicAdd(&syncData->m_jacobianMatrixRowIndexCounter, jointInfo->m_autoPaircount);
// if (island->m_hasUnilateralJoints) {
// rowCount = GetJacobianDerivatives (island, threadIndex, false, rowBase, rowCount, timestep);
// }
// rowCount = GetJacobianDerivatives (island, threadIndex, true, rowBase, rowCount, timestep);
GetJacobianDerivativesParallel (jointInfo, threadIndex, false, rowBase, syncData->m_timestep);
dgInt32 index = jointInfo->m_autoPairstart;
dgInt32 count = jointInfo->m_autoPaircount;
dgInt32 m0 = jointInfo->m_m0;
dgInt32 m1 = jointInfo->m_m1;
//_ASSERTE (m0 >= 0);
//_ASSERTE (m0 < bodyCount);
dgBody* const body0 = bodyArray[m0].m_body;
dgFloat32 invMass0 = body0->m_invMass[3];
const dgMatrix& invInertia0 = body0->m_invWorldInertiaMatrix;
//_ASSERTE (m1 >= 0);
//_ASSERTE (m1 < bodyCount);
dgBody* const body1 = bodyArray[m1].m_body;
dgFloat32 invMass1 = body1->m_invMass[3];
const dgMatrix& invInertia1 = body1->m_invWorldInertiaMatrix;
for (dgInt32 i = 0; i < count; i ++) {
dgJacobianMatrixElement* const row = &matrixRow[index];
row->m_JMinv.m_jacobian_IM0.m_linear = row->m_Jt.m_jacobian_IM0.m_linear.Scale (invMass0);
row->m_JMinv.m_jacobian_IM0.m_angular = invInertia0.UnrotateVector (row->m_Jt.m_jacobian_IM0.m_angular);
dgVector tmpDiag (row->m_JMinv.m_jacobian_IM0.m_linear.CompProduct(row->m_Jt.m_jacobian_IM0.m_linear));
tmpDiag += row->m_JMinv.m_jacobian_IM0.m_angular.CompProduct(row->m_Jt.m_jacobian_IM0.m_angular);
dgVector tmpAccel (row->m_JMinv.m_jacobian_IM0.m_linear.CompProduct(body0->m_accel));
tmpAccel += row->m_JMinv.m_jacobian_IM0.m_angular.CompProduct(body0->m_alpha);
row->m_JMinv.m_jacobian_IM1.m_linear = row->m_Jt.m_jacobian_IM1.m_linear.Scale (invMass1);
row->m_JMinv.m_jacobian_IM1.m_angular = invInertia1.UnrotateVector (row->m_Jt.m_jacobian_IM1.m_angular);
tmpDiag += row->m_JMinv.m_jacobian_IM1.m_linear.CompProduct(row->m_Jt.m_jacobian_IM1.m_linear);
tmpDiag += row->m_JMinv.m_jacobian_IM1.m_angular.CompProduct(row->m_Jt.m_jacobian_IM1.m_angular);
tmpAccel += row->m_JMinv.m_jacobian_IM1.m_linear.CompProduct(body1->m_accel);
tmpAccel += row->m_JMinv.m_jacobian_IM1.m_angular.CompProduct(body1->m_alpha);
dgFloat32 extenalAcceleration = -(tmpAccel.m_x + tmpAccel.m_y + tmpAccel.m_z);
//row->m_extAccel = extenalAcceleration;
row->m_deltaAccel = extenalAcceleration;
row->m_coordenateAccel += extenalAcceleration;
row->m_force = row->m_jointFeebackForce[0];
//force[index] = 0.0f;
_ASSERTE (row->m_diagDamp >= dgFloat32(0.1f));
_ASSERTE (row->m_diagDamp <= dgFloat32(100.0f));
dgFloat32 stiffness = DG_PSD_DAMP_TOL * row->m_diagDamp;
dgFloat32 diag = (tmpDiag.m_x + tmpDiag.m_y + tmpDiag.m_z);
_ASSERTE (diag > dgFloat32 (0.0f));
row->m_diagDamp = diag * stiffness;
diag *= (dgFloat32(1.0f) + stiffness);
//solverMemory.m_diagJMinvJt[index] = diag;
row->m_invDJMinvJt = dgFloat32(1.0f) / diag;
index ++;
}
}
world->SyncThreads(&syncData->m_initJacobianMatrixSync);
}
void dgWorldDynamicUpdate::SolverInitInternalForcesParallel (dgParallelSolverSyncData* const syncData, dgInt32 threadIndex) const
{
dgWorld* const world = (dgWorld*) this;
dgInt32* const treadLocks = &m_solverMemory.m_treadLocks[0];
const dgInt32* const jointInfoIndexArray = syncData->m_jointInfoMap;
dgJacobian* const internalForces = &m_solverMemory.m_internalForces[0];
dgJacobianMatrixElement* const matrixRow = &m_solverMemory.m_memory[0];
dgInt32* const atomicIndex = &syncData->m_initIntenalForceAccumulatorCounter;
dgJointInfo* const constraintArray = (dgJointInfo*) &world->m_jointsMemory[0];
dgVector zero(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));
for (dgInt32 i = dgAtomicAdd(atomicIndex, 1); i < syncData->m_jointCount; i = dgAtomicAdd(atomicIndex, 1)) {
dgJacobian y0;
dgJacobian y1;
y0.m_linear = zero;
y0.m_angular = zero;
y1.m_linear = zero;
y1.m_angular = zero;
dgInt32 jointIndex = jointInfoIndexArray[i];
dgJointInfo* const jointInfo = &constraintArray[jointIndex];
_ASSERTE (dgInt32 (jointInfo->m_joint->m_index) == i);
dgInt32 first = jointInfo->m_autoPairstart;
dgInt32 count = jointInfo->m_autoPaircount;
for (dgInt32 j = 0; j < count; j ++) {
dgJacobianMatrixElement* const row = &matrixRow[j + first];
dgFloat32 val = row->m_force;
_ASSERTE (dgCheckFloat(val));
y0.m_linear += row->m_Jt.m_jacobian_IM0.m_linear.Scale (val);
y0.m_angular += row->m_Jt.m_jacobian_IM0.m_angular.Scale (val);
y1.m_linear += row->m_Jt.m_jacobian_IM1.m_linear.Scale (val);
y1.m_angular += row->m_Jt.m_jacobian_IM1.m_angular.Scale (val);
}
dgInt32 m0 = jointInfo->m_m0;
dgInt32 m1 = jointInfo->m_m1;
world->GetIndirectLock (&treadLocks[m0]);
internalForces[m0].m_linear += y0.m_linear;
internalForces[m0].m_angular += y0.m_angular;
world->ReleaseIndirectLock(&treadLocks[m0]);
world->GetIndirectLock (&treadLocks[m1]);
internalForces[m1].m_linear += y1.m_linear;
internalForces[m1].m_angular += y1.m_angular;
world->ReleaseIndirectLock(&treadLocks[m1]);
}
world->SyncThreads(&syncData->m_initIntenalForceAccumulatorSync);
}
void dgWorldDynamicUpdate::CalculateForcesGameModeParallel (dgParallelSolverSyncData* const syncData, dgInt32 threadIndex) const
{
dgWorld* const world = (dgWorld*) this;
dgInt32* const treadLocks = &m_solverMemory.m_treadLocks[0];
const dgInt32* const bodyInfoIndexArray = syncData->m_bodyInfoMap;
const dgInt32* const jointInfoIndexArray = syncData->m_jointInfoMap;
dgBodyInfo* const bodyArray = (dgBodyInfo*) &world->m_bodiesMemory[0];
dgJointInfo* const constraintArray = (dgJointInfo*) &world->m_jointsMemory[0];
dgJacobianMatrixElement* const matrixRow = &m_solverMemory.m_memory[0];
dgJacobian* const internalVeloc = &m_solverMemory.m_internalVeloc[0];
dgJacobian* const internalForces = &m_solverMemory.m_internalForces[0];
dgFloat32 invTimestepSrc = dgFloat32 (1.0f) / syncData->m_timestep;
dgFloat32 invStep = (dgFloat32 (1.0f) / dgFloat32 (LINEAR_SOLVER_SUB_STEPS));
dgFloat32 timestep = syncData->m_timestep * invStep;
dgFloat32 invTimestep = invTimestepSrc * dgFloat32 (LINEAR_SOLVER_SUB_STEPS);
_ASSERTE (syncData->m_bodyCount ? (bodyArray[0].m_body == world->m_sentionelBody) : !syncData->m_bodyCount);
dgInt32 maxPasses = dgInt32 (world->m_solverMode + DG_BASE_ITERATION_COUNT);
if (maxPasses > DG_MAX_PASSES) {
maxPasses = DG_MAX_PASSES;
}
dgFloat32 firstPassCoef = dgFloat32 (0.0f);
for (dgInt32 step = 0; step < LINEAR_SOLVER_SUB_STEPS; step ++) {
dgJointAccelerationDecriptor joindDesc;
joindDesc.m_timeStep = timestep;
joindDesc.m_invTimeStep = invTimestep;
joindDesc.m_firstPassCoefFlag = firstPassCoef;
dgInt32* const jointAtomicIndex = &syncData->m_calculateForcesLock[step].m_jointAccelerationAtomicIndex;
for (dgInt32 i = dgAtomicAdd(jointAtomicIndex, 1); i < syncData->m_jointCount; i = dgAtomicAdd(jointAtomicIndex, 1)) {
dgInt32 curJoint = jointInfoIndexArray[i];
joindDesc.m_rowsCount = constraintArray[curJoint].m_autoPaircount;
joindDesc.m_rowMatrix = &matrixRow[constraintArray[curJoint].m_autoPairstart];
constraintArray[curJoint].m_joint->JointAccelerations (&joindDesc);
}
world->SyncThreads(&syncData->m_calculateForcesLock[step].m_jointAccelerationSync);
firstPassCoef = dgFloat32 (1.0f);
dgFloat32 accNorm = DG_SOLVER_MAX_ERROR * dgFloat32 (2.0f);
for (dgInt32 passes = 0; (passes < maxPasses) && (accNorm > DG_SOLVER_MAX_ERROR); passes ++) {
accNorm = dgFloat32 (0.0f);
dgInt32* const atomicIndex = &syncData->m_calculateForcesLock[step].m_JointForceAtomicIndex[passes];
for (dgInt32 i = dgAtomicAdd(atomicIndex, 1); i < syncData->m_jointCount; i = dgAtomicAdd(atomicIndex, 1)) {
dgInt32 curJoint = jointInfoIndexArray[i];
dgInt32 m0 = constraintArray[curJoint].m_m0;
dgInt32 m1 = constraintArray[curJoint].m_m1;
dgInt32 index = constraintArray[curJoint].m_autoPairstart;
dgInt32 rowsCount = constraintArray[curJoint].m_autoPaircount;
world->GetIndirectLock (&syncData->m_subStepLocks);
while (m0 && treadLocks[m0]) {
//dgThreadYield();
}
while (m1 && treadLocks[m1]) {
//dgThreadYield();
}
treadLocks[m0] = 1;
treadLocks[m1] = 1;
world->ReleaseIndirectLock(&syncData->m_subStepLocks);
dgVector linearM0 (internalForces[m0].m_linear);
dgVector angularM0 (internalForces[m0].m_angular);
dgVector linearM1 (internalForces[m1].m_linear);
dgVector angularM1 (internalForces[m1].m_angular);
for (dgInt32 k = 0; k < rowsCount; k ++) {
dgJacobianMatrixElement* const row = &matrixRow[index];
dgVector acc (row->m_JMinv.m_jacobian_IM0.m_linear.CompProduct(linearM0));
acc += row->m_JMinv.m_jacobian_IM0.m_angular.CompProduct (angularM0);
acc += row->m_JMinv.m_jacobian_IM1.m_linear.CompProduct (linearM1);
acc += row->m_JMinv.m_jacobian_IM1.m_angular.CompProduct (angularM1);
dgFloat32 a = row->m_coordenateAccel - acc.m_x - acc.m_y - acc.m_z - row->m_force * row->m_diagDamp;
dgFloat32 f = row->m_force + row->m_invDJMinvJt * a;
dgInt32 frictionIndex = row->m_normalForceIndex;
_ASSERTE (((frictionIndex < 0) && (matrixRow[frictionIndex].m_force == dgFloat32 (1.0f))) || ((frictionIndex >= 0) && (matrixRow[frictionIndex].m_force >= dgFloat32 (0.0f))));
dgFloat32 frictionNormal = matrixRow[frictionIndex].m_force;
dgFloat32 lowerFrictionForce = frictionNormal * row->m_lowerBoundFrictionCoefficent;
dgFloat32 upperFrictionForce = frictionNormal * row->m_upperBoundFrictionCoefficent;
if (f > upperFrictionForce) {
a = dgFloat32 (0.0f);
f = upperFrictionForce;
} else if (f < lowerFrictionForce) {
a = dgFloat32 (0.0f);
f = lowerFrictionForce;
}
accNorm = GetMax (accNorm, dgAbsf (a));
dgFloat32 prevValue = f - row->m_force;
row->m_force = f;
linearM0 += row->m_Jt.m_jacobian_IM0.m_linear.Scale (prevValue);
angularM0 += row->m_Jt.m_jacobian_IM0.m_angular.Scale (prevValue);
linearM1 += row->m_Jt.m_jacobian_IM1.m_linear.Scale (prevValue);
angularM1 += row->m_Jt.m_jacobian_IM1.m_angular.Scale (prevValue);
index ++;
}
internalForces[m0].m_linear = linearM0;
internalForces[m0].m_angular = angularM0;
internalForces[m1].m_linear = linearM1;
internalForces[m1].m_angular = angularM1;
treadLocks[m0] = 0;
treadLocks[m1] = 0;
}
syncData->m_accNorm[threadIndex] = accNorm;
world->SyncThreads(&syncData->m_calculateForcesLock[step].m_JointForceSync[passes]);
accNorm = dgFloat32 (0.0f);
for (dgInt32 i = 0; i < DG_MAX_THREADS_HIVE_COUNT; i ++) {
accNorm = GetMax (accNorm, dgAbsf (syncData->m_accNorm[i]));
}
//accNorm = 1.0f;
}
dgInt32* const bodyAtomicIndex = &syncData->m_calculateForcesLock[step].m_bodyVelocityAtomicIndex;
for (dgInt32 i = dgAtomicAdd(bodyAtomicIndex, 1); i < syncData->m_bodyCount; i = dgAtomicAdd(bodyAtomicIndex, 1)) {
dgInt32 index = bodyInfoIndexArray[i];
_ASSERTE (index);
dgBody* const body = bodyArray[index].m_body;
_ASSERTE (body->m_index == index);
dgVector force (body->m_accel + internalForces[index].m_linear);
dgVector torque (body->m_alpha + internalForces[index].m_angular);
dgVector accel (force.Scale (body->m_invMass.m_w));
dgVector alpha (body->m_invWorldInertiaMatrix.RotateVector (torque));
body->m_veloc += accel.Scale(timestep);
body->m_omega += alpha.Scale(timestep);
internalVeloc[index].m_linear += body->m_veloc;
internalVeloc[index].m_angular += body->m_omega;
}
world->SyncThreads(&syncData->m_calculateForcesLock[step].m_bodyVelocityAtomicSync);
}
dgInt32 hasJointFeeback = 0;
dgInt32* const saveForcefeebackAtomicIndex = &syncData->m_saveForcefeebackCounter;
for (dgInt32 i = dgAtomicAdd(saveForcefeebackAtomicIndex, 1); i < syncData->m_jointCount; i = dgAtomicAdd(saveForcefeebackAtomicIndex, 1)) {
dgInt32 curJoint = jointInfoIndexArray[i];
dgInt32 first = constraintArray[curJoint].m_autoPairstart;
dgInt32 count = constraintArray[curJoint].m_autoPaircount;
for (dgInt32 j = 0; j < count; j ++) {
dgJacobianMatrixElement* const row = &matrixRow[j + first];
dgFloat32 val = row->m_force;
_ASSERTE (dgCheckFloat(val));
row->m_jointFeebackForce[0] = val;
}
hasJointFeeback |= (constraintArray[i].m_joint->m_updaFeedbackCallback ? 1 : 0);
}
syncData->m_hasJointFeeback[threadIndex] = hasJointFeeback;
world->SyncThreads(&syncData->m_saveForcefeebackSync);
hasJointFeeback = 0;
for (dgInt32 i = 0; i < DG_MAX_THREADS_HIVE_COUNT; i ++) {
hasJointFeeback |= syncData->m_hasJointFeeback[i];
}
// dgFloat32 maxAccNorm2 = maxAccNorm * maxAccNorm;
dgFloat32 maxAccNorm2 = DG_SOLVER_MAX_ERROR * DG_SOLVER_MAX_ERROR;
dgVector zero(dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));
dgInt32* const updateBodyVelocityCounter = &syncData->m_updateBodyVelocityCounter;
for (dgInt32 i = dgAtomicAdd(updateBodyVelocityCounter, 1); i < syncData->m_bodyCount; i = dgAtomicAdd(updateBodyVelocityCounter, 1)) {
dgInt32 index = bodyInfoIndexArray[i];
_ASSERTE (index);
dgBody* const body = bodyArray[index].m_body;
#ifdef DG_WIGHT_FINAL_RK4_DERIVATIVES
body->m_veloc = internalVeloc[index].m_linear.Scale(invStep);
body->m_omega = internalVeloc[index].m_angular.Scale(invStep);
#endif
dgVector accel = (body->m_veloc - body->m_netForce).Scale (invTimestepSrc);
dgVector alpha = (body->m_omega - body->m_netTorque).Scale (invTimestepSrc);
if ((accel % accel) < maxAccNorm2) {
accel = zero;
}
if ((alpha % alpha) < maxAccNorm2) {
alpha = zero;
}
body->m_accel = accel;
body->m_alpha = alpha;
body->m_netForce = accel.Scale (body->m_mass[3]);
alpha = body->m_matrix.UnrotateVector(alpha);
body->m_netTorque = body->m_matrix.RotateVector (alpha.CompProduct(body->m_mass));
}
world->SyncThreads(&syncData->m_updateBodyVelocitySync);
if (hasJointFeeback) {
dgInt32* const m_updateForcefeebackCounter = &syncData->m_updateForcefeebackCounter;
for (dgInt32 i = dgAtomicAdd(m_updateForcefeebackCounter, 1); i < syncData->m_jointCount; i = dgAtomicAdd(m_updateForcefeebackCounter, 1)) {
dgInt32 curJoint = jointInfoIndexArray[i];
if (constraintArray[curJoint].m_joint->m_updaFeedbackCallback) {
constraintArray[curJoint].m_joint->m_updaFeedbackCallback (*constraintArray[curJoint].m_joint, syncData->m_timestep, threadIndex);
}
}
world->SyncThreads(&syncData->m_updateForcefeebackSync);
}
}
|
[
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
] |
[
[
[
1,
646
]
]
] |
42990a3f122aacc7d63958eaabcd224bac7b2933
|
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
|
/rl/trunk/engine/core/src/World.cpp
|
9a1ff66c814140777d8de5e76c4aa4a97e7700cf
|
[
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
jacmoe/dsa-hl-svn
|
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
|
97798e1f54df9d5785fb206c7165cd011c611560
|
refs/heads/master
| 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,068 |
cpp
|
/* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* 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
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#include "stdinc.h" //precompiled header
#include "World.h"
#include "Exception.h"
#include "CoreMessages.h"
#include "MessagePump.h"
using namespace Ogre;
namespace rl {
World::World(SceneType sceneType)
: mSceneMgr(0),
mCamera(0),
mSceneFile(),
mActiveActor(0),
mUniqueNameSeed(0)
{
mSceneMgr = Root::getSingleton()
.createSceneManager(sceneType, "world_sm");
}
SceneManager* World::getSceneManager(void) const
{
return mSceneMgr;
}
void World::setSceneManager(SceneManager* SceneMgr)
{
mSceneMgr = SceneMgr;
}
//Enables / disables a 'sky plane' i.e.
void World::setSkyPlane(bool enable, const Plane &plane,
const String &materialName, Real scale, Real tiling,
bool drawFirst, Real bow)
{
mSceneMgr->setSkyPlane(enable, plane, materialName, scale,
tiling, drawFirst, bow);
}
void World::setAmbientLight(Real r, Real g, Real b)
{
mSceneMgr->setAmbientLight(ColourValue(r,g,b));
}
//Enables / disables a 'sky box' i.e.
void World::setSkyBox(bool enable, const String &materialName, Real distance, bool drawFirst )
{
mSceneMgr->setSkyBox(enable, materialName,
distance, drawFirst, Quaternion::ZERO);
}
//Enables / disables a 'sky dome' i.e.
void World::setSkyDome(bool enable, const String &materialName,
Real curvature, Real tiling, Real distance, bool drawFirst)
{
mSceneMgr->setSkyDome(enable, materialName, curvature,
tiling, distance, drawFirst, Quaternion::ZERO);
}
//Sets the fogging mode applied to the scene.
void World::setFog(FogMode mode, const ColourValue &colour,
Real expDensity, Real linearStart, Real linearEnd)
{
mSceneMgr->setFog(Ogre::FogMode(mode), colour,
expDensity, linearStart, linearEnd );
}
//Returns the fog mode for the scene.
rl::World::FogMode World::getFogMode(void) const
{
return rl::World::FogMode(mSceneMgr->getFogMode( ));
}
//Returns the fog colour for the scene.
const ColourValue& World::getFogColour(void) const
{
return mSceneMgr->getFogColour();
}
//Returns the fog start distance for the scene.
Real World::getFogStart(void) const
{
return mSceneMgr->getFogStart();
}
//Returns the fog end distance for the scene.
Real World::getFogEnd(void) const
{
return mSceneMgr->getFogEnd();
}
Vector3 World::getStartPoint() const
{
return Vector3::ZERO;
}
void World::setCastShadows(bool enabled)
{
Throw(OperationNotSupportedException,
"SceneManager does not support shadows");
}
void World::setShowBoundingBoxes( bool dis )
{
mSceneMgr->showBoundingBoxes( dis );
}
Ogre::String World::getUniqueName()
{
return "__RL_WORLD_UNIQUE_NAME__" + StringConverter::toString(++mUniqueNameSeed);
}
void World::fireAfterSceneLoaded()
{
MessagePump::getSingleton().sendMessage<MessageType_SceneLoaded>();
}
void World::fireBeforeClearScene()
{
MessagePump::getSingleton().sendMessage<MessageType_SceneClearing>();
}
}
|
[
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013",
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013",
"ablock@4c79e8ff-cfd4-0310-af45-a38c79f83013",
"zero-gravity@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] |
[
[
[
1,
1
],
[
4,
4
],
[
6,
9
],
[
11,
11
],
[
13,
13
],
[
15,
15
],
[
19,
23
],
[
31,
38
],
[
115,
115
],
[
127,
141
]
],
[
[
2,
2
],
[
5,
5
],
[
10,
10
],
[
12,
12
],
[
14,
14
],
[
18,
18
],
[
24,
25
],
[
28,
29
],
[
39,
49
],
[
51,
68
],
[
70,
74
],
[
76,
76
],
[
78,
78
],
[
80,
86
],
[
88,
92
],
[
94,
98
],
[
100,
104
],
[
106,
113
],
[
117,
121
],
[
142,
142
]
],
[
[
3,
3
],
[
16,
17
],
[
50,
50
],
[
75,
75
],
[
79,
79
],
[
87,
87
],
[
93,
93
],
[
99,
99
],
[
105,
105
],
[
116,
116
],
[
123,
123
]
],
[
[
26,
27
],
[
30,
30
],
[
69,
69
],
[
77,
77
],
[
114,
114
],
[
122,
122
],
[
124,
126
]
]
] |
5d503e8036d15a64bdc25b8b668d48325377397c
|
804e416433c8025d08829a08b5e79fe9443b9889
|
/src/graphics/graphics.cpp
|
44e3f9c693856a5e7d07cb230a3cea42afe285b4
|
[
"BSD-2-Clause"
] |
permissive
|
cstrahan/argss
|
e77de08db335d809a482463c761fb8d614e11ba4
|
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
|
refs/heads/master
| 2020-05-20T05:30:48.876372 | 2010-10-03T23:21:59 | 2010-10-03T23:21:59 | 1,682,890 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 11,743 |
cpp
|
/////////////////////////////////////////////////////////////////////////////
// ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
// Headers
///////////////////////////////////////////////////////////
#include <string>
#include "tools/time.h"
#include "graphics/graphics.h"
#include "aruby.h"
#include "argss/classes/aerror.h"
#include "config.h"
#include "player.h"
#include "output.h"
#include "graphics/sprite.h"
#include "graphics/tilemap.h"
#include "graphics/text.h"
#ifdef MACOSX
#include "gl.h"
#else
#include "gl/gl.h"
#endif
///////////////////////////////////////////////////////////
// Global Variables
///////////////////////////////////////////////////////////
int Graphics::fps;
int Graphics::framerate;
int Graphics::framecount;
Color Graphics::backcolor;
int Graphics::brightness;
double Graphics::framerate_interval;
std::map<unsigned long, Drawable*> Graphics::drawable_map;
std::map<unsigned long, Drawable*>::iterator Graphics::it_drawable_map;
std::list<ZObj> Graphics::zlist;
std::list<ZObj>::iterator Graphics::it_zlist;
long Graphics::creation;
long Graphics::last_tics;
long Graphics::last_tics_wait;
long Graphics::next_tics_fps;
///////////////////////////////////////////////////////////
/// Initialize
///////////////////////////////////////////////////////////
void Graphics::Init() {
fps = 0;
framerate = 40;
framecount = 0;
backcolor = Color(0, 0, 0, 0);
brightness = 255;
creation = 0;
framerate_interval = 1000.0 / framerate;
last_tics = Time::GetTime() + (long)framerate_interval;
next_tics_fps = Time::GetTime() + 1000;
InitOpenGL();
Text::Init();
Tilemap::Init();
}
///////////////////////////////////////////////////////////
/// Initialize OpengGL
///////////////////////////////////////////////////////////
void Graphics::InitOpenGL() {
glViewport(0, 0, Player::GetWidth(), Player::GetHeight());
glShadeModel(GL_FLAT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, Player::GetWidth(), Player::GetHeight(), 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_BLEND);
glClearColor(
(GLclampf)(backcolor.red / 255.0f),
(GLclampf)(backcolor.green / 255.0f),
(GLclampf)(backcolor.blue / 255.0f),
(GLclampf)(backcolor.alpha / 255.0f)
);
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT);
Player::SwapBuffers();
}
///////////////////////////////////////////////////////////
/// Exit
///////////////////////////////////////////////////////////
void Graphics::Exit() {
for (it_drawable_map = drawable_map.begin(); it_drawable_map != drawable_map.end(); it_drawable_map++) {
delete it_drawable_map->second;
}
drawable_map.clear();
Bitmap::DisposeBitmaps();
}
///////////////////////////////////////////////////////////
/// Refresh all graphic objects
///////////////////////////////////////////////////////////
void Graphics::RefreshAll() {
for (it_drawable_map = drawable_map.begin(); it_drawable_map != drawable_map.end(); it_drawable_map++) {
it_drawable_map->second->RefreshBitmaps();
}
Bitmap::RefreshBitmaps();
}
///////////////////////////////////////////////////////////
/// Wait
///////////////////////////////////////////////////////////
void Graphics::TimerWait(){
last_tics_wait = Time::GetTime();
}
///////////////////////////////////////////////////////////
/// Continue
///////////////////////////////////////////////////////////
void Graphics::TimerContinue() {
last_tics += Time::GetTime() - last_tics_wait;
next_tics_fps += Time::GetTime() - last_tics_wait;
}
///////////////////////////////////////////////////////////
/// Update
///////////////////////////////////////////////////////////
void Graphics::Update() {
static long tics;
static long tics_fps = Time::GetTime();
static long frames = 0;
static double waitframes = 0;
static double cyclesleftover;
Player::Update();
/*if (waitframes >= 1) {
waitframes -= 1;
return;
}*/
tics = Time::GetTime();
if ((tics - last_tics) >= framerate_interval) {// || (framerate_interval - tics + last_tics) < 12) {
//cyclesleftover = waitframes;
//waitframes = (double)(tics - last_tics) / framerate_interval - cyclesleftover;
//last_tics += (tics - last_tics);
last_tics = tics;
DrawFrame();
framecount++;
frames++;
if (tics >= next_tics_fps) {
next_tics_fps += 1000;
fps = frames;
frames = 0;
char title[255];
sprintf(title, "%s - %d FPS", Config::Title.c_str(), fps);
Player::main_window->SetTitle(title);
}
} else {
Time::SleepMs((long)(framerate_interval) - (tics - last_tics));
}
}
///////////////////////////////////////////////////////////
/// Draw Frame
///////////////////////////////////////////////////////////
void Graphics::DrawFrame() {
glClear(GL_COLOR_BUFFER_BIT);
for (it_zlist = zlist.begin(); it_zlist != zlist.end(); it_zlist++) {
Graphics::drawable_map[it_zlist->GetId()]->Draw(it_zlist->GetZ());
}
if (brightness < 255) {
glDisable(GL_TEXTURE_2D);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glColor4f(0.0f, 0.0f, 0.0f, (float)(1.0f - brightness / 255.0f));
glBegin(GL_QUADS);
glVertex2i(0, 0);
glVertex2i(0, Player::GetHeight());
glVertex2i(Player::GetWidth(), Player::GetHeight());
glVertex2i(Player::GetWidth(), 0);
glEnd();
}
Player::SwapBuffers();
}
///////////////////////////////////////////////////////////
/// Freeze screen
///////////////////////////////////////////////////////////
void Graphics::Freeze() {
// TODO
}
///////////////////////////////////////////////////////////
/// Transition effect
///////////////////////////////////////////////////////////
void Graphics::Transition(int duration, std::string filename, int vague) {
// TODO
}
///////////////////////////////////////////////////////////
/// Reset frames
///////////////////////////////////////////////////////////
void Graphics::FrameReset() {
last_tics = Time::GetTime();
next_tics_fps = Time::GetTime() + 1000;
}
///////////////////////////////////////////////////////////
/// Wait frames
///////////////////////////////////////////////////////////
void Graphics::Wait(int duration) {
for (int i = duration; i > 0; i--) {
Update();
}
}
///////////////////////////////////////////////////////////
/// Resize screen
///////////////////////////////////////////////////////////
void Graphics::ResizeScreen(int width, int height) {
Player::ResizeWindow(width, height);
glViewport(0, 0, width, height);
glShadeModel(GL_FLAT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
Player::SwapBuffers();
}
///////////////////////////////////////////////////////////
/// Snap scree to bitmap
///////////////////////////////////////////////////////////
VALUE Graphics::SnapToBitmap() {
return Qnil;
}
///////////////////////////////////////////////////////////
/// Fade out
///////////////////////////////////////////////////////////
void Graphics::FadeOut(int duration) {
int n = brightness / duration;
for (;duration > 0; duration--) {
brightness -= n;
Update();
}
if (brightness > 0) {
brightness = 0;
Update();
}
}
///////////////////////////////////////////////////////////
/// Fade in
///////////////////////////////////////////////////////////
void Graphics::FadeIn(int duration) {
int n = 255 / duration;
for (;duration > 0; duration--) {
brightness += n;
Update();
}
if (brightness < 255) {
brightness = 255;
Update();
}
}
///////////////////////////////////////////////////////////
/// Properties
///////////////////////////////////////////////////////////
int Graphics::GetFrameRate() {
return framerate;
}
void Graphics::SetFrameRate(int nframerate) {
framerate = nframerate;
framerate_interval = 1000.0 / framerate;
}
int Graphics::GetFrameCount() {
return framecount;
}
void Graphics::SetFrameCount(int nframecount) {
framecount = nframecount;
}
VALUE Graphics::GetBackColor() {
return backcolor.GetARGSS();
}
void Graphics::SetBackColor(VALUE nbackcolor) {
backcolor = Color(nbackcolor);
glClearColor(
(GLclampf)(backcolor.red / 255.0f),
(GLclampf)(backcolor.green / 255.0f),
(GLclampf)(backcolor.blue / 255.0f),
(GLclampf)(backcolor.alpha / 255.0f)
);
}
int Graphics::GetBrightness() {
return brightness;
}
void Graphics::SetBrightness(int nbrightness) {
brightness = nbrightness;
}
///////////////////////////////////////////////////////////
/// Sort ZObj
///////////////////////////////////////////////////////////
bool Graphics::SortZObj(ZObj &first, ZObj &second) {
if (first.GetZ() < second.GetZ()) return true;
else if (first.GetZ() > second.GetZ()) return false;
else return first.GetCreation() < second.GetCreation();
}
///////////////////////////////////////////////////////////
/// Register ZObj
///////////////////////////////////////////////////////////
void Graphics::RegisterZObj(long z, unsigned long id) {
creation += 1;
ZObj zobj(z, creation, id);
zlist.push_back(zobj);
zlist.sort(SortZObj);
}
void Graphics::RegisterZObj(long z, unsigned long id, bool multiz) {
ZObj zobj(z, 999999, id);
zlist.push_back(zobj);
zlist.sort(SortZObj);
}
///////////////////////////////////////////////////////////
/// Remove ZObj
///////////////////////////////////////////////////////////
struct remove_zobj_id : public std::binary_function<ZObj, ZObj, bool> {
remove_zobj_id(VALUE val) : id(val) {}
bool operator () (ZObj &obj) const {return obj.GetId() == id;}
unsigned long id;
};
void Graphics::RemoveZObj(unsigned long id) {
zlist.remove_if (remove_zobj_id(id));
}
///////////////////////////////////////////////////////////
/// Update ZObj Z
///////////////////////////////////////////////////////////
void Graphics::UpdateZObj(unsigned long id, long z) {
for (it_zlist = zlist.begin(); it_zlist != zlist.end(); it_zlist++) {
if (it_zlist->GetId() == id) {
it_zlist->SetZ(z);
break;
}
}
zlist.sort(SortZObj);
}
|
[
"vgvgf@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda",
"npepinpe@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda"
] |
[
[
[
1,
40
],
[
44,
44
],
[
46,
389
]
],
[
[
41,
43
],
[
45,
45
]
]
] |
b1a4d5c315241f716c26528117c81acd213dc5df
|
fac8de123987842827a68da1b580f1361926ab67
|
/inc/physics/Common/Base/Fwd/hkstandardheader.h
|
46c5bd9d988410665a75d4056d2c34d92e6ed788
|
[] |
no_license
|
blockspacer/transporter-game
|
23496e1651b3c19f6727712a5652f8e49c45c076
|
083ae2ee48fcab2c7d8a68670a71be4d09954428
|
refs/heads/master
| 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,590 |
h
|
/*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_STANDARD_HEADER
// Some compiler vendors do not ship the c++ standard headers
// but do ship the c ones. We cannot use the c versions in
// all cases however since they are not all compatible with c++.
# if (__GNUC__ == 2) && (__GNUC_MINOR__ == 95)
# define HK_STANDARD_HEADER(_i) <_i##.h>
# else
# define HK_STANDARD_HEADER(_i) <c##_i>
# endif
namespace std { }
#endif // HK_STANDARD_HEADER
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
|
[
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] |
[
[
[
1,
34
]
]
] |
ae2a2fa27b4292685f873b3c5625315a02197320
|
0ee189afe953dc99825f55232cd52b94d2884a85
|
/mlog/Manager.cpp
|
29c9485aef95537729ac30381291f008bf3fe948
|
[] |
no_license
|
spolitov/lib
|
fed99fa046b84b575acc61919d4ef301daeed857
|
7dee91505a37a739c8568fdc597eebf1b3796cf9
|
refs/heads/master
| 2016-09-11T02:04:49.852151 | 2011-08-11T18:00:44 | 2011-08-11T18:00:44 | 2,192,752 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 17,765 |
cpp
|
#include "pch.h"
#if !MLOG_NO_LOGGING
#include "Logger.h"
#include "Utils.h"
#include "Manager.h"
namespace mlog {
namespace {
class Data : public mstd::singleton<Data> {
public:
void appname(const std::string & value)
{
appname_ = value;
}
const std::string & appname() const
{
return appname_;
}
private:
std::string appname_;
MSTD_SINGLETON_DECLARATION(Data);
};
}
template<class Devices, class F>
bool setupDevice(Devices & devices, const std::string & name, const F & f, boost::mutex::scoped_lock & lock)
{
for(typename Devices::iterator i = devices.begin(); i != devices.end(); ++i)
for(typename Devices::value_type::iterator j = i->begin(); j != i->end(); ++j)
if((*j)->name() == name)
{
f(devices, i, j);
return true;
}
return false;
}
void Manager::setup(const std::string & expr)
{
std::string::size_type dp = expr.find('.');
if(dp == std::string::npos)
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Invalid setup syntax - '.' expected"));
std::string::size_type ep = expr.find('=', dp);
if(ep == std::string::npos)
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Invalid setup syntax - '=' expected"));
std::string name = expr.substr(0, dp);
boost::trim(name);
std::string prop = expr.substr(dp + 1, ep - dp - 1);
boost::trim(prop);
std::string value = expr.substr(ep + 1);
boost::trim(value);
boost::mutex::scoped_lock lock(mutex_);
if(name == "device")
setupDevice(prop, value, lock);
else if(name == "manager")
{
if(prop == "realtime")
realtime_ = value == "1" || value == "true";
} else if(prop == "level")
setupLevel(name, value, lock);
else if(prop == "group")
setupGroup(name, value, lock);
else
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Unknown command: " + expr));
}
template<class Type>
class Updater {
public:
typedef void (LogParticipant::*Func)(Type type);
explicit Updater(Func func, Type value)
: func_(func), value_(value) {}
template<class D, class I, class J>
void operator()(D&, I&, J j) const
{
((**j).*func_)(value_);
}
template<class T>
void operator()(T & t) const
{
(t.*func_)(value_);
}
private:
Func func_;
Type value_;
};
template<class F>
void Manager::setup(const std::string & name, const F & f, boost::mutex::scoped_lock & lock)
{
if(name.empty())
{
f(rootLogger_);
BOOST_FOREACH(const Loggers::value_type & i, loggers_)
f(const_cast<detail::LoggerImpl&>(i.second));
} else {
SharedDevices newDevices(new Devices(*devices_));
if(mlog::setupDevice(*newDevices, name, f, lock))
devices_ = newDevices;
else
f(registerLogger(name, lock));
}
}
void Manager::setupLevel(const std::string & name, const std::string & value, boost::mutex::scoped_lock & lock)
{
LogLevel level;
if(value == "emergency")
level = llEmergency;
else if(value == "alert")
level = llAlert;
else if(value == "critical")
level = llCritical;
else if(value == "error")
level = llError;
else if(value == "warning")
level = llWarning;
else if(value == "notice")
level = llNotice;
else if(value == "info")
level = llInfo;
else if(value == "debug")
level = llDebug;
else {
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Unknown log level: " + value));
std::terminate();
}
setup(name, Updater<LogLevel>(&detail::LoggerImpl::level, level), lock);
}
class UpdateGroup {
public:
explicit UpdateGroup(boost::uint32_t group)
: group_(group) {}
template<class D, class I, class J>
void operator()(D& d, I i, J j) const
{
if(static_cast<boost::uint32_t>(i - d.begin()) != group_)
{
typename std::iterator_traits<J>::value_type t = *j;
i->erase(j);
if(d.size() <= group_)
d.resize(group_ + 1);
d[group_].push_back(t);
}
}
void operator()(detail::LoggerImpl & logger) const
{
logger.group(group_);
}
private:
boost::uint32_t group_;
};
void Manager::setupGroup(const std::string & name, const std::string & value, boost::mutex::scoped_lock & lock)
{
uint32_t group = mstd::str2int10<uint32_t>(value);
if(name.empty())
{
rootLogger_.group(group);
BOOST_FOREACH(const Loggers::value_type & i, loggers_)
const_cast<detail::LoggerImpl&>(i.second).group(group);
} else
registerLogger(name, lock).group(group);
setup(name, UpdateGroup(group), lock);
}
namespace {
class CheckName {
public:
explicit CheckName(const std::string & name)
: name_(name) {}
template<class F>
bool operator()(const F & f)
{
return f->name() == name_;
}
private:
std::string name_;
};
}
class CFileLogDevice {
public:
explicit CFileLogDevice(FILE * handle)
: handle_(handle)
{
}
void operator()(const char * str, size_t len)
{
fwrite(str, 1, len, handle_);
fflush(handle_);
}
void changeHandle(FILE * value)
{
handle_ = value;
}
private:
FILE * handle_;
};
class SyslogLogDevice {
public:
void operator()(const char * out, size_t len)
{
}
};
class NullLogDevice {
public:
void operator()(const char * out, size_t len)
{
}
};
class FClose {
public:
void operator()(FILE * file)
{
if(file != 0)
fclose(file);
}
};
class FileHolder : public boost::noncopyable {
public:
explicit FileHolder(const std::string & fname)
: fname_(fname), handle_(fopen(fname.c_str(), "ab"))
{
if(!handle_)
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Failed to open for writing: " + fname));
}
FILE * handle()
{
return handle_;
}
const std::string & fname() const
{
return fname_;
}
void close()
{
fclose(handle_);
handle_ = 0;
}
void reopen()
{
handle_ = fopen(fname_.c_str(), "wb");
if(!handle_)
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Failed to open for writing: " + fname_));
}
~FileHolder()
{
if(handle_)
fclose(handle_);
}
private:
std::string fname_;
FILE * handle_;
};
#if defined(BOOST_WINDOWS)
DWORD getpid()
{
return GetCurrentProcessId();
}
#endif
std::string parse(const std::string & fname)
{
std::string result;
result.reserve(fname.length());
std::string::const_iterator end = fname.end(), p = end;
for(std::string::const_iterator i = fname.begin(); i != end; ++i)
{
char c = *i;
if(c == '%')
{
if(p == end)
p = i;
else {
std::string key = std::string(p + 1, i);
if(key.empty())
result.push_back('%');
else if(key == "pid")
{
char buf[0x20];
result += mstd::itoa(getpid(), buf);
} else if(key == "app")
result += Data::instance().appname();
else if(key == "now")
{
std::string temp = boost::lexical_cast<std::string>(onow());
std::replace(temp.begin(), temp.end(), ':', '-');
result += temp;
} else
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Unknown key: " + key));
p = end;
}
} else if(p == end)
result.push_back(c);
}
return result;
}
class FileLogDevice : private FileHolder, private CFileLogDevice {
public:
explicit FileLogDevice(const std::string & fname, size_t threshold, size_t count)
: FileHolder(parse(fname)), CFileLogDevice(handle()), threshold_(threshold), count_(count)
{
current_ = ftell(handle());
checkLimit();
std::ostringstream out;
out << "============== NEW LOG STARTED at ";
out << boost::posix_time::microsec_clock::local_time();
out << " ==============" << std::endl;
std::string message = out.str();
(*this)(message.c_str(), message.length());
}
void operator()(const char * out, size_t len)
{
boost::lock_guard<boost::mutex> guard(mutex_);
CFileLogDevice::operator ()(out, len);
current_ += len;
checkLimit();
}
private:
void checkLimit()
{
if(threshold_ && current_ >= threshold_)
{
close();
if(count_)
{
try {
boost::filesystem::path c;
size_t i = 0;
for(; i != count_; ++i)
{
c = history(i);
if(!exists(c))
break;
}
if(i == count_)
{
c = history(0);
remove(c);
for(size_t i = 1; i != count_; ++i)
{
boost::filesystem::path next(history(i));
rename(next, c);
c = next;
}
}
rename(fname(), c);
} catch(boost::system::system_error &) {
}
}
reopen();
changeHandle(handle());
current_ = 0;
}
}
boost::filesystem::path history(size_t idx) const
{
char buf[0x20];
return fname() + "." + mstd::itoa(idx, buf);
}
boost::mutex mutex_;
size_t threshold_;
size_t current_;
size_t count_;
};
template<class F>
class SharedDevice {
public:
explicit SharedDevice(F * f)
: f_(f) {}
void operator()(const char * out, size_t len) const
{
(*f_)(out, len);
}
private:
boost::shared_ptr<F> f_;
};
template<class F>
SharedDevice<F> shared(F * f)
{
return SharedDevice<F>(f);
}
LogDevice * createDevice(const std::string & name, const std::string & value)
{
LogDevice::Device device;
if(value == "stdout")
device = CFileLogDevice(stdout);
else if(value == "stderr")
device = CFileLogDevice(stderr);
else if(value == "syslog")
device = SyslogLogDevice();
else if(value == "null")
device = NullLogDevice();
else if(boost::starts_with(value, "file("))
{
if(value[value.length() - 1] != ')')
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("File device syntax: file(filename)"));
std::string args = value.substr(5, value.length() - 6);
std::string::size_type p = args.find(',');
size_t threshold = 1 << 20;
if(p != std::string::npos)
{
threshold = mstd::str2int10<size_t>(args.substr(p + 1));
args.erase(p);
boost::trim(args);
}
device = shared(new FileLogDevice(args, threshold, 5));
} else
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Unknown log device: " + value));
return new LogDevice(name, device);
}
struct EraseDevice {
template<class D, class I, class J>
void operator()(D&, I i, J j) const
{
i->erase(j);
}
};
class ChangeDevice {
public:
explicit ChangeDevice(const LogDevicePtr & device)
: device_(device) {}
template<class D, class I, class J>
void operator()(D&, I i, J j) const
{
*j = device_;
}
private:
LogDevicePtr device_;
};
void Manager::setupDevice(const std::string & prop, const std::string & value, boost::mutex::scoped_lock & lock)
{
SharedDevices newDevices(new Devices(*devices_));
if(prop == "remove")
{
if(value == "*")
Devices(1).swap(*newDevices);
else {
if(!mlog::setupDevice(*newDevices, value, EraseDevice(), lock))
BOOST_THROW_EXCEPTION(ManagerException() << mstd::error_message("Unknown log device: " + value));
}
} else {
LogDevicePtr newDevice(createDevice(prop, value));
if(!mlog::setupDevice(*newDevices, prop, ChangeDevice(newDevice), lock))
{
newDevices->resize(std::max(static_cast<size_t>(1), newDevices->size()));
(*newDevices)[0].push_back(newDevice);
}
}
devices_ = newDevices;
}
void Manager::setListener(LogLevel level, const Listener & listener)
{
boost::lock_guard<boost::mutex> lock(mutex_);
listenerLevel_ = level;
listener_ = listener;
}
void Manager::output(const char * logger, const mstd::pbuffer & buf)
{
if(realtime_)
{
boost::lock_guard<boost::mutex> lock(mutex_);
queue_.push_back(Queue::value_type(logger, buf));
cond_.notify_one();
if(!threadStarted_)
{
threadStarted_ = true;
thread_ = boost::thread(&Manager::execute, this);
}
} else {
SharedDevices devices;
{
boost::lock_guard<boost::mutex> lock(mutex_);
devices = devices_;
}
Listener listener;
bool listenerChecked = false;
process(*devices, logger, buf, listener, listenerChecked);
}
}
void Manager::process(Devices & devices, const char * logger, const mstd::pbuffer & buf, Listener & listener, bool & listenerChecked)
{
char * p = buf->ptr();
uint32_t group = *mstd::pointer_cast<uint32_t*>(p);
p += sizeof(group);
LogLevel level = *mstd::pointer_cast<LogLevel*>(p);
p += sizeof(level);
size_t len = *mstd::pointer_cast<size_t*>(p);
p += sizeof(len);
DeviceGroup & devs = devices[0];
DeviceGroup::iterator i = devs.begin();
DeviceGroup::iterator end = devs.end();
for(; i != end; ++i)
{
LogDevice & device = **i;
device.output(level, p, len);
}
if(group && group < devices.size())
{
DeviceGroup & devs = devices[group];
DeviceGroup::iterator i = devs.begin();
DeviceGroup::iterator end = devs.end();
for(; i != end; ++i)
{
LogDevice & device = **i;
device.output(level, p, len);
}
}
if(level <= listenerLevel_)
{
if(!listenerChecked)
{
boost::lock_guard<boost::mutex> lock(mutex_);
listener = listener_;
listenerChecked = true;
}
if(!listener.empty())
listener(group, level, logger, p, len);
}
}
void Manager::execute()
{
Queue queue;
try {
boost::unique_lock<boost::mutex> lock(mutex_);
while(!boost::this_thread::interruption_requested())
{
if(queue_.empty())
cond_.wait(lock);
else {
queue.swap(queue_);
SharedDevices devices = devices_;
mstd::reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
Listener listener;
bool listenerChecked = false;
for(Queue::const_iterator q = queue.begin(), qend = queue.end(); q != qend; ++q)
process(*devices, q->first, q->second, listener, listenerChecked);
queue.clear();
}
}
} catch(boost::thread_interrupted&) {
}
}
detail::LoggerImpl & Manager::registerLogger(const std::string & name)
{
boost::mutex::scoped_lock lock(mutex_);
return registerLogger(name, lock);
}
detail::LoggerImpl & Manager::registerLogger(const std::string & name, boost::mutex::scoped_lock & lock)
{
Loggers::iterator i = loggers_.find(name);
if(i == loggers_.end())
i = loggers_.insert(Loggers::value_type(name, detail::LoggerImpl(rootLogger_.level()))).first;
return const_cast<detail::LoggerImpl&>(i->second);
}
void Manager::setAppName(const char * value)
{
Data::instance().appname(value);
}
Manager::Manager()
: rootLogger_(llWarning),
devices_(new Devices(1, DeviceGroup(1, LogDevicePtr(new LogDevice("console", CFileLogDevice(stdout)))))),
threadStarted_(false), realtime_(false)
{
mstd::buffers::instance();
levelName(llError);
}
Manager::~Manager()
{
if(threadStarted_)
{
for(;;)
{
{
boost::lock_guard<boost::mutex> lock(mutex_);
if(queue_.empty())
break;
}
boost::this_thread::yield();
}
thread_.interrupt();
cond_.notify_one();
thread_.join();
}
}
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
653
]
]
] |
d4b7ac11c70359a18846a12a6a1bb43dc6b91ad1
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/renaissance/rnsbasicactions/src/ngpinventory/ngpinsertininventory.cc
|
6ce59af5ce817830a31558a3772eccbb92d25abb
|
[] |
no_license
|
ugozapad/TheZombieEngine
|
832492930df28c28cd349673f79f3609b1fe7190
|
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
|
refs/heads/master
| 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,457 |
cc
|
//------------------------------------------------------------------------------
// ngpinsertininventory.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "precompiled/pchrnsbasicactions.h"
#include "ngpinventory/ngpinsertininventory.h"
#include "ncgameplayliving/ncgameplayliving.h"
#include "rnsgameplay/ninventorycontainer.h"
#include "rnsgameplay/ninventoryitem.h"
#include "rnsgameplay/ninventorymanager.h"
//------------------------------------------------------------------------------
nNebulaScriptClass(nGPInsertInInventory, "ngpbasicaction");
//------------------------------------------------------------------------------
/**
Nebula class scripting initialization
*/
NSCRIPT_INITCMDS_BEGIN(nGPInsertInInventory)
NSCRIPT_ADDCMD('INIT', bool, Init, 4, (nEntityObject*,const char *,int,int), 0, ());
NSCRIPT_INITCMDS_END()
//------------------------------------------------------------------------------
/**
*/
nGPInsertInInventory::nGPInsertInInventory()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nGPInsertInInventory::~nGPInsertInInventory()
{
this->End();
}
//------------------------------------------------------------------------------
/**
@param entity entity that change the weapon
@param itemName name of the item to insert
@param slot where to insert the item
@returns true if basic action is valid
*/
bool
nGPInsertInInventory::Init (nEntityObject* entity, const char * itemName, int slot, int amount )
{
bool valid = true;
this->entity = entity;
// get gameplay
ncGameplayLiving * gameplayLiving = 0;
gameplayLiving = this->entity->GetComponent<ncGameplayLiving>();
valid = gameplayLiving != 0;
// get inventory container
nInventoryContainer * inventory = 0;
if( valid )
{
inventory = gameplayLiving->GetInventory();
valid = inventory != 0;
n_assert2( valid, "Entity without inventory" );
}
// create the item
nInventoryItem * item = 0;
nInventoryManager * manager = nInventoryManager::Instance();
if( valid )
{
item = manager->NewItem( itemName );
valid = item != 0;
n_assert2( valid, "Can not create item" );
}
// put amount in item
if( valid )
{
if( item->IsStackable() && amount > 0 )
{
item->SetStack( amount );
}
}
// insert item into inventory
if( valid )
{
valid = inventory->InsertItem( item, static_cast<nInventoryContainer::WeaponSlotType>(slot) );
n_assert2( valid, "Can insert item in the inventory" );
if( ! valid )
{
manager->DeleteItem( item );
}
}
this->init = valid;
return valid;
}
//------------------------------------------------------------------------------
/**
@returns true when basic action is done
*/
bool
nGPInsertInInventory::Run()
{
return this->IsDone();
}
//------------------------------------------------------------------------------
/**
@returns true when basic action is done
*/
bool
nGPInsertInInventory::IsDone()const
{
return true;
}
//------------------------------------------------------------------------------
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
[
[
[
1,
127
]
]
] |
fe947210f91fad8dc4d09b0860bc39d0c7a69432
|
1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50
|
/gaze/gaze_reader_VI_t.cpp
|
5be90b0902c4222e7c48552aa84651c89de2e618
|
[] |
no_license
|
llvllrbreeze/alcorapp
|
dfe2551f36d346d73d998f59d602c5de46ef60f7
|
3ad24edd52c19f0896228f55539aa8bbbb011aac
|
refs/heads/master
| 2021-01-10T07:36:01.058011 | 2008-12-16T12:51:50 | 2008-12-16T12:51:50 | 47,865,136 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 20,604 |
cpp
|
#include "gaze_reader_VI_t.h"
#include "alcor/matlab/matlab_mx_utils.hpp"
#include "alcor/core/image_utils.h"
//-------------------------------------------------------------------------++
//#include "alcor.extern/CImg/CImg.h"
//using namespace cimg_library;
//-------------------------------------------------------------------------++
#define WRITESTRUCTS_
//-------------------------------------------------------------------------++
namespace all { namespace gaze {
//-------------------------------------------------------------------------++
gaze_reader_VI_t::gaze_reader_VI_t():
current_sample_(0)
, nsamples_(0)
{
}
//-------------------------------------------------------------------------++
gaze_reader_VI_t::~gaze_reader_VI_t()
{
if (gazelog_.is_open())
gazelog_.close();
if (log_type_ == 1) {
cvReleaseCapture(&eye_avi_[left]);
cvReleaseCapture(&eye_avi_[right]);
cvReleaseCapture(&scene_avi_[left]);
cvReleaseCapture(&scene_avi_[right]);
}
}
//-------------------------------------------------------------------------++
void gaze_reader_VI_t::load(std::string& binlog)
{
//
gazelog_.open(binlog.c_str(), std::ios::in|std::ios::binary);
printf("\nSession data:\n");
gazelog_.read((char*)&nsamples_, sizeof(nsamples_));
printf("-> nsamples: %d\n", nsamples_);
gazelog_.read((char*)&total_elapsed_, sizeof(total_elapsed_));
printf("-> total time: %f\n", total_elapsed_);
gazelog_.read((char*)&log_type_, sizeof(log_type_));
if (log_type_ == 0)
printf("-> binary log\n");
else
printf("-> avi log\n");
gazelog_.read((char*)&eyedims_[left], sizeof(eyedims_[left]));
printf("-> left eye dims: %d:%d:%d\n", eyedims_[left].row_, eyedims_[left].col_, eyedims_[left].depth_);
gazelog_.read((char*)&eyedims_[right], sizeof(eyedims_[right]));
printf("-> right eye dims: %d:%d:%d\n", eyedims_[right].row_, eyedims_[right].col_, eyedims_[right].depth_);
gazelog_.read((char*)&scenedims_[left], sizeof(scenedims_[left]));
printf("-> left scene dims: %d:%d:%d\n", scenedims_[left].row_, scenedims_[left].col_, scenedims_[left].depth_);
gazelog_.read((char*)&scenedims_[right], sizeof(scenedims_[right]));
printf("-> right scene dims: %d:%d:%d\n", scenedims_[right].row_, scenedims_[right].col_, scenedims_[right].depth_);
printf("\nOffsets:\n");
gazelog_.read((char*)&elapsed_offset_, sizeof(elapsed_offset_));
printf("elapsed offset: %d\n", elapsed_offset_);
gazelog_.read((char*)&eye_offset_[left], sizeof(eye_offset_[left]));
printf("left eye offset: %d\n", eye_offset_[left]);
gazelog_.read((char*)&eye_offset_[right], sizeof(eye_offset_[right]));
printf("right eye offset: %d\n", eye_offset_[right]);
gazelog_.read((char*)&scene_offset_[left], sizeof(scene_offset_[left]));
printf("left scence offset: %d\n", scene_offset_[left]);
gazelog_.read((char*)&scene_offset_[right], sizeof(scene_offset_[right]));
printf("right scence offset: %d\n", scene_offset_[right]);
gazelog_.read((char*)&rpy_offset_, sizeof(rpy_offset_));
printf("rpy offset: %d\n", rpy_offset_);
//
//header_offset_ = sizeof(nsamples_)
// + sizeof(total_elapsed_)
// + sizeof(eyedims_)
// + sizeof(scenedims_)
// + sizeof(elapsed_offset_)
// + sizeof(eye_offset_)
// + sizeof(scene_offset_)
// + sizeof(depth_offset_)
// + sizeof(rpy_offset_)
// ;
//size_t per_sample_offset_ =
// elapsed_offset_
// + eye_offset_[left]
// + scene_offset_[left]
// + depth_offset_
// + rpy_offset_;
//printf("header offset: %d\n", header_offset_);
//printf("per sample offset: %d\n", per_sample_offset_);
if (log_type_ == 0)
sample = boost::bind(&gaze_reader_VI_t::sample_bin_, this);
else if (log_type_ == 1)
sample = boost::bind(&gaze_reader_VI_t::sample_avi_, this);
else
sample = NULL;
allocate_();
}
//-------------------------------------------------------------------------++
void gaze_reader_VI_t::allocate_()
{
//ieye[left].reset ( new core::uint8_t [ eye_offset_ ] );
//ieye[right].reset ( new core::uint8_t [ eye_offset_ ] );
//iscene.reset( new core::uint8_t [ scene_offset_] );
//idepth.reset( new core::single_t [ depth_offset_] );
if (log_type_ == 0) {
jpeg_dec_.set_output_ordering(all::core::interleaved_tag);
enc_eye_data_[left].data.reset(new all::core::uint8_t [eye_offset_[left]]);
enc_eye_data_[right].data.reset(new all::core::uint8_t [eye_offset_[right]]);
enc_scene_data_[left].data.reset(new all::core::uint8_t [scene_offset_[left]]);
enc_scene_data_[right].data.reset(new all::core::uint8_t [scene_offset_[right]]);
}
else if (log_type_ == 1) {
eye_avi_[left] = cvCreateFileCapture("eye_left.avi");
eye_avi_[right] = cvCreateFileCapture("eye_right.avi");
scene_avi_[left] = cvCreateFileCapture("scene_left.avi");
scene_avi_[right] = cvCreateFileCapture("scene_right.avi");
}
//for matlab array creation
ieye[left].reset(new all::core::uint8_t[eye_offset_[left]]);
ieye[right].reset(new all::core::uint8_t[eye_offset_[right]]);
iscene[left].reset(new all::core::uint8_t[scene_offset_[left]]);
iscene[right].reset(new all::core::uint8_t[scene_offset_[right]]);
idepth.reset(new all::core::single_t[scene_offset_[left]]);
eye_img_[left] = cvCreateImage(cvSize(eyedims_[left].col_, eyedims_[left].row_),IPL_DEPTH_8U, 3);
eye_img_[right] = cvCreateImage(cvSize(eyedims_[right].col_, eyedims_[right].row_),IPL_DEPTH_8U, 3);
eye_bw_img_[left] = cvCreateImage(cvSize(eyedims_[left].col_, eyedims_[left].row_),IPL_DEPTH_8U, 1);
eye_bw_img_[right] = cvCreateImage(cvSize(eyedims_[right].col_, eyedims_[right].row_),IPL_DEPTH_8U, 1);
scene_img_[left] = cvCreateImage(cvSize(scenedims_[left].col_, scenedims_[left].row_),IPL_DEPTH_8U, 3);
scene_img_[right] = cvCreateImage(cvSize(scenedims_[right].col_, scenedims_[right].row_),IPL_DEPTH_8U, 3);
eye_img_[left]->origin = IPL_ORIGIN_BL;
eye_img_[right]->origin = IPL_ORIGIN_BL;
eye_bw_img_[left]->origin = IPL_ORIGIN_BL;
eye_bw_img_[right]->origin = IPL_ORIGIN_BL;
scene_img_[left]->origin = IPL_ORIGIN_BL;
scene_img_[right]->origin = IPL_ORIGIN_BL;
//stereo_process.init("config/gaze_stereo.ini");
//_eye_filter[left].LoadCameraParams("cmos2.ini");
//_eye_filter[right].LoadCameraParams("cmos2.ini");
current_sample_ = 0;
}
//-------------------------------------------------------------------------++
bool gaze_reader_VI_t::sample_bin_()
{
if(!eof())
{
current_sample_++;
//elapsed time .. in seconds
gazelog_.read((char*)&elapsed_, elapsed_offset_);
gazelog_.read((char*)&enc_eye_data_[left].size, sizeof(std::size_t));
gazelog_.read((char*)enc_eye_data_[left].data.get(), enc_eye_data_[left].size);
gazelog_.read((char*)&enc_eye_data_[right].size, sizeof(enc_eye_data_[right].size));
gazelog_.read((char*)enc_eye_data_[right].data.get(), enc_eye_data_[right].size);
gazelog_.read((char*)&enc_scene_data_[left].size, sizeof(enc_scene_data_[left].size));
gazelog_.read((char*)enc_scene_data_[left].data.get(), enc_scene_data_[left].size);
gazelog_.read((char*)&enc_scene_data_[right].size, sizeof(enc_scene_data_[right].size));
gazelog_.read((char*)enc_scene_data_[right].data.get(), enc_scene_data_[right].size);
jpeg_dec_.decode(dec_eye_data_[left], enc_eye_data_[left].data, enc_eye_data_[left].size);
jpeg_dec_.decode(dec_eye_data_[right], enc_eye_data_[right].data, enc_eye_data_[right].size);
jpeg_dec_.decode(dec_scene_data_[left], enc_scene_data_[left].data, enc_scene_data_[left].size);
jpeg_dec_.decode(dec_scene_data_[right], enc_scene_data_[right].data, enc_scene_data_[right].size);
//ieye[left] = (dec_eye_data_[left].data);
//ieye[right] = (dec_eye_data_[right].data);
//iscene[left] = (dec_scene_data_[left].data);
//iscene[right] = (dec_scene_data_[right].data);
memcpy(eye_bw_img_[left]->imageData, dec_eye_data_[left].data.get(), eye_offset_[left]);
memcpy(eye_bw_img_[right]->imageData, dec_eye_data_[right].data.get(), eye_offset_[right]);
memcpy(scene_img_[left]->imageData, dec_scene_data_[left].data.get(), scene_offset_[left]);
memcpy(scene_img_[right]->imageData, dec_scene_data_[right].data.get(), scene_offset_[right]);
//cvCvtColor(eye_img_[left], eye_bw_img_[left], CV_BGR2GRAY);
//cvCvtColor(eye_img_[right], eye_bw_img_[right], CV_BGR2GRAY);
///Orientation
gazelog_.read((char*)&ihead, rpy_offset_);
}
else
return false;
return true;
}
bool gaze_reader_VI_t::sample_avi_() {
if(!eof())
{
current_sample_++;
//elapsed time .. in seconds
gazelog_.read((char*)&elapsed_, elapsed_offset_);
eye_img_[left] = cvQueryFrame(eye_avi_[left]);
eye_img_[right] = cvQueryFrame(eye_avi_[right]);
scene_img_[left] = cvQueryFrame(scene_avi_[left]);
scene_img_[right] = cvQueryFrame(scene_avi_[right]);
cvCvtColor(eye_img_[left], eye_bw_img_[left], CV_BGR2GRAY);
cvCvtColor(eye_img_[right], eye_bw_img_[right], CV_BGR2GRAY);
//memcpy(ieye[left].get(), eye_bw_img_[left]->imageData, eye_offset_[left]);
//memcpy(ieye[right].get(), eye_bw_img_[right]->imageData, eye_offset_[right]);
//memcpy(iscene[left].get(), scene_img_[left]->imageData, scene_offset_[left]);
//memcpy(iscene[right].get(), scene_img_[right]->imageData, scene_offset_[right]);
///Orientation
gazelog_.read((char*)&ihead, rpy_offset_);
}
else
return false;
return true;
}
//-------------------------------------------------------------------------++
void gaze_reader_VI_t::reset()
{
gazelog_.seekg(header_offset_);
current_sample_ = 0;
}
//-------------------------------------------------------------------------++
///
bool gaze_reader_VI_t::next()
{
return sample();
}
//-------------------------------------------------------------------------++
///jump at num sample
bool gaze_reader_VI_t::peek(size_t num)
{
if(num < nsamples_)
{
gazelog_.seekg(header_offset_ + ((num-1) * per_sample_offset_));
current_sample_ = num-1;
return sample();
}
else
return false;
}
//-------------------------------------------------------------------------++
///
void gaze_reader_VI_t::play(bool bshow, bool bsavemat)
{
//reset();
double last_elapsed = 0;
unsigned int timeroffset;
cvNamedWindow("EyeLEFT");
cvNamedWindow("EyeRIGHT");
cvNamedWindow("SceneLEFT");
cvNamedWindow("SceneRIGHT");
//cvNamedWindow("Depth");
/* IplImage* eye_left = cvCreateImage(cvSize(eyedims_[left].col_, eyedims_[left].row_),IPL_DEPTH_8U, 1);
IplImage* eye_right = cvCreateImage(cvSize(eyedims_[right].col_, eyedims_[right].row_),IPL_DEPTH_8U, 1);
IplImage* scene_left = cvCreateImage(cvSize(scenedims_[left].col_, scenedims_[left].row_),IPL_DEPTH_8U, 3);
IplImage* scene_right = cvCreateImage(cvSize(scenedims_[right].col_, scenedims_[right].row_),IPL_DEPTH_8U, 3);*/
///
while(sample())
{
//TIME
//timeroffset = static_cast<unsigned int> ( (elapsed_- last_elapsed) * 1000.0);
//core::BOOST_SLEEP( timeroffset );
//idepth = stereo_process.do_stereo(scene_img_[left], scene_img_[right]);
//IplImage* stereo_pair[] = {scene_img_[left], scene_img_[right]};
//stereo_process.undistort(stereo_pair, stereo_pair);
//_eye_filter[left].Undistort(&eye_bw_img_[left], &eye_bw_img_[left]);
//_eye_filter[right].Undistort(&eye_bw_img_[right], &eye_bw_img_[right]);
//memcpy(eye_left->imageData, ieye[left].get(), eye_offset_[left]);
//memcpy(eye_right->imageData, ieye[right].get(), eye_offset_[right]);
//memcpy(scene_left->imageData, iscene[left].get(), scene_offset_[left]);
//memcpy(scene_right->imageData, iscene[right].get(), scene_offset_[right]);
//cvConvertImage(scene_left, scene_left, CV_CVTIMG_FLIP);
//cvConvertImage(scene_right, scene_right, CV_CVTIMG_FLIP);
//eye_left->origin = IPL_ORIGIN_BL;
//eye_right->origin = IPL_ORIGIN_BL;
//cvConvertImage(eye_left, eye_img_[left], CV_CVTIMG_FLIP);
//cvConvertImage(eye_right, eye_img_[right], CV_CVTIMG_FLIP);
if(bshow)
{
//memcpy(eye_left->imageData, ieye[left].get(), eye_offset_[left]);
//memcpy(eye_right->imageData, ieye[right].get(), eye_offset_[right]);
//memcpy(scene_left->imageData, iscene[left].get(), scene_offset_[left]);
//memcpy(scene_right->imageData, iscene[right].get(), scene_offset_[right]);
//cvCvtColor(scene_left, scene_left, CV_RGB2BGR);
//cvCvtColor(scene_right, scene_right, CV_RGB2BGR);
cvShowImage("EyeLEFT", eye_bw_img_[left]);
cvShowImage("EyeRIGHT", eye_bw_img_[right]);
cvShowImage("SceneLEFT", scene_img_[left]);
cvShowImage("SceneRIGHT", scene_img_[right]);
//cvShowImage("Depth", stereo_process.get_disparity());
cvWaitKey(1);
}
////////////////////////////////////////////////////////////////////////
if (bsavemat) {
//cvFlip(eye_bw_img_[left], eye_bw_img_[left], 0);
//cvFlip(eye_bw_img_[right], eye_bw_img_[right], 0);
//cvFlip(scene_img_[left], scene_img_[left], 0);
//cvFlip(scene_img_[right], scene_img_[right], 0);
if(log_type_ == 0) {
cvFlip(eye_bw_img_[left], eye_bw_img_[left], 0);
cvFlip(eye_bw_img_[right], eye_bw_img_[right], 0);
cvConvertImage(scene_img_[left], scene_img_[left], CV_CVTIMG_FLIP);
cvConvertImage(scene_img_[right], scene_img_[right], CV_CVTIMG_FLIP);
}
memcpy(ieye[left].get(), eye_bw_img_[left]->imageData, eye_offset_[left]);
memcpy(ieye[right].get(), eye_bw_img_[right]->imageData, eye_offset_[right]);
memcpy(iscene[left].get(), scene_img_[left]->imageData, scene_offset_[left]);
memcpy(iscene[right].get(), scene_img_[right]->imageData, scene_offset_[right]);
matlab_dump();
}
////////////////////////////////////////////////////////////////////////
//for next loop
last_elapsed = elapsed_;
}
}
//-------------------------------------------------------------------------++
///
void gaze_reader_VI_t::matlab_dump()
{
////////////////////////////////////////////////////////////////////////
//MATLAB --------------------------------------------------------------+
//
MATFile *pmat = 0;
//MATLAB
std::string namebase = "./gazelog_";
//
namebase += boost::lexical_cast<std::string>(current_sample_);
namebase += ".mat";
//
pmat = matOpen(namebase.c_str(), "w");
mxArray* mx_scene[2];
mxArray* mx_eye[2];
//mxArray* mx_depth;
//
//printf("\nrgb\n");
//-----------------
mx_scene[left] =
matlab::buffer2array<core::uint8_t>::create_from_interleaved(iscene[left].get()
, matlab::row_major
, scenedims_[left].row_
, scenedims_[left].col_);
mx_scene[right] =
matlab::buffer2array<core::uint8_t>::create_from_interleaved(iscene[right].get()
, matlab::row_major
, scenedims_[right].row_
, scenedims_[right].col_);
//mx_depth =
// all::matlab::buffer2array<core::single_t>::create_from_planar(
// idepth.get()
// , matlab::row_major
// , scenedims_[left].row_
// , scenedims_[left].col_);
//printf("eye\n");
//------------------
mx_eye[left] =
matlab::buffer2array<core::uint8_t>::create_from_planar(ieye[left].get()
, matlab::row_major
, eyedims_[left].row_
, eyedims_[left].col_
, 1);
mx_eye[right] =
matlab::buffer2array<core::uint8_t>::create_from_planar(ieye[right].get()
, matlab::row_major
, eyedims_[right].row_
, eyedims_[right].col_
, 1);
//------------------
//printf("time\n");
mxArray* mx_time =
mxCreateScalarDouble(elapsed_);
//------------------
//printf("roll, pitch, yaw\n");
mxArray* mx_roll =
mxCreateScalarDouble(ihead.roll.deg());
mxArray* mx_pitch =
mxCreateScalarDouble(ihead.pitch.deg());
mxArray* mx_yaw =
mxCreateScalarDouble(ihead.yaw.deg());
//------------------
const char *field_names[] = { "elapsed",
"scene_left" ,
"scene_right",
"depth" ,
"eye_left" ,
"eye_right",
"roll" ,
"pitch" ,
"yaw" };
mwSize dims[2] = {1, 1};
mxArray* ostruct= mxCreateStructArray(2, dims, 9, field_names);
int elapsed_field
, scene_left_field
, scene_right_field
, depth_field
, eye_left_field
, eye_right_field
, roll_field
, pitch_field
, yaw_field;
elapsed_field = mxGetFieldNumber(ostruct, "elapsed");
scene_left_field = mxGetFieldNumber(ostruct, "scene_left");
scene_right_field = mxGetFieldNumber(ostruct, "scene_right");
//depth_field = mxGetFieldNumber(ostruct, "depth");
eye_left_field = mxGetFieldNumber(ostruct, "eye_left");
eye_right_field = mxGetFieldNumber(ostruct, "eye_right");
roll_field = mxGetFieldNumber(ostruct, "roll");
pitch_field = mxGetFieldNumber(ostruct, "pitch");
yaw_field = mxGetFieldNumber(ostruct, "yaw");
//time
mxSetFieldByNumber( ostruct
, 0
, elapsed_field
, mx_time);
//scene
mxSetFieldByNumber( ostruct
, 0
, scene_left_field
, mx_scene[left]);
mxSetFieldByNumber( ostruct
, 0
, scene_right_field
, mx_scene[right]);
//depth
//mxSetFieldByNumber( ostruct
// , 0
// , depth_field
// , mx_depth);
//imeye
mxSetFieldByNumber( ostruct
, 0
, eye_left_field
, mx_eye[left]);
mxSetFieldByNumber( ostruct
, 0
, eye_right_field
, mx_eye[right]);
//roll
mxSetFieldByNumber( ostruct
, 0
, roll_field
, mx_roll);
//pitch
mxSetFieldByNumber( ostruct
, 0
, pitch_field
, mx_pitch);
//yaw
mxSetFieldByNumber( ostruct
, 0
, yaw_field
, mx_yaw);
//write to matfile
matPutVariable(pmat, "gazelog", ostruct);
//
//printf("Close mat\n");
matClose(pmat);
//
//printf("Destroy array\n");
mxDestroyArray(mx_scene[left]);
mxDestroyArray(mx_scene[right]);
//mxDestroyArray(mx_depth);
mxDestroyArray(mx_eye[left]);
mxDestroyArray(mx_eye[right]);
mxDestroyArray(mx_time);
mxDestroyArray(mx_roll);
mxDestroyArray(mx_pitch);
mxDestroyArray(mx_yaw);
}
//-------------------------------------------------------------------------++
bool gaze_reader_VI_t::eof()
{
return current_sample_ == nsamples_;
}
//-------------------------------------------------------------------------++
}}//all::gaze
|
[
"stefano.marra@1ffd000b-a628-0410-9a29-793f135cad17"
] |
[
[
[
1,
530
]
]
] |
dd8180ace38d017a4a63ed8879d5bf9490c09f92
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/nGENE Proj/DeviceKeyboard.h
|
4c08096af09267484dc59a3002c54371bf7c34a4
|
[] |
no_license
|
svn2github/ngene
|
b2cddacf7ec035aa681d5b8989feab3383dac012
|
61850134a354816161859fe86c2907c8e73dc113
|
refs/heads/master
| 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 8,768 |
h
|
/*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: DeviceKeyboard.h
Version: 0.04
---------------------------------------------------------------------------
*/
#pragma once
#ifndef __INC_DEVICEKEYBOARD_H_
#define __INC_DEVICEKEYBOARD_H_
#include "InputDevice.h"
namespace nGENE
{
/// Keys constants taken directly from DirectInput
enum KEY_CONSTANT
{
KC_ESCAPE = 0x01,
KC_1 = 0x02,
KC_2 = 0x03,
KC_3 = 0x04,
KC_4 = 0x05,
KC_5 = 0x06,
KC_6 = 0x07,
KC_7 = 0x08,
KC_8 = 0x09,
KC_9 = 0x0A,
KC_0 = 0x0B,
KC_MINUS = 0x0C, /* - on main keyboard */
KC_EQUALS = 0x0D,
KC_BACK = 0x0E, /* backspace */
KC_TAB = 0x0F,
KC_Q = 0x10,
KC_W = 0x11,
KC_E = 0x12,
KC_R = 0x13,
KC_T = 0x14,
KC_Y = 0x15,
KC_U = 0x16,
KC_I = 0x17,
KC_O = 0x18,
KC_P = 0x19,
KC_LBRACKET = 0x1A,
KC_RBRACKET = 0x1B,
KC_RETURN = 0x1C, /* Enter on main keyboard */
KC_LCONTROL = 0x1D,
KC_A = 0x1E,
KC_S = 0x1F,
KC_D = 0x20,
KC_F = 0x21,
KC_G = 0x22,
KC_H = 0x23,
KC_J = 0x24,
KC_K = 0x25,
KC_L = 0x26,
KC_SEMICOLON = 0x27,
KC_APOSTROPHE = 0x28,
KC_GRAVE = 0x29, /* accent grave */
KC_LSHIFT = 0x2A,
KC_BACKSLASH = 0x2B,
KC_Z = 0x2C,
KC_X = 0x2D,
KC_C = 0x2E,
KC_V = 0x2F,
KC_B = 0x30,
KC_N = 0x31,
KC_M = 0x32,
KC_COMMA = 0x33,
KC_PERIOD = 0x34, /* . on main keyboard */
KC_SLASH = 0x35, /* '/' on main keyboard */
KC_RSHIFT = 0x36,
KC_MULTIPLY = 0x37, /* * on numeric keypad */
KC_LMENU = 0x38, /* left Alt */
KC_SPACE = 0x39,
KC_CAPITAL = 0x3A,
KC_F1 = 0x3B,
KC_F2 = 0x3C,
KC_F3 = 0x3D,
KC_F4 = 0x3E,
KC_F5 = 0x3F,
KC_F6 = 0x40,
KC_F7 = 0x41,
KC_F8 = 0x42,
KC_F9 = 0x43,
KC_F10 = 0x44,
KC_NUMLOCK = 0x45,
KC_SCROLL = 0x46, /* Scroll Lock */
KC_NUMPAD7 = 0x47,
KC_NUMPAD8 = 0x48,
KC_NUMPAD9 = 0x49,
KC_SUBTRACT = 0x4A, /* - on numeric keypad */
KC_NUMPAD4 = 0x4B,
KC_NUMPAD5 = 0x4C,
KC_NUMPAD6 = 0x4D,
KC_ADD = 0x4E, /* + on numeric keypad */
KC_NUMPAD1 = 0x4F,
KC_NUMPAD2 = 0x50,
KC_NUMPAD3 = 0x51,
KC_NUMPAD0 = 0x52,
KC_DECIMAL = 0x53, /* . on numeric keypad */
KC_OEM_102 = 0x56, /* < > | on UK/Germany keyboards */
KC_F11 = 0x57,
KC_F12 = 0x58,
KC_F13 = 0x64, /* (NEC PC98) */
KC_F14 = 0x65, /* (NEC PC98) */
KC_F15 = 0x66, /* (NEC PC98) */
KC_KANA = 0x70, /* (Japanese keyboard) */
KC_ABNT_C1 = 0x73, /* / ? on Portugese (Brazilian) keyboards */
KC_CONVERT = 0x79, /* (Japanese keyboard) */
KC_NOCONVERT = 0x7B, /* (Japanese keyboard) */
KC_YEN = 0x7D, /* (Japanese keyboard) */
KC_ABNT_C2 = 0x7E, /* Numpad . on Portugese (Brazilian) keyboards */
KC_NUMPADEQUALS = 0x8D, /* = on numeric keypad (NEC PC98) */
KC_PREVTRACK = 0x90, /* Previous Track (KC_CIRCUMFLEX on Japanese keyboard) */
KC_AT = 0x91, /* (NEC PC98) */
KC_COLON = 0x92, /* (NEC PC98) */
KC_UNDERLINE = 0x93, /* (NEC PC98) */
KC_KANJI = 0x94, /* (Japanese keyboard) */
KC_STOP = 0x95, /* (NEC PC98) */
KC_AX = 0x96, /* (Japan AX) */
KC_UNLABELED = 0x97, /* (J3100) */
KC_NEXTTRACK = 0x99, /* Next Track */
KC_NUMPADENTER = 0x9C, /* Enter on numeric keypad */
KC_RCONTROL = 0x9D,
KC_MUTE = 0xA0, /* Mute */
KC_CALCULATOR = 0xA1, /* Calculator */
KC_PLAYPAUSE = 0xA2, /* Play / Pause */
KC_MEDIASTOP = 0xA4, /* Media Stop */
KC_VOLUMEDOWN = 0xAE, /* Volume - */
KC_VOLUMEUP = 0xB0, /* Volume + */
KC_WEBHOME = 0xB2, /* Web home */
KC_NUMPADCOMMA = 0xB3, /* , on numeric keypad (NEC PC98) */
KC_DIVIDE = 0xB5, /* / on numeric keypad */
KC_SYSRQ = 0xB7,
KC_RMENU = 0xB8, /* right Alt */
KC_PAUSE = 0xC5, /* Pause */
KC_HOME = 0xC7, /* Home on arrow keypad */
KC_UP = 0xC8, /* UpArrow on arrow keypad */
KC_PGUP = 0xC9, /* PgUp on arrow keypad */
KC_LEFT = 0xCB, /* LeftArrow on arrow keypad */
KC_RIGHT = 0xCD, /* RightArrow on arrow keypad */
KC_END = 0xCF, /* End on arrow keypad */
KC_DOWN = 0xD0, /* DownArrow on arrow keypad */
KC_PGDOWN = 0xD1, /* PgDn on arrow keypad */
KC_INSERT = 0xD2, /* Insert on arrow keypad */
KC_DELETE = 0xD3, /* Delete on arrow keypad */
KC_LWIN = 0xDB, /* Left Windows key */
KC_RWIN = 0xDC, /* Right Windows key */
KC_APPS = 0xDD, /* AppMenu key */
KC_POWER = 0xDE, /* System Power */
KC_SLEEP = 0xDF, /* System Sleep */
KC_WAKE = 0xE3, /* System Wake */
KC_WEBSEARCH = 0xE5, /* Web Search */
KC_WEBFAVORITES = 0xE6, /* Web Favorites */
KC_WEBREFRESH = 0xE7, /* Web Refresh */
KC_WEBSTOP = 0xE8, /* Web Stop */
KC_WEBFORWARD = 0xE9, /* Web Forward */
KC_WEBBACK = 0xEA, /* Web Back */
KC_MYCOMPUTER = 0xEB, /* My Computer */
KC_MAIL = 0xEC, /* Mail */
KC_MEDIASELECT = 0xED /* Media Select */
};
// Structure describing keyboard event
struct KeyboardEvent
{
/// Buffer containing old states of all the keys
char m_cOldKeyBuffer[256];
/// Buffer containing states of all the keys
char m_cKeyBuffer[256];
bool isKeyDown(dword _key) const {return (m_cKeyBuffer[_key] & 0x80) != 0;}
bool isKeyUp(dword _key) const {return (m_cKeyBuffer[_key] & 0x80) == 0;}
bool isKeyPressed(dword _key) const {return (((m_cKeyBuffer[_key] & 0x80) == 0) && ((m_cOldKeyBuffer[_key] & 0x80) != 0));}
};
/** Abstract Keyboard class.
@remarks
You have to provide own implementation for every
API used.
*/
class DeviceKeyboard: public InputDevice
{
public:
DeviceKeyboard();
virtual ~DeviceKeyboard();
/// Creates the keyboard device.
virtual void createDevice()=0;
/// Retrieves input from the keyboard device.
virtual void retrieveData()=0;
/// Checks whether specified key is down.
virtual bool isKeyDown(dword _key) const=0;
};
}
#endif
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
208
]
]
] |
b1ccb71e77e3d622a69d0ba3bcc6d037138f298c
|
22b6d8a368ecfa96cb182437b7b391e408ba8730
|
/engine/include/qvIInputTranslatorFactory.h
|
5ef48f6e4eda8f3f3a8906803cd5d217a2e848ba
|
[
"MIT"
] |
permissive
|
drr00t/quanticvortex
|
2d69a3e62d1850b8d3074ec97232e08c349e23c2
|
b780b0f547cf19bd48198dc43329588d023a9ad9
|
refs/heads/master
| 2021-01-22T22:16:50.370688 | 2010-12-18T12:06:33 | 2010-12-18T12:06:33 | 85,525,059 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,039 |
h
|
/**************************************************************************************************
//This code is part of QuanticVortex for latest information, see http://www.quanticvortex.org
//
//Copyright (c) 2009-2010 QuanticMinds Software Ltda.
//
//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 __I_INPUT_TRANSLATOR_FACTORY_H_
#define __I_INPUT_TRANSLATOR_FACTORY_H_
#include "qvIInputTranslator.h"
#include "qvCommandArgs.h"
namespace qv
{
namespace input
{
class IInputTranslatorFactory
{
public:
virtual qv::input::IInputTranslator* addInputTranslator (const c8* inputTranslatorName, u32 inputTranslatorHashType, qv::CommandArgs* args, bool realTime = false) = 0;
virtual u32 getCreatableInputTranslatorCount() const = 0;
virtual bool getCreateableInputTranslator( u32 inputTranslatorHashType) const = 0;
};
}
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
52
]
]
] |
c2848ab44d3463cf7019c68f0f9b520d5a3e9429
|
6c8c4728e608a4badd88de181910a294be56953a
|
/UiModule/Common/UiVisibilityAction.cpp
|
11351d641ce566d8e8dc2026ad519285ef821f62
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
caocao/naali
|
29c544e121703221fe9c90b5c20b3480442875ef
|
67c5aa85fa357f7aae9869215f840af4b0e58897
|
refs/heads/master
| 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 920 |
cpp
|
// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "UiVisibilityAction.h"
namespace UiServices
{
UiVisibilityAction::UiVisibilityAction(QGraphicsWidget *controlled_widget, QObject *parent) :
UiAction(parent, true),
controlled_widget_(controlled_widget)
{
connect(this, SIGNAL(toggled(bool)), SLOT(ToggleVisibility()));
}
void UiVisibilityAction::SetControlledWidget(QGraphicsWidget *controlled_widget)
{
controlled_widget_ = controlled_widget;
}
void UiVisibilityAction::ToggleVisibility()
{
if (!controlled_widget_)
return;
if (controlled_widget_->isVisible())
controlled_widget_->hide();
else
controlled_widget_->show();
emit VisibilityChanged(controlled_widget_->isVisible());
}
}
|
[
"[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3"
] |
[
[
[
1,
32
]
]
] |
430c65ae52c9eace30bf5038f77d9bd4a7fdb43a
|
5a39be53de11cddb52af7d0b70b56ef94cc52d35
|
/doc/P3相关工具包/ChiAnalyzer/Analyzer/Analyzer.H
|
7df8a06c27afe162c8b1088826df6b822af78afc
|
[] |
no_license
|
zchn/jsepku
|
2b76eb5d118f86a5c942a9f4ec25a5adae24f802
|
8290fef5ff8abaf62cf050cead489dc7d44efa5f
|
refs/heads/master
| 2016-09-10T19:44:23.882210 | 2008-01-01T07:32:13 | 2008-01-01T07:32:13 | 33,052,475 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 1,370 |
h
|
#ifndef _ANALYZER_H_
#define _ANALYZER_H_
#include "../Result/Result.cpp"
#include "../Unknown/UnknowWord.cpp"
#include "../Tag/Span.cpp"
#include"../Utility/Dictionary.cpp"
#include"../Segment/Segment.cpp"
#include"../Segment/Queue.cpp"
#include"../Segment/SegGraph.cpp"
#include"../Segment/DynamicArray.cpp"
#include"../Segment/NShortPath.cpp"
#include"../Utility/ContextStat.cpp"
#include"../Utility/Utility.cpp"
#include <string>
//*****************************************************************************
//类名称:Analyzer
//定义该类的目的:完成中文分词功能
//类属性:功能类
//*****************************************************************************
class Analyzer{
private:
bool m_bValid;
//Segment Class
CResult m_Result;
bool isValid() const;
public:
//constructor
Analyzer();
//destructor
virtual ~Analyzer();
//return true if the analyzer is ready, should be invoked first.
bool init();
//the input is a std::string to be processed, sSource;
//the output is saved in sResult
bool processString(const std::string &sSource, std::string &sResult);
//the input is the path of the file to be processed, sFilePath;
//the output is saved in sResult
bool processFile(const std::string &sFilePath, std::string &sResult);
};
#endif
|
[
"joyanlj@702d1322-cd41-0410-9eed-0fefee27d168"
] |
[
[
[
1,
49
]
]
] |
7644a8f7238ffe2e74b2ea8930c85e96c7b9ca2a
|
0ce35229d1698224907e00f1fdfb34cfac5db1a2
|
/voiture.cpp
|
6f5ce8aeb753d862ee96c7b98fb63db0d6dbf099
|
[] |
no_license
|
manudss/efreiloca
|
f7b1089b6ba74ff26e6320044f66f9401ebca21b
|
54e8c4af1aace11f35846e63880a893e412b3309
|
refs/heads/master
| 2020-06-05T17:34:02.234617 | 2007-06-04T19:12:15 | 2007-06-04T19:12:15 | 32,325,713 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 108 |
cpp
|
#include "StdAfx.h"
#include "voiture.h"
voiture::voiture(void)
{
}
voiture::~voiture(void)
{
}
|
[
"pootoonet@65b228c9-682f-0410-abd1-c3b8cf015911"
] |
[
[
[
1,
10
]
]
] |
967ea544b82823c4224741cca52ece0b1aeb4be7
|
58ef4939342d5253f6fcb372c56513055d589eb8
|
/SimulateMessage/Client/source/Views/src/MainScreenView.cpp
|
5dd7526e716a1bef222bd0ce85dc364903d14cec
|
[] |
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 | 3,507 |
cpp
|
/*
============================================================================
Name : MainScreenView.cpp
Author : zengcity
Copyright : Your copyright notice
Description : CMainScreenView implementation
============================================================================
*/
// INCLUDE FILES
#include <aknviewappui.h>
#include <eikmenup.h>
#include "MainScreenView.h"
#include "SHPlatform.h"
// ============================ MEMBER FUNCTIONS ===============================
CMainScreenView::CMainScreenView()
{
// No implementation required
iContainer = NULL;
}
CMainScreenView::~CMainScreenView()
{
DoDeactivate();
//add your code here ...
}
CMainScreenView* CMainScreenView::NewLC()
{
CMainScreenView* self = new (ELeave) CMainScreenView();
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
CMainScreenView* CMainScreenView::NewL()
{
CMainScreenView* self = CMainScreenView::NewLC();
CleanupStack::Pop(); // self;
return self;
}
void CMainScreenView::ConstructL()
{
BaseConstructL(R_VIEW_MAINSCREEN);
//add your code here...
}
/**
*
* */
TUid CMainScreenView::Id() const
{
return TUid::Uid(ESimulateMessageMainScreenViewId);
}
void CMainScreenView::HandleCommandL(TInt aCommand)
{
switch (aCommand)
{
case ECommandCreate:
break;
case ECommandCreateNew:
SHModel()->SetEditModel(CSHModel::EEditModelCreate);
SHChangeView(ESimulateMessageEditViewId);
break;
case ECommandCreateFrom:
SHChangeView(ESimulateMessageLoadDraftViewId);
break;
case ECommandManage:
break;
case ECommandManageEdit:
iContainer->EditSelectedTask();
break;
case ECommandmanageRemove:
iContainer->RemoveSelectedTask();
break;
case ECommandRemovedScreen:
SHChangeView(ESimulateMessageRemovedScreenViewId);
break;
case ECommandActiveServer:
SHSession().ActiveSchedule();
break;
case ECommandDeactiveServer:
SHSession().DeactiveSchedule();
break;
case ECommandSetting:
SHChangeView(ESimulateMessageSettingViewId);
break;
default:
AppUi()->HandleCommandL(aCommand);
}
}
void CMainScreenView::HandleStatusPaneSizeChange()
{
if (iContainer != NULL)
iContainer->SetRect(ClientRect());
}
/**
*
* */
void CMainScreenView::DoActivateL(const TVwsViewId& aPrevViewId,
TUid /*aCustomMessageId*/, const TDesC8& aCustomMessage)
{
if (iContainer == NULL)
{
iContainer = CMainScreenContainer::NewL(ClientRect());
iContainer->SetMopParent(this);
AppUi()->AddToStackL(*this, iContainer);
//add your init code ...
if ( aCustomMessage.Length() > 0)
if (aCustomMessage.Compare(KViewChangeParamReboot) == 0)
{
SHSession().RebootSchedule();
}
}
}
void CMainScreenView::DoDeactivate()
{
if (iContainer != NULL)
{
AppUi()->RemoveFromViewStack(*this, iContainer);
delete iContainer;
iContainer = NULL;
}
}
void CMainScreenView::DynInitMenuPaneL( TInt aResourceId, CEikMenuPane* aMenuPane )
{
if (aResourceId == R_MAINSCREEN_MENU)
{
TBool state = SHSession().IsScheduleActive();
if (state)
{
aMenuPane->SetItemDimmed(ECommandActiveServer, ETrue);
aMenuPane->SetItemDimmed(ECommandDeactiveServer, EFalse);
}
else
{
aMenuPane->SetItemDimmed(ECommandActiveServer, EFalse);
aMenuPane->SetItemDimmed(ECommandDeactiveServer, ETrue);
}
}
}
// End of File
|
[
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] |
[
[
[
1,
154
]
]
] |
87b10a02354888d3a131fefe24d85e07a6224a30
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/serialization/test/test_primitive.cpp
|
5201088e6e4c9b45f9aa868830b1f70ac53a02df
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
willrebuild/flyffsf
|
e5911fb412221e00a20a6867fd00c55afca593c7
|
d38cc11790480d617b38bb5fc50729d676aef80d
|
refs/heads/master
| 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,850 |
cpp
|
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_primitive.cpp
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// test implementation level "primitive_type"
#include <fstream>
#include "test_tools.hpp"
#include <boost/preprocessor/stringize.hpp>
#include BOOST_PP_STRINGIZE(BOOST_ARCHIVE_TEST)
#include <boost/serialization/level.hpp>
#include <boost/serialization/nvp.hpp>
struct A
{
template<class Archive>
void serialize(Archive &ar, const unsigned int /* file_version */){
// note: should never fail here
BOOST_STATIC_ASSERT(0 == sizeof(Archive));
}
};
std::ostream & operator<<(std::ostream &os, const A & /* a */){ return os;}
std::istream & operator>>(std::istream &is, A & /* a */){return is;}
#ifndef BOOST_NO_STD_WSTREAMBUF
std::wostream & operator<<(std::wostream &os, const A & /* a */){ return os;}
std::wistream & operator>>(std::wistream &is, A & /* a */){return is;}
#endif
BOOST_CLASS_IMPLEMENTATION(A, boost::serialization::primitive_type)
void out(const char *testfile, A & a)
{
test_ostream os(testfile, TEST_STREAM_FLAGS);
test_oarchive oa(os);
oa << BOOST_SERIALIZATION_NVP(a);
}
void in(const char *testfile, A & a)
{
test_istream is(testfile, TEST_STREAM_FLAGS);
test_iarchive ia(is);
ia >> BOOST_SERIALIZATION_NVP(a);
}
int
test_main( int /* argc */, char* /* argv */[] )
{
const char * testfile = boost::archive::tmpnam(NULL);
BOOST_REQUIRE(NULL != testfile);
A a;
out(testfile, a);
in(testfile, a);
return EXIT_SUCCESS;
}
// EOF
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
65
]
]
] |
df94de63c0e0a58390a4cbcb6245dd1fec8059b8
|
74c8da5b29163992a08a376c7819785998afb588
|
/NetAnimal/Game/wheel/WheelAnimalController/include/DoubleProcess.h
|
50597686c0b974217805b72341cf224d3a810975
|
[] |
no_license
|
dbabox/aomi
|
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
|
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
|
refs/heads/master
| 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,091 |
h
|
#ifndef __Orz_DoubleProcess_h__
#define __Orz_DoubleProcess_h__
#include "WheelAnimalControllerConfig.h"
#include "Something.h"
#include "WheelAnimalSceneObj.h"
#include "ObjectLights.h"
#include "WheelAnimalProcess.h"
#include "WinnerAnimation.h"
#include "ColorChange.h"
//#include "WheelUI.h"
#include "ProcessFactory.h"
namespace Orz
{
class DoubleProRun: public WheelAnimalProcess, public UpdateToEnable<DoubleProRun>
{
public:
DoubleProRun();
void enable(void);
virtual bool update(TimeType interval);
virtual ~DoubleProRun(void);
void clear(void);
private:
TimeType _time;
;
SoundPlayerPtr _DoubleProRunMusic;
bool _DoubleProRunIsEnd;
bool _DoubleProRunIsPlaying;
};
//////////////////////////////////////////////////////////////////////////////////////
class DoubleShowWinner: public WheelAnimalProcess, public UpdateToEnable<DoubleShowWinner>
{
public:
DoubleShowWinner( boost::shared_ptr<WheelAnimalSceneObj> scene, int winner, const Ogre::Degree & angle);
void enable(void);
virtual ~DoubleShowWinner(void);
void clear();
virtual bool update(TimeType interval/*********/);
private:
boost::shared_ptr<WinnerAnimation> _winnerAnim;
boost::shared_ptr<WheelAnimalSceneObj> _scene;
Ogre::SceneNode * _end;
Ogre::AnimationState * _animation;
int _winner;
;
Ogre::AnimationState * _camAnimation;
};
/////////////////////////////////////////////////////////////////////////////////////
class RotateAnimation;
class DoubleGameRotate: public WheelAnimalProcess , public UpdateToEnable<DoubleGameRotate>
{
public:
DoubleGameRotate(boost::shared_ptr<WheelAnimalSceneObj> scene,
boost::shared_ptr<RotateAnimation> needle,
boost::shared_ptr<RotateAnimation> rotate,
int nAngle,
int rAngle
);
virtual ~DoubleGameRotate(void);
virtual void enable(void);
virtual bool update(TimeType interval/*********/);
void clear(void);
private:
boost::shared_ptr<WheelAnimalSceneObj> _scene;
boost::shared_ptr<RotateAnimation> _rotate;
boost::shared_ptr<RotateAnimation> _needle;
SoundPlayerPtr _DoubleGameRotateMusic;
};
/////////////////////////////////////////////////////////////////////////////////////////////
class DoublePlayAnimation: public WheelAnimalProcess,public UpdateToEnable<DoublePlayAnimation>
{
public:
DoublePlayAnimation(boost::shared_ptr<WheelAnimalSceneObj> scene, WinEffectPtr effect , int winner);
virtual ~DoublePlayAnimation(void);
void clear(void);
void enable(void);
bool update(Orz::TimeType interval);
private:
boost::shared_ptr<WheelAnimalSceneObj> _scene;
int _winner;
TimeType _time;
WinEffectPtr _effect;
;
SoundPlayerPtr _DoublePlayAnimationMusic;
};
////////////////////////////////////////////////////////////////////////////
class DoubleProcess5: public WheelAnimalProcess, public UpdateToEnable<DoubleProcess5>
{
public:
DoubleProcess5();
virtual ~DoubleProcess5(void);
void enable(void);
bool update(Orz::TimeType interval);
void clear(void);
private:
TimeType _time;
};
//////////////////////////////////////////////////////////////////////////////////////////////
class ProcessFactoryDouble:public ProcessFactory
{
public:
ProcessFactoryDouble(
boost::shared_ptr<WheelAnimalSceneObj> scene,
WinEffectPtr effect,
boost::shared_ptr<RotateAnimation> needle,
boost::shared_ptr<RotateAnimation> rotate,
ObjectLightsPtr objLights
);
virtual ~ProcessFactoryDouble(void);
Process0Ptr createProcess0(void);
ProcessPtr createProcess1(void) ;
ProcessPtr createProcess2(void) ;
ProcessPtr createProcess3(void);
ProcessPtr createProcess4(void);
/* ProcessPtr createProcess5(void);*/
private:
boost::shared_ptr<RotateAnimation> _rotate;
boost::shared_ptr<RotateAnimation> _needle;
boost::shared_ptr<AnimalChange> _ac;
WinEffectPtr _effect;
};
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
157
]
]
] |
afb338577f5ae7ef5473d73e329ee4f04c8da7ef
|
ec4c161b2baf919424d8d21cd0780cf8065e3f69
|
/Velo/Source/Embedded Controller/arduino/cGPS.cpp
|
3cdc41d3772e1066c4cfb9a3ce23fca60dcb26b5
|
[] |
no_license
|
jhays200/EV-Tracking
|
b215d2a915987fe7113a05599bda53f254248cfa
|
06674e6f0f04fc2d0be1b1d37124a9a8e0144467
|
refs/heads/master
| 2016-09-05T18:41:21.650852 | 2011-06-04T01:50:25 | 2011-06-04T01:50:25 | 1,673,213 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,753 |
cpp
|
///////////////////////////////////////////////////////////
// cGPS.cpp
// Implementation of the Class cGPS
// Created on: 05-May-2010 3:28:23 AM
// Original author: shawn.mcginnis
///////////////////////////////////////////////////////////
#include "cGPS.h"
cGPS::cGPS()
{
//GPS Serial Line
Serial3.begin(38200);
}
cGPS::~cGPS()
{
}
bool cGPS::Update()
{
for( int i = Serial3.available() ; i > 0 ; --i )
{
if( gps.Parse(Serial3.read()) )
{
//TODO: Messaging.Send()
i = -1;
Serial2.print("\nGPS Date: ");
Serial2.print(gps.utc.hour,DEC);
Serial2.print(":");
Serial2.print(gps.utc.min,DEC);
Serial2.print(":");
Serial2.print(gps.utc.sec,DEC);
Serial2.print(" ");
Serial2.print(gps.utc.month,DEC);
Serial2.print("-");
Serial2.print(gps.utc.day,DEC);
Serial2.print("-20");
Serial2.print(gps.utc.year,DEC);
Serial2.print(" UTC\n");
delay(50);
Serial2.print("Location: ");
Serial2.printFloat(gps.latitude,8);
Serial2.print(", ");
Serial2.printFloat(gps.longitude,8);
Serial2.print("\n");
delay(50);
Serial2.print(" Speed: ");
Serial2.print(gps.speed);
Serial2.print("mph\n");
delay(50);
Serial2.print(" Heading: ");
Serial2.print(gps.direction);
Serial2.print("deg ");
Serial2.print(gps.declination);
Serial2.print("dec");
}
}
return false;
}
|
[
"[email protected]"
] |
[
[
[
1,
68
]
]
] |
8f55d9bdc82738cfe1f0b95c32d1959a04ce614d
|
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
|
/Code/TootleAudio/TLAudio.cpp
|
ead4f53cf61ec0a401ddd688452fab2601677da1
|
[] |
no_license
|
SoylentGraham/Tootle
|
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
|
17002da0936a7af1f9b8d1699d6f3e41bab05137
|
refs/heads/master
| 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,566 |
cpp
|
#include "TLAudio.h"
#include <TootleAsset/TLAsset.h>
namespace TLAudio
{
namespace Platform
{
SyncBool Init();
SyncBool Update();
SyncBool Shutdown();
// Low level audio routines
Bool CreateSource(TRefRef SourceRef);
Bool RemoveSource(TRefRef SourceRef);
Bool CreateBuffer(TRefRef AudioAssetRef); // wrapper which loads the asset then does create buffer
Bool CreateBuffer(TLAsset::TAudio& AudioAsset);
Bool RemoveBuffer(TRefRef AudioAssetRef);
Bool HasSource(TRefRef AudioSourceRef);
Bool HasBuffer(TRefRef AudioAssetRef);
Bool AttachSourceToBuffer(TRefRef AudioSourceRef, TRefRef AudioAssetRef, Bool bStreaming);
// Audio control
Bool StartAudio(TRefRef AudioSourceRef);
Bool StopAudio(TRefRef AudioSourceRef);
Bool PauseAudio(TRefRef AudioSourceRef);
Bool DetermineFinishedAudio(TArray<TRef>& refArray);
// Audio Properties
Bool SetPitch(TRefRef AudioSourceRef, const float fPitch);
Bool GetPitch(TRefRef AudioSourceRef, float& fPitch);
Bool SetVolume(TRefRef AudioSourceRef, const float fVolume);
Bool GetVolume(TRefRef AudioSourceRef, float& fVolume);
Bool SetLooping(TRefRef AudioSourceRef, const Bool bLooping);
Bool GetIsLooping(TRefRef AudioSourceRef, Bool& bLooping);
Bool SetRelative(TRefRef AudioSourceRef, const Bool bRelative);
Bool GetIsRelative(TRefRef AudioSourceRef, Bool& bRelative);
Bool SetPosition(TRefRef AudioSourceRef, const float3 vPosition);
Bool GetPosition(TRefRef AudioSourceRef, float3& vPosition);
Bool SetVelocity(TRefRef AudioSourceRef, const float3 vVelocity);
Bool GetVelocity(TRefRef AudioSourceRef, float3& vVelocity);
Bool SetMinRange(TRefRef AudioSourceRef, const float fDistance);
Bool SetMaxRange(TRefRef AudioSourceRef, const float fDistance);
Bool SetRateOfDecay(TRefRef AudioSourceRef, const float fRateOfDecay);
// Audio system listener (aka a virtual microphone)
void SetListener(const TListenerProperties& Props);
Bool Enable();
Bool Disable();
Bool Activate();
Bool Deactivate();
}
}
//------------------------------------------------
// wrapper which loads the asset then does create buffer
//------------------------------------------------
Bool TLAudio::Platform::CreateBuffer(TRefRef AudioAssetRef)
{
TLAsset::TAudio* pAudioAsset = TLAsset::GetAsset<TLAsset::TAudio>( AudioAssetRef );
if ( !pAudioAsset )
return FALSE;
return CreateBuffer( *pAudioAsset );
}
|
[
"[email protected]",
"[email protected]"
] |
[
[
[
1,
68
]
],
[
[
69,
79
]
]
] |
1f31a328b7a42a64be4f6ad78318a855cd25f423
|
9b3df03cb7e134123cf6c4564590619662389d35
|
/Typedefs.h
|
4d26c8f015669a1748527e28a7b502452e0ed372
|
[] |
no_license
|
CauanCabral/Computacao_Grafica
|
a32aeff2745f40144a263c16483f53db7375c0ba
|
d8673aed304573415455d6a61ab31b68420b6766
|
refs/heads/master
| 2016-09-05T16:48:36.944139 | 2010-12-09T19:32:05 | 2010-12-09T19:32:05 | null | 0 | 0 | null | null | null | null |
ISO-8859-10
|
C++
| false | false | 1,765 |
h
|
#ifndef __Typedefs_h
#define __Typedefs_h
//[]------------------------------------------------------------------------[]
//| |
//| GVSG Foundation Classes |
//| Version 1.0 |
//| |
//| CopyrightŪ 2007, Paulo Aristarco Pagliosa |
//| All Rights Reserved. |
//| |
//[]------------------------------------------------------------------------[]
//
// OVERVIEW: Typedefs.h
// ========
// Commom typedefs.
typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned long uint32;
typedef signed long int32;
typedef unsigned int uint;
#define UINT8(buf,i) (*(uint8*)((uint8*)buf + (i)))
#define INT8(buf,i) (*(int8*)((uint8*)buf + (i)))
#define UINT16(buf,i) (*(uint16*)((uint8*)buf + (i)))
#define INT16(buf,i) (*(int16*)((uint8*)buf + (i)))
#define UINT32(buf,i) (*(uint32*)((uint8*)buf + (i)))
#define INT32(buf,i) (*(int32*)((uint8*)buf + (i)))
#define INT(buf,i) (*(int*)((uint8*)buf + (i)))
namespace System
{ // begin namespace System
//
// Auxiliary functions
//
template <typename T>
inline void
swap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
template <typename T>
inline bool
checkRange(const T& x, const T& a, const T& b)
{
return x >= a && x <= b;
}
} // end namespace System
#endif // __Typedefs_h
|
[
"[email protected]"
] |
[
[
[
1,
59
]
]
] |
d24404c90aa301aafb97947e58b714585ee89d55
|
de98f880e307627d5ce93dcad1397bd4813751dd
|
/3libs/ut/include/OXRegistryWatchNotifier.h
|
07338d6f8897429cd568dedb0c44047536f8060c
|
[] |
no_license
|
weimingtom/sls
|
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
|
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
|
refs/heads/master
| 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,123 |
h
|
// ==========================================================================
// Class Specification : COXRegistryWatchNotifier
// ==========================================================================
// Header File : OXRegistryWatchNotifier.h
// Version: 9.3
// //////////////////////////////////////////////////////////////////////////
// Properties :
// NO Abstract class (does not have any objects)
// YES Derived from CObject
// NO Is a Cwnd.
// NO Two stage creation (constructor & Create())
// NO Has a message map
// NO Needs a resource (template)
// NO Persistent objects (saveable on disk)
// NO Uses exceptions
// //////////////////////////////////////////////////////////////////////////
// Description :
// This class encapsulates the notification parameters.
// When you specify a Registry key to watch for and window to receive notification message,
// you can specify some additional parameters for this watch: type of changes to be reported,
// whether or not subkeys should be watched as well, etc. All these parameters are encapsulated
// in COXRegistryWatchNotifier class that can be used for its retrieving.
// Example :
// COXRegistryWatchNotifier RegWatchNotifier;
// ...
// ::RegNotifyChangeKeyValue(RegWatchNotifier.GetRegKey(), RegWatchNotifier.GetWatchSubtree(),
// RegWatchNotifier.GetWatchFilter(), (HANDLE)RegWatchNotifier.GetEvent());
// Remark :
// COXRegistryWatcher class has a "watch queue" of COXRegistryWatchNotifier objects. Each of these
// notifiers has its own unique ID, that can be retrieved by COXRegistryWatchNotifier::GetWatchID().
// Prerequisites (necessary conditions):
/////////////////////////////////////////////////////////////////////////////
#ifndef __OXREGISTRYWATCHNOTIFIER_H__
#define __OXREGISTRYWATCHNOTIFIER_H__
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "OXDllExt.h"
#include <afxmt.h>
class OX_CLASS_DECL COXRegistryWatchNotifier : public CObject
{
friend class COXRegistryWatcher;
// Data members -------------------------------------------------------------
public:
protected:
BOOL m_bPost;
BOOL m_bWatchSubtree;
DWORD m_dwNotifyFilter;
DWORD m_dwID;
HKEY m_hWatchKey;
HWND m_hWndDst;
CEvent* m_phWatchEvent;
CTime m_tNotificationTime;
private:
// Member functions ---------------------------------------------------------
public:
COXRegistryWatchNotifier();
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Constructs the COXRegistryWatchNotifier object and initializes members.
CTime GetNotificationTime() const;
// --- In :
// --- Out :
// --- Returns : Notification time.
// --- Effect : Returns the time when the notification was received.
HKEY GetRegKey() const;
// --- In :
// --- Out :
// --- Returns : Registry key handle.
// --- Effect : Returns the original key specification that is being watch.
BOOL GetWatchSubtree() const;
// --- In :
// --- Out :
// --- Returns : Subtrees watch flag.
// --- Effect : Returns whether subtrees are being watched.
DWORD GetWatchFilter() const;
// --- In :
// --- Out :
// --- Returns : Watch filter - combination of flags that control which changes should be
// reported. Flags are described in the "Data members - public:" section
// of COXRegistryWatcher Class Specification.
// --- Effect : Returns the watch filter that is being used.
DWORD GetWatchID() const;
// --- In :
// --- Out :
// --- Returns : Watch notifier ID (>0), or 0 - if this notifier is not initialized
// in "watch queue" of COXRegistryWatcher.
// --- Effect : Returns the watch notifier ID.
CEvent* GetEvent() const;
// --- In :
// --- Out :
// --- Returns : Pointer to CEvent object that represents notification event.
// --- Effect : Retrieves the Registry notification event. When Registry key is changed,
// this event is signaled.
CWnd* GetWndDst() const;
// --- In :
// --- Out :
// --- Returns : Pointer to CWnd object that represents receiving window.
// --- Effect : Returns the window that receives the notification message.
BOOL GetPost() const;
// --- In :
// --- Out :
// --- Returns : If TRUE, notification message is posted to a window, if FALSE, message sent.
// --- Effect : Returns whether notification message posted or sent to a window.
COXRegistryWatchNotifier& operator=(const COXRegistryWatchNotifier& RegistryWatchNotifier);
// --- In : RegistryWatchNotifier : source object.
// --- Out :
// --- Returns :
// --- Effect : Assignment operator.
protected:
void SetMembers(HKEY hWatchKey, BOOL bWatchSubtree, DWORD dwNotifyFilter, CEvent* phWatchEvent, DWORD dwID);
void SetNotificationTime();
void SetPost(BOOL bPost);
void SetWndDst(CWnd* pWndDst);
private:
};
// Include inline functions
#include "OXRegistryWatchNotifier.inl"
#endif // __OXREGISTRYWATCHNOTIFIER_H__
// //////////////////////////////////////////////////////////////////////////
|
[
"[email protected]"
] |
[
[
[
1,
158
]
]
] |
c540f02c6f0000c4337c518ddb3da034afade4d8
|
4c3c35e4fe1ff2567ef20f0b203fe101a4a2bf20
|
/HW2/src/main.cpp
|
0b99ccf57b4e4ff43892b95810876a97c0ba61ca
|
[] |
no_license
|
kolebole/monopolocoso
|
63c0986707728522650bd2704a5491d1da20ecf7
|
a86c0814f5da2f05e7676b2e41f6858d87077e6a
|
refs/heads/master
| 2021-01-19T15:04:09.283953 | 2011-03-27T23:21:53 | 2011-03-27T23:21:53 | 34,309,551 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 816 |
cpp
|
#include <fstream>
#include "Gz.h"
using namespace std;
Gz gz;
int main() {
gz.initFrameSize(320, 240);
gz.clearColor(GzColor(0, 0, 0)); //Background color: Black
gz.enable(GZ_DEPTH_TEST); //Use depth test
gz.clearDepth(-100); //Default depth: -100
ifstream fi("Tris.txt");
int nTri;
fi>>nTri; //Number of triangles
gz.clear(GZ_COLOR_BUFFER | GZ_DEPTH_BUFFER); //Clear frame buffer with background color
//Clear depth buffer with default depth
GzVertex v;
GzColor c;
gz.begin(GZ_TRIANGLES); //Draw triangles
for (int i=0; i<nTri; i++)
for (int j=0; j<3; j++) {
fi>>v[X]>>v[Y]>>v[Z];
gz.addVertex(v);
fi>>c[R]>>c[G]>>c[B]>>c[A];
gz.addColor(c);
}
gz.end();
fi.close();
gz.toImage().save("myTeaPot.bmp");
return 0;
}
|
[
"[email protected]@a7811d78-34aa-4512-2aaf-9c23cbf1bc95",
"chuminhtri@a7811d78-34aa-4512-2aaf-9c23cbf1bc95"
] |
[
[
[
1,
35
],
[
37,
39
]
],
[
[
36,
36
]
]
] |
052a5dc0367f660ddc5017c8731253146bb343ff
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/Tutorials/Tutorial_1_1/MyFirstApp.cpp
|
cb9ade70958e3211c72e793a728e61e2675613f9
|
[] |
no_license
|
svn2github/ngene
|
b2cddacf7ec035aa681d5b8989feab3383dac012
|
61850134a354816161859fe86c2907c8e73dc113
|
refs/heads/master
| 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 953 |
cpp
|
#include "MyFirstApp.h"
#include "nGENE.h"
void MyFirstApp::createApplication()
{
FrameworkWin32::createApplication();
Renderer::getSingleton().setClearColour(0, 40, 160);
SceneManager* sm = Engine::getSingleton().getSceneManager(0);
Camera* cam;
cam = sm->createCamera(L"CameraFirstPerson", L"Camera");
cam->setPosition(Vector3(0.0f, 2.0f, -5.0f));
sm->getRootNode()->addChild(L"Camera", cam);
Engine::getSingleton().setActiveCamera(cam);
PrefabBox* box = sm->createBox(1.0f, 2.0f, 1.0f);
box->setPosition(0.0f, 3.0f, 7.0f);
Surface* surf = box->getSurface(L"Base");
Material* mat = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"crate");
surf->setMaterial(mat);
sm->getRootNode()->addChild(L"Box", box);
Engine::getSingleton().getRenderer().setLightEnabled(false);
}
int main()
{
MyFirstApp app;
app.createApplication();
app.run();
app.shutdown();
return 0;
}
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
38
]
]
] |
96b57a7635fb4ee2841b9b0bc672b25ae7400c21
|
ee44b7f80be6bddad3e337991acccdac4dc7b8a7
|
/MVAnalyzer/FocusArea.h
|
0962d641af0b3aab04fb895709945c8a12339151
|
[] |
no_license
|
vuduykhuong1412/mv-analyzer
|
d97a11e71a7189dac6414fea369eaa773e7789fa
|
3eb424bd8ee5938453dc342944ec3ec8af9bb3e7
|
refs/heads/master
| 2021-01-10T01:28:22.124681 | 2009-05-27T16:08:00 | 2009-05-27T16:08:00 | 48,032,634 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,971 |
h
|
#if !defined(AFX_FOCUSAREA_H__C5815FC7_9857_444A_8123_AA176B78EA85__INCLUDED_)
#define AFX_FOCUSAREA_H__C5815FC7_9857_444A_8123_AA176B78EA85__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// FocusArea.h : header file
//
#include "defines.h"
#include "MBData.h"
class CMVAnalyzerDlg;
/////////////////////////////////////////////////////////////////////////////
// CFocusArea window
class CFocusArea : public CStatic
{
// Construction
public:
CFocusArea();
// Attributes
public:
// Operations
public:
int bBlink;
CMVAnalyzerDlg* pDlg;
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CFocusArea)
//}}AFX_VIRTUAL
// Implementation
public:
void ModifyMV(MVData* new_mv);
unsigned char Y[FOCUS_PIX_SIZE][FOCUS_PIX_SIZE];
MVData * GetCurrMV(void);
void NextMV(void);
void SetFocusArea(CMBData *mbd, int bx, int by);
virtual ~CFocusArea();
// Generated message map functions
protected:
//{{AFX_MSG(CFocusArea)
afx_msg void OnPaint();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
CMVPlayback *Pic;
int FocusBlockY;
int FocusBlockX;
unsigned char * RGBbuf;
CMBData *qmb; // block structure
BITMAPINFO * BmpInfo; void GetClientRectSize(void);
int rw, rh;
int CurrMV_No;
MVData CurrMV;
void DrawBackground(CDC *pDC);
void DrawBlock(CDC *pDC, int x1, int y1, int x2, int y2, int Q);
void DrawArrow(CDC *pDC, int vx, int vy, double cx, double cy, int Q);
int toWindowX(double x);
int toWindowY(double y);
int toPictureX(int x);
int toPictureY(int y);
void ShowFocusBlock(CDC *pDC);
void ShowFocusArea(CDC *pDC);
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_FOCUSAREA_H__C5815FC7_9857_444A_8123_AA176B78EA85__INCLUDED_)
|
[
"taopin@727d0554-1d2d-11de-b56b-c9554f25afe1"
] |
[
[
[
1,
79
]
]
] |
e29e89d139116f4371c1c5a0076b54d894be5139
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/graph/example/bfs_neighbor.cpp
|
7a79ca6d912945057c0a7704d4be4134a3940350
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Artistic-2.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
willrebuild/flyffsf
|
e5911fb412221e00a20a6867fd00c55afca593c7
|
d38cc11790480d617b38bb5fc50729d676aef80d
|
refs/heads/master
| 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,635 |
cpp
|
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/config.hpp>
#include <algorithm>
#include <vector>
#include <utility>
#include <iostream>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/neighbor_bfs.hpp>
#include <boost/property_map.hpp>
/*
This examples shows how to use the breadth_first_search() GGCL
algorithm, specifically the 3 argument variant of bfs that assumes
the graph has a color property (property) stored internally.
Two pre-defined visitors are used to record the distance of each
vertex from the source vertex, and also to record the parent of each
vertex. Any number of visitors can be layered and passed to a GGCL
algorithm.
The call to vertices(G) returns an STL-compatible container which
contains all of the vertices in the graph. In this example we use
the vertices container in the STL for_each() function.
Sample Output:
0 --> 2
1 --> 1 3 4
2 --> 1 3 4
3 --> 1 4
4 --> 0 1
distances: 1 2 1 2 0
parent[0] = 4
parent[1] = 2
parent[2] = 0
parent[3] = 2
parent[4] = 0
*/
template <class ParentDecorator>
struct print_parent {
print_parent(const ParentDecorator& p_) : p(p_) { }
template <class Vertex>
void operator()(const Vertex& v) const {
std::cout << "parent[" << v << "] = " << p[v] << std::endl;
}
ParentDecorator p;
};
template <class NewGraph, class Tag>
struct graph_copier
: public boost::base_visitor<graph_copier<NewGraph, Tag> >
{
typedef Tag event_filter;
graph_copier(NewGraph& graph) : new_g(graph) { }
template <class Edge, class Graph>
void operator()(Edge e, Graph& g) {
boost::add_edge(boost::source(e, g), boost::target(e, g), new_g);
}
private:
NewGraph& new_g;
};
template <class NewGraph, class Tag>
inline graph_copier<NewGraph, Tag>
copy_graph(NewGraph& g, Tag) {
return graph_copier<NewGraph, Tag>(g);
}
int main(int , char* [])
{
typedef boost::adjacency_list<
boost::mapS, boost::vecS, boost::bidirectionalS,
boost::property<boost::vertex_color_t, boost::default_color_type,
boost::property<boost::vertex_degree_t, int,
boost::property<boost::vertex_in_degree_t, int,
boost::property<boost::vertex_out_degree_t, int> > > >
> Graph;
Graph G(5);
boost::add_edge(0, 2, G);
boost::add_edge(1, 1, G);
boost::add_edge(1, 3, G);
boost::add_edge(1, 4, G);
boost::add_edge(2, 1, G);
boost::add_edge(2, 3, G);
boost::add_edge(2, 4, G);
boost::add_edge(3, 1, G);
boost::add_edge(3, 4, G);
boost::add_edge(4, 0, G);
boost::add_edge(4, 1, G);
typedef Graph::vertex_descriptor Vertex;
// Array to store predecessor (parent) of each vertex. This will be
// used as a Decorator (actually, its iterator will be).
std::vector<Vertex> p(boost::num_vertices(G));
// VC++ version of std::vector has no ::pointer, so
// I use ::value_type* instead.
typedef std::vector<Vertex>::value_type* Piter;
// Array to store distances from the source to each vertex . We use
// a built-in array here just for variety. This will also be used as
// a Decorator.
boost::graph_traits<Graph>::vertices_size_type d[5];
std::fill_n(d, 5, 0);
// The source vertex
Vertex s = *(boost::vertices(G).first);
p[s] = s;
boost::neighbor_breadth_first_search
(G, s,
boost::visitor(boost::make_neighbor_bfs_visitor
(std::make_pair(boost::record_distances(d, boost::on_tree_edge()),
boost::record_predecessors(&p[0],
boost::on_tree_edge())))));
boost::print_graph(G);
if (boost::num_vertices(G) < 11) {
std::cout << "distances: ";
#ifdef BOOST_OLD_STREAM_ITERATORS
std::copy(d, d + 5, std::ostream_iterator<int, char>(std::cout, " "));
#else
std::copy(d, d + 5, std::ostream_iterator<int>(std::cout, " "));
#endif
std::cout << std::endl;
std::for_each(boost::vertices(G).first, boost::vertices(G).second,
print_parent<Piter>(&p[0]));
}
return 0;
}
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
151
]
]
] |
929474853782016fa75517c0e748a91877be29ce
|
382b459563be90227848e5125f0d37f83c1e2a4f
|
/Schedule/src/markevaluator.cpp
|
b91df11998047475b00370852d90cb06f1ea7ed1
|
[] |
no_license
|
Maciej-Poleski/SchoolTools
|
516c9758dfa153440a816a96e3f05c7f290daf6c
|
e55099f77eb0f65b75a871d577cc4054221b9802
|
refs/heads/master
| 2023-07-02T09:07:31.185410 | 2010-07-11T20:56:59 | 2010-07-11T20:56:59 | 392,391,718 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 41 |
cpp
|
#include "../include/markevaluator.h"
|
[
"[email protected]"
] |
[
[
[
1,
2
]
]
] |
b35a69921c7e9152bc9c2664eac74ec36d589444
|
6dac9369d44799e368d866638433fbd17873dcf7
|
/src/branches/01032005/vfs/q2bsp/VFSPlugin_Q2BSP.h
|
1ee268b2f8936a151838d378a7cb63e8aff4e709
|
[] |
no_license
|
christhomas/fusionengine
|
286b33f2c6a7df785398ffbe7eea1c367e512b8d
|
95422685027bb19986ba64c612049faa5899690e
|
refs/heads/master
| 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,439 |
h
|
#ifndef _VFSPLUGIN_Q2H_
#define _VFSPLUGIN_Q2H_
#include <vfs/VirtualFS.h>
#include <mesh/Vertex.h>
#include <Fusion.h>
#define BSPMAGIC "IBSP"
#define BSPVERSION 38
#define NUMBERLUMPS 19
#define BSP_ENTITIES 0
#define BSP_PLANES 1
#define BSP_VERTEX 2
#define BSP_VIS 3
#define BSP_NODES 4
#define BSP_TEXINFO 5
#define BSP_FACES 6
#define BSP_LIGHTMAPS 7
#define BSP_LEAVES 8
#define BSP_LEAFFACETABLE 9
#define BSP_LEAFBRUSHTABLE 10
#define BSP_EDGES 11
#define BSP_FACEEDGETABLE 12
#define BSP_MODELS 13
#define BSP_BRUSHES 14
#define BSP_BRUSHSIDES 15
#define BSP_POP 16
#define BSP_AREAS 17
#define BSP_AREAPORTALS 18
/** @ingroup VFSPlugin_Q2Group */
struct BSPLump{
unsigned int offset; // offset (in bytes) of the data from the beginning of the file
unsigned int length; // length (in bytes) of the data
};
/** @ingroup VFSPlugin_Q2Group */
struct BSPHeader{
unsigned int magic; // magic number ("IBSP")
unsigned int version; // version of the BSP format (38)
BSPLump lump[NUMBERLUMPS]; // directory of the lumps
};
/** @ingroup VFSPlugin_Q2Group */
struct BSPFace{
unsigned short plane; // index of the plane the face is parallel to
unsigned short plane_side; // set if the normal is parallel to the plane normal
unsigned int first_edge; // index of the first edge (in the face edge array)
unsigned short num_edges; // number of consecutive edges (in the face edge array)
unsigned short texture_info; // index of the texture info structure
unsigned char lightmap_syles[4]; // styles (bit flags) for the lightmaps
unsigned int lightmap_offset; // offset of the lightmap (in bytes) in the lightmap lump
};
/** @ingroup VFSPlugin_Q2Group */
struct BSPPlane{
Vertex3f normal; // A, B, C components of the plane equation
float distance; // D component of the plane equation
unsigned int type; // ?
};
/** @ingroup VFSPlugin_Q2Group */
struct BSPNode{
unsigned int plane; // index of the splitting plane (in the plane array)
int front_child; // index of the front child node or leaf
int back_child; // index of the back child node or leaf
Vertex3s bbox_min; // minimum x, y and z of the bounding box
Vertex3s bbox_max; // maximum x, y and z of the bounding box
unsigned short first_face; // index of the first face (in the face array)
unsigned short num_faces; // number of consecutive edges (in the face array)
};
/** @ingroup VFSPlugin_Q2Group */
struct BSPLeaf{
unsigned int brush_or; // ?
unsigned short cluster; // -1 for cluster indicates no visibility information
unsigned short area; // ?
Vertex3s bbox_min; // bounding box minimums
Vertex3s bbox_max; // bounding box maximums
unsigned short first_leaf_face; // index of the first face (in the face leaf array)
unsigned short num_leaf_faces; // number of consecutive edges (in the face leaf array)
unsigned short first_leaf_brush; // ?
unsigned short num_leaf_brushes; // ?
};
/** @ingroup VFSPlugin_Q2Group */
struct BSPTexInfo{
Vertex3f u_axis;
float u_offset;
Vertex3f v_axis;
float v_offset;
unsigned int flags;
unsigned int value;
char name[32];
unsigned int next_texinfo;
};
/** @ingroup VFSPlugin_Q2Group */
struct BSPVisibilityLump
{
unsigned int pvs; // offset (in bytes) from the beginning of the visibility lump
unsigned int phs; // ?
};
/** @ingroup VFSPlugin_Q2Group */
struct BSPEdge{
short v1; // Edge vertex 1
short v2; // Edge vertex 2
};
/** @ingroup VFSPlugin_Q2Group
* @brief File format plugin to read/write Quake2 BSP files
*/
class VFSPlugin_Q2BSP: public VFSPlugin{
protected:
// file info object
MeshFileInfo *m_fileinfo;
BSPHeader *m_header;
unsigned int m_numvertex;
unsigned int m_numfaces;
unsigned int m_numedges;
unsigned int m_numfaceedges;
unsigned int m_numtexinfo;
// Temporary geometry, surface structures
BSPFace *m_face;
BSPEdge *m_edge;
Vertex3f *m_position;
int *m_faceedge;
BSPTexInfo *m_texinfo;
char * ReadData (int length);
void Read_Header (void);
void Read_Entities (void);
void Read_Planes (void);
void Read_Vertices (void);
void Read_Visibility (void);
void Read_Nodes (void);
void Read_Texture_Information (void);
void Read_Faces (void);
void Read_Lightmaps (void);
void Read_Leaves (void);
void Read_Leaf_Face_Table (void);
void Read_Leaf_Brush_Table (void);
void Read_Edges (void);
void Read_Face_Edge_Table (void);
void Read_Models (void);
void Read_Brushes (void);
void Read_Brush_Sides (void);
void Read_Pop (void);
void Read_Areas (void);
void Read_Area_Portals (void);
void ProcessMesh (void);
void CentreMesh (void);
void CreateSurfaces (void);
void BuildPolygonLists (IVertexBuffer *vb);
void CountPolygons (IVertexBuffer *vb);
void AssignTextureCoords (IVertexBuffer *vb);
public:
VFSPlugin_Q2BSP ();
virtual ~VFSPlugin_Q2BSP ();
virtual FileInfo * Read (unsigned char *buffer, unsigned int length);
virtual char * Write (FileInfo *data, unsigned int &length);
virtual std::string Type (void);
};
#endif // #ifndef _VFSPLUGIN_Q2H_
|
[
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] |
[
[
[
1,
191
]
]
] |
554e93e73a98a65d85f8f46f3c5ee7dedf204aee
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/Dependencies/LuaBind/luabind/luabind-0.9/luabind-0.9/src/class.cpp
|
f33f3989f41656fbcde435612a03c9ffb3191fa0
|
[
"MIT"
] |
permissive
|
svn2github/ngene
|
b2cddacf7ec035aa681d5b8989feab3383dac012
|
61850134a354816161859fe86c2907c8e73dc113
|
refs/heads/master
| 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 9,479 |
cpp
|
// Copyright (c) 2004 Daniel Wallin and Arvid Norberg
// 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.
#define LUABIND_BUILDING
#include <boost/foreach.hpp>
#include <luabind/lua_include.hpp>
#include <luabind/config.hpp>
#include <luabind/class.hpp>
#include <luabind/nil.hpp>
#include <cstring>
#include <iostream>
namespace luabind
{
LUABIND_API detail::nil_type nil;
}
namespace luabind { namespace detail {
namespace
{
struct cast_entry
{
cast_entry(class_id src, class_id target, cast_function cast)
: src(src)
, target(target)
, cast(cast)
{}
class_id src;
class_id target;
cast_function cast;
};
} // namespace unnamed
struct class_registration : registration
{
class_registration(char const* name);
void register_(lua_State* L) const;
const char* m_name;
mutable std::map<const char*, int, detail::ltstr> m_static_constants;
typedef std::pair<type_id, cast_function> base_desc;
mutable std::vector<base_desc> m_bases;
type_id m_type;
class_id m_id;
class_id m_wrapper_id;
type_id m_wrapper_type;
std::vector<cast_entry> m_casts;
scope m_scope;
scope m_members;
scope m_default_members;
};
class_registration::class_registration(char const* name)
{
m_name = name;
}
void class_registration::register_(lua_State* L) const
{
LUABIND_CHECK_STACK(L);
assert(lua_type(L, -1) == LUA_TTABLE);
lua_pushstring(L, m_name);
detail::class_rep* crep;
detail::class_registry* r = detail::class_registry::get_registry(L);
// create a class_rep structure for this class.
// allocate it within lua to let lua collect it on
// lua_close(). This is better than allocating it
// as a static, since it will then be destructed
// when the program exits instead.
// warning: we assume that lua will not
// move the userdata memory.
lua_newuserdata(L, sizeof(detail::class_rep));
crep = reinterpret_cast<detail::class_rep*>(lua_touserdata(L, -1));
new(crep) detail::class_rep(
m_type
, m_name
, L
);
// register this new type in the class registry
r->add_class(m_type, crep);
lua_pushstring(L, "__luabind_class_map");
lua_rawget(L, LUA_REGISTRYINDEX);
class_map& classes = *static_cast<class_map*>(
lua_touserdata(L, -1));
lua_pop(L, 1);
classes.put(m_id, crep);
bool const has_wrapper = m_wrapper_id != registered_class<null_type>::id;
if (has_wrapper)
classes.put(m_wrapper_id, crep);
crep->m_static_constants.swap(m_static_constants);
detail::class_registry* registry = detail::class_registry::get_registry(L);
crep->get_default_table(L);
m_scope.register_(L);
m_default_members.register_(L);
lua_pop(L, 1);
crep->get_table(L);
m_members.register_(L);
lua_pop(L, 1);
lua_pushstring(L, "__luabind_cast_graph");
lua_gettable(L, LUA_REGISTRYINDEX);
cast_graph* const casts = static_cast<cast_graph*>(
lua_touserdata(L, -1));
lua_pop(L, 1);
lua_pushstring(L, "__luabind_class_id_map");
lua_gettable(L, LUA_REGISTRYINDEX);
class_id_map* const class_ids = static_cast<class_id_map*>(
lua_touserdata(L, -1));
lua_pop(L, 1);
class_ids->put(m_id, m_type);
if (has_wrapper)
class_ids->put(m_wrapper_id, m_wrapper_type);
BOOST_FOREACH(cast_entry const& e, m_casts)
{
casts->insert(e.src, e.target, e.cast);
}
for (std::vector<base_desc>::iterator i = m_bases.begin();
i != m_bases.end(); ++i)
{
LUABIND_CHECK_STACK(L);
// the baseclass' class_rep structure
detail::class_rep* bcrep = registry->find_class(i->first);
detail::class_rep::base_info base;
base.pointer_offset = 0;
base.base = bcrep;
crep->add_base_class(base);
// copy base class table
crep->get_table(L);
bcrep->get_table(L);
lua_pushnil(L);
while (lua_next(L, -2))
{
lua_pushvalue(L, -2); // copy key
lua_gettable(L, -5);
if (!lua_isnil(L, -1))
{
lua_pop(L, 2);
continue;
}
lua_pop(L, 1);
lua_pushvalue(L, -2); // copy key
lua_insert(L, -2);
lua_settable(L, -5);
}
lua_pop(L, 2);
// copy base class detaults table
crep->get_default_table(L);
bcrep->get_default_table(L);
lua_pushnil(L);
while (lua_next(L, -2))
{
lua_pushvalue(L, -2); // copy key
lua_gettable(L, -5);
if (!lua_isnil(L, -1))
{
lua_pop(L, 2);
continue;
}
lua_pop(L, 1);
lua_pushvalue(L, -2); // copy key
lua_insert(L, -2);
lua_settable(L, -5);
}
lua_pop(L, 2);
}
lua_settable(L, -3);
}
// -- interface ---------------------------------------------------------
class_base::class_base(char const* name)
: scope(std::auto_ptr<registration>(
m_registration = new class_registration(name))
)
{
}
void class_base::init(
type_id const& type_id_, class_id id
, type_id const& wrapper_type, class_id wrapper_id)
{
m_registration->m_type = type_id_;
m_registration->m_id = id;
m_registration->m_wrapper_type = wrapper_type;
m_registration->m_wrapper_id = wrapper_id;
}
void class_base::add_base(type_id const& base, cast_function cast)
{
m_registration->m_bases.push_back(std::make_pair(base, cast));
}
void class_base::add_member(registration* member)
{
std::auto_ptr<registration> ptr(member);
m_registration->m_members.operator,(scope(ptr));
}
void class_base::add_default_member(registration* member)
{
std::auto_ptr<registration> ptr(member);
m_registration->m_default_members.operator,(scope(ptr));
}
const char* class_base::name() const
{
return m_registration->m_name;
}
void class_base::add_static_constant(const char* name, int val)
{
m_registration->m_static_constants[name] = val;
}
void class_base::add_inner_scope(scope& s)
{
m_registration->m_scope.operator,(s);
}
void class_base::add_cast(
class_id src, class_id target, cast_function cast)
{
m_registration->m_casts.push_back(cast_entry(src, target, cast));
}
void add_custom_name(type_id const& i, std::string& s)
{
s += " [";
s += i.name();
s += "]";
}
std::string get_class_name(lua_State* L, type_id const& i)
{
std::string ret;
assert(L);
class_registry* r = class_registry::get_registry(L);
class_rep* crep = r->find_class(i);
if (crep == 0)
{
ret = "custom";
add_custom_name(i, ret);
}
else
{
/* TODO reimplement this?
if (i == crep->holder_type())
{
ret += "smart_ptr<";
ret += crep->name();
ret += ">";
}
else if (i == crep->const_holder_type())
{
ret += "smart_ptr<const ";
ret += crep->name();
ret += ">";
}
else*/
{
ret += crep->name();
}
}
return ret;
};
}} // namespace luabind::detail
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
337
]
]
] |
a14779aa8f207efe88b585e2a755939557480986
|
c95a83e1a741b8c0eb810dd018d91060e5872dd8
|
/libs/MFCStub/mfcs_types.h
|
d6182f54f9b21714724a26f8a38bc5f8ed7182c3
|
[] |
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 | 756 |
h
|
// mfcs_types.h - Types for the MFC stub
#ifndef __MFCS_TYPES_H__
#define __MFCS_TYPES_H__
#include "stdlith.h"
// string types
typedef const char *LPCTSTR;
typedef const char *LPCSTR;
typedef char *LPSTR;
typedef char *LPTSTR;
// Signed version of CMoArray
template <class T>
class CSignedMoArray : public CMoArray<T>
{
public:
int32 GetSize() const { return (int32)CMoArray<T>::GetSize(); }
};
// CArray replacement (the second parameter is ignored)
template <class T, class A>
class CArray : public CSignedMoArray<T>
{
};
// Rename position objects
#define POSITION LPOS
// Lists and typedef'ed arrays
typedef CLinkedList<void *> CPtrList;
typedef CSignedMoArray<uint32> CDWordArray;
#endif // __MFCS_TYPES_H__
|
[
"[email protected]"
] |
[
[
[
1,
35
]
]
] |
c2f85c51c46cb6af254fedd3ea0fbc666426b995
|
a841c4a8db70eac01125b85de02c68714fe71fcc
|
/Src/Hexxagon/Hexxagon.h
|
7bbf6bca338a211931c043f1702be32ef35bf0cf
|
[] |
no_license
|
Iceyer/seedcup2009
|
73c3020806f753b30fab618a7bfd3da8f8441337
|
de5fce458116e2c71440cf733aaeb1cc55b2440c
|
refs/heads/master
| 2016-09-05T12:12:02.101164 | 2010-02-02T04:10:54 | 2010-02-02T04:10:54 | 32,113,136 | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 497 |
h
|
// Hexxagon.h : PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CHexxagonApp:
// 有关此类的实现,请参阅 Hexxagon.cpp
//
class CHexxagonApp : public CWinApp
{
public:
CHexxagonApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
DECLARE_MESSAGE_MAP()
};
extern CHexxagonApp theApp;
|
[
"icesyaoran@c2d47732-b0c4-11de-9c04-c7668166297d"
] |
[
[
[
1,
31
]
]
] |
54bf0365d5a158d7bbc8f250558c0aa59e956c5c
|
5095bbe94f3af8dc3b14a331519cfee887f4c07e
|
/Shared/SEGReport/KWTest.h
|
bca2eff9ff4ebf806d3bf700cfd0effe58062ffc
|
[] |
no_license
|
sativa/apsim_development
|
efc2b584459b43c89e841abf93830db8d523b07a
|
a90ffef3b4ed8a7d0cce1c169c65364be6e93797
|
refs/heads/master
| 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 380 |
h
|
//---------------------------------------------------------------------------
#ifndef KWTestH
#define KWTestH
#include "RealSet.h"
#include <db.hpp>
class XMLNode;
class DataContainer;
void processKWTest(DataContainer& parent,
const XMLNode& properties,
vector<TDataSet*> sources,
TDataSet& result);
#endif
|
[
"hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8"
] |
[
[
[
1,
14
]
]
] |
078421e8f893aecac2b8d9fec29ae077acc705ba
|
59166d9d1eea9b034ac331d9c5590362ab942a8f
|
/XMLTree2Geom/xml/xmlRoot/xmlBranch/xmlBranchSave.cpp
|
ce15dc63ac7fdde5a4027ddf8c012d4f6a71ee07
|
[] |
no_license
|
seafengl/osgtraining
|
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
|
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
|
refs/heads/master
| 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 323 |
cpp
|
#include "xmlBranchSave.h"
xmlBranchSave::xmlBranchSave() : m_pData( NULL )
{
}
xmlBranchSave::~xmlBranchSave()
{
}
ticpp::Node* xmlBranchSave::GetXmlData( const binBranch &_data )
{
//получить xml тег с сформированными данными
m_pData = &_data;
return NULL;
}
|
[
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
] |
[
[
[
1,
19
]
]
] |
315abe68a440c2578114c253b5afde802f1caf30
|
772690258e7a85244cc871d744bf54fc4e887840
|
/ms22vv/Castle Defence Ogre3d/Castle Defence Ogre3d/View/Camera/Perspective.cpp
|
143a52d23f8639a5eddee88fed57c5f06a31f684
|
[] |
no_license
|
Argos86/dt2370
|
f735d21517ab55de19cea933b467f46837bb6401
|
4a393a3c83deb3cb6df90b36a9c59e2e543917ee
|
refs/heads/master
| 2021-01-13T00:53:43.286445 | 2010-02-01T07:43:50 | 2010-02-01T07:43:50 | 36,057,264 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,148 |
cpp
|
#include <OgreRoot.h>
#include <OgreSceneManager.h>
#include <OgreCamera.h>
#include <OgreVector2.h>
#include <OgreVector3.h>
#include <OgreQuaternion.h>
#include <OgreRenderWindow.h>
#include <OgreViewport.h>
#include "Perspective.h"
#include "Camera.h"
Perspective::Perspective(Ogre::SceneManager *a_scenemgr, Ogre::RenderWindow *a_window, Ogre::String a_name)
: CameraManager (a_scenemgr, a_window, a_name)
{
m_cameraNode->attachObject(m_camera);
m_camera->setPosition(Ogre::Vector3(0,0,0));
m_cameraNode->setPosition(Ogre::Vector3(-1000,+1000,+1000));
m_camera->lookAt(Ogre::Vector3(-200,0,+400));
}
void Perspective::Update(Ogre::Vector3 a_weaponPosition, Ogre::Quaternion a_weaponOrientation, Ogre::Vector2 a_mousePosition)
{
m_cameraNode->setPosition( Ogre::Vector3(-1000,+1000,+1000) );
}
void Perspective::ResetOrientation()
{
std::cout << "Camera::Quaternion = " << this->GetOrientation() << std::endl;
m_camera->lookAt(Ogre::Vector3(-200,0,+400));
m_cameraNode->setPosition(Ogre::Vector3(-1000,+1000,+1000));
m_offsetX = 0;
m_offsetY = 0;
}
Perspective::~Perspective()
{
}
|
[
"[email protected]@3422cff2-cdd9-11de-91bf-0503b81643b9"
] |
[
[
[
1,
41
]
]
] |
bf88117f7a386242c006381b70113be32e716b5f
|
11dfb7197905169a3f0544eeaf507fe108d50f7e
|
/CCDCamWrapper/CCDCamWrapper/CCDCamWrapper_wrap.cxx
|
98f12f71b9c50e4fac49e8d6ef561a8571a7043c
|
[] |
no_license
|
rahulbhadani/adaptive-optics
|
67791a49ecbb085ac8effdc44e5177b0357b0fa7
|
e2b296664b7674e87a5a68ec7b794144b37ae74d
|
refs/heads/master
| 2020-04-28T00:08:24.585833 | 2011-08-09T22:28:11 | 2011-08-09T22:28:11 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 9,611 |
cxx
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.40
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */
#define SWIGJAVA
#ifdef __cplusplus
/* SwigValueWrapper is described in swig.swg */
template<typename T> class SwigValueWrapper {
struct SwigMovePointer {
T *ptr;
SwigMovePointer(T *p) : ptr(p) { }
~SwigMovePointer() { delete ptr; }
SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; }
} pointer;
SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
SwigValueWrapper(const SwigValueWrapper<T>& rhs);
public:
SwigValueWrapper() : pointer(0) { }
SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; }
operator T&() const { return *pointer.ptr; }
T *operator&() { return pointer.ptr; }
};
template <typename T> T SwigValueInit() {
return T();
}
#endif
/* -----------------------------------------------------------------------------
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
* ----------------------------------------------------------------------------- */
/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif
/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif
/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
# elif defined(__ICC)
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
#endif
#ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
# pragma warning(disable : 4505) /* unreferenced local function has been removed */
# endif
#endif
#ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
# define SWIGUNUSEDPARM(p)
# else
# define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif
/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif
/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif
/* exporting methods */
#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
# ifndef GCC_HASCLASSVISIBILITY
# define GCC_HASCLASSVISIBILITY
# endif
#endif
#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORT __attribute__ ((visibility("default")))
# else
# define SWIGEXPORT
# endif
# endif
#endif
/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif
/* Fix for jlong on some versions of gcc on Windows */
#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
typedef long long __int64;
#endif
/* Fix for jlong on 64-bit x86 Solaris */
#if defined(__x86_64)
# ifdef _LP64
# undef _LP64
# endif
#endif
#include <jni.h>
#include <stdlib.h>
#include <string.h>
/* Support for throwing Java exceptions */
typedef enum {
SWIG_JavaOutOfMemoryError = 1,
SWIG_JavaIOException,
SWIG_JavaRuntimeException,
SWIG_JavaIndexOutOfBoundsException,
SWIG_JavaArithmeticException,
SWIG_JavaIllegalArgumentException,
SWIG_JavaNullPointerException,
SWIG_JavaDirectorPureVirtual,
SWIG_JavaUnknownError
} SWIG_JavaExceptionCodes;
typedef struct {
SWIG_JavaExceptionCodes code;
const char *java_exception;
} SWIG_JavaExceptions_t;
static void SWIGUNUSED SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionCodes code, const char *msg) {
jclass excep;
static const SWIG_JavaExceptions_t java_exceptions[] = {
{ SWIG_JavaOutOfMemoryError, "java/lang/OutOfMemoryError" },
{ SWIG_JavaIOException, "java/io/IOException" },
{ SWIG_JavaRuntimeException, "java/lang/RuntimeException" },
{ SWIG_JavaIndexOutOfBoundsException, "java/lang/IndexOutOfBoundsException" },
{ SWIG_JavaArithmeticException, "java/lang/ArithmeticException" },
{ SWIG_JavaIllegalArgumentException, "java/lang/IllegalArgumentException" },
{ SWIG_JavaNullPointerException, "java/lang/NullPointerException" },
{ SWIG_JavaDirectorPureVirtual, "java/lang/RuntimeException" },
{ SWIG_JavaUnknownError, "java/lang/UnknownError" },
{ (SWIG_JavaExceptionCodes)0, "java/lang/UnknownError" }
};
const SWIG_JavaExceptions_t *except_ptr = java_exceptions;
while (except_ptr->code != code && except_ptr->code)
except_ptr++;
jenv->ExceptionClear();
excep = jenv->FindClass(except_ptr->java_exception);
if (excep)
jenv->ThrowNew(excep, msg);
}
/* Contract support */
#define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, msg); return nullreturn; } else
#include <string>
/* Includes the header in the wrapper code */
extern bool init_camera(int driver);
extern char *get_note();
extern int capture_frame();
extern unsigned short get_frame_at_pos(int x, int y);
extern int test_me();
extern int set_roi(int x, int y, int dx, int dy);
extern int shutdown();
#ifdef __cplusplus
extern "C" {
#endif
SWIGEXPORT jboolean JNICALL Java_loci_hardware_camera_swig_CCDCamWrapperJNI_init_1camera(JNIEnv *jenv, jclass jcls, jint jarg1) {
jboolean jresult = 0 ;
int arg1 ;
bool result;
(void)jenv;
(void)jcls;
arg1 = (int)jarg1;
result = (bool)init_camera(arg1);
jresult = (jboolean)result;
return jresult;
}
SWIGEXPORT jstring JNICALL Java_loci_hardware_camera_swig_CCDCamWrapperJNI_get_1note(JNIEnv *jenv, jclass jcls) {
jstring jresult = 0 ;
char *result = 0 ;
(void)jenv;
(void)jcls;
result = (char *)get_note();
if (result) jresult = jenv->NewStringUTF((const char *)result);
return jresult;
}
SWIGEXPORT jint JNICALL Java_loci_hardware_camera_swig_CCDCamWrapperJNI_capture_1frame(JNIEnv *jenv, jclass jcls) {
jint jresult = 0 ;
int result;
(void)jenv;
(void)jcls;
result = (int)capture_frame();
jresult = (jint)result;
return jresult;
}
SWIGEXPORT jint JNICALL Java_loci_hardware_camera_swig_CCDCamWrapperJNI_get_1frame_1at_1pos(JNIEnv *jenv, jclass jcls, jint jarg1, jint jarg2) {
jint jresult = 0 ;
int arg1 ;
int arg2 ;
unsigned short result;
(void)jenv;
(void)jcls;
arg1 = (int)jarg1;
arg2 = (int)jarg2;
result = (unsigned short)get_frame_at_pos(arg1,arg2);
jresult = (jint)result;
return jresult;
}
SWIGEXPORT jint JNICALL Java_loci_hardware_camera_swig_CCDCamWrapperJNI_test_1me(JNIEnv *jenv, jclass jcls) {
jint jresult = 0 ;
int result;
(void)jenv;
(void)jcls;
result = (int)test_me();
jresult = (jint)result;
return jresult;
}
SWIGEXPORT jint JNICALL Java_loci_hardware_camera_swig_CCDCamWrapperJNI_set_1roi(JNIEnv *jenv, jclass jcls, jint jarg1, jint jarg2, jint jarg3, jint jarg4) {
jint jresult = 0 ;
int arg1 ;
int arg2 ;
int arg3 ;
int arg4 ;
int result;
(void)jenv;
(void)jcls;
arg1 = (int)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
arg4 = (int)jarg4;
result = (int)set_roi(arg1,arg2,arg3,arg4);
jresult = (jint)result;
return jresult;
}
SWIGEXPORT jint JNICALL Java_loci_hardware_camera_swig_CCDCamWrapperJNI_shutdown(JNIEnv *jenv, jclass jcls) {
jint jresult = 0 ;
int result;
(void)jenv;
(void)jcls;
result = (int)shutdown();
jresult = (jint)result;
return jresult;
}
#ifdef __cplusplus
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
330
]
]
] |
fd9117cf4aabf0148b6c2b2465d262e0446a0502
|
8a3fce9fb893696b8e408703b62fa452feec65c5
|
/业余时间学习笔记/MemPool/MemPool/eEventDef.h
|
893e37b541564b74bfc9003b12ba3786fe3c9f70
|
[] |
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 |
WINDOWS-1252
|
C++
| false | false | 3,629 |
h
|
#pragma once
#define COM_BINE(a,b) ( (a<<16) | b )
#define DEF_IMPL_FACTORY_FUN( classname, baseclassname) \
static baseclassname* create();\
static void destory(baseclassname*p)
#define DEL_IMPL_FACTORY_FUN( classname, baseclassname) \
baseclassname* classname::create(){ return new classname(); } \
void classname::destory(baseclassname*p) { if(p){ delete p ; p=next;} }
#define FAC_IMPL_FACTORY_FUN( classname, baseclassname) \
static baseclassname* create(){ return new classname(); } \
static void destory(baseclassname*p) { if(p){ delete p ; p=next;} }
#define BIND( id , classname ) \
;
#define LP_SNMP_0(pname)
#define LP_SNMP_1(pname) pname##1
#define LP_SNMP_2(pname) LP_SNMP_1(pname), pname##2
#define LP_SNMP_3(pname) LP_SNMP_2(pname), pname##3
#define LP_SNMP_4(pname) LP_SNMP_3(pname), pname##4
#define LP_SNMP_5(pname) LP_SNMP_4(pname), pname##5
#define LP_SNMP_6(pname) LP_SNMP_5(pname), pname##6
#define LP_SNMP_7(pname) LP_SNMP_6(pname), pname##7
#define LP_SNMP_8(pname) LP_SNMP_7(pname), pname##8
#define LP_SNMP_9(pname) LP_SNMP_8(pname), pname##9
#define LP_SNMP_10(pname) LP_SNMP_9(pname), pname##10
#define DP_MTMP_0(type,name)
#define DP_MTMP_1(type,name) type##1 name##1
#define DP_MTMP_2(type,name) DP_MTMP_1(type,name), type##2 name##2
#define DP_MTMP_3(type,name) DP_MTMP_2(type,name), type##3 name##3
#define DP_MTMP_4(type,name) DP_MTMP_3(type,name), type##4 name##4
#define DP_MTMP_5(type,name) DP_MTMP_4(type,name), type##5 name##5
#define DP_MTMP_6(type,name) DP_MTMP_5(type,name), type##6 name##6
#define DP_MTMP_7(type,name) DP_MTMP_6(type,name), type##7 name##7
#define DP_MTMP_8(type,name) DP_MTMP_7(type,name), type##8 name##8
#define DP_MTMP_9(type,name) DP_MTMP_8(type,name), type##9 name##9
#define DP_MTMP_10(type,name) DP_MTMP_9(type,name), type##10 name##10
#define DP_STMP_0(type,pname)
#define DP_STMP_1(type,pname) type pname##1
#define DP_STMP_2(type,pname) DP_STMP_1(type,pname), type pname##2
#define DP_STMP_3(type,pname) DP_STMP_2(type,pname), type pname##3
#define DP_STMP_4(type,pname) DP_STMP_3(type,pname), type pname##4
#define DP_STMP_5(type,pname) DP_STMP_4(type,pname), type pname##5
#define DP_STMP_6(type,pname) DP_STMP_5(type,pname), type pname##6
#define DP_STMP_7(type,pname) DP_STMP_6(type,pname), type pname##7
#define DP_STMP_8(type,pname) DP_STMP_7(type,pname), type pname##8
#define DP_STMP_9(type,pname) DP_STMP_8(type,pname), type pname##9
#define DP_STMP_10(type,pname) DP_STMP_9(type,pname), type pname##10
template <class T>
inline T * CALL_CON( T * ptMem )
{
T * pt = new(ptMem)T;
return pt;
}
#define DEFINE_CALL_CON( paramcount ) template <class T, DP_STMP_##paramcount( typename, tp ) >\
inline T * Alloc(unsigned long lSize, DP_MTMP_##paramcount( tp, p ) ){\
void* ptMem = Alloc(lSize);\
if( !ptMem) return NULL; \
T * pt = new(ptMem)T( LP_SNMP_##paramcount( p ) );\
return pt;\
}
/// ¶þ·Ö²éÕÒË÷Òý
sstatic inline int FindIndx(unsigned long * Arr, int l , int r ,unsigned long Value)
static inline long FindIndx(unsigned long * Arr, int l , int r ,unsigned long Value)
{
int low = ( l+r )/2;
if( Arr[low] == Value ) return low;
else if( low == 0 )
{
if( Arr[low] >= Value)
return low;
return r;
}
else if ( low == r ) return r;
else if ( low > 0 && low <= r-2 && Value > Arr[low-1] && Value < Arr[low] ) return low;
else if ( Arr[low] < Value ) return FindIndx(Arr,low+1,r,Value);
else if ( Arr[low] > Value ) return FindIndx(Arr,l,low-1,Value);
return low;
}
|
[
"[email protected]"
] |
[
[
[
1,
91
]
]
] |
151fb8d8656304302c3d68cbdc5e3043b760ef3d
|
fca81f35295cceafd1525f0c40910bce7d4880af
|
/Source/EnemyUnitDataManager.h
|
7a7fb2b2e662e408e4505231f1abf8d5a046d75f
|
[] |
no_license
|
armontoubman/massexpand
|
b324da674cd5013ba1076865d33fc16bfac4f01f
|
4daec6bd7d5799de1019e341917c1179158daaa4
|
refs/heads/master
| 2021-01-10T13:55:47.067590 | 2011-11-20T16:20:48 | 2011-11-20T16:20:48 | 50,496,084 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,648 |
h
|
#pragma once
#include <BWAPI.h>
#include "HighCommand.h"
class HighCommand;
#include "EnemyUnitData.h"
#include <boost/unordered_map.hpp>
#include "Task.h"
using namespace BWAPI;
typedef boost::unordered_map<Unit*, EnemyUnitData> EnemyUnitMap ;
/**
* The EnemyUnitDataManager maintains additional data about enemy units, such as their last known position.
*/
class EnemyUnitDataManager
{
public:
EnemyUnitDataManager(HighCommand* h);
void update();
void onStart();
void onUnitDiscover(Unit* u);
void onUnitEvade(Unit* u);
void onUnitShow(Unit* u);
void onUnitHide(Unit* u);
void onUnitCreate(Unit* u);
void onUnitDestroy(Unit* u);
void onUnitMorph(Unit* u);
void onUnitRenegade(Unit* u);
/**
* For every enemy unit, a CombatTask is created with the unit as target.
*/
void createTask(TaskType tasktype, Position position, Unit* u);
std::list<Task> getTasklist(TaskType tasktype);
/**
* Find the enemy unit closest to the given unit that can attack air units.
*/
BWAPI::Unit* nearestEnemyThatCanAttackAir(BWAPI::Unit* unit);
/**
* Count the number of known enemy units of type unittype.
*/
int count(BWAPI::UnitType unittype);
/**
* Return the entire collection of enemy units and data.
*/
EnemyUnitMap getMap();
/**
* Return only the collection of known flying enemy units.
*/
EnemyUnitMap mapIsFlyer(EnemyUnitMap map);
std::string chat();
private:
HighCommand* hc;
void updateUnit(Unit* u);
void cleanup();
void clearTasklists();
EnemyUnitMap unitmap;
std::list<Task> scouttasklist;
std::list<Task> combattasklist;
};
|
[
"[email protected]"
] |
[
[
[
1,
68
]
]
] |
89f10bdddb3cb323cd150e1d742d2295b4374db8
|
b22c254d7670522ec2caa61c998f8741b1da9388
|
/shared/ActorObject.cpp
|
99c34dd4eaf81750a641121781324a2e8679c818
|
[] |
no_license
|
ldaehler/lbanet
|
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
|
ecb54fc6fd691f1be3bae03681e355a225f92418
|
refs/heads/master
| 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,205 |
cpp
|
/*
------------------------[ Lbanet Source ]-------------------------
Copyright (C) 2009
Author: Vivien Delage [Rincevent_123]
Email : [email protected]
-------------------------------[ GNU License ]-------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------
*/
#include <zoidcom.h>
#include "ActorObject.h"
#include "LogHandler.h"
#include "ObjectsDescription.h"
#include "ZoidSerializer.h"
#include "GameClientCallbackBase.h"
// declare static member
ZCom_ClassID ActorObject::m_classid = ZCom_Invalid_ID;
/************************************************************************/
/* register this class
/************************************************************************/
void ActorObject::registerClass(ZCom_Control *_control)
{
m_classid = _control->ZCom_registerClass("ActorObject", ZCOM_CLASSFLAG_ANNOUNCEDATA);
}
/************************************************************************/
/* constructor
/************************************************************************/
ActorObject::ActorObject(ZCom_Control *_control, unsigned int zoidlevel, unsigned int myid,
const ObjectInfo & oinfo, GameClientCallbackBase * callback)
: m_myid(myid), m_callback(callback)
{
//inform callback of new actor creation
if(m_callback)
m_physicObj = m_callback->AddObject(m_myid, oinfo, false);
#ifndef _ZOID_USED_NEW_VERSION_
m_node->registerNodeDynamic(m_classid, _control);
#else
_control->ZCom_registerDynamicNode( m_node, m_classid );
#endif
#ifdef _DEBUG
LogHandler::getInstance()->LogToFile("New Node " + GetObjectName());
#endif
// only do that on authority
if(m_node->getRole() == eZCom_RoleAuthority)
{
// add announcement data
ZCom_BitStream *adata = new ZCom_BitStream();
ZoidSerializer zoids(adata);
oinfo.Serialize(&zoids);
m_node->setAnnounceData(adata);
// change zoidlevel
m_node->applyForZoidLevel( zoidlevel );
//m_node->removeFromZoidLevel( 1 );
}
}
/************************************************************************/
/* destructor
/************************************************************************/
ActorObject::~ActorObject()
{
#ifdef _DEBUG
LogHandler::getInstance()->LogToFile("Deleting node " + GetObjectName());
#endif
//inform callback of actor removed
if(m_callback)
m_callback->RemObject(m_myid);
}
|
[
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] |
[
[
[
1,
101
]
]
] |
08f6a6cc7b0ebb0eb10f10e106fda528463bc6d4
|
0dba4a3016f3ad5aa22b194137a72efbc92ab19e
|
/tools/mapeditor/main.h
|
2e1b9c03b3e94ff52eca7393d87363eaabd43460
|
[] |
no_license
|
BackupTheBerlios/albion2
|
11e89586c3a2d93821b6a0d3332c1a7ef1af6abf
|
bc3d9ba9cf7b8f7579a58bc190a4abb32b30c716
|
refs/heads/master
| 2020-12-30T10:23:18.448750 | 2007-01-26T23:58:42 | 2007-01-26T23:58:42 | 39,515,887 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,631 |
h
|
/*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __MAIN_H__
#define __MAIN_H__
#ifdef WIN32
#include <windows.h>
#endif
#include <iostream>
#include <math.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <engine.h>
#include <msg.h>
#include <core.h>
#include <net.h>
#include <gfx.h>
#include <gui.h>
#include <event.h>
#include <camera.h>
#include <a2emodel.h>
#include <scene.h>
#include <ode.h>
#include <ode_object.h>
#include <light.h>
#include <shader.h>
#include <lua.h>
#include <xml.h>
#include "mgui.h"
#include "map.h"
#include "mapeditor.h"
using namespace std;
msg* m;
net* n;
core* c;
engine* e;
gfx* agfx;
event* aevent;
camera* cam;
file_io* fio;
gui* agui;
shader* s;
lua* l;
xml* x;
scene* sce;
SDL_Surface* sf;
bool done = false;
SDL_Event ievent;
mapeditor* me;
mgui* megui;
bool button_left_pressed = false;
#endif
|
[
"[email protected]"
] |
[
[
[
1,
74
]
]
] |
73ff8e33ebeee1566935752a819fd9cb8b76b26f
|
b4ec0cb07a6e388ba33dde1ee3494a970aba8a0d
|
/filesearch/exception_dump.cpp
|
5181ecdec6743cf1486d8283820c12c30a702e9b
|
[] |
no_license
|
ashenone0917/pea-search
|
2eed03fc2314909f69a8c3c7cbca511eba192bd3
|
3837dbcc2767d6358b726587b9a77d3c0f015a9d
|
refs/heads/master
| 2023-03-18T08:28:11.348474 | 2011-12-30T12:36:00 | 2011-12-30T12:36:00 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,345 |
cpp
|
#include "env.h"
#include "common.h"
#include <cstdio>
#include <map>
#include "client/windows/handler/exception_handler.h"
#include "client/windows/sender/crash_report_sender.h"
static google_breakpad::ExceptionHandler *eh;
static google_breakpad::CrashReportSender *sender;
extern "C" {
static bool SendReport(const WCHAR* dump_path,
const WCHAR* minidump_id,
void* context,
EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo* assertion,
bool succeeded){
if(!succeeded) return true;
WCHAR buffer[MAX_PATH], *p=buffer;
{
wcscpy_s(p,MAX_PATH,dump_path);
p += wcslen(dump_path);
#ifdef WIN32
*p++ = L'\\';
#else
*p++ = L'/';
#endif
wcscpy_s(p,MAX_PATH-(p-buffer),minidump_id);
p += wcslen(minidump_id);
wcscpy_s(p,MAX_PATH-(p-buffer),L".dmp");
}
std::wstring file(buffer),response;
std::map<std::wstring,std::wstring> map;
{
WCHAR osbuf[MAX_PATH];
get_os(osbuf);
std::wstring os(osbuf);
map[L"dump[os]"]=os;
//map.insert(make_pair(L"os",L"os"));
}
{
WCHAR cpubuf[MAX_PATH];
get_cpu(cpubuf);
std::wstring cpu(cpubuf);
map[L"dump[cpu]"]=cpu;
}
{
WCHAR diskbuf[MAX_PATH];
get_disk(diskbuf);
std::wstring disk(diskbuf);
map[L"dump[disk]"]=disk;
}
{
WCHAR verbuf[MAX_PATH];
get_ver(verbuf);
std::wstring ver(verbuf);
map[L"dump[ver]"]=ver;
}
{
WCHAR userbuf[MAX_PATH];
get_user(userbuf);
std::wstring user(userbuf);
map[L"dump[user]"]=user;
}
google_breakpad::ReportResult ret = sender->SendCrashReport(L"http://www.wandouss.com/dumps/",map,file,&response);
if(ret==google_breakpad::RESULT_FAILED) sender->SendCrashReport(L"http://60.191.119.190:3333/dumps/",map,file,&response);
return true;
}
void breakpad_init() {
eh = new google_breakpad::ExceptionHandler(L".", NULL, SendReport, NULL,
google_breakpad::ExceptionHandler::HANDLER_ALL);
sender = new google_breakpad::CrashReportSender(L"gigaso_dump_send");
sender->set_max_reports_per_day(3);
}
BOOL request_dump(){
return eh->WriteMinidump()==true;
}
}// extern "C"
|
[
"[email protected]"
] |
[
[
[
1,
84
]
]
] |
1a7eb8d1175446823d98142efbbeffa45a2a4fd0
|
282057a05d0cbf9a0fe87457229f966a2ecd3550
|
/SMSServer/include/SMSServerDB.h
|
de8369f4a3f6fd3e6fe86ac480af4ad6f8abf9fd
|
[] |
no_license
|
radtek/eibsuite
|
0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd
|
4504fcf4fa8c7df529177b3460d469b5770abf7a
|
refs/heads/master
| 2021-05-29T08:34:08.764000 | 2011-12-06T20:42:06 | 2011-12-06T20:42:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,386 |
h
|
#ifndef __USER_ENTRY_HEADER__
#define __USER_ENTRY_HEADER__
#include "CString.h"
#include "GenericDB.h"
#define SMS_DB_FILE "Sms.db"
#define PHONE_NUMBER_BLOCK_PREFIX_STR "PHONE_NUMBER-"
#define ALERT_PARAM_STR "EIB_TO_SMS"
#define SMS_COMMAND_STR "SMS_TO_EIB"
#define ALERT_PARAM_SEPERATOR_STR ":"
#define CMD_PARAM_SEPERATO_STR ":"
struct _AddressValueKey
{
_AddressValueKey(unsigned short d_address,unsigned short value)
{
_d_address = d_address;
_value = value;
}
_AddressValueKey(const _AddressValueKey& rhs)
{
_d_address = rhs._d_address;
_value = rhs._value;
}
bool operator == (const _AddressValueKey& avk) const
{
return (_d_address == avk._d_address && _value == avk._value);
}
bool operator < (const _AddressValueKey& avk) const
{
if(_d_address < avk._d_address) return true;
if(_d_address == avk._d_address && _value < avk._value) return true;
return false;
}
bool operator > (const _AddressValueKey& avk) const
{
if(_d_address > avk._d_address) return true;
if(_d_address == avk._d_address && _value > avk._value) return true;
return false;
}
unsigned short _d_address;
unsigned short _value;
};
typedef struct _AddressValueKey AddressValueKey;
class CUserAlertRecord
{
public:
CUserAlertRecord() {};
virtual ~CUserAlertRecord() {};
unsigned char GetValue() const{ return _value;}
unsigned short GetDestAddress() const { return _d_address;}
const CString& GetPoneNumber() const{ return _phone_number; }
const CString& GetTextMessage() const{ return _text_msg;}
void SetDestAddress(unsigned short address) { _d_address = address;}
void SetValue(unsigned char value) { _value = value;}
void SetPhoneNumber(const CString& phone_number) { _phone_number = phone_number; }
void SetTextMessage(const CString& text_message) { _text_msg = text_message;}
bool operator==(const CUserAlertRecord& other)
{
return (_value == other._value && _d_address == other._d_address);
}
private:
unsigned short _d_address;
unsigned char _value;
CString _text_msg;
CString _phone_number;
};
class CSMSServerDB;
class CUserEntry
{
public:
CUserEntry() {};
virtual ~CUserEntry(){};
const CString& GetPhoneNumber() const{ return _phone_number;} const
void SetPhoneNumber(const CString& phone_number) { _phone_number = phone_number;}
void SetName(const CString& name) { _name = name;}
const CString& GetName() const{ return _name;}
void ClearAll();
bool AddAlertRecord(CUserAlertRecord& alert);
bool AddSmsCommand(CUserAlertRecord& cmd);
friend class CSMSServerDB;
map<AddressValueKey,CUserAlertRecord>& GetEibToSmsDB() { return _eib_to_sms_db;}
map<CString,CUserAlertRecord>& GetSmsToEibDB() { return _sms_to_eib_db;}
const map<AddressValueKey,CUserAlertRecord>& GetEibToSmsDBConst() const { return _eib_to_sms_db;}
const map<CString,CUserAlertRecord>& GetSmsToEibDBConst() const { return _sms_to_eib_db;}
private:
void Print() const;
bool Edit();
void PrintAllMappings();
bool DeleteSingleMapping();
bool AddSingleMapping(bool eib2sms, bool sms2eib);
private:
CString _name;
CString _phone_number;
map<AddressValueKey,CUserAlertRecord> _eib_to_sms_db;
map<CString,CUserAlertRecord> _sms_to_eib_db;
};
class CSMSServerDB : public CGenericDB<CString,CUserEntry>
{
public:
CSMSServerDB();
virtual ~CSMSServerDB();
virtual void OnReadParamComplete(CUserEntry& current_record, const CString& param,const CString& value);
virtual void OnReadRecordComplete(CUserEntry& current_record);
virtual void OnReadRecordNameComplete(CUserEntry& current_record, const CString& record_name);
virtual void OnSaveRecordStarted(const CUserEntry& record,CString& record_name, list<pair<CString, CString> >& param_values);
bool FindSmsMesaages(unsigned short d_address, unsigned short value, list<CUserAlertRecord>& result) ;
bool FindEibMessages(const CString& sms_msg, list<CUserAlertRecord>& result) ;
void InteractiveConf();
void Print();
private:
void ParseAlertRecord(const CString& alert_record,CUserEntry& record);
void ParseCommandRecord(const CString& command_record,CUserEntry& record);
bool AddUserEntry(CUserEntry& entry);
bool EditUserEntry(const CString& file_name);
bool DeleteUserEntry(const CString& file_name);
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
150
]
]
] |
021a5b346157bd4751452703c103747e1f808c9f
|
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
|
/trunk/Dependencies/Xerces/include/xercesc/framework/BinOutputStream.cpp
|
57ccab658888ce95eb443a391d5e1d22fcb58e2d
|
[] |
no_license
|
svn2github/ngene
|
b2cddacf7ec035aa681d5b8989feab3383dac012
|
61850134a354816161859fe86c2907c8e73dc113
|
refs/heads/master
| 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,497 |
cpp
|
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: BinOutputStream.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/framework/BinOutputStream.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// BinOutputStream: Virtual destructor!
// ---------------------------------------------------------------------------
BinOutputStream::~BinOutputStream()
{
}
// ---------------------------------------------------------------------------
// BinOutputStream: Hidden Constructors
// ---------------------------------------------------------------------------
BinOutputStream::BinOutputStream()
{
}
XERCES_CPP_NAMESPACE_END
|
[
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] |
[
[
[
1,
44
]
]
] |
0858765b08dbaed00fb7e40e7f840cfb8625de78
|
b29db0ed953e13ddcd53617326060dcc0466b76b
|
/plugin/ossimOpenCVSURFFeatures.cpp
|
49a0b9262148268aa0872a81281f35378220daa9
|
[] |
no_license
|
jartieda/opencv-ossim-plugin
|
1e974fb99d3401233e8c1e7c6d427b567eff3e9c
|
9cf03e0f3d0cff1e1fa11409ba5d898dd0601fca
|
refs/heads/master
| 2021-01-23T18:12:36.361248 | 2010-11-24T12:00:53 | 2010-11-24T12:00:53 | 32,137,081 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 6,222 |
cpp
|
// Copyright (C) 2010 Argongra
//
// OSSIM 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.
//
// This software 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.
//
// You should have received a copy of the GNU General Public License
// along with this software. If not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-
// 1307, USA.
//
// See the GPL in the COPYING.GPL file for more details.
//
//*************************************************************************
#include <ossim/base/ossimRefPtr.h>
#include "ossimOpenCVSURFFeatures.h"
#include <ossim/imaging/ossimU8ImageData.h>
#include <ossim/base/ossimConstants.h>
#include <ossim/base/ossimCommon.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/imaging/ossimImageSourceFactoryBase.h>
#include <ossim/imaging/ossimImageSourceFactoryRegistry.h>
#include <ossim/imaging/ossimAnnotationPolyObject.h>
#include <ossim/base/ossimRefPtr.h>
#include <ossim/base/ossimNumericProperty.h>
RTTI_DEF1(ossimOpenCVSURFFeatures, "ossimOpenCVSURFFeatures", ossimImageSourceFilter)
ossimOpenCVSURFFeatures::ossimOpenCVSURFFeatures(ossimObject* owner)
:ossimImageSourceFilter(owner),
theTile(NULL),
theHessianThreshold(50)
{
}
ossimOpenCVSURFFeatures::~ossimOpenCVSURFFeatures()
{
}
ossimRefPtr<ossimImageData> ossimOpenCVSURFFeatures::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel)
{
if(!isSourceEnabled())
{
return ossimImageSourceFilter::getTile(tileRect, resLevel);
}
long w = tileRect.width();
long h = tileRect.height();
if(!theTile.valid()) initialize();
if(!theTile.valid()) return 0;
ossimRefPtr<ossimImageData> data = 0;
if(theInputConnection)
{
data = theInputConnection->getTile(tileRect, resLevel);
} else {
return 0;
}
if(!data.valid()) return 0;
if(data->getDataObjectStatus() == OSSIM_NULL || data->getDataObjectStatus() == OSSIM_EMPTY)
{
return 0;
}
theTile->setImageRectangle(tileRect);
theTile->makeBlank();
theTile->setOrigin(tileRect.ul());
runUcharTransformation(data.get());
printf("Tile (%d,%d) finished!\n",tileRect.ul().x,tileRect.ul().y);
return theTile;
}
void ossimOpenCVSURFFeatures::initialize()
{
if(theInputConnection)
{
theTile = 0;
theTile = new ossimU8ImageData(this,
1,
theInputConnection->getTileWidth(),
theInputConnection->getTileHeight());
theTile->initialize();
}
}
ossimScalarType ossimOpenCVSURFFeatures::getOutputScalarType() const
{
if(!isSourceEnabled())
{
return ossimImageSourceFilter::getOutputScalarType();
}
return OSSIM_UCHAR;
}
ossim_uint32 ossimOpenCVSURFFeatures::getNumberOfOutputBands() const
{
if(!isSourceEnabled())
{
return ossimImageSourceFilter::getNumberOfOutputBands();
}
return 1;
}
bool ossimOpenCVSURFFeatures::saveState(ossimKeywordlist& kwl, const char* prefix)const
{
ossimImageSourceFilter::saveState(kwl, prefix);
kwl.add(prefix,"hessian_threshold", theHessianThreshold, true);
return true;
}
bool ossimOpenCVSURFFeatures::loadState(const ossimKeywordlist& kwl,
const char* prefix)
{
ossimImageSourceFilter::loadState(kwl, prefix);
const char* lookup = kwl.find(prefix, "hessian_threshold");
if(lookup)
{
theHessianThreshold = ossimString(lookup).toDouble();
printf("Read from spec file. hessian_threshold: %f\n",theHessianThreshold);
}
return true;
}
void ossimOpenCVSURFFeatures::runUcharTransformation(ossimImageData* tile)
{
IplImage *input;
IplImage *output;
IplImage *temp;
char* bSrc;
char* bDst;
//int nChannels = tile->getNumberOfBands();
//for(int k=0; k<nChannels; k++) {
input = cvCreateImageHeader(cvSize(tile->getWidth(),tile->getHeight()),8,1);
output = cvCreateImageHeader(cvSize(tile->getWidth(),tile->getHeight()),8,1);
temp = cvCreateImage(cvGetSize(input),32,1);
CvMemStorage* storage = cvCreateMemStorage(0);
bSrc = static_cast<char*>(tile->getBuf(0));
input->imageData=bSrc;
bDst = static_cast<char*>(theTile->getBuf());
output->imageData=bDst;
CvSeq *imageKeypoints = NULL;
cvCopy(input,output);
CvSURFParams params = cvSURFParams(theHessianThreshold, 1);
cvExtractSURF(input,NULL,&imageKeypoints,NULL,storage,params);
int numKeyPoints = imageKeypoints->total;
for (int i=0;i<numKeyPoints;i++){
CvSURFPoint* corner = (CvSURFPoint*)cvGetSeqElem(imageKeypoints,i);
theKeyPoints.push_back(ossimDpt(corner->pt.x,corner->pt.y)+tile->getOrigin());
cvCircle(output,cvPointFrom32f(corner->pt),1,cvScalar(0),1);
}
cvReleaseImageHeader(&input);
cvReleaseImageHeader(&output);
cvReleaseImage(&temp);
//}
theTile->validate();
}
void ossimOpenCVSURFFeatures::setProperty(ossimRefPtr<ossimProperty> property)
{
if(!property) return;
ossimString name = property->getName();
if(name == "hessian_threshold")
{
theHessianThreshold = property->valueToString().toDouble();
}
else
{
ossimImageSourceFilter::setProperty(property);
}
}
ossimRefPtr<ossimProperty> ossimOpenCVSURFFeatures::getProperty(const ossimString& name)const
{
if(name == "hessian_threshold")
{
ossimNumericProperty* numeric = new ossimNumericProperty(name,
ossimString::toString(theHessianThreshold));
numeric->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64);
numeric->setCacheRefreshBit();
return numeric;
}
return ossimImageSourceFilter::getProperty(name);
}
void ossimOpenCVSURFFeatures::getPropertyNames(std::vector<ossimString>& propertyNames)const
{
ossimImageSourceFilter::getPropertyNames(propertyNames);
propertyNames.push_back("hessian_threshold");
}
|
[
"whatnickd@f338cb41-fd2a-0410-a340-718c64ddaef4"
] |
[
[
[
1,
221
]
]
] |
9d43ba5755f24b55df959f10392c08bcfa11a4f0
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/regex/v4/basic_regex_creator.hpp
|
9e78fa744fbbc3b09d72e926672084639c886ac0
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
willrebuild/flyffsf
|
e5911fb412221e00a20a6867fd00c55afca593c7
|
d38cc11790480d617b38bb5fc50729d676aef80d
|
refs/heads/master
| 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 44,050 |
hpp
|
/*
*
* Copyright (c) 2004
* John Maddock
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE basic_regex_creator.cpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: Declares template class basic_regex_creator which fills in
* the data members of a regex_data object.
*/
#ifndef BOOST_REGEX_V4_BASIC_REGEX_CREATOR_HPP
#define BOOST_REGEX_V4_BASIC_REGEX_CREATOR_HPP
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_PREFIX
#endif
namespace boost{
namespace re_detail{
template <class charT>
struct digraph : public std::pair<charT, charT>
{
digraph() : std::pair<charT, charT>(0, 0){}
digraph(charT c1) : std::pair<charT, charT>(c1, 0){}
digraph(charT c1, charT c2) : std::pair<charT, charT>(c1, c2)
{}
#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
digraph(const digraph<charT>& d) : std::pair<charT, charT>(d.first, d.second){}
#endif
template <class Seq>
digraph(const Seq& s) : std::pair<charT, charT>()
{
BOOST_ASSERT(s.size() <= 2);
BOOST_ASSERT(s.size());
this->first = s[0];
this->second = (s.size() > 1) ? s[1] : 0;
}
};
template <class charT, class traits>
class basic_char_set
{
public:
typedef digraph<charT> digraph_type;
typedef typename traits::string_type string_type;
typedef typename traits::char_class_type mask_type;
basic_char_set()
{
m_negate = false;
m_has_digraphs = false;
m_classes = 0;
m_negated_classes = 0;
m_empty = true;
}
void add_single(const digraph_type& s)
{
m_singles.insert(m_singles.end(), s);
if(s.second)
m_has_digraphs = true;
m_empty = false;
}
void add_range(const digraph_type& first, const digraph_type& end)
{
m_ranges.insert(m_ranges.end(), first);
m_ranges.insert(m_ranges.end(), end);
if(first.second)
{
m_has_digraphs = true;
add_single(first);
}
if(end.second)
{
m_has_digraphs = true;
add_single(end);
}
m_empty = false;
}
void add_class(mask_type m)
{
m_classes |= m;
m_empty = false;
}
void add_negated_class(mask_type m)
{
m_negated_classes |= m;
m_empty = false;
}
void add_equivalent(const digraph_type& s)
{
m_equivalents.insert(m_equivalents.end(), s);
if(s.second)
{
m_has_digraphs = true;
add_single(s);
}
m_empty = false;
}
void negate()
{
m_negate = true;
//m_empty = false;
}
//
// accessor functions:
//
bool has_digraphs()const
{
return m_has_digraphs;
}
bool is_negated()const
{
return m_negate;
}
typedef typename std::vector<digraph_type>::const_iterator list_iterator;
list_iterator singles_begin()const
{
return m_singles.begin();
}
list_iterator singles_end()const
{
return m_singles.end();
}
list_iterator ranges_begin()const
{
return m_ranges.begin();
}
list_iterator ranges_end()const
{
return m_ranges.end();
}
list_iterator equivalents_begin()const
{
return m_equivalents.begin();
}
list_iterator equivalents_end()const
{
return m_equivalents.end();
}
mask_type classes()const
{
return m_classes;
}
mask_type negated_classes()const
{
return m_negated_classes;
}
bool empty()const
{
return m_empty;
}
private:
std::vector<digraph_type> m_singles; // a list of single characters to match
std::vector<digraph_type> m_ranges; // a list of end points of our ranges
bool m_negate; // true if the set is to be negated
bool m_has_digraphs; // true if we have digraphs present
mask_type m_classes; // character classes to match
mask_type m_negated_classes; // negated character classes to match
bool m_empty; // whether we've added anything yet
std::vector<digraph_type> m_equivalents; // a list of equivalence classes
};
template <class charT, class traits>
class basic_regex_creator
{
public:
basic_regex_creator(regex_data<charT, traits>* data);
std::ptrdiff_t getoffset(void* addr)
{
return getoffset(addr, m_pdata->m_data.data());
}
std::ptrdiff_t getoffset(const void* addr, const void* base)
{
return static_cast<const char*>(addr) - static_cast<const char*>(base);
}
re_syntax_base* getaddress(std::ptrdiff_t off)
{
return getaddress(off, m_pdata->m_data.data());
}
re_syntax_base* getaddress(std::ptrdiff_t off, void* base)
{
return static_cast<re_syntax_base*>(static_cast<void*>(static_cast<char*>(base) + off));
}
void init(unsigned l_flags)
{
m_pdata->m_flags = l_flags;
m_icase = l_flags & regex_constants::icase;
}
regbase::flag_type flags()
{
return m_pdata->m_flags;
}
void flags(regbase::flag_type f)
{
m_pdata->m_flags = f;
if(m_icase != static_cast<bool>(f & regbase::icase))
{
m_icase = static_cast<bool>(f & regbase::icase);
}
}
re_syntax_base* append_state(syntax_element_type t, std::size_t s = sizeof(re_syntax_base));
re_syntax_base* insert_state(std::ptrdiff_t pos, syntax_element_type t, std::size_t s = sizeof(re_syntax_base));
re_literal* append_literal(charT c);
re_syntax_base* append_set(const basic_char_set<charT, traits>& char_set);
re_syntax_base* append_set(const basic_char_set<charT, traits>& char_set, mpl::false_*);
re_syntax_base* append_set(const basic_char_set<charT, traits>& char_set, mpl::true_*);
void finalize(const charT* p1, const charT* p2);
protected:
regex_data<charT, traits>* m_pdata; // pointer to the basic_regex_data struct we are filling in
const ::boost::regex_traits_wrapper<traits>&
m_traits; // convenience reference to traits class
re_syntax_base* m_last_state; // the last state we added
bool m_icase; // true for case insensitive matches
unsigned m_repeater_id; // the id of the next repeater
bool m_has_backrefs; // true if there are actually any backrefs
unsigned m_backrefs; // bitmask of permitted backrefs
boost::uintmax_t m_bad_repeats; // bitmask of repeats we can't deduce a startmap for;
typename traits::char_class_type m_word_mask; // mask used to determine if a character is a word character
typename traits::char_class_type m_mask_space; // mask used to determine if a character is a word character
typename traits::char_class_type m_lower_mask; // mask used to determine if a character is a lowercase character
typename traits::char_class_type m_upper_mask; // mask used to determine if a character is an uppercase character
typename traits::char_class_type m_alpha_mask; // mask used to determine if a character is an alphabetic character
private:
basic_regex_creator& operator=(const basic_regex_creator&);
basic_regex_creator(const basic_regex_creator&);
void fixup_pointers(re_syntax_base* state);
void create_startmaps(re_syntax_base* state);
int calculate_backstep(re_syntax_base* state);
void create_startmap(re_syntax_base* state, unsigned char* l_map, unsigned int* pnull, unsigned char mask);
unsigned get_restart_type(re_syntax_base* state);
void set_all_masks(unsigned char* bits, unsigned char);
bool is_bad_repeat(re_syntax_base* pt);
void set_bad_repeat(re_syntax_base* pt);
syntax_element_type get_repeat_type(re_syntax_base* state);
void probe_leading_repeat(re_syntax_base* state);
};
template <class charT, class traits>
basic_regex_creator<charT, traits>::basic_regex_creator(regex_data<charT, traits>* data)
: m_pdata(data), m_traits(*(data->m_ptraits)), m_last_state(0), m_repeater_id(0), m_has_backrefs(false), m_backrefs(0)
{
m_pdata->m_data.clear();
m_pdata->m_status = ::boost::regex_constants::error_ok;
static const charT w = 'w';
static const charT s = 's';
static const charT l[5] = { 'l', 'o', 'w', 'e', 'r', };
static const charT u[5] = { 'u', 'p', 'p', 'e', 'r', };
static const charT a[5] = { 'a', 'l', 'p', 'h', 'a', };
m_word_mask = m_traits.lookup_classname(&w, &w +1);
m_mask_space = m_traits.lookup_classname(&s, &s +1);
m_lower_mask = m_traits.lookup_classname(l, l + 5);
m_upper_mask = m_traits.lookup_classname(u, u + 5);
m_alpha_mask = m_traits.lookup_classname(a, a + 5);
m_pdata->m_word_mask = m_word_mask;
BOOST_ASSERT(m_word_mask != 0);
BOOST_ASSERT(m_mask_space != 0);
BOOST_ASSERT(m_lower_mask != 0);
BOOST_ASSERT(m_upper_mask != 0);
BOOST_ASSERT(m_alpha_mask != 0);
}
template <class charT, class traits>
re_syntax_base* basic_regex_creator<charT, traits>::append_state(syntax_element_type t, std::size_t s)
{
// if the state is a backref then make a note of it:
if(t == syntax_element_backref)
this->m_has_backrefs = true;
// append a new state, start by aligning our last one:
m_pdata->m_data.align();
// set the offset to the next state in our last one:
if(m_last_state)
m_last_state->next.i = m_pdata->m_data.size() - getoffset(m_last_state);
// now actually extent our data:
m_last_state = static_cast<re_syntax_base*>(m_pdata->m_data.extend(s));
// fill in boilerplate options in the new state:
m_last_state->next.i = 0;
m_last_state->type = t;
return m_last_state;
}
template <class charT, class traits>
re_syntax_base* basic_regex_creator<charT, traits>::insert_state(std::ptrdiff_t pos, syntax_element_type t, std::size_t s)
{
// append a new state, start by aligning our last one:
m_pdata->m_data.align();
// set the offset to the next state in our last one:
if(m_last_state)
m_last_state->next.i = m_pdata->m_data.size() - getoffset(m_last_state);
// remember the last state position:
std::ptrdiff_t off = getoffset(m_last_state) + s;
// now actually insert our data:
re_syntax_base* new_state = static_cast<re_syntax_base*>(m_pdata->m_data.insert(pos, s));
// fill in boilerplate options in the new state:
new_state->next.i = s;
new_state->type = t;
m_last_state = getaddress(off);
return new_state;
}
template <class charT, class traits>
re_literal* basic_regex_creator<charT, traits>::append_literal(charT c)
{
re_literal* result;
// start by seeing if we have an existing re_literal we can extend:
if((0 == m_last_state) || (m_last_state->type != syntax_element_literal))
{
// no existing re_literal, create a new one:
result = static_cast<re_literal*>(append_state(syntax_element_literal, sizeof(re_literal) + sizeof(charT)));
result->length = 1;
*static_cast<charT*>(static_cast<void*>(result+1)) = m_traits.translate(c, m_icase);
}
else
{
// we have an existing re_literal, extend it:
std::ptrdiff_t off = getoffset(m_last_state);
m_pdata->m_data.extend(sizeof(charT));
m_last_state = result = static_cast<re_literal*>(getaddress(off));
charT* characters = static_cast<charT*>(static_cast<void*>(result+1));
characters[result->length] = m_traits.translate(c, m_icase);
++(result->length);
}
return result;
}
template <class charT, class traits>
inline re_syntax_base* basic_regex_creator<charT, traits>::append_set(
const basic_char_set<charT, traits>& char_set)
{
typedef mpl::bool_< (sizeof(charT) == 1) > truth_type;
return char_set.has_digraphs()
? append_set(char_set, static_cast<mpl::false_*>(0))
: append_set(char_set, static_cast<truth_type*>(0));
}
template <class charT, class traits>
re_syntax_base* basic_regex_creator<charT, traits>::append_set(
const basic_char_set<charT, traits>& char_set, mpl::false_*)
{
typedef typename traits::string_type string_type;
typedef typename basic_char_set<charT, traits>::list_iterator item_iterator;
typedef typename traits::char_class_type mask_type;
re_set_long<mask_type>* result = static_cast<re_set_long<mask_type>*>(append_state(syntax_element_long_set, sizeof(re_set_long<mask_type>)));
//
// fill in the basics:
//
result->csingles = static_cast<unsigned int>(::boost::re_detail::distance(char_set.singles_begin(), char_set.singles_end()));
result->cranges = static_cast<unsigned int>(::boost::re_detail::distance(char_set.ranges_begin(), char_set.ranges_end())) / 2;
result->cequivalents = static_cast<unsigned int>(::boost::re_detail::distance(char_set.equivalents_begin(), char_set.equivalents_end()));
result->cclasses = char_set.classes();
result->cnclasses = char_set.negated_classes();
if(flags() & regbase::icase)
{
// adjust classes as needed:
if(((result->cclasses & m_lower_mask) == m_lower_mask) || ((result->cclasses & m_upper_mask) == m_upper_mask))
result->cclasses |= m_alpha_mask;
if(((result->cnclasses & m_lower_mask) == m_lower_mask) || ((result->cnclasses & m_upper_mask) == m_upper_mask))
result->cnclasses |= m_alpha_mask;
}
result->isnot = char_set.is_negated();
result->singleton = !char_set.has_digraphs();
//
// remember where the state is for later:
//
std::ptrdiff_t offset = getoffset(result);
//
// now extend with all the singles:
//
item_iterator first, last;
first = char_set.singles_begin();
last = char_set.singles_end();
while(first != last)
{
charT* p = static_cast<charT*>(this->m_pdata->m_data.extend(sizeof(charT) * (first->second ? 3 : 2)));
p[0] = m_traits.translate(first->first, m_icase);
if(first->second)
{
p[1] = m_traits.translate(first->second, m_icase);
p[2] = 0;
}
else
p[1] = 0;
++first;
}
//
// now extend with all the ranges:
//
first = char_set.ranges_begin();
last = char_set.ranges_end();
while(first != last)
{
// first grab the endpoints of the range:
digraph<charT> c1 = *first;
c1.first = this->m_traits.translate(c1.first, this->m_icase);
c1.second = this->m_traits.translate(c1.second, this->m_icase);
++first;
digraph<charT> c2 = *first;
c2.first = this->m_traits.translate(c2.first, this->m_icase);
c2.second = this->m_traits.translate(c2.second, this->m_icase);
++first;
string_type s1, s2;
// different actions now depending upon whether collation is turned on:
if(flags() & regex_constants::collate)
{
// we need to transform our range into sort keys:
#if BOOST_WORKAROUND(__GNUC__, < 3)
string_type in(3, charT(0));
in[0] = c1.first;
in[1] = c1.second;
s1 = this->m_traits.transform(in.c_str(), (in[1] ? in.c_str()+2 : in.c_str()+1));
in[0] = c2.first;
in[1] = c2.second;
s2 = this->m_traits.transform(in.c_str(), (in[1] ? in.c_str()+2 : in.c_str()+1));
#else
charT a1[3] = { c1.first, c1.second, charT(0), };
charT a2[3] = { c2.first, c2.second, charT(0), };
s1 = this->m_traits.transform(a1, (a1[1] ? a1+2 : a1+1));
s2 = this->m_traits.transform(a2, (a2[1] ? a2+2 : a2+1));
#endif
if(s1.size() == 0)
s1 = string_type(1, charT(0));
if(s2.size() == 0)
s2 = string_type(1, charT(0));
}
else
{
if(c1.second)
{
s1.insert(s1.end(), c1.first);
s1.insert(s1.end(), c1.second);
}
else
s1 = string_type(1, c1.first);
if(c2.second)
{
s2.insert(s2.end(), c2.first);
s2.insert(s2.end(), c2.second);
}
else
s2.insert(s2.end(), c2.first);
}
if(s1 > s2)
{
// Oops error:
return 0;
}
charT* p = static_cast<charT*>(this->m_pdata->m_data.extend(sizeof(charT) * (s1.size() + s2.size() + 2) ) );
re_detail::copy(s1.begin(), s1.end(), p);
p[s1.size()] = charT(0);
p += s1.size() + 1;
re_detail::copy(s2.begin(), s2.end(), p);
p[s2.size()] = charT(0);
}
//
// now process the equivalence classes:
//
first = char_set.equivalents_begin();
last = char_set.equivalents_end();
while(first != last)
{
string_type s;
if(first->second)
{
#if BOOST_WORKAROUND(__GNUC__, < 3)
string_type in(3, charT(0));
in[0] = first->first;
in[1] = first->second;
s = m_traits.transform_primary(in.c_str(), in.c_str()+2);
#else
charT cs[3] = { first->first, first->second, charT(0), };
s = m_traits.transform_primary(cs, cs+2);
#endif
}
else
s = m_traits.transform_primary(&first->first, &first->first+1);
if(s.empty())
return 0; // invalid or unsupported equivalence class
charT* p = static_cast<charT*>(this->m_pdata->m_data.extend(sizeof(charT) * (s.size()+1) ) );
re_detail::copy(s.begin(), s.end(), p);
p[s.size()] = charT(0);
++first;
}
//
// finally reset the address of our last state:
//
m_last_state = result = static_cast<re_set_long<mask_type>*>(getaddress(offset));
return result;
}
namespace{
template<class T>
inline bool char_less(T t1, T t2)
{
return t1 < t2;
}
template<>
inline bool char_less<char>(char t1, char t2)
{
return static_cast<unsigned char>(t1) < static_cast<unsigned char>(t2);
}
template<>
inline bool char_less<signed char>(signed char t1, signed char t2)
{
return static_cast<unsigned char>(t1) < static_cast<unsigned char>(t2);
}
}
template <class charT, class traits>
re_syntax_base* basic_regex_creator<charT, traits>::append_set(
const basic_char_set<charT, traits>& char_set, mpl::true_*)
{
typedef typename traits::string_type string_type;
typedef typename basic_char_set<charT, traits>::list_iterator item_iterator;
re_set* result = static_cast<re_set*>(append_state(syntax_element_set, sizeof(re_set)));
bool negate = char_set.is_negated();
std::memset(result->_map, 0, sizeof(result->_map));
//
// handle singles first:
//
item_iterator first, last;
first = char_set.singles_begin();
last = char_set.singles_end();
while(first != last)
{
for(unsigned int i = 0; i < (1 << CHAR_BIT); ++i)
{
if(this->m_traits.translate(static_cast<charT>(i), this->m_icase)
== this->m_traits.translate(first->first, this->m_icase))
result->_map[i] = true;
}
++first;
}
//
// OK now handle ranges:
//
first = char_set.ranges_begin();
last = char_set.ranges_end();
while(first != last)
{
// first grab the endpoints of the range:
charT c1 = this->m_traits.translate(first->first, this->m_icase);
++first;
charT c2 = this->m_traits.translate(first->first, this->m_icase);
++first;
// different actions now depending upon whether collation is turned on:
if(flags() & regex_constants::collate)
{
// we need to transform our range into sort keys:
charT c3[2] = { c1, charT(0), };
string_type s1 = this->m_traits.transform(c3, c3+1);
c3[0] = c2;
string_type s2 = this->m_traits.transform(c3, c3+1);
if(s1 > s2)
{
// Oops error:
return 0;
}
BOOST_ASSERT(c3[1] == charT(0));
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
c3[0] = static_cast<charT>(i);
string_type s3 = this->m_traits.transform(c3, c3 +1);
if((s1 <= s3) && (s3 <= s2))
result->_map[i] = true;
}
}
else
{
if(char_less<charT>(c2, c1))
{
// Oops error:
return 0;
}
// everything in range matches:
std::memset(result->_map + static_cast<unsigned char>(c1), true, 1 + static_cast<unsigned char>(c2) - static_cast<unsigned char>(c1));
}
}
//
// and now the classes:
//
typedef typename traits::char_class_type mask_type;
mask_type m = char_set.classes();
if(flags() & regbase::icase)
{
// adjust m as needed:
if(((m & m_lower_mask) == m_lower_mask) || ((m & m_upper_mask) == m_upper_mask))
m |= m_alpha_mask;
}
if(m != 0)
{
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
if(this->m_traits.isctype(static_cast<charT>(i), m))
result->_map[i] = true;
}
}
//
// and now the negated classes:
//
m = char_set.negated_classes();
if(flags() & regbase::icase)
{
// adjust m as needed:
if(((m & m_lower_mask) == m_lower_mask) || ((m & m_upper_mask) == m_upper_mask))
m |= m_alpha_mask;
}
if(m != 0)
{
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
if(0 == this->m_traits.isctype(static_cast<charT>(i), m))
result->_map[i] = true;
}
}
//
// now process the equivalence classes:
//
first = char_set.equivalents_begin();
last = char_set.equivalents_end();
while(first != last)
{
string_type s;
BOOST_ASSERT(static_cast<charT>(0) == first->second);
s = m_traits.transform_primary(&first->first, &first->first+1);
if(s.empty())
return 0; // invalid or unsupported equivalence class
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
charT c[2] = { (static_cast<charT>(i)), charT(0), };
string_type s2 = this->m_traits.transform_primary(c, c+1);
if(s == s2)
result->_map[i] = true;
}
++first;
}
if(negate)
{
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
result->_map[i] = !(result->_map[i]);
}
}
return result;
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::finalize(const charT* p1, const charT* p2)
{
// we've added all the states we need, now finish things off.
// start by adding a terminating state:
append_state(syntax_element_match);
// extend storage to store original expression:
std::ptrdiff_t len = p2 - p1;
m_pdata->m_expression_len = len;
charT* ps = static_cast<charT*>(m_pdata->m_data.extend(sizeof(charT) * (1 + (p2 - p1))));
m_pdata->m_expression = ps;
re_detail::copy(p1, p2, ps);
ps[p2 - p1] = 0;
// fill in our other data...
// successful parsing implies a zero status:
m_pdata->m_status = 0;
// get the first state of the machine:
m_pdata->m_first_state = static_cast<re_syntax_base*>(m_pdata->m_data.data());
// fixup pointers in the machine:
fixup_pointers(m_pdata->m_first_state);
// create nested startmaps:
create_startmaps(m_pdata->m_first_state);
// create main startmap:
std::memset(m_pdata->m_startmap, 0, sizeof(m_pdata->m_startmap));
m_pdata->m_can_be_null = 0;
m_bad_repeats = 0;
create_startmap(m_pdata->m_first_state, m_pdata->m_startmap, &(m_pdata->m_can_be_null), mask_all);
// get the restart type:
m_pdata->m_restart_type = get_restart_type(m_pdata->m_first_state);
// optimise a leading repeat if there is one:
probe_leading_repeat(m_pdata->m_first_state);
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::fixup_pointers(re_syntax_base* state)
{
while(state)
{
switch(state->type)
{
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
// set the id of this repeat:
static_cast<re_repeat*>(state)->id = m_repeater_id++;
// fall through:
case syntax_element_alt:
std::memset(static_cast<re_alt*>(state)->_map, 0, sizeof(static_cast<re_alt*>(state)->_map));
static_cast<re_alt*>(state)->can_be_null = 0;
// fall through:
case syntax_element_jump:
static_cast<re_jump*>(state)->alt.p = getaddress(static_cast<re_jump*>(state)->alt.i, state);
// fall through again:
default:
if(state->next.i)
state->next.p = getaddress(state->next.i, state);
else
state->next.p = 0;
}
state = state->next.p;
}
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::create_startmaps(re_syntax_base* state)
{
// non-recursive implementation:
// create the last map in the machine first, so that earlier maps
// can make use of the result...
//
// This was originally a recursive implementation, but that caused stack
// overflows with complex expressions on small stacks (think COM+).
// start by saving the case setting:
bool l_icase = m_icase;
std::vector<std::pair<bool, re_syntax_base*> > v;
while(state)
{
switch(state->type)
{
case syntax_element_toggle_case:
// we need to track case changes here:
m_icase = static_cast<re_case*>(state)->icase;
state = state->next.p;
continue;
case syntax_element_alt:
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
// just push the state onto our stack for now:
v.push_back(std::pair<bool, re_syntax_base*>(m_icase, state));
state = state->next.p;
break;
case syntax_element_backstep:
// we need to calculate how big the backstep is:
static_cast<re_brace*>(state)->index
= this->calculate_backstep(state->next.p);
if(static_cast<re_brace*>(state)->index < 0)
{
// Oops error:
if(0 == this->m_pdata->m_status) // update the error code if not already set
this->m_pdata->m_status = boost::regex_constants::error_bad_pattern;
//
// clear the expression, we should be empty:
//
this->m_pdata->m_expression = 0;
this->m_pdata->m_expression_len = 0;
//
// and throw if required:
//
if(0 == (this->flags() & regex_constants::no_except))
{
std::string message = this->m_pdata->m_ptraits->error_string(boost::regex_constants::error_bad_pattern);
boost::regex_error e(message, boost::regex_constants::error_bad_pattern, 0);
e.raise();
}
}
// fall through:
default:
state = state->next.p;
}
}
// now work through our list, building all the maps as we go:
while(v.size())
{
const std::pair<bool, re_syntax_base*>& p = v.back();
m_icase = p.first;
state = p.second;
v.pop_back();
// Build maps:
m_bad_repeats = 0;
create_startmap(state->next.p, static_cast<re_alt*>(state)->_map, &static_cast<re_alt*>(state)->can_be_null, mask_take);
m_bad_repeats = 0;
create_startmap(static_cast<re_alt*>(state)->alt.p, static_cast<re_alt*>(state)->_map, &static_cast<re_alt*>(state)->can_be_null, mask_skip);
// adjust the type of the state to allow for faster matching:
state->type = this->get_repeat_type(state);
}
// restore case sensitivity:
m_icase = l_icase;
}
template <class charT, class traits>
int basic_regex_creator<charT, traits>::calculate_backstep(re_syntax_base* state)
{
typedef typename traits::char_class_type mask_type;
int result = 0;
while(state)
{
switch(state->type)
{
case syntax_element_startmark:
if((static_cast<re_brace*>(state)->index == -1)
|| (static_cast<re_brace*>(state)->index == -2))
{
state = static_cast<re_jump*>(state->next.p)->alt.p->next.p;
continue;
}
else if(static_cast<re_brace*>(state)->index == -3)
{
state = state->next.p->next.p;
continue;
}
break;
case syntax_element_endmark:
if((static_cast<re_brace*>(state)->index == -1)
|| (static_cast<re_brace*>(state)->index == -2))
return result;
break;
case syntax_element_literal:
result += static_cast<re_literal*>(state)->length;
break;
case syntax_element_wild:
case syntax_element_set:
result += 1;
break;
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_backref:
case syntax_element_rep:
case syntax_element_combining:
case syntax_element_long_set_rep:
case syntax_element_backstep:
{
re_repeat* rep = static_cast<re_repeat *>(state);
// adjust the type of the state to allow for faster matching:
state->type = this->get_repeat_type(state);
if((state->type == syntax_element_dot_rep)
|| (state->type == syntax_element_char_rep)
|| (state->type == syntax_element_short_set_rep))
{
if(rep->max != rep->min)
return -1;
result += static_cast<int>(rep->min);
state = rep->alt.p;
continue;
}
else if((state->type == syntax_element_long_set_rep))
{
BOOST_ASSERT(rep->next.p->type == syntax_element_long_set);
if(static_cast<re_set_long<mask_type>*>(rep->next.p)->singleton == 0)
return -1;
if(rep->max != rep->min)
return -1;
result += static_cast<int>(rep->min);
state = rep->alt.p;
continue;
}
}
return -1;
case syntax_element_long_set:
if(static_cast<re_set_long<mask_type>*>(state)->singleton == 0)
return -1;
result += 1;
break;
case syntax_element_jump:
state = static_cast<re_jump*>(state)->alt.p;
continue;
default:
break;
}
state = state->next.p;
}
return -1;
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::create_startmap(re_syntax_base* state, unsigned char* l_map, unsigned int* pnull, unsigned char mask)
{
int not_last_jump = 1;
// track case sensitivity:
bool l_icase = m_icase;
while(state)
{
switch(state->type)
{
case syntax_element_toggle_case:
l_icase = static_cast<re_case*>(state)->icase;
state = state->next.p;
break;
case syntax_element_literal:
{
// don't set anything in *pnull, set each element in l_map
// that could match the first character in the literal:
if(l_map)
{
l_map[0] |= mask_init;
charT first_char = *static_cast<charT*>(static_cast<void*>(static_cast<re_literal*>(state) + 1));
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
if(m_traits.translate(static_cast<charT>(i), l_icase) == first_char)
l_map[i] |= mask;
}
}
return;
}
case syntax_element_end_line:
{
// next character must be a line separator (if there is one):
if(l_map)
{
l_map[0] |= mask_init;
l_map['\n'] |= mask;
l_map['\r'] |= mask;
l_map['\f'] |= mask;
l_map[0x85] |= mask;
}
// now figure out if we can match a NULL string at this point:
if(pnull)
create_startmap(state->next.p, 0, pnull, mask);
return;
}
case syntax_element_backref:
// can be null, and any character can match:
if(pnull)
*pnull |= mask;
// fall through:
case syntax_element_wild:
{
// can't be null, any character can match:
set_all_masks(l_map, mask);
return;
}
case syntax_element_match:
{
// must be null, any character can match:
set_all_masks(l_map, mask);
if(pnull)
*pnull |= mask;
return;
}
case syntax_element_word_start:
{
// recurse, then AND with all the word characters:
create_startmap(state->next.p, l_map, pnull, mask);
if(l_map)
{
l_map[0] |= mask_init;
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
if(!m_traits.isctype(static_cast<charT>(i), m_word_mask))
l_map[i] &= static_cast<unsigned char>(~mask);
}
}
return;
}
case syntax_element_word_end:
{
// recurse, then AND with all the word characters:
create_startmap(state->next.p, l_map, pnull, mask);
if(l_map)
{
l_map[0] |= mask_init;
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
if(m_traits.isctype(static_cast<charT>(i), m_word_mask))
l_map[i] &= static_cast<unsigned char>(~mask);
}
}
return;
}
case syntax_element_buffer_end:
{
// we *must be null* :
if(pnull)
*pnull |= mask;
return;
}
case syntax_element_long_set:
if(l_map)
{
typedef typename traits::char_class_type mask_type;
if(static_cast<re_set_long<mask_type>*>(state)->singleton)
{
l_map[0] |= mask_init;
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
charT c = static_cast<charT>(i);
if(&c != re_is_set_member(&c, &c + 1, static_cast<re_set_long<mask_type>*>(state), *m_pdata, m_icase))
l_map[i] |= mask;
}
}
else
set_all_masks(l_map, mask);
}
return;
case syntax_element_set:
if(l_map)
{
l_map[0] |= mask_init;
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
if(static_cast<re_set*>(state)->_map[
static_cast<unsigned char>(m_traits.translate(static_cast<charT>(i), l_icase))])
l_map[i] |= mask;
}
}
return;
case syntax_element_jump:
// take the jump:
state = static_cast<re_alt*>(state)->alt.p;
not_last_jump = -1;
break;
case syntax_element_alt:
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
{
re_alt* rep = static_cast<re_alt*>(state);
if(rep->_map[0] & mask_init)
{
if(l_map)
{
// copy previous results:
l_map[0] |= mask_init;
for(unsigned int i = 0; i <= UCHAR_MAX; ++i)
{
if(rep->_map[i] & mask_any)
l_map[i] |= mask;
}
}
if(pnull)
{
if(rep->can_be_null & mask_any)
*pnull |= mask;
}
}
else
{
// we haven't created a startmap for this alternative yet
// so take the union of the two options:
if(is_bad_repeat(state))
{
set_all_masks(l_map, mask);
if(pnull)
*pnull |= mask;
return;
}
set_bad_repeat(state);
create_startmap(state->next.p, l_map, pnull, mask);
if((state->type == syntax_element_alt)
|| (static_cast<re_repeat*>(state)->min == 0)
|| (not_last_jump == 0))
create_startmap(rep->alt.p, l_map, pnull, mask);
}
}
return;
case syntax_element_soft_buffer_end:
// match newline or null:
if(l_map)
{
l_map[0] |= mask_init;
l_map['\n'] |= mask;
l_map['\r'] |= mask;
}
if(pnull)
*pnull |= mask;
return;
case syntax_element_endmark:
// need to handle independent subs as a special case:
if(static_cast<re_brace*>(state)->index < 0)
{
// can be null, any character can match:
set_all_masks(l_map, mask);
if(pnull)
*pnull |= mask;
return;
}
else
{
state = state->next.p;
break;
}
case syntax_element_startmark:
// need to handle independent subs as a special case:
if(static_cast<re_brace*>(state)->index == -3)
{
state = state->next.p->next.p;
break;
}
// otherwise fall through:
default:
state = state->next.p;
}
++not_last_jump;
}
}
template <class charT, class traits>
unsigned basic_regex_creator<charT, traits>::get_restart_type(re_syntax_base* state)
{
//
// find out how the machine starts, so we can optimise the search:
//
while(state)
{
switch(state->type)
{
case syntax_element_startmark:
case syntax_element_endmark:
state = state->next.p;
continue;
case syntax_element_start_line:
return regbase::restart_line;
case syntax_element_word_start:
return regbase::restart_word;
case syntax_element_buffer_start:
return regbase::restart_buf;
case syntax_element_restart_continue:
return regbase::restart_continue;
default:
state = 0;
continue;
}
}
return regbase::restart_any;
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::set_all_masks(unsigned char* bits, unsigned char mask)
{
//
// set mask in all of bits elements,
// if bits[0] has mask_init not set then we can
// optimise this to a call to memset:
//
if(bits)
{
if(bits[0] == 0)
(std::memset)(bits, mask, 1u << CHAR_BIT);
else
{
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
bits[i] |= mask;
}
bits[0] |= mask_init;
}
}
template <class charT, class traits>
bool basic_regex_creator<charT, traits>::is_bad_repeat(re_syntax_base* pt)
{
switch(pt->type)
{
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
{
unsigned id = static_cast<re_repeat*>(pt)->id;
if(id > sizeof(m_bad_repeats) * CHAR_BIT)
return true; // run out of bits, assume we can't traverse this one.
static const boost::uintmax_t one = 1uL;
return m_bad_repeats & (one << id);
}
default:
return false;
}
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::set_bad_repeat(re_syntax_base* pt)
{
switch(pt->type)
{
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
{
unsigned id = static_cast<re_repeat*>(pt)->id;
static const boost::uintmax_t one = 1uL;
if(id <= sizeof(m_bad_repeats) * CHAR_BIT)
m_bad_repeats |= (one << id);
}
default:
break;
}
}
template <class charT, class traits>
syntax_element_type basic_regex_creator<charT, traits>::get_repeat_type(re_syntax_base* state)
{
typedef typename traits::char_class_type mask_type;
if(state->type == syntax_element_rep)
{
// check to see if we are repeating a single state:
if(state->next.p->next.p->next.p == static_cast<re_alt*>(state)->alt.p)
{
switch(state->next.p->type)
{
case re_detail::syntax_element_wild:
return re_detail::syntax_element_dot_rep;
case re_detail::syntax_element_literal:
return re_detail::syntax_element_char_rep;
case re_detail::syntax_element_set:
return re_detail::syntax_element_short_set_rep;
case re_detail::syntax_element_long_set:
if(static_cast<re_detail::re_set_long<mask_type>*>(state->next.p)->singleton)
return re_detail::syntax_element_long_set_rep;
break;
default:
break;
}
}
}
return state->type;
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::probe_leading_repeat(re_syntax_base* state)
{
// enumerate our states, and see if we have a leading repeat
// for which failed search restarts can be optimised;
do
{
switch(state->type)
{
case syntax_element_startmark:
if(static_cast<re_brace*>(state)->index >= 0)
{
state = state->next.p;
continue;
}
return;
case syntax_element_endmark:
case syntax_element_start_line:
case syntax_element_end_line:
case syntax_element_word_boundary:
case syntax_element_within_word:
case syntax_element_word_start:
case syntax_element_word_end:
case syntax_element_buffer_start:
case syntax_element_buffer_end:
case syntax_element_restart_continue:
state = state->next.p;
break;
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
if(this->m_has_backrefs == 0)
static_cast<re_repeat*>(state)->leading = true;
// fall through:
default:
return;
}
}while(state);
}
} // namespace re_detail
} // namespace boost
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_SUFFIX
#endif
#endif
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
1296
]
]
] |
36bc1a1038a0c25138e13c78dd54bbd7c1b44e2d
|
794e836e421d42388b87f295cfe0c3056c392845
|
/trunk/src/compiler/Architecture.h
|
d626c846edd93a12bec8b25e96fe6bd46061d9b2
|
[
"BSD-3-Clause"
] |
permissive
|
BackupTheBerlios/bf-dev-svn
|
e892779b283458510ad00b17696baf3898a061b2
|
1afb8c5679fecf15cb0cfe8e7447df1cc3e4e9c4
|
refs/heads/master
| 2021-01-25T05:35:41.850282 | 2006-06-21T18:24:12 | 2006-06-21T18:24:12 | 40,672,917 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 643 |
h
|
#ifndef __ARCHITECTURE_H__
#define __ARCHITECTURE_H__ __ARCHITECTURE_H__
#include <string>
class Architecture
{
public:
enum BfCharacter
{
INIT,
INC = '+',
DEC = '-',
INPUT = ',',
OUTPUT = '.',
NEXT_CELL = '>',
PREV_CELL = '<',
START_LOOP = '[',
END_LOOP = ']',
END
};
Architecture();
virtual ~Architecture() = 0;
virtual std::string getAsmStatement(BfCharacter code) const = 0;
virtual std::string getAsmSystemCall() const = 0;
void setIFilename(std::string fn);
void setOFilename(std::string fn);
protected:
std::string iFilename;
std::string oFilename;
};
#endif
|
[
"wolmo@cef5e46f-a703-0410-a4eb-a1b77d141377"
] |
[
[
[
1,
38
]
]
] |
aacfda2efbc88acac042d1837a6a7649288592d5
|
6f796044ae363f9ca58c66423c607e3b59d077c7
|
/source/Gui/GameElement.h
|
19b11f65b3c11fe9e8d09105cd2eb0d8217faeac
|
[] |
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 | 1,129 |
h
|
#ifndef _H_GAMEELEMENT
#define _H_GAMEELEMENT
#include "../expat/expat.h"
#include "../GuiBase/InputDevices.h"
typedef enum {
GEP_KEYBOARD_JOYSTICK,
} GEP;
class GuiImage;
class GameElement
{
public:
GameElement();
GameElement(GameElement* parent);
virtual ~GameElement();
unsigned CalcCRC(unsigned crc = 0);
void SetName(const char *str);
void SetCommandLine(const char *str);
void SetScreenShot(int number, const char *str);
void SetKeyMapping(BTN key, int event);
void SetCheatFile(const char *str);
void SetProperty(GEP prop, bool value);
char *GetName(void);
char *GetCommandLine(void);
char *GetScreenShot(int number);
char *GetCheatFile(void);
bool GetProperty(GEP prop);
int GetKeyMapping(BTN key);
void FreeImage(int number);
GuiImage* GetImage(int number);
void DeleteImage(int number);
GameElement *next;
private:
char *name;
char *cmdline;
char *screenshot[2];
char *cheatfile;
GuiImage *image[2];
unsigned properties;
int key_map[BTN_LAST];
};
#endif
|
[
"timbrug@c2eab908-c631-11dd-927d-974589228060",
"[email protected]"
] |
[
[
[
1,
15
],
[
18,
48
]
],
[
[
16,
17
]
]
] |
7ba73e8b955debe483fc67792e2340ff0c2b398e
|
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
|
/tags/pygccxml_dev_0.9.5/unittests/data/attributes.hpp
|
2f89c9282a465bd7a6928dbdf3e753ec61310e39
|
[
"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 | 582 |
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 __atributes_hpp__
#define __atributes_hpp__
#define _out_ __attribute( (gccxml( "out" ) ) )
#define _sealed_ __attribute( (gccxml( "sealed" ) ) )
#define _no_throw_ __attribute( (gccxml( "no throw" ) ) )
namespace attributes{
_sealed_ struct numeric_t{
_no_throw_ void do_nothing( _out_ int& x ){}
};
}
#endif//__atributes_hpp__
|
[
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] |
[
[
[
1,
24
]
]
] |
46757b648fe91388e6b7b24753be2d18fa4b9781
|
1c80a726376d6134744d82eec3129456b0ab0cbf
|
/Project/C++/C++/练习/Visual C++程序设计与应用教程/Li2_1/Li2_1.cpp
|
96e0c681ce565daf97fbcb49cfd405c3509f8f8e
|
[] |
no_license
|
dabaopku/project_pku
|
338a8971586b6c4cdc52bf82cdd301d398ad909f
|
b97f3f15cdc3f85a9407e6bf35587116b5129334
|
refs/heads/master
| 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 3,661 |
cpp
|
// Li2_1.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "Li2_1.h"
#include "MainFrm.h"
#include "Li2_1Doc.h"
#include "Li2_1View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CLi2_1App
BEGIN_MESSAGE_MAP(CLi2_1App, CWinApp)
ON_COMMAND(ID_APP_ABOUT, &CLi2_1App::OnAppAbout)
// 基于文件的标准文档命令
ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen)
// 标准打印设置命令
ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
// CLi2_1App 构造
CLi2_1App::CLi2_1App()
{
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CLi2_1App 对象
CLi2_1App theApp;
// CLi2_1App 初始化
BOOL CLi2_1App::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
// 初始化 OLE 库
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
LoadStdProfileSettings(4); // 加载标准 INI 文件选项(包括 MRU)
// 注册应用程序的文档模板。文档模板
// 将用作文档、框架窗口和视图之间的连接
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CLi2_1Doc),
RUNTIME_CLASS(CMainFrame), // 主 SDI 框架窗口
RUNTIME_CLASS(CLi2_1View));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
// 分析标准外壳命令、DDE、打开文件操作的命令行
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// 调度在命令行中指定的命令。如果
// 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// 唯一的一个窗口已初始化,因此显示它并对其进行更新
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
// 仅当具有后缀时才调用 DragAcceptFiles
// 在 SDI 应用程序中,这应在 ProcessShellCommand 之后发生
return TRUE;
}
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// 用于运行对话框的应用程序命令
void CLi2_1App::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CLi2_1App 消息处理程序
|
[
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] |
[
[
[
1,
147
]
]
] |
3a8b1d7e544ef38efac236b8dc5107f09f63ce4f
|
83904296a02c9ecd2868ff37f4fc0c77f09e1b26
|
/parser/earley_parser.cpp
|
316c0732c4d8fb5e1b0ce0a26739979a5846414f
|
[] |
no_license
|
Coldiep/ezop
|
5aad951ef47b90f5ce5c2d82582d733deb13f04a
|
c463b7a554f66b291aa3f2497ebe8e93687758a4
|
refs/heads/master
| 2021-05-26T15:28:43.152483 | 2011-08-14T19:36:06 | 2011-08-14T19:36:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 14,518 |
cpp
|
#define DUMP_CONTENT
#include "earley_parser.h"
using parser::EarleyParser;
//#ifdef DUMP_CONTENT
void EarleyParser::Item::Dump(Grammar* grammar, std::ostream& out) {
bool dot_printed = false;
out << state_number_ << "." << order_number_ << " ";
out << "[ " << grammar->GetSymbolName(grammar->GetLhsOfRule(rule_id_)) << " --> ";
for (unsigned rule_pos = 0; grammar->GetRhsOfRule(rule_id_, rule_pos) != Grammar::kBadSymbolId; ++rule_pos) {
if (rhs_pos_ == rule_pos) {
out << "* ";
dot_printed = true;
}
out << grammar->GetSymbolName(grammar->GetRhsOfRule(rule_id_, rule_pos));
out << " ";
}
if (not dot_printed) out << " * ";
out << ", " << origin_ << ", ";
if (lptr_) out << lptr_->state_number_ << "." << lptr_->order_number_;
else out << "null";
out << ", ";
if (not rptrs_.empty()) {
out << "<";
bool first = true;
for (Rptr cur = rptrs_.get_first(); not rptrs_.is_end(); cur = rptrs_.get_next()) {
if (cur.item_) {
if (first) {
first = false;
} else {
out << ", ";
}
out << "(" << cur.item_->state_number_ << "." << cur.item_->order_number_ << ")";
} else {
out << "(T)";
}
}
out << ">";
} else {
out << "<>";
}
out << " ]\n";
}
//#endif // DUMP_CONTENT
inline EarleyParser::Item* EarleyParser::State::AddItem(EarleyParser* parser, Grammar::RuleId rule_id, unsigned dot, size_t origin, Item* lptr, Item* rptr, Context::Ptr context) {
// Получаем идентификатор символа в правой части правила. Если метка стоит в конце правила, то
// будет возвращен 0, который используется как индекс для меток в конце правила.
Grammar::SymbolId symbol_id = grammar_->GetRhsOfRule(rule_id, dot);
// Инициализируем ситуацию.
Item* item = disp_->GetItem(rule_id, dot, origin, lptr);
if (context.get()) item->rptrs_.push_back(Item::Rptr(context, rptr));
item->order_number_ = num_of_items_;
item->state_number_ = id_;
// И добавляем ее в соответствующий список.
items_[symbol_id].elems_.push_back(item);
state_items_.push_back(item);
++num_of_items_;
// Если символ в левой части правила -- начальный и метка в конце правила, то выставляем соответствующий флаг.
if (grammar_->GetLhsOfRule(item->rule_id_) == grammar_->GetStartSymbol() and item->origin_ == 0) {
is_completed_ = true;
}
// Проверка на правило вида A --> epsilon.
if (dot == 0 and symbol_id == Grammar::kBadSymbolId) {
SymbolItemList& er_item_list = items_with_empty_rules_[grammar_->GetLhsOfRule(rule_id) - grammar_->GetNumOfTerminals() - 1];
for (Item* cur = er_item_list.elems_.get_first(); cur; cur = er_item_list.elems_.get_next()) {
if (*item == *cur) {
return item;
}
}
er_item_list.elems_.push_back(item);
}
// Правило -- это правило вида A --> alpha * B beta. Надо добавить ситуацию для правила B --> epsilon в список
// необработанных ситуаций.
else if (symbol_id != Grammar::kBadSymbolId and grammar_->IsNonterminal(symbol_id)) {
SymbolItemList& er_item_list = items_with_empty_rules_[symbol_id - grammar_->GetNumOfTerminals() - 1];
for (Item* cur = er_item_list.elems_.get_first(); cur; cur = er_item_list.elems_.get_next()) {
parser->PutItemToNonhandledList(cur, true);
}
}
return item;
}
inline void EarleyParser::Completer(size_t state_id, Item* item) {
// Текущее состояние.
State* cur_state = state_disp_.GetState(state_id);
// Состояние, в котором была порождена ситуация.
State* origin_state = state_disp_.GetState(item->origin_);
// Начинаем обработку только, если определены текущее состояние и состояние, где была
// порождена данная ситуация.
if (cur_state and origin_state) {
// Список ситуаций с точкой перед символом в левой части правила переданной ситуации.
State::SymbolItemList& or_item_list = origin_state->items_[grammar_->GetLhsOfRule(item->rule_id_)];
for (Item* cur = or_item_list.elems_.get_first(); cur; cur = or_item_list.elems_.get_next()) {
// Спрашиваем у интерпретатора, нужно ли добавлять новое состояние.
Context::Ptr context = interpretator_->HandleNonTerminal(item, cur);
// В случае неоднозначности одна и та же ситуация может обрабатываться несколько раз, проверяем это.
if (context.get() and not IsItemInList(cur_state->items_[grammar_->GetRhsOfRule(cur->rule_id_, cur->rhs_pos_ + 1)], cur, item)) {
// Сдвигаем символ после точки в обрабатываемой ситуации и добавляем ее в текущее состояние.
Item* new_item = cur_state->AddItem(this, cur->rule_id_, cur->rhs_pos_ + 1, cur->origin_, cur, item, context);
PutItemToNonhandledList(new_item, true);
# ifdef DUMP_CONTENT
new_item->Dump(grammar_, std::cout);
# endif
}
}
}
}
inline void EarleyParser::Predictor(size_t state_id, Item* item) {
// Текущее состояние.
State* cur_state = state_disp_.GetState(state_id);
// Символ после точки в правой части правила ситуации.
unsigned sym_after_dot = grammar_->GetRhsOfRule(item->rule_id_, item->rhs_pos_);
// Если текущая ситуация еще не была обработана операцией Predictor, то обрабатываем ее.
if (cur_state and not cur_state->items_[sym_after_dot].handled_by_predictor_) {
// Получаем список правил, в которых данный символ стоит в левой части.
Grammar::RuleIdList& rules_list = grammar_->GetSymRules(sym_after_dot - grammar_->GetNumOfTerminals());
for (unsigned cur = rules_list.get_first(); not rules_list.is_end(); cur = rules_list.get_next()) {
// Добавляем ситуацию на основе этого правила.
Item* new_item = cur_state->AddItem(this, cur, 0, cur_state->id_, NULL, NULL, Context::Ptr());
PutItemToNonhandledList(new_item, false);
# ifdef DUMP_CONTENT
new_item->Dump(grammar_, std::cout);
# endif
}
cur_state->items_[sym_after_dot].handled_by_predictor_ = true;
}
}
inline bool EarleyParser::Scanner(size_t state_id, Token::Ptr token, size_t& new_state_id) {
// Идентификатор символа, по которому будет производиться сдвиг.
unsigned cur_symbol_id = grammar_->GetInternalSymbolByExtrernalId(token->type_);
if (State* cur_state = state_disp_.GetState(state_id)) {
// Получаем список ситуаций, у которых точка стоит перед данным символом.
State::SymbolItemList& term_item_list = cur_state->items_[cur_symbol_id];
if (term_item_list.elems_.size()) {
// Создаем новое состояние для данного символа.
new_state_id = state_disp_.AddState(token);
if (State* next_state = state_disp_.GetState(new_state_id)) {
for (Item* cur = term_item_list.elems_.get_first(); cur; cur = term_item_list.elems_.get_next()) {
// Спрашиваем у интерпретатора, нужно ли добавлять новое состояние.
Context::Ptr context = interpretator_->HandleTerminal(token, cur);
if (context.get()) {
// Добавляем новую ситуацию со сдвинутой точкой в новое состояние.
Item* new_item = next_state->AddItem(this, cur->rule_id_, cur->rhs_pos_ + 1, cur->origin_, cur, NULL, context);
PutItemToNonhandledList(new_item, false);
# ifdef DUMP_CONTENT
new_item->Dump(grammar_, std::cout);
# endif
}
}
return true;
}
}
}
return false;
}
inline void EarleyParser::Closure(size_t state_id) {
// Проходим по необработанным ситуациям и обрабатываем их операциями Completer или Predictor.
while (not nonhandled_items_.empty()) {
Item* item = nonhandled_items_.pop();
unsigned sym_index = grammar_->GetRhsOfRule(item->rule_id_, item->rhs_pos_);
// Если у ситуации точка в конце правила, то надо применить операцию Completer.
if (sym_index == Grammar::kBadSymbolId) {
Completer(state_id, item);
// Если символ после точки нетерминал, то применяем операцию Predictor.
} else if (grammar_->IsNonterminal(sym_index)) {
Predictor(state_id, item);
}
}
}
inline bool EarleyParser::InitFirstState(size_t& state_id) {
state_id = state_disp_.AddState(Token::Ptr(new Token()));
State* next_state = state_disp_.GetState(state_id);
Grammar::RuleIdList& rules_list = grammar_->GetSymRules(grammar_->GetStartSymbol() - grammar_->GetNumOfTerminals());
if (rules_list.empty()) {
return false;
}
for (unsigned cur = rules_list.get_first(); not rules_list.is_end(); cur = rules_list.get_next()) {
Item* new_item = next_state->AddItem(this, cur, 0, state_id, NULL, NULL, Context::Ptr());
PutItemToNonhandledList(new_item, false);
# ifdef DUMP_CONTENT
new_item->Dump(grammar_, std::cout );
# endif
}
next_state->items_[grammar_->GetStartSymbol()].handled_by_predictor_ = true;
return true;
}
bool EarleyParser::Parse() {
// Сообщаем интерпретатору о начале работы.
interpretator_->Start(this);
// Инициализируем начальное состояние.
size_t first_state_id = 0;
if (not InitFirstState(first_state_id)) {
return false;
}
Closure(first_state_id);
// Проходим по цепочке (дереву при неоднозначности) терминалов, возвращаемой лексическим анализатором.
StateList cur_gen_states, res_states;
cur_gen_states.push_back(first_state_id);
while (not cur_gen_states.empty()) {
// Обрабатываем все состояния из текущего множества.
StateList next_gen_states;
while (not cur_gen_states.empty()) {
size_t state_id = cur_gen_states.pop_front();
State* state = state_disp_.GetState(state_id);
// Получаем список токенов, идущих за данным.
Lexer::TokenList tokens = lexer_->GetTokens(state->token_);
for (Lexer::TokenList::iterator it = tokens.begin(); it != tokens.end(); ++it) {
// Для каждого токена осуществляем сдвиг и итеративно применяем операции Completer и Predictor.
size_t new_state_id = 0;
if (Scanner(state_id, *it, new_state_id)) {
Closure(new_state_id);
next_gen_states.push_back(new_state_id);
if (lexer_->IsEnd(*it)) {
res_states.push_back(new_state_id);
}
}
}
}
// Проделываем следующую итерацию над следующем множеством состояний.
cur_gen_states = next_gen_states;
}
// Проходим по списку состояний, построенных для последних символов в потоке.
bool parse_well = false;
for (size_t state_id = res_states.get_first(); not res_states.is_end(); state_id = res_states.get_next()) {
State* state = state_disp_.GetState(state_id);
for (Item* item = state->state_items_.get_first(); not state->state_items_.is_end(); item = state->state_items_.get_next()) {
if (grammar_->GetLhsOfRule(item->rule_id_) == grammar_->GetStartSymbol() and item->origin_ == 0) {
parse_well = true;
interpretator_->End(item);
}
}
}
return parse_well;
}
void EarleyParser::Reset() {
}
#if 0
inline bool earley_parser::error_scanner()
{
state& cur_state = *states_[ states_.size() - 1 ];
// items to pass to handle_error method
private_::item_list_t term_items;
for( int i = 1; i <= grammar_->GetNumOfTerminals(); ++ i )
{
state::item_list& term_item_list = cur_state.items_[ i ];
for( item* cur = term_item_list.elems_.get_first(); cur ; cur = term_item_list.elems_.get_next() )
{
term_items.push_back( cur );
}
}
error_cost_list_t* error_cost_list = semantics_->handle_error( &term_items, cur_token_ );
states_.push_back( new state() );
state& new_state = *states_[ states_.size() - 1 ];
new_state.init( this, grammar_, (int)states_.size() - 1, cur_token_ );
item* cur = term_items.get_first();
int error_cost = error_cost_list->get_first();
for( ; cur ; cur = term_items.get_next(), error_cost = error_cost_list->get_next() )
{
int new_error_cost = cur->error_ + error_cost;
if( new_error_cost <= max_error_value_ )
{
// deletion
item* new_item = new_state.add_item( cur->rule_id_, cur->rhs_pos_, cur->origin_, 0, 0, new_error_cost );
put_item_to_nonhandled_list( new_item, false );
// insertion
new_item = new_state.add_item( cur->rule_id_, cur->rhs_pos_ + 1, cur->origin_, cur, 0, new_error_cost );
put_item_to_nonhandled_list( new_item, false );
}
}
delete error_cost_list;
if( term_items.empty() ) return false;
return true;
}
#endif
|
[
"[email protected]",
"[email protected]",
"[email protected]"
] |
[
[
[
1,
76
],
[
78,
88
],
[
90,
288
],
[
290,
327
]
],
[
[
77,
77
],
[
89,
89
]
],
[
[
289,
289
]
]
] |
8ffb52b33822589e2a3416b842630dddda8a5090
|
a2904986c09bd07e8c89359632e849534970c1be
|
/topcoder/completed/MostProfitable.cpp
|
b93c9fb828c87e5bdbcead1fe5071348b8413683
|
[] |
no_license
|
naturalself/topcoder_srms
|
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
|
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
|
refs/heads/master
| 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,600 |
cpp
|
// BEGIN CUT HERE
// END CUT HERE
#line 5 "MostProfitable.cpp"
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
class MostProfitable {
public:
string bestItem(vector <int> costs, vector <int> prices, vector <int> sales, vector <string> items) {
long int now_profit=0;
long int max_profit=0;
int max_profit_index=0;
for(int i=0;i<(int)costs.size();i++){
now_profit = (prices[i]-costs[i])*sales[i];
if(now_profit > max_profit){
max_profit = now_profit;
max_profit_index = i;
}
}
if(max_profit == 0){
return "";
}else{
return items[max_profit_index];
}
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {100,120,150,1000}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {110,110,200,2000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {20,100,50,3}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arr3[] = {"Video Card","256M Mem","CPU/Mobo combo","Complete machine"}; vector <string> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); string Arg4 = "Complete machine"; verify_case(0, Arg4, bestItem(Arg0, Arg1, Arg2, Arg3)); }
void test_case_1() { int Arr0[] = {100}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {134}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arr3[] = {"Service, at cost"}; vector <string> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); string Arg4 = ""; verify_case(1, Arg4, bestItem(Arg0, Arg1, Arg2, Arg3)); }
void test_case_2() { int Arr0[] = {38,24}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {37,23}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1000,643}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arr3[] = {"Letter","Postcard"}; vector <string> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); string Arg4 = ""; verify_case(2, Arg4, bestItem(Arg0, Arg1, Arg2, Arg3)); }
void test_case_3() { int Arr0[] = {10,10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {11,12}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {2,1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arr3[] = {"A","B"}; vector <string> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); string Arg4 = "A"; verify_case(3, Arg4, bestItem(Arg0, Arg1, Arg2, Arg3)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
MostProfitable ___test;
___test.run_test(-1);
}
// END CUT HERE
|
[
"shin@CF-7AUJ41TT52JO.(none)"
] |
[
[
[
1,
58
]
]
] |
c87b8d980d0adaddb00154c473ebbf981689bcd8
|
cf58ec40b7ea828aba01331ee3ab4c7f2195b6ca
|
/Nestopia/core/board/NstBoardCxRom.cpp
|
a483e1c800bd05207c264defb4da6c07dadb1cc0
|
[] |
no_license
|
nicoya/OpenEmu
|
e2fd86254d45d7aa3d7ef6a757192e2f7df0da1e
|
dd5091414baaaddbb10b9d50000b43ee336ab52b
|
refs/heads/master
| 2021-01-16T19:51:53.556272 | 2011-08-06T18:52:40 | 2011-08-06T18:52:40 | 2,131,312 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,624 |
cpp
|
////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia 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.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#include "NstBoard.hpp"
#include "NstBoardCxRom.hpp"
namespace Nes
{
namespace Core
{
namespace Boards
{
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("s", on)
#endif
CnRom::Ce::Ce(const Context& c)
: mask(0x0), state(0x0)
{
if (c.chr.Pin(26) == L"CE")
{
mask |= 0x1;
state |= 0x1;
}
else if (c.chr.Pin(26) == L"/CE")
{
mask |= 0x1;
state |= 0x0;
}
if (c.chr.Pin(27) == L"CE")
{
mask |= 0x2;
state |= 0x2;
}
else if (c.chr.Pin(27) == L"/CE")
{
mask |= 0x2;
state |= 0x0;
}
}
CnRom::CnRom(const Context& c)
: Board(c), ce(c) {}
void CnRom::SubReset(bool)
{
if (ce.mask)
{
Map( 0x8000U, 0xFFFFU, &CnRom::Poke_8000 );
}
else if (board == Type::STD_CNROM)
{
Map( CHR_SWAP_8K_BC );
}
else
{
Map( 0x8000U, 0xFFFFU, CHR_SWAP_8K );
}
}
void CpRom::SubReset(const bool hard)
{
Map( CHR_SWAP_4K_1_BC );
if (hard)
chr.SwapBank<SIZE_4K,0x1000>(0);
}
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("", on)
#endif
NES_ACCESSOR(CnRom,ChrOpenBus)
{
return 0xFF;
}
NES_POKE_AD(CnRom,8000)
{
data = GetBusData(address,data);
ppu.Update();
chr.SwapBank<SIZE_8K,0x0000>( data & ~ce.mask );
if ((data & ce.mask) == ce.state)
chr.ResetAccessors();
else
chr.SetAccessors( this, &CnRom::Access_ChrOpenBus, &CnRom::Access_ChrOpenBus );
}
}
}
}
|
[
"[email protected]"
] |
[
[
[
1,
115
]
]
] |
b4a90a2ab53877179a0fb546474dd8d3f489d835
|
91b964984762870246a2a71cb32187eb9e85d74e
|
/SRC/OFFI SRC!/_Interface/WndGuideSystem.h
|
a632225d9a6a106b708eb2086dd16370e1f987fe
|
[] |
no_license
|
willrebuild/flyffsf
|
e5911fb412221e00a20a6867fd00c55afca593c7
|
d38cc11790480d617b38bb5fc50729d676aef80d
|
refs/heads/master
| 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,886 |
h
|
// GuideSystem.h: interface for the CGuideSystem class.
//
//////////////////////////////////////////////////////////////////////
#ifndef __WNDGUIDESYSTEM__H
#define __WNDGUIDESYSTEM__H
#include "wndTutorial.h"
typedef struct GUIDE_STRUCT
{
CString m_str;
int m_nkey;
int m_nEventMsg;
BOOL m_bBeginner;
BOOL m_bFlag;
BOOL m_bIsClear;
int m_nShowLevel;
#if __VER >= 12 // __MOD_TUTORIAL
int m_nSequence;
int m_nVicCondition;
int m_nLevel;
UINT m_nInput;
CString m_strInput;
GUIDE_STRUCT()
{
init();
};
void init()
{
m_nLevel = m_nInput = m_nkey = m_nEventMsg = m_bBeginner = m_bFlag = m_nShowLevel = m_nSequence = m_nVicCondition = 0;
m_strInput.Empty();
m_str.Empty();
};
#endif
} GUIDE_STRUCT;
class CWndGuideTextMgr : public CWndNeuz
{
public:
CString m_strHelpKey;
CTexture* m_pTextureBG;
CRect m_Rect[4];
int m_nCurrentVector;
vector<GUIDE_STRUCT> m_VecGuideText;
GUIDE_STRUCT GetGuideText()
{
return m_VecGuideText[m_nCurrentVector];
}
void AddGuideText( GUIDE_STRUCT guide );
#if __VER >= 12 // __MOD_TUTORIAL
void _SetGuideText( GUIDE_STRUCT guide, bool bIsNext);
#else
void _SetGuideText( GUIDE_STRUCT guide );
#endif
CWndGuideTextMgr();
~CWndGuideTextMgr();
void UpDate();
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
virtual void PaintFrame( C2DRender* p2DRender );
virtual BOOL OnEraseBkgnd( C2DRender* p2DRender );
};
class CWndGuideSelection : public CWndNeuz
{
public:
CWndGuideSelection();
virtual ~CWndGuideSelection();
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
virtual void OnRButtonDown( UINT nFlags, CPoint point );
};
#if __VER >= 12 // __MOD_TUTORIAL
typedef map<int, GUIDE_STRUCT>::value_type mgValType;
typedef map<int, GUIDE_STRUCT>::iterator mgMapItor;
#define NO_CONDITION 0
#define CAMERA_ROTATION 1
#define CAMERA_ZOOMED 2
#define INPUT_KEY 3
#define INPUT_STRING 4
#define MOVE_ON_MOUSE 5
#define MOVE_ON_KEY 6
#define OPEN_WINDOW 7
struct CONDITION
{
bool bIsCamMove;
bool bIsCamZoomed;
UINT nInputKey;
bool bIsClickOnLand;
bool bIsKeyMove;
int nOpenedWindowID;
CString strInput;
void Init()
{
bIsKeyMove = bIsCamMove = bIsCamZoomed = bIsClickOnLand = false;
nOpenedWindowID = nInputKey = 0;
strInput.Empty();
};
};
class CWndInfoPang : public CWndNeuz
{
public:
CWndInfoPang() {};
virtual ~CWndInfoPang();
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
virtual void OnRButtonUp( UINT nFlags, CPoint point );
};
#endif
class CWndGuideSystem : public CWndNeuz
{
public:
BOOL m_bIsLoad;
enum { ANI_INTRO = 0, ANI_IDLE, ANI_BYTE };
enum { KEY = 0, STR };
DWORD m_dwGuideLevel;
DWORD m_dwTime;
BYTE m_bAniState;
#if __VER >= 12 // __MOD_TUTORIAL
vector<GUIDE_STRUCT> m_vecEventGuide;
map<int, GUIDE_STRUCT> m_mapGuide;
mgMapItor m_CurrentIter;
GUIDE_STRUCT m_CurrentGuide;
CONDITION m_Condition;
BOOL CheckCompletion(GUIDE_STRUCT Guide);
BOOL PassToNext();
CWndTutorial* m_pWndTutorialView;
bool m_bIsViewVisible;
#else
list<int> m_listGuideMsg;
list<GUIDE_STRUCT> m_listGuide;
list<GUIDE_STRUCT*> m_listGuideChart;
#endif
CModelObject* m_pModel;
CWndGuideTextMgr* m_wndGuideText;
CWndGuideSelection* m_wndGuideSelection;
CWndMenu m_wndMenuPlace;
public:
void SetAni(int nJob, int nAniKind);
void ChangeModel( int nJob );
void CreateGuideSelection();
void GuideStart(BOOL ischart = FALSE);
void PushBack( GUIDE_STRUCT guide );
BOOL m_bIsGuideChart[2];
CWndGuideSystem();
virtual ~CWndGuideSystem();
void SendGuideMessage( int nMsg );
BOOL LoadGuide( LPCTSTR lpszFileName );
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
virtual void OnRButtonDown( UINT nFlags, CPoint point );
virtual void PaintFrame( C2DRender* p2DRender );
virtual BOOL Process();
virtual void OnLButtonDblClk( UINT nFlags, CPoint point );
};
#endif // __WNDGUIDESYSTEM__H
|
[
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] |
[
[
[
1,
215
]
]
] |
b8a686974b55e69b5ab1eeeeced53c542ac28226
|
2ca3ad74c1b5416b2748353d23710eed63539bb0
|
/Src/Lokapala/Raptor/APIHookingManager.cpp
|
2f67ae76848d2076f1ae20aa74cc63251aefcd23
|
[] |
no_license
|
sjp38/lokapala
|
5ced19e534bd7067aeace0b38ee80b87dfc7faed
|
dfa51d28845815cfccd39941c802faaec9233a6e
|
refs/heads/master
| 2021-01-15T16:10:23.884841 | 2009-06-03T14:56:50 | 2009-06-03T14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,259 |
cpp
|
/**@file APIHookingManager.cpp
* @brief CAPIHookingManager 클래스의 멤버함수들을 구현
* @author siva
*/
#include "stdafx.h"
#include "APIHookingManager.h"
#include "APIHookExport.h"
/**@brief 자신의 실행 경로를 알아내서 메모리에 저장해 둔다.
*/
void CAPIHookingManager::WriteSelfPathToMemory()
{
WCHAR *selfPath = (WCHAR *)malloc(sizeof(WCHAR)*MAX_PATH);
GetModuleFileName(NULL,selfPath,MAX_PATH);
char *converted = (char *)malloc(sizeof(char)*MAX_PATH);
m_map = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, sizeof(char)*MAX_PATH, _T("raptorSelfPath"));
if(!m_map)
{
AfxMessageBox(_T("message map create fail!!"));
}
converted = (char *)MapViewOfFile(m_map, FILE_MAP_WRITE, 0, 0, 0);
USES_CONVERSION;
memcpy(converted, W2A(selfPath), MAX_PATH);
free(selfPath);
}
/**@brief APILib dll을 이용해 TerminateProcess를 글로벌 후킹한다.
*/
void CAPIHookingManager::StartAPIHooking()
{
WriteSelfPathToMemory();
TerminateProcessGlobalHook(true, 0);
}
/**@brief APILib dll을 이용해 TerminateProcess의 글로벌 후킹을 해제한다.
*/
void CAPIHookingManager::StopAPIHooking()
{
TerminateProcessGlobalHook(false, 0);
}
|
[
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
] |
[
[
[
1,
45
]
]
] |
3e78105a6aab8d03ab55fe7be10000f8045f7a32
|
7a6f06d37d3a1cf37532fb12935031e558b8a6ce
|
/patch/source/Irrlicht/CXMeshFileLoader.h
|
c6a831bc1e0fb71ba4c536125f58356d37aecd1d
|
[] |
no_license
|
pecc0/phx-irrlicht
|
8ab7192e2604f3d1f7f4dc45a86118d162574a69
|
d1009e6e46e2056fb1e046855c95ab39b2bb3fba
|
refs/heads/master
| 2016-09-05T19:00:20.648062 | 2011-01-19T22:02:51 | 2011-01-19T22:02:51 | 32,383,460 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,517 |
h
|
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_X_MESH_FILE_LOADER_H_INCLUDED__
#define __C_X_MESH_FILE_LOADER_H_INCLUDED__
#include "IMeshLoader.h"
#include "irrString.h"
#include "CSkinnedMesh.h"
namespace irr
{
namespace io
{
class IFileSystem;
class IReadFile;
} // end namespace io
namespace scene
{
class IMeshManipulator;
//! Meshloader capable of loading x meshes.
class CXMeshFileLoader : public IMeshLoader
{
public:
//! Constructor
CXMeshFileLoader(scene::ISceneManager* smgr, io::IFileSystem* fs);
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".cob")
virtual bool isALoadableFileExtension(const c8* fileName) const;
//! creates/loads an animated mesh from the file.
//! \return Pointer to the created mesh. Returns 0 if loading failed.
//! If you no longer need the mesh, you should call IAnimatedMesh::drop().
//! See IReferenceCounted::drop() for more information.
virtual IAnimatedMesh* createMesh(io::IReadFile* file);
struct SXTemplateMaterial
{
core::stringc Name; // template name from Xfile
video::SMaterial Material; // material
};
struct SXMesh
{
SXMesh() : MaxSkinWeightsPerVertex(0), MaxSkinWeightsPerFace(0), BoneCount(0),AttachedJointID(-1),HasSkinning(false), HasVertexColors(false) {}
// this mesh contains triangulated texture data.
// because in an .x file, faces can be made of more than 3
// vertices, the indices data structure is triangulated during the
// loading process. The IndexCountPerFace array is filled during
// this triangulation process and stores how much indices belong to
// every face. This data structure can be ignored, because all data
// in this structure is triangulated.
core::stringc Name;
u32 MaxSkinWeightsPerVertex;
u32 MaxSkinWeightsPerFace;
u32 BoneCount;
core::array< u32 > IndexCountPerFace; // default 3, but could be more
core::array<scene::SSkinMeshBuffer*> Buffers;
core::array<video::S3DVertex> Vertices;
core::array<u32> Indices;
core::array<u32> FaceMaterialIndices; // index of material for each face
core::array<video::SMaterial> Materials; // material array
s32 AttachedJointID;
bool HasSkinning;
bool HasVertexColors;
core::array<u32> WeightJoint;
core::array<u32> WeightNum;
};
public:
bool load(io::IReadFile* file);
bool readFileIntoMemory(io::IReadFile* file);
virtual bool parseFile();
bool parseDataObject();
bool parseDataObjectTemplate();
bool parseDataObjectFrame(CSkinnedMesh::SJoint *parent);
bool parseDataObjectTransformationMatrix(core::matrix4 &mat);
bool parseDataObjectMesh(SXMesh &mesh);
bool parseDataObjectSkinWeights(SXMesh &mesh);
bool parseDataObjectSkinMeshHeader(SXMesh &mesh);
bool parseDataObjectMeshNormals(SXMesh &mesh);
bool parseDataObjectMeshTextureCoords(SXMesh &mesh);
bool parseDataObjectMeshVertexColors(SXMesh &mesh);
bool parseDataObjectMeshMaterialList(SXMesh &mesh);
bool parseDataObjectMaterial(video::SMaterial& material);
bool parseDataObjectAnimationSet();
bool parseDataObjectAnimation();
bool parseDataObjectAnimationKey(ISkinnedMesh::SJoint *joint);
bool parseDataObjectTextureFilename(core::stringc& texturename);
virtual bool parseUnknownDataObject();
//! places pointer to next begin of a token, and ignores comments
void findNextNoneWhiteSpace();
//! places pointer to next begin of a token, which must be a number,
// and ignores comments
void findNextNoneWhiteSpaceNumber();
//! returns next parseable token. Returns empty string if no token there
core::stringc getNextToken();
//! reads header of dataobject including the opening brace.
//! returns false if error happened, and writes name of object
//! if there is one
bool readHeadOfDataObject(core::stringc* outname=0);
//! checks for closing curly brace, returns false if not there
bool checkForClosingBrace();
//! checks for one following semicolons, returns false if not there
bool checkForOneFollowingSemicolons();
//! checks for two following semicolons, returns false if they are not there
bool checkForTwoFollowingSemicolons();
//! reads a x file style string
bool getNextTokenAsString(core::stringc& out);
void readUntilEndOfLine();
core::stringc stripPathFromString(core::stringc string, bool returnPath);
u16 readBinWord();
u32 readBinDWord();
u32 readInt();
f32 readFloat();
bool readVector2(core::vector2df& vec);
bool readVector3(core::vector3df& vec);
bool readMatrix(core::matrix4& mat);
bool readRGB(video::SColor& color);
bool readRGBA(video::SColor& color);
ISceneManager* SceneManager;
io::IFileSystem* FileSystem;
core::array<CSkinnedMesh::SJoint*> *AllJoints;
CSkinnedMesh* AnimatedMesh;
u32 MajorVersion;
u32 MinorVersion;
bool BinaryFormat;
// counter for number arrays in binary format
u32 BinaryNumCount;
c8* Buffer;
const c8* P;
c8* End;
c8 FloatSize;
u32 Line;
core::stringc FilePath;
CSkinnedMesh::SJoint *CurFrame;
core::array<SXMesh*> Meshes;
core::array<SXTemplateMaterial> TemplateMaterials;
protected:
virtual CSkinnedMesh* getNewMesh(void);
};
} // end namespace scene
} // end namespace irr
#endif
|
[
"[email protected]@8db76cfa-2e72-11de-afe2-b5feb05456f9"
] |
[
[
[
1,
203
]
]
] |
f27af4679efad2ddc4ad2e735c16b191b85259a9
|
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
|
/archive/2544/c.cpp
|
37771b71f2d2d6da8b48439439465d493b18e4d6
|
[] |
no_license
|
Emerson21/uva-problems
|
399d82d93b563e3018921eaff12ca545415fd782
|
3079bdd1cd17087cf54b08c60e2d52dbd0118556
|
refs/heads/master
| 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,529 |
cpp
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int mx,my;
char mat[30][30];
bool tenta(int x,int y) {
if(x==-1 || x==mx) return false;
if(y==my) return false;
if(mat[y][x]=='P') return false;
if(mat[y][x]=='!') return false;
if(mat[y][x]=='S') return false;
int j = (y-1) % 4;
int i;
if(y==0) goto n;
if(j==0) {
for(i=y;i!=my;i++) if(mat[i][x]=='S') goto h;
} if(i==1) {
for(i=x;i>=0;i--) if(mat[y][i]=='S') goto h;
} if(i==2) {
//cout << "pos: " << y << "," << x << " procurando para cima" << endl;
for(i=y;i>=0;i--) if(mat[i][x]=='S') goto h;
} if(i==3) {
for(i=x;i!=mx;i++) if(mat[y][i]=='S') goto h;
}
n:
cout << y << "," << x << endl;
if(mat[y][x]=='G') return true;
if(tenta(x-1,y+1)) return true;
if(tenta(x,y+1)) return true;
if(tenta(x+1,y+1)) return true;
h:
if(mat[y][x]=='O') mat[y][x] = '!';
return false;
}
int main() {
int i;
char st[100];
while(true) {
scanf(" ");
gets(st);
if(st[0]=='E') break;
sscanf(st,"START %d %d",&mx,&my);
for(i=0;i!=my;i++) gets(mat[i]);
int pos;
for(i=0;i!=mx;i++) if(mat[0][i]=='L') break;
if(tenta(i,0)) {
cout << "FERRET" << endl;
} else {
cout << "GARRET" << endl;
}
gets(st);
}
}
|
[
"[email protected]"
] |
[
[
[
1,
61
]
]
] |
bf1d3456f5fb206f65d848e1cd90f10c228e1666
|
5dd0d48b279823c791ba070e1db53f0137055c29
|
/BTDialog.h
|
87e08bc49d00ac20152088cfbed88fb0134e91c0
|
[] |
no_license
|
ralex1975/pstviewtool
|
4b93349cf54ac7d93abbe199462f7eada44c752e
|
52f59893ad4390358053541b0257b4a7f2767024
|
refs/heads/master
| 2020-05-22T01:53:13.553501 | 2010-02-16T22:52:47 | 2010-02-16T22:52:47 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 896 |
h
|
#pragma once
#include "NDBViewer.h"
#include "NDBViewDlg.h"
#include "NDBViewChildDlg.h"
// CBTDialog dialog
static const COLORREF c_BBTPage = RGB(125,0,0);
static const COLORREF c_NBTPage = RGB(0,0,125);
static const COLORREF c_BothPage = RGB(0,0,0);
static const COLORREF c_Empty = RGB(255,255,255);
static const COLORREF c_BTPastEOF = RGB(210,210,210);
class CBTDialog : public CNDBViewChildDlg
{
DECLARE_DYNAMIC(CBTDialog)
public:
CBTDialog(NDBViewer * pNDBViewer, CNDBViewDlg * pNDBViewDlg, CWnd* pParent = NULL); // standard constructor
virtual ~CBTDialog();
// Dialog Data
enum { IDD = IDD_AMAP_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
afx_msg void OnPaint();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
NDBViewer * m_pNDBViewer;
CBitmap * m_pBTMap;
DECLARE_MESSAGE_MAP()
};
|
[
"terrymah@localhost"
] |
[
[
[
1,
34
]
]
] |
8717ba55f5092e6afc727b85c9b923dafd172a9c
|
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
|
/terralib/src/DSDK/include/base/lti_utils.h
|
e137b6573c32072a5179bd2fed4ce93d928be5c9
|
[] |
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 |
UTF-8
|
C++
| false | false | 6,449 |
h
|
/* $Id: lti_utils.h 5124 2006-10-27 11:40:40Z lubia $ */
/* //////////////////////////////////////////////////////////////////////////
// //
// This code is Copyright (c) 2004 LizardTech, Inc, 1008 Western Avenue, //
// Suite 200, Seattle, WA 98104. Unauthorized use or distribution //
// prohibited. Access to and use of this code is permitted only under //
// license from LizardTech, Inc. Portions of the code are protected by //
// US and foreign patents and other filings. All Rights Reserved. //
// //
////////////////////////////////////////////////////////////////////////// */
/* PUBLIC */
#ifndef LTI_UTILS_H
#define LTI_UTILS_H
// lt_lib_base
#include "lt_base.h"
// lt_lib_mrsid_core
#include "lti_types.h"
LT_BEGIN_NAMESPACE(LizardTech)
#if defined(LT_COMPILER_MS)
#pragma warning(push,4)
#endif
/**
* utility functions
*
* The LTIUtils class contains a number of generally useful static functions, e.g.
* functions which operate on the enums declared in lti_types.h
*
* @note This is a "static" class; do not instantiate.
*/
class LTIUtils
{
public:
/**
* returns number of samples per pixel
*
* This function returns the number of samples (bands) per pixel
* for the given colorspace, e.g. 3 for RGB. If the number of
* bands is not known for a given colorspace, 0 will be returned.
*
* @param colorspace the colorspace to query
* @return the number of bands
*/
static lt_uint8 getSamplesPerPixel(LTIColorSpace colorspace);
/**
* returns number of bytes for a given a datatype
*
* This function returns the number of bytes for a given datatype,
* e.g. 1 for LTI_DATATYPE_UINT8 or 4 for LTI_DATATYPE_FLOAT32.
*
* @param datatype the datatype to query
* @return the number of bytes
*/
static lt_uint8 getNumBytes(LTIDataType datatype);
/**
* returns true if datatype is signed
*
* This function returns true if and only if the datatype
* can represent signed values.
*
* @param datatype the datatype to query
* @return true, if signed
*/
static bool isSigned(LTIDataType datatype);
/**
* returns true if datatype is integral
*
* This function returns true if and only if the datatype
* is integral, i.e. not floating point.
*
* @param datatype the datatype to query
* @return true, if an integer datatype
*/
static bool isIntegral(LTIDataType datatype);
/**
* @name Dynamic range conversion functions
*/
/*@{*/
/**
* convert from window/level to min/max
*
* This function converts a "window and level" style of dynamic range
* to a "minimum and maximum" style.
*
* @param window the window value
* @param level the level value
* @param drmin the dynamic range minimum value
* @param drmax the dynamic range maximum value
*/
static void convertWindowLevelToMinMax(double window, double level,
double& drmin, double& drmax);
/**
* convert from min/max to window/level
*
* This function converts a "minimum and maximum" style of dynamic range
* to a "window and level" style.
*
* The "window" is defined as the width of the range, i.e. maximum - minimum + 1.
* The "level" is defined as the center of the window, i.e. minimum + 1/2 * window.
*
* @param drmin the dynamic range minimum value
* @param drmax the dynamic range maximum value
* @param window the window value
* @param level the level value
*/
static void convertMinMaxToWindowLevel(double drmin, double drmax,
double& window, double& level);
/*@}*/
/**
* @name Mag/level conversion functions
*/
/*@{*/
/**
* convert mag to level
*
* This function converts a "magnification" value to a "level" value.
*
* Examples:
* \li full resolution: mag of 1.0 equals level of 0
* \li down-sampled: mag of 0.5 equals level of 1
* \li up-sampled: mag of 2.0 equals level of -1
*
* @param mag the magnification value to convert
* @return the magnification expressed as a level
*/
static lt_int32 magToLevel(double mag);
/**
* convert level to mag
*
* This function converts a "level" value to a "magnification" value.
*
* See magToLevel() for examples.
*
* @param level the level value to convert
* @return the level expressed as a magnification
*/
static double levelToMag(lt_int32 level);
/*@}*/
/**
* get SDK version information
*
* This function returns SDK version and build information. The major,
* minor, and revision numbers correspond to the public SDK version
* number. For this SDK series, \a major will be 4. The revision number
* is used to indicate the intermediate release point, e.g. "Technology
* Preview 8". The build number and branch name are for internal use by
* LizardTech.
*
* @param major the major version number
* @param minor the minor version number
* @param revision the revision number
* @param build the build number
* @param branch the branch name
*/
static void getVersionInfo(lt_uint32& major,
lt_uint32& minor,
lt_uint32& revision,
lt_uint32& build,
const char*& branch);
/**
* get SDK version information as a string
*
* This function returns SDK version and build information as a formatted
* string. The string will be of the form "SDK Version MAJOR.MINOR.REVISION.BUILD.BRANCH",
* using the values returned from LTIUtils::getVersionInfo().
*
* @return the version string
*/
static const char* getVersionString();
private:
// nope
LTIUtils();
LTIUtils(const LTIUtils&);
};
LT_END_NAMESPACE(LizardTech)
#if defined(LT_COMPILER_MS)
#pragma warning(pop)
#endif
#endif // LTI_UTILS_H
|
[
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
] |
[
[
[
1,
202
]
]
] |
4077ba2d5a1d8041d3900293b49cf4ef0b530178
|
208475bcab65438eed5d8380f26eacd25eb58f70
|
/QianExe/yx_DriverCtrlKaiTian.h
|
d2365d1561e01528422988f02032a07cde70f9d9
|
[] |
no_license
|
awzhang/MyWork
|
83b3f0b9df5ff37330c0e976310d75593f806ec4
|
075ad5d0726c793a0c08f9158080a144e0bb5ea5
|
refs/heads/master
| 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null |
GB18030
|
C++
| false | false | 3,983 |
h
|
#ifndef _YX_DRVCTRL_KAITIAN_H_
#define _YX_DRVCTRL_KAITIAN_H_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define DRIVERPICPATH L"\\Resflh2\\DriverPIC.jpg"
#define RCVPICPACKSIZE 1024//照片接收每包大小
#define SNDPICPACKSIZE 512//照片传输每包大小
class CKTDriverCtrl
{
public:
#pragma pack(push,1)
struct frm4004
{
byte driverID[3];//司机身份信息
char driverName[10];//司机姓名
byte level;//服务等级
char copName[20];//公司名称
frm4004(){memset(this,0,sizeof(*this));}
};
struct frm4005
{
byte driverID[3];//司机身份信息
WORD totalPack;//总包数
byte winSize;//窗口大小
frm4005(){memset(this,0,sizeof(*this));}
};
struct frm4006
{
byte driverID[3];//司机身份信息
byte flag;//标志位
WORD packNum;//包号
WORD packSize;//包大小
byte data[1024];//包内容
frm4006(){memset(this,0,sizeof(*this));}
};
struct frm4045
{
byte driverID[3];//司机身份信息
byte resType;
frm4045(){memset(this,0,sizeof(*this));}
};
struct frm4046
{
byte driverID[3];//司机身份信息
byte curWin;//当前窗口序号
byte winSta[2];//窗口状态
frm4046(){memset(this,0,sizeof(*this));}
};
//传输照片请求
struct frmD6
{
byte type;
byte driverID[3];//司机身份信息
WORD packNum;//总包数
frmD6(){ memset(this,0,sizeof(*this));type=0xD6;}
};
//照片数据
struct frmD8
{
byte type;
WORD curPack;
WORD dataLen;
byte data[SNDPICPACKSIZE];
frmD8(){ memset(this,0,sizeof(*this));type=0xD8;}
};
//交接班请求
struct frmDC
{
byte type;
byte driverID[3];//当前司机身份信息
frmDC(){ memset(this,0,sizeof(*this));type=0xDC;}
};
//电子服务证信息
struct frmD4
{
byte type;
frm4004 info;
frmD4(){ memset(this,0,sizeof(*this));type=0xD4;}
};
#pragma pack(pop)
struct PICRCVINFO
{
byte driverID[3];//司机身份信息
WORD totalPack;//总包数
WORD curPack;//当前包
WORD curWin;//当前窗口序号
byte winSize;//窗口大小
byte winNum;//窗口总数
byte lastWinSize;//最后一包窗口大小
byte winSta[2];//窗口状态
byte rcvSta;//接收状态0表示未接收完毕,1表示接收完毕
PICRCVINFO(){memset(this,0,sizeof(*this));}
};
struct PICSNDINFO
{
byte driverID[3];//司机身份信息
WORD packNum;//总包数
WORD curPack;//当前包
byte sendSta;//发送状态1表示未发送完,2表示已发送完
PICSNDINFO(){memset(this,0,sizeof(*this));}
};
bool m_bSendPicWork;
bool m_bSendPicExit;
pthread_t m_pthreadSendPic;//发送照片线程
private:
PICRCVINFO m_objPicRcvInfo;
PICSNDINFO m_objPicSndInfo;
//byte m_bytSendPackNum;//当前发送包序号
int m_iResPicTime;
public:
CKTDriverCtrl();
virtual ~CKTDriverCtrl();
void Init();
void Release();
void P_TmReSendPicProc();
void P_TmResPicProc();
void P_ThreadSendPic();
int DealComuD5( char* v_szData, DWORD v_dwDataLen );
int DealComuD7( char* v_szData, DWORD v_dwDataLen );
int DealComuD9( char* v_szData, DWORD v_dwDataLen );
int DealComuDA( char* v_szData, DWORD v_dwDataLen );
int DealComuDB( char* v_szData, DWORD v_dwDataLen );
int Deal4004( char* v_szData, DWORD v_dwDataLen );
int Deal4005( char* v_szData, DWORD v_dwDataLen );
int Deal4006( char* v_szData, DWORD v_dwDataLen );
int Deal4008( char* v_szData, DWORD v_dwDataLen );
void ClearSendThd();
bool SendPic();
void BeginSendPic();
void SndDrvChgInf(byte* v_aryODriverID,byte v_bytLen);
void PicTest();//照片传输测试
void DriverInfoTest();//请求电子服务证信息测试
void DrvInfoChgTest();//交接班测试
private:
WORD _GetPicFileSize();
void _ReqDriverInfo(char* v_szDriverID,DWORD v_dwDataLen);
bool _ReqSendPic();//请求发送
void _Send4046();
};
#endif
|
[
"[email protected]"
] |
[
[
[
1,
163
]
]
] |
ccd8c4ea351b84d44e2927740c671fee05884907
|
2d4221efb0beb3d28118d065261791d431f4518a
|
/OIDE源代码/OLIDE/Controls/HexEdit/HexEdit.cpp
|
74ce63e5cf8c791ead3c9a710d49959042cf819b
|
[] |
no_license
|
ophyos/olanguage
|
3ea9304da44f54110297a5abe31b051a13330db3
|
38d89352e48c2e687fd9410ffc59636f2431f006
|
refs/heads/master
| 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 12,602 |
cpp
|
// File : HexEdit.cpp
// Version : 1.0
// Date : 21. Jan 2005
// Author : Luo Pei'dn
// Email : [email protected]
// Systems : VC6.0/7.0 and VC7.1 (Run under (Window 98/ME), Windows Nt 2000/XP/2003)
//
// For bugreport please email me
//
// You are free to use/modify this code but leave this header intact.
// You are free to use it in any of your applications.
// HexEdit.cpp : implementation file
//
#include "stdafx.h"
#include "HexEdit.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define MES_UNDO _T("&Undo")
#define MES_CUT _T("Cu&t")
#define MES_COPY _T("&Copy")
#define MES_PASTE _T("&Paste")
#define MES_DELETE _T("&Delete")
#define MES_SELECTALL _T("Select &All")
#define MES_CONVERT _T("Con&vert")
#define ME_SELECTALL WM_USER + 0x700
#define ME_CONVERT WM_USER + 0x701
/////////////////////////////////////////////////////////////////////////////
// CHexEdit
CHexEdit::CHexEdit():m_bHex(false),m_bEnd(false)
{
this->m_icHexText.clrBkColor=RGB(219,247,220);
this->m_icHexText.clrTextColor=RGB(74,115,132);
this->m_icDecText.clrBkColor=RGB(251,244,170);
this->m_icDecText.clrTextColor=RGB(192,97,10);
this->m_bkHexBrush.CreateSolidBrush(this->m_icHexText.clrBkColor);
this->m_bkDecBrush.CreateSolidBrush(this->m_icDecText.clrBkColor);
}
CHexEdit::~CHexEdit()
{
m_bkHexBrush.DeleteObject();
m_bkDecBrush.DeleteObject();
}
BEGIN_MESSAGE_MAP(CHexEdit, CEdit)
//{{AFX_MSG_MAP(CHexEdit)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_CHAR()
ON_MESSAGE(ME_CONVERT, OnConvert)
//}}AFX_MSG_MAP
ON_WM_CONTEXTMENU()
ON_CONTROL_REFLECT(EN_UPDATE, OnEnUpdate)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CHexEdit message handlers
HBRUSH CHexEdit::CtlColor(CDC* pDC, UINT nCtlColor)
{
// TODO: Change any attributes of the DC here
// TODO: Return a non-NULL brush if the parent's handler should not be called
if(m_bHex)
{
pDC->SetTextColor(this->m_icHexText.clrTextColor);
pDC->SetBkColor(this->m_icHexText.clrBkColor);
return m_bkHexBrush;
}
else
{
pDC->SetTextColor(this->m_icDecText.clrTextColor);
pDC->SetBkColor(this->m_icDecText.clrBkColor);
return m_bkDecBrush;
}
}
void CHexEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// TODO: Add your message handler code here and/or call default
CEdit::OnChar(nChar, nRepCnt, nFlags);
}
//void CHexEdit::OnChange()
//{
// // TODO: If this is a RICHEDIT control, the control will not
// // send this notification unless you override the CEdit::OnInitDialog()
// // function and call CRichEditCtrl().SetEventMask()
// // with the ENM_CHANGE flag ORed into the mask.
//
// // TODO: Add your control notification handler code here
//
//}
BOOL CHexEdit::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
int start,end;
GetSel(start,end);
CString text;
this->GetWindowText(text);
char head=0,second=0;
if(text.GetLength()>0) head=text.GetAt(0);
if(text.GetLength()>1) second=text.GetAt(1);
bool bCut=true;
if (pMsg->message == WM_KEYDOWN)
{
if (pMsg->wParam=='X')
{
if(::GetKeyState(VK_CONTROL) < 0)
{
//Cut
if(second=='X'||second=='x'){
//does not allow cut first char
if(start==0&&end==1)
bCut=false;
}
if(bCut) return CEdit::PreTranslateMessage(pMsg);
else
return TRUE;
}
else return CEdit::PreTranslateMessage(pMsg);
}
else if(pMsg->wParam=='V')
{
if(::GetKeyState(VK_CONTROL)<0)
{
//Paste
bool bPaste=true;
if(!IsClipboardFormatAvailable(CF_UNICODETEXT)) bPaste=false;
if(!this->OpenClipboard())
::AfxMessageBox(_T("Cannot open clipboard!"));
HGLOBAL hglb;
LPTSTR lptstr;
hglb=GetClipboardData(CF_UNICODETEXT);
if (hglb != NULL)
{
lptstr =(LPTSTR) GlobalLock(hglb);
//Check invalid hex string
if(!this->IsHexConvertableText(lptstr))
{
bPaste=false;
}
}
CloseClipboard();
if(!bPaste) return TRUE;
else
return CEdit::PreTranslateMessage(pMsg);
}
else return CEdit::PreTranslateMessage(pMsg);
}
else if(pMsg->wParam==VK_DELETE)
{
if(second=='X'||second=='x'){
//does not allow delete first char
if(start==0&&end<=1)
bCut=false;
}
if(bCut) return CEdit::PreTranslateMessage(pMsg);
else
return TRUE;
}
else
return CEdit::PreTranslateMessage(pMsg);
}
else if (pMsg->message == WM_CHAR)
{
int c=(int)pMsg->wParam;
if(pMsg->wParam<32)
{
if(pMsg->wParam==8&&(second=='x'||second=='X')&&head=='0'&&end==1) //does not allow to delete '0' before x
return TRUE;
else
return CEdit::PreTranslateMessage(pMsg);//Control code
}
if(second=='x'||second=='X')
{
//does not allow to change head except select includes first and second
if(start<=1&&end<=1) return TRUE;
}
if(start==1&&(c=='X'||c=='x')&&head=='0') {pMsg->wParam='x';return CEdit::PreTranslateMessage(pMsg);}
else if(c>=48&&c<=57||c>='A'&&c<='F') return CEdit::PreTranslateMessage(pMsg);
else if(c>='a'&&c<='f') {pMsg->wParam-=32; return CEdit::PreTranslateMessage(pMsg);}
else return TRUE;
}
else
return CEdit::PreTranslateMessage(pMsg);
}
void CHexEdit::DoDataExchange(CDataExchange* pDX)
{
// TODO: 在此添加专用代码和/或调用基类
::AfxMessageBox(_T("dsaf"));
CEdit::DoDataExchange(pDX);
}
void CHexEdit::OnContextMenu(CWnd* pWnd, CPoint point)
{
int start,end;
GetSel(start,end);
CString text;
this->GetWindowText(text);
char head=0,second=0;
bool bCut=true;
SetFocus();
CMenu menu;
menu.CreatePopupMenu();
//No problems with default undo
BOOL bReadOnly = GetStyle() & ES_READONLY;
DWORD flags = CanUndo() && !bReadOnly ? 0 : MF_GRAYED;
menu.InsertMenu(0, MF_BYPOSITION | flags, EM_UNDO,
MES_UNDO);
menu.InsertMenu(1, MF_BYPOSITION | MF_SEPARATOR);
//No problem with default Copy
DWORD sel = GetSel();
flags = LOWORD(sel) == HIWORD(sel) ? MF_GRAYED : 0;
menu.InsertMenu(2, MF_BYPOSITION | flags, WM_COPY,
MES_COPY);
//Cut and delete should be modified
if(text.GetLength()>0) head=text.GetAt(0);
if(text.GetLength()>1) second=text.GetAt(1);
if(second=='X'||second=='x'){
//does not allow cut first char
if(start==0&&end==1)
bCut=false;
}
flags = (flags == MF_GRAYED || bReadOnly||!bCut) ? MF_GRAYED : 0;
menu.InsertMenu(2, MF_BYPOSITION | flags, WM_CUT,
MES_CUT);
menu.InsertMenu(4, MF_BYPOSITION | flags, WM_CLEAR,
MES_DELETE);
//Paste should be modified
flags = IsClipboardFormatAvailable(CF_UNICODETEXT) &&
!bReadOnly ? 0 : MF_GRAYED;
if(!this->OpenClipboard())
::AfxMessageBox(_T("Cannot open clipboard!"));
HGLOBAL hglb;
LPTSTR lptstr;
hglb=GetClipboardData(CF_UNICODETEXT);
if (hglb != NULL)
{
lptstr =(LPTSTR) GlobalLock(hglb);
//Check invalid hex string
if(!this->IsHexConvertableText(lptstr))
{
flags=MF_GRAYED;
}
}
CloseClipboard();
menu.InsertMenu(4, MF_BYPOSITION | flags, WM_PASTE,
MES_PASTE);
menu.InsertMenu(6, MF_BYPOSITION | MF_SEPARATOR);
//No problem with default Sel All
int len = GetWindowTextLength();
flags = (!len || (LOWORD(sel) == 0 && HIWORD(sel) ==
len)) ? MF_GRAYED : 0;
menu.InsertMenu(7, MF_BYPOSITION | flags, ME_SELECTALL,
MES_SELECTALL);
flags=0;
if(text.GetLength()==0||(text.GetLength()==2&&text.Find(_T("0x"))==0))
flags=MF_GRAYED;
menu.InsertMenu(8, MF_BYPOSITION | MF_SEPARATOR);
menu.InsertMenu(9, MF_BYPOSITION | flags, ME_CONVERT,
MES_CONVERT);
menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON |
TPM_RIGHTBUTTON, point.x, point.y, this);
}
BOOL CHexEdit::OnCommand(WPARAM wParam, LPARAM lParam)
{
switch (LOWORD(wParam))
{
case EM_UNDO:
case WM_CUT:
case WM_COPY:
case WM_CLEAR:
case WM_PASTE:this->FormatClipboard();
return (BOOL)SendMessage(LOWORD(wParam));
case ME_SELECTALL:
return (BOOL)SendMessage (EM_SETSEL, 0, -1);
case ME_CONVERT:
return (BOOL)SendMessage(ME_CONVERT,0,0);
default:
return CEdit::OnCommand(wParam, lParam);
}
}
bool CHexEdit::IsHexConvertableText(LPTSTR _text)
{
int start,end;
GetSel(start,end);
CString text;
this->GetWindowText(text);
char head=0,second=0;
bool bPaste=true;
if(text.GetLength()>0) head=text.GetAt(0);
if(text.GetLength()>1) second=text.GetAt(1);
if(second=='X'||second=='x')
{
if(end<=1)
bPaste=false;
}
if(!bPaste) return bPaste;
//Check
unsigned int i=0;
if(wcslen(_text)>=2)
{
if(_text[0]=='0'&&(_text[1]=='x'||_text[1]=='X'))
{
if((second=='x'||second=='X')&&(!(start==0&&end>=2)))
bPaste=false;
else if(start>0)
bPaste=false;
else
i+=2;
}
}
if(!bPaste) return bPaste;
if(wcslen(_text)>=1)
{
if(head=='0'&&(_text[0]=='x'||_text[0]=='X'))
{
i++;
}
if((_text[0]=='x'||_text[0]=='X'))
{
if(head!='0'&&start==0)
bPaste=false;
else if(!(start==1&&end>=1&&head=='0'))
bPaste=false;
}
}
if(!bPaste) return bPaste;
for(;i<wcslen(_text);i++)
{
wchar_t c=_text[i];
if(!(c>=48&&c<=57||c>='A'&&c<='F'||c>='a'&&c<='f'))
{
bPaste=false;
break;
}
}
return bPaste;
}
void CHexEdit::FormatClipboard()
{
LPTSTR lptstr,lptstrCopy;
HGLOBAL hglb;
if(!this->OpenClipboard())
return;
if(!IsClipboardFormatAvailable(CF_UNICODETEXT))
return;
hglb=GetClipboardData(CF_UNICODETEXT);
if (hglb != NULL)
{
lptstr =(LPTSTR) GlobalLock(hglb);
for(unsigned int i=0;i<wcslen(lptstr);i++)
{
if(lptstr[i]!='X'&&lptstr[i]!='x')
lptstr[i]=toupper(lptstr[i]);
if(lptstr[i]=='X')
lptstr[i]='x';
}
hglb = GlobalAlloc(GMEM_MOVEABLE,
(wcslen(lptstr)+1) * sizeof(TCHAR));
if (hglb == NULL)
{
CloseClipboard();
return;
}
lptstrCopy = (LPTSTR)GlobalLock(hglb);
memcpy(lptstrCopy, lptstr,wcslen(lptstr)*sizeof(wchar_t));
GlobalUnlock(hglb);
SetClipboardData(CF_UNICODETEXT,hglb);
CloseClipboard();
}
}
void CHexEdit::SetHexColor(COLORREF clrBack, COLORREF clrText)
{
this->m_icHexText.clrBkColor=clrBack;
this->m_icHexText.clrTextColor=clrText;
m_bkHexBrush.DeleteObject();
this->m_bkHexBrush.CreateSolidBrush(this->m_icHexText.clrBkColor);
}
void CHexEdit::SetDecColor(COLORREF clrBack, COLORREF clrText)
{
this->m_icDecText.clrBkColor=clrBack;
this->m_icDecText.clrTextColor=clrText;
m_bkDecBrush.DeleteObject();
this->m_bkDecBrush.CreateSolidBrush(this->m_icDecText.clrBkColor);
}
void CHexEdit::OnEnUpdate()
{
// TODO: 如果该控件是 RICHEDIT 控件,则它将不会
// 发送该通知,除非重写 CEdit::OnInitDialog()
// 函数,将 EM_SETEVENTMASK 消息发送到控件,
// 同时将 ENM_UPDATE 标志“或”运算到 lParam 掩码中。
// TODO: 在此添加控件通知处理程序代码
CString text;
this->GetWindowText(text);
//Hex or Dec?
this->m_bHex=false;
if(text.Find(_T("0x"))==0)
this->m_bHex=true;
for(int i=0;i<text.GetLength();i++)
{
wchar_t c=text.GetAt(i);
if(c>='A'&&c<='F')
this->m_bHex=true;
}
this->RedrawWindow();
}
LRESULT CHexEdit::OnConvert(WPARAM wParam, LPARAM lParam)
{
CString text;
this->GetWindowText(text);
if(this->m_bHex)
{
//convert hex to dec
UINT n=0;
if(text.Find(_T("0x"))==0)
swscanf(text.GetBuffer(0)+2,_T("%x"),&n);
else
swscanf(text.GetBuffer(0),_T("%x"),&n);
text.Format(_T("%u"),n);
this->SetWindowText(text);
}
else
{
//convert dec to hex
UINT n=0;
swscanf(text.GetBuffer(0),_T("%d"),&n);
text.Format(_T("0x%X"),n);
this->SetWindowText(text);
}
return 0;
}
unsigned int CHexEdit::GetValue(void)
{
CString text;
this->GetWindowText(text);
if(this->m_bHex)
{
//hex
unsigned int n=0;
if(text.Find(_T("0x"))==0)
swscanf(text.GetBuffer(0)+2,_T("%x"),&n);
else
swscanf(text.GetBuffer(0),_T("%x"),&n);
return n;
}
else
{
//convert dec to hex
unsigned int n=0;
swscanf(text.GetBuffer(0),_T("%u"),&n);
return n;
}
}
void CHexEdit::SetValue(unsigned int _value,bool _bHex)
{
CString text;
if(!_bHex)
{
text.Format(_T("%u"),_value);
}
else
text.Format(_T("0x%x"),_value);
this->SetWindowText(text);
}
|
[
"[email protected]"
] |
[
[
[
1,
501
]
]
] |
28582af5318b70f7cc2cef9d21b15ab935167917
|
2aff7486e6c7afdbda48b7a5f424b257d47199df
|
/src/Gui/Frames/output2.cpp
|
f3bb8ee1ed019527192f403ba9de57aa6ef27d2a
|
[] |
no_license
|
offlinehacker/LDI_test
|
46111c60985d735c00ea768bdd3553de48ba2ced
|
7b77d3261ee657819bae3262e3ad78793b636622
|
refs/heads/master
| 2021-01-10T20:44:55.324019 | 2011-08-17T16:41:43 | 2011-08-17T16:41:43 | 2,220,496 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,266 |
cpp
|
///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Apr 16 2008)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "output2.h"
///////////////////////////////////////////////////////////////////////////
Output2::Output2( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style )
{
wxBoxSizer* bMainSizer;
bMainSizer = new wxBoxSizer( wxVERTICAL );
m_staticText1 = new wxStaticText( this, wxID_ANY, wxT("Contours:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText1->Wrap( -1 );
bMainSizer->Add( m_staticText1, 0, wxALL, 5 );
m_grid1 = new wxGrid( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 );
// Grid
m_grid1->CreateGrid( 6, 4 );
m_grid1->EnableEditing( false );
m_grid1->EnableGridLines( true );
m_grid1->EnableDragGridSize( false );
m_grid1->SetMargins( 0, 0 );
// Columns
m_grid1->SetColSize( 0, 40 );
m_grid1->SetColSize( 1, 40 );
m_grid1->SetColSize( 2, 40 );
m_grid1->SetColSize( 3, 40 );
m_grid1->EnableDragColMove( false );
m_grid1->EnableDragColSize( false );
m_grid1->SetColLabelSize( 15 );
m_grid1->SetColLabelValue( 0, wxT("Obj") );
m_grid1->SetColLabelValue( 1, wxT("Mer") );
m_grid1->SetColLabelValue( 2, wxT("CX") );
m_grid1->SetColLabelValue( 3, wxT("CY") );
m_grid1->SetColLabelAlignment( wxALIGN_CENTRE, wxALIGN_CENTRE );
// Rows
m_grid1->SetRowSize( 0, 17 );
m_grid1->SetRowSize( 1, 17 );
m_grid1->SetRowSize( 2, 17 );
m_grid1->SetRowSize( 3, 17 );
m_grid1->SetRowSize( 4, 17 );
m_grid1->SetRowSize( 5, 17 );
m_grid1->EnableDragRowSize( false );
m_grid1->SetRowLabelSize( 10 );
m_grid1->SetRowLabelAlignment( wxALIGN_CENTRE, wxALIGN_CENTRE );
// Label Appearance
// Cell Defaults
m_grid1->SetDefaultCellBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) );
m_grid1->SetDefaultCellAlignment( wxALIGN_LEFT, wxALIGN_TOP );
bMainSizer->Add( m_grid1, 0, wxALL, 5 );
this->SetSizer( bMainSizer );
this->Layout();
}
Output2::~Output2()
{
}
|
[
"[email protected]"
] |
[
[
[
1,
68
]
]
] |
d0c8dd5c37a739b0d5ed66b515b11f621ce7c162
|
9bd0004220edc6cde7927d06f4d06d05a57d6d7d
|
/xq/pipe/io.cpp
|
27853ed5dfae28de24806d7aecdbe0b291c3d7cb
|
[] |
no_license
|
lwm3751/folium
|
32b8c1450d8a1dc1c899ac959493fd4ae5166264
|
e32237b6bb5dabbce64ea08e2cf8f4fe60b514d5
|
refs/heads/master
| 2021-01-22T03:12:58.594929 | 2011-01-09T15:36:02 | 2011-01-09T15:36:02 | 26,789,096 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,762 |
cpp
|
#include "eleeye/pipe.h"
#include "io.h"
#include <boost/utility.hpp>
namespace folium
{
class io_implement: public io, private boost::noncopyable
{
public:
bool open(const char* path);
virtual bool readable();
virtual string readline();
virtual void writeline(const string&);
private:
PipeStruct m_pipe;
string m_line;
};
bool io_implement::open(const char* path)
{
m_pipe.Open(path);
return true;
}
bool io_implement::readable()
{
if (m_line.empty())
{
char buffer[LINE_INPUT_MAX_CHAR];
if (m_pipe.LineInput(buffer))
m_line = buffer;
}
return !m_line.empty();
}
string io_implement::readline()
{
if (m_line.empty())
{
char buffer[LINE_INPUT_MAX_CHAR];
if (m_pipe.LineInput(buffer))
m_line = buffer;
}
string line = m_line;
m_line.clear();
return line;
}
void io_implement::writeline(const string& line)
{
m_pipe.LineOutput(line.c_str());
}
boost::shared_ptr<io> stdio()
{
static boost::shared_ptr<io_implement> instance;
if (NULL == instance.get())
{
instance = boost::shared_ptr<io_implement>(new io_implement());
instance->open(NULL);
}
return instance;
}
boost::shared_ptr<io> openexe(const string& path)
{
boost::shared_ptr<io_implement> ioobject(new io_implement());
if (ioobject->open(path.c_str()))
return ioobject;
return boost::shared_ptr<io>();
}
}
|
[
"lwm3751@cb49bd84-cb2d-0410-93fd-e1760d46b244"
] |
[
[
[
1,
71
]
]
] |
3aeb31e696bbdfe4ec4e243af27aadb96e04869b
|
788d308fcb292f68c9f7eea3ae0a93e446737769
|
/lsad.cpp
|
df53b9fc7f05138410e4abb551199d6063f1d661
|
[] |
no_license
|
Tobbe/lsactivedesktop
|
60a8e6630d96926cdf1e6e84f5ac4a65f8feff1e
|
dbfefd89fbabb92ec986b62acf05bfddf22df57b
|
refs/heads/master
| 2021-01-22T07:13:47.766351 | 2011-08-15T12:55:52 | 2011-08-15T12:55:52 | 866,056 | 5 | 5 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,520 |
cpp
|
#include "lsad.h"
#include "webform.h"
#include "lsapi.h"
#include "webwindow.h"
#include "webformdispatchimpl.h"
#include "jslitestep.h"
#include "lsadsettings.h"
#include <string>
static const char className[] = "LSADWndClass";
LSAD::LSAD(HINSTANCE hInstance, HWND hWndLSMsgWnd, LSADSettings *settings)
{
this->hInstance = hInstance;
this->hWndLSMsgWnd = hWndLSMsgWnd;
this->settings = settings;
}
DWORD LSAD::ThreadEntry(LPVOID lpParameter)
{
LSAD *that = static_cast<LSAD*>(lpParameter);
return that->ThreadMain();
}
DWORD LSAD::ThreadMain()
{
OleInitialize(0);
WNDCLASSEX wcex;
ZeroMemory(&wcex, sizeof(wcex));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)StaticWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = sizeof(this);
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = NULL;
wcex.lpszMenuName = NULL;
wcex.lpszClassName = className;
wcex.hIconSm = NULL;
if (!RegisterClassEx(&wcex)) {
MessageBox(NULL, "Failed to register lsad class", "Error", MB_OK);
//reportError("Error registering LSActiveDesktop window class");
return 1;
}
jsLiteStep = new JSLiteStep();
jsLiteStep->AddRef();
webformDispatchImpl = new WebformDispatchImpl(jsLiteStep);
for (std::map<std::string, LSADWebWndProp>::iterator it = settings->windowProperties.begin(); it != settings->windowProperties.end(); it++) {
webWindows.insert(std::make_pair(it->first, new WebWindow(webformDispatchImpl)));
}
HWND hWndCreate = CreateWindowEx(0, className, "LSAD", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
CW_USEDEFAULT, CW_USEDEFAULT, 400, 400, NULL, NULL, hInstance, (LPVOID)this);
if (hWndCreate == NULL) {
MessageBox(NULL, "Failed to create window", "Error", MB_OK);
//reportError("Error creating LSActiveDesktop window");
UnregisterClass(className, hInstance);
return 1;
}
PostMessage(hWndLSMsgWnd, WM_LSADCREATED, (WPARAM)hWndCreate, (LPARAM)NULL);
//ShowWindow(hWndCreate, SW_SHOW);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
for (std::map<std::string, WebWindow*>::iterator it = webWindows.begin(); it != webWindows.end(); it++) {
delete it->second;
}
delete webformDispatchImpl;
jsLiteStep->Release();
OleUninitialize();
return (int)msg.wParam;
}
LRESULT CALLBACK LSAD::StaticWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_NCCREATE) {
LSAD *lsad = (LSAD*)((LPCREATESTRUCT(lParam))->lpCreateParams);
lsad->hWnd = hWnd;
#pragma warning(suppress:4244)
SetWindowLongPtr(hWnd, 0, (LONG_PTR)lsad);
return DefWindowProc(hWnd, msg, wParam, lParam);
}
#pragma warning(suppress:4312)
LSAD *lsad = (LSAD*)GetWindowLongPtr(hWnd, 0);
if (lsad == NULL) {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return lsad->InstanceWndProc(msg, wParam, lParam);
}
LRESULT LSAD::InstanceWndProc(UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_CREATE: {
for (std::map<std::string, WebWindow*>::iterator it = webWindows.begin(); it != webWindows.end(); it++) {
int x = settings->windowProperties[it->first].x;
int y = settings->windowProperties[it->first].y;
int width = settings->windowProperties[it->first].width;
int height = settings->windowProperties[it->first].height;
std::string url = settings->windowProperties[it->first].url;
bool showScrollbars = settings->windowProperties[it->first].showScrollbars;
it->second->Create(hInstance, x, y, width, height, showScrollbars);
it->second->webForm->Go(url.c_str());
y += 400;
}
break;
}
case WM_PAINT: {
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
FillRect(ps.hdc, &ps.rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
EndPaint(hWnd,&ps);
return 0;
}
case LSAD_BANGNAVIGATE: {
std::string *name = reinterpret_cast<std::string*>(wParam);
std::string *url = reinterpret_cast<std::string*>(lParam);
if (webWindows[*name]) {
webWindows[*name]->webForm->Go(url->c_str());
}
delete url;
delete name;
break;
}
case LSAD_BANGBACK: {
std::string *name = reinterpret_cast<std::string*>(wParam);
if (webWindows[*name]) {
webWindows[*name]->webForm->Back();
}
delete name;
break;
}
case LSAD_BANGFORWARD: {
std::string *name = reinterpret_cast<std::string*>(wParam);
if (webWindows[*name]) {
webWindows[*name]->webForm->Forward();
}
delete name;
break;
}
case LSAD_BANGRUNJSFUNCTION: {
std::string *name = reinterpret_cast<std::string*>(wParam);
std::string *cmd = reinterpret_cast<std::string*>(lParam);
if (webWindows[*name]) {
webWindows[*name]->webForm->RunJSFunction(*cmd);
}
delete cmd;
delete name;
break;
}
case LSAD_BANGREFRESH: {
std::string *name = reinterpret_cast<std::string*>(wParam);
if (webWindows[*name]) {
webWindows[*name]->webForm->Refresh(false);
}
delete name;
break;
}
case LSAD_BANGREFRESHCACHE: {
std::string *name = reinterpret_cast<std::string*>(wParam);
if (webWindows[*name]) {
webWindows[*name]->webForm->Refresh(true);
}
delete name;
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
|
[
"[email protected]"
] |
[
[
[
1,
202
]
]
] |
b91920a6ef6011fc749ce7fe436898c7e70cc18d
|
3e6e5d5b2ec9b8616288ae20c55ea3a1f5900178
|
/3DTetris/source/TGameGUI.cpp
|
bff4c19f79d0661983716ce2ef264410dbb2824c
|
[] |
no_license
|
sanke/3dtetrisgame
|
8ad404dcdd764eb13db0bfc949edb34a77eb0f21
|
e5bcf219e4ee3b0995809d70a83d92e001e7e50d
|
refs/heads/master
| 2021-01-16T21:18:41.949403 | 2010-06-27T20:58:27 | 2010-06-27T20:58:27 | 32,506,729 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 92 |
cpp
|
#include "TGameGUI.h"
TGameGUI::TGameGUI(void)
{
}
TGameGUI::~TGameGUI(void)
{
}
|
[
"unocoder@localhost"
] |
[
[
[
1,
9
]
]
] |
768dbc82bd6e008477975fdd309785e2d821f595
|
91e66307c16b7bc5ac09a00e59e22872029d2dfe
|
/code/ChainApp/inputer.cpp
|
1dc17217ac16b2378325b72ace77c12b621519b0
|
[] |
no_license
|
BackupTheBerlios/artbody-svn
|
52a7d0e780b077c9972ab25558916b772b8d8289
|
3dde2231e92d6c53b33021e333da1a434ab10c44
|
refs/heads/master
| 2016-09-03T01:53:14.446671 | 2008-02-06T16:33:58 | 2008-02-06T16:33:58 | 40,725,063 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,614 |
cpp
|
//////////////////////////////////////////////////////////////////////////
// inputer.cpp
//////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <Windows.h>
#include <gl/glut.h>
#include "inputer.h"
using namespace inp;
Inputer::Inputer(void)
{
_clearState();
return;
}
Inputer::~Inputer()
{
;
}
bool Inputer::addHdl(InputerHdl * pHdl)
{
if (sys::HdlCollection<InputerHdl>::addHdl(pHdl)) {
pHdl->_inputer = this;
return true;
}
return false;
}
bool Inputer::removeHdl(InputerHdl * pHdl)
{
if (sys::HdlCollection<InputerHdl>::removeHdl(pHdl)) {
pHdl->_inputer = NULL;
return true;
}
return false;
}
void Inputer::processInput(const InputParams& params)
{
unsigned int i;
_curParams = params;
for (i = 0; i < _hdlArray.size(); i++) {
_hdlArray[i]->onInput(params);
}
_clearState();
return;
}
void Inputer::MapGLInputToApp(const unsigned char* c, const int* msButton, const int* msBtnState,
const int* sysBtnState, const int* x, const int* y,
inp::InputParams& params)
{
if (c) {
params.sym = *c;
}
if (msButton) {
switch (*msButton) {
case GLUT_LEFT_BUTTON:
params.button = inp::MouseBtnLeft;
break;
case GLUT_MIDDLE_BUTTON:
params.button = inp::MouseBtnMiddle;
break;
case GLUT_RIGHT_BUTTON:
params.button = inp::MouseBtnRight;
break;
}
}
if (msBtnState) {
switch (*msBtnState) {
case GLUT_UP:
params.msBtnState = inp::BtnUp;
break;
case GLUT_DOWN:
params.msBtnState = inp::BtnDown;
break;
}
}
#define CHECK_AND_SET(srcState, srcStateVal, dstState, dstStateVal) \
dstState |= (srcState & srcStateVal) ? dstStateVal : 0
if (sysBtnState) {
CHECK_AND_SET(*sysBtnState, GLUT_ACTIVE_SHIFT, params.sysKeyState, inp::SHIFT_KEY_PRESS);
CHECK_AND_SET(*sysBtnState, GLUT_ACTIVE_CTRL, params.sysKeyState, inp::CTRL_KEY_PRESS);
CHECK_AND_SET(*sysBtnState, GLUT_ACTIVE_ALT, params.sysKeyState, inp::ALT_KEY_PRESS);
}
#undef CHECK_AND_SET
if (x) {
params.x = *x;
}
if (y) {
params.y = *y;
}
return;
}
//void Inputer::onKeyboardInput(unsigned char c, int x, int y)
//{
// _curParams.sym
// _sym = c;
// _x = x;
// _y = y;
// processInput();
// return;
//}
//
//void Inputer::onMouseInput(int button, int state, int x, int y)
//{
// _button = button;
// _btnState = state;
// _x = x;
// _y = y;
// processInput();
// return;
//}
//
// private
//
void Inputer::_clearState()
{
InputParams defParams;
_curParams.sym = defParams.sym;
_curParams.button = defParams.button;
_curParams.msBtnState = defParams.msBtnState;
_curParams.sysKeyState = defParams.sysKeyState;
_curParams.x = defParams.x;
_curParams.y = defParams.y;
return;
}
//////////////////////////////////////////////////////////////////////////
// InputParams
//////////////////////////////////////////////////////////////////////////
InputParams::InputParams()
{
sym = 0;
button = MouseBtnUndef;
msBtnState = BtnUndef;
sysKeyState = 0;
x = 0;
y = 0;
}
|
[
"ilya_p@70fd935d-ab2c-0410-87c7-a1c3f06a4c7f"
] |
[
[
[
1,
158
]
]
] |
c97788ea17db8ad7751ef00c755ed8696b72a2cc
|
f838c6ad5dd7ffa6d9687b0eb49d5381e6f2e776
|
/branches/unix_develop/src/libwic/acoder.cpp
|
abba0a39d1fa0e55a8b607403056469fed7ee016
|
[] |
no_license
|
BackupTheBerlios/wiccoder-svn
|
e773acb186aa9966eaf7848cda454ab0b5d948c5
|
c329182382f53d7a427caec4b86b11968d516af9
|
refs/heads/master
| 2021-01-11T11:09:56.248990 | 2009-08-19T11:28:23 | 2009-08-19T11:28:23 | 40,806,440 | 0 | 0 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 17,889 |
cpp
|
/*! \file acoder.cpp
\version 0.0.1
\author mice, ICQ: 332-292-380, mailto:[email protected]
\brief Реализация класса wic::acoder - арифметического кодера
\todo Более подробно описать файл acoder.cpp
*/
////////////////////////////////////////////////////////////////////////////////
// headers
// standard C++ library headers
// none
// libwic headers
#include <wic/libwic/acoder.h>
////////////////////////////////////////////////////////////////////////////////
// wic namespace
namespace wic {
////////////////////////////////////////////////////////////////////////////////
// acoder class public definitions
/*! \param[in] buffer_sz Размер памяти (в байтах), выделяемой под внутренний
буфер
*/
acoder::acoder(const sz_t buffer_sz):
_buffer_sz(buffer_sz), _buffer(0),
_out_stream(0), _aencoder(0),
_in_stream(0), _adecoder(0)
{
assert(0 < _buffer_sz);
// выделение памяти под внутренний буфер
_buffer = new byte_t[_buffer_sz];
if (0 == _buffer) throw std::bad_alloc();
// создание битовых потоков для арифметического кодера
_out_stream = new BITOutMemStream((char *)_buffer, _buffer_sz);
_in_stream = new BITInMemStream((char *)_buffer, _buffer_sz);
if (0 == _out_stream || 0 == _in_stream) throw std::bad_alloc();
#ifdef LIBWIC_DEBUG
_dbg_out_stream.open("dumps/[acoder]models.out");
#endif
}
/*! Освобождает память занимаемую внтуренним буфером
*/
acoder::~acoder()
{
// освобождаем кодеры
_rm_coders();
// освобождаем потоки
if (0 != _out_stream) delete _out_stream;
if (0 != _out_stream) delete _in_stream;
// освобождаем буфер
if (0 != _buffer) delete[] _buffer;
}
/*! \return Размер закодированных данных (в байтах)
Возвращает <i>0</i>, если арифметический енкодер ещё не создан.
\sa acoder::use()
*/
sz_t acoder::encoded_sz() const
{
if (0 == _out_stream) return 0;
return sz_t(_out_stream->PackedBytes());
}
/*!
*/
void acoder::use(const models_t &models)
{
_mk_coders(models);
}
/*!
*/
void acoder::encode_start()
{
// проверка утверждений
assert(0 != _aencoder);
assert(0 != _out_stream);
// начало арифметического кодирования
_aencoder->StartPacking();
// инициализация моделей
_init_models(_aencoder);
#ifdef LIBWIC_DEBUG
for (models_t::iterator i = _models.begin(); _models.end() != i; ++i)
{
model_t &model = (*i);
model._encoded_symbols = 0;
model._encoded_freqs.assign(model._symbols, 0);
}
#endif
}
/*!
*/
void acoder::encode_stop()
{
// проверка утверждений
assert(0 != _aencoder);
assert(0 != _out_stream);
// помещение EOF символа в поток
// _aencoder->PutEOF();
// завершение кодирования
_aencoder->EndPacking();
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good()) dbg_encoder_info(_dbg_out_stream);
#endif
}
/*! \param[in] value Значение для кодирования
\param[in] model_no Номер модели
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (имитация кодирования с перенастройкой
моделей без реального помещения символов в выходной поток).
\note В отладочном режиме функция изменяет значения полей
model_t::_encoded_symbols и model_t::_encoded_freqs для выбранной
модели, даже при виртуальном кодировании, несмотря на то, что
реального кодирования не производится.
*/
void acoder::put_value(const value_type &value, const sz_t model_no,
const bool virtual_encode)
{
// проверка утверждений
assert(0 != _aencoder);
assert(0 != _out_stream);
assert(0 <= model_no && model_no < sz_t(_models.size()));
model_t &model = _models[model_no];
assert(model.min <= value && value <= model.max);
const value_type enc_val = (value + model._delta);
assert(0 <= enc_val && enc_val < model._symbols);
#ifdef LIBWIC_DEBUG
++(model._encoded_symbols);
++(model._encoded_freqs[enc_val]);
#endif
// выбор модели и кодирование (учитывая смещение)
_aencoder->model(model_no);
// при виртуальном кодировании не производится реальная запись
// в выходной поток
if (!virtual_encode) _aencoder->put(enc_val);
// обновление модели арифметического кодера
_aencoder->update_model(enc_val);
}
/*!
*/
void acoder::decode_start()
{
// проверка утверждений
assert(0 != _adecoder);
assert(0 != _in_stream);
// начало арифметического декодирования
_adecoder->StartUnpacking();
// инициализация моделей
_init_models(_adecoder);
#ifdef LIBWIC_DEBUG
for (models_t::iterator i = _models.begin(); _models.end() != i; ++i)
{
model_t &model = (*i);
model._decoded_symbols = 0;
model._decoded_freqs.assign(model._symbols, 0);
}
#endif
}
/*!
*/
void acoder::decode_stop()
{
// проверка утверждений
assert(0 != _adecoder);
assert(0 != _in_stream);
// завершение декодирования
_adecoder->EndUnpacking();
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good()) dbg_decoder_info(_dbg_out_stream);
#endif
}
/*! \param[in] model_no Номер модели
*/
acoder::value_type acoder::get_value(const sz_t model_no)
{
// проверка утверждений
assert(0 != _adecoder);
assert(0 != _in_stream);
assert(0 <= model_no && model_no < int(_models.size()));
model_t &model = _models[model_no];
// выбор модели и декодирование (учитывая смещение)
_adecoder->model(model_no);
value_type dec_val;
(*_adecoder) >> dec_val;
#ifdef LIBWIC_DEBUG
++(model._decoded_symbols);
++(model._decoded_freqs[dec_val]);
#endif
return (dec_val - model._delta);
}
/*! \param[out] out Стандартный поток для вывода
*/
void acoder::dbg_encoder_info(std::ostream &out)
{
assert(0 != _aencoder);
out << "[encoder models information] ----------------------------";
out << std::endl;
#ifdef LIBWIC_DEBUG
unsigned int total_symbols = 0;
#endif
for (sz_t i = 0; sz_t(_models.size()) > i; ++i)
{
out << "#" << std::setw(2) << i;
_aencoder->model(i);
const model_t &model = _models[i];
#ifdef LIBWIC_DEBUG
out << "[" << std::setw(5) << model._symbols << "]";
#endif
const unsigned int bits = _aencoder->model()->bit_counter;
out << ": ";
out << std::setw(8) << bits << " bits |";
out << std::setw(7) << (bits / 8) << " bytes";
#ifdef LIBWIC_DEBUG
const unsigned int encoded_symbols = model._encoded_symbols;
total_symbols += encoded_symbols;
out << " |" << std::setw(7) << encoded_symbols << " symbols";
#endif
out << std::endl;
#ifdef LIBWIC_DEBUG
_dbg_freqs_out(out, model._encoded_freqs, model, i, _aencoder);
#endif
}
#ifdef LIBWIC_DEBUG
out << "Total symbols: " << std::setw(6) << total_symbols << std::endl;
#endif
out << "[/encoder models information] ---------------------------";
out << std::endl;
}
/*! \param[in] file Имя файла в который будет производиться вывод
*/
void acoder::dbg_encoder_info(const std::string &file)
{
std::ofstream out(file.c_str());
if (out.good()) dbg_encoder_info(out);
}
/*! \param[out] out Стандартный поток для вывода
*/
void acoder::dbg_decoder_info(std::ostream &out)
{
assert(0 != _adecoder);
out << "[decoder models information] ----------------------------";
out << std::endl;
#ifdef LIBWIC_DEBUG
unsigned int total_symbols = 0;
#endif
for (sz_t i = 0; sz_t(_models.size()) > i; ++i)
{
out << "#" << std::setw(2) << i;
_adecoder->model(i);
const model_t &model = _models[i];
#ifdef LIBWIC_DEBUG
out << "[" << std::setw(5) << model._symbols << "]";
#endif
const unsigned int bits = _adecoder->model()->bit_counter;
out << ": ";
out << std::setw(8) << bits << " bits |";
out << std::setw(7) << (bits / 8) << " bytes";
#ifdef LIBWIC_DEBUG
const unsigned int decoded_symbols = model._decoded_symbols;
total_symbols += decoded_symbols;
out << " |" << std::setw(7) << decoded_symbols << " symbols";
#endif
out << std::endl;
#ifdef LIBWIC_DEBUG
_dbg_freqs_out(out, model._decoded_freqs, model, i, _adecoder);
#endif
}
#ifdef LIBWIC_DEBUG
out << "Total symbols: " << std::setw(6) << total_symbols << std::endl;
#endif
out << "[/decoder models information] ---------------------------";
out << std::endl;
}
/*! \param[in] file Имя файла в который будет производиться вывод
*/
void acoder::dbg_decoder_info(const std::string &file)
{
std::ofstream out(file.c_str());
if (out.good()) dbg_decoder_info(out);
}
////////////////////////////////////////////////////////////////////////////////
// acoder class protected definitions
/*! \param[in] model Модель
\return Количество символов в алфавите
*/
acoder::value_type acoder::_symbols_count(const model_t &model)
{
assert(model.min <= model.max);
return (model.max - model.min + 1);
}
/*! \param[in] models Модели
\return Модели в формате для арифметического кодера
\attention Функция должна вызываться после acoder::_refresh_models()
*/
int *acoder::_mk_models(const models_t &models)
{
// проверка наличия моделей
assert(0 < models.size());
// выделение памяти под модели
int *const result = new int[models.size()];
if (0 == result) throw std::bad_alloc();
// копирование моделей из вектора
int k = 0;
for (models_t::const_iterator i = models.begin(); models.end() != i; ++i)
{
result[k++] = i->_symbols;
}
return result;
}
/*! \param[in,out] models_ptr Модели в формате для арифметического кодера
*/
void acoder::_rm_models(const int *const models_ptr)
{
if (0 != models_ptr) delete[] models_ptr;
}
/*! \param[in] models Модели арифметического кодера для обновления
Функция выполняет следующие действия:
- актуализирует поле model_t::_delta
- актуализирует поле model_t::_symbols
*/
void acoder::_refresh_models(models_t &models)
{
for (models_t::iterator i = models.begin(); models.end() != i; ++i)
{
model_t &model = (*i);
model._delta = - model.min;
model._symbols = _symbols_count(model);
}
}
/*! \param[in] coder_base Базовый класс для арифметических енкодера и
декодера
*/
void acoder::_init_models(arcoder_base *const coder_base)
{
// проверка утверждений
assert(0 != coder_base);
assert(coder_base->Models().Size() == _models.size());
// обновление внутренней информации моделей
_refresh_models(_models);
// сброс статистик
coder_base->ResetStatistics();
// инициализация моделей
for (sz_t i = 0; 2/*coder_base->Models().Size()*/ > i; i++)
{
const model_t &model = _models[i];
coder_base->model(i);
for (int j = 0; model._symbols > j; ++j)
{
coder_base->update_model(j);
}
}
coder_base->model(6);
coder_base->update_model(7);
coder_base->update_model(7);
coder_base->update_model(7);
coder_base->update_model(7);
coder_base->update_model(7);
coder_base->update_model(7);
coder_base->update_model(7);
coder_base->update_model(7);
coder_base->model(7);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->model(8);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->update_model(0);
coder_base->model(9);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->model(10);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
coder_base->update_model(0xf);
}
/*! \param[in] models Модели
Функция создаёт енкодер и декодер.
*/
void acoder::_mk_coders(const models_t &models)
{
// проверка утверждений
assert(0 != _out_stream);
assert(0 != _in_stream);
// освобождение старых объектов
_rm_coders();
// сохранение настроек моделей
_models = models;
// обновление моделей
_refresh_models(_models);
// модели для аркодера
const int *const models_ptr = _mk_models(_models);
// создание новых объектов енкодера и декодера
_aencoder = new ArCoderWithBitCounter<BITOutMemStream>(
int(_models.size()), models_ptr, *_out_stream);
_adecoder = new ArDecoderWithBitCounter<BITInMemStream>(
int(_models.size()), models_ptr, *_in_stream);
// освобождение моделей для аркодера
_rm_models(models_ptr);
// проверка полученных значений
if (0 == _aencoder || 0 == _adecoder) throw std::bad_alloc();
}
/*!
*/
void acoder::_rm_coders()
{
if (0 != _aencoder) {
delete _aencoder;
_aencoder = 0;
}
if (0 != _adecoder) {
delete _adecoder;
_adecoder = 0;
}
}
/*! \param[in] coder_base Базовый класс для арифметических енкодера и
декодера
\param[in] value Значение, символ из алфавита модели
\param[in] model_no Номер используемой модели
\return Битовые затраты на кодирование символа
*/
double acoder::_entropy_eval(arcoder_base *const coder_base,
const value_type &value, const sz_t model_no)
{
// проверка утверждений
assert(0 != coder_base);
assert(coder_base->Models().Size() == _models.size());
assert(0 <= model_no && model_no < int(_models.size()));
const model_t &model = _models[model_no];
assert(model.min <= value && value <= model.max);
// выбор модели и подсчёт битовых затрат (учитывая смещение)
coder_base->model(model_no);
const double entropy = coder_base->entropy_eval(value + model._delta);
return entropy;
}
#ifdef LIBWIC_DEBUG
/*! \param[out] out Стандартный поток для вывода
\param[in] freqs Вектор частот символов
\param[in] model Используемая модель
\param[in] model_no Номер используемой модели
\param[in] coder_base Базовый класс используемого арифметического кодера
\note Функция меняет текущую модель арифметического кодера на модель
с номером model_no.
*/
void acoder::_dbg_freqs_out(std::ostream &out,
const std::vector<unsigned int> &freqs,
const model_t &model, const sz_t model_no,
arcoder_base *const coder_base)
{
// поиск максимальной частоты
unsigned int freq_max = 0;
for (sz_t i = 0; sz_t(freqs.size()) > i; ++i)
{
if (freq_max < freqs[i]) freq_max = freqs[i];
}
// переключение текущей модели
if (0 != coder_base) coder_base->model(model_no);
// вывод частот
for (sz_t i = 0; sz_t(freqs.size()) > i; ++i)
{
const unsigned int freq = freqs[i];
if (0 == freq) continue;
// вывод диаграммы
out << "\t" << std::setw(5) << (i - model._delta) << "|";
for (sz_t k = (36 * freq / freq_max); 0 < k; --k) out << '+';
// числовое значение частоты
out << std::setw(7) << freq;
// числовое значение энтропии
out << "; e=" << std::setprecision(5) << coder_base->entropy_eval(i);
out << std::endl;
}
}
#endif
} // namespace wic
|
[
"kulikov@b1028fda-012f-0410-8370-c1301273da9f"
] |
[
[
[
1,
658
]
]
] |
d07b5d00c20b3f9266b32461b4ffc686a2360970
|
ef23e388061a637f82b815d32f7af8cb60c5bb1f
|
/src/mame/includes/strnskil.h
|
60bafaeeecdaa982736748dc887d6df9c4e457bd
|
[] |
no_license
|
marcellodash/psmame
|
76fd877a210d50d34f23e50d338e65a17deff066
|
09f52313bd3b06311b910ed67a0e7c70c2dd2535
|
refs/heads/master
| 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 552 |
h
|
class strnskil_state : public driver_device
{
public:
strnskil_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT8 *m_videoram;
UINT8 *m_xscroll;
UINT8 m_scrl_ctrl;
tilemap_t *m_bg_tilemap;
UINT8 *m_spriteram;
size_t m_spriteram_size;
};
/*----------- defined in video/strnskil.c -----------*/
WRITE8_HANDLER( strnskil_videoram_w );
WRITE8_HANDLER( strnskil_scrl_ctrl_w );
PALETTE_INIT( strnskil );
VIDEO_START( strnskil );
SCREEN_UPDATE( strnskil );
|
[
"Mike@localhost"
] |
[
[
[
1,
23
]
]
] |
0356e265fd5c6c0a6047b83edb99600cbb2f8aca
|
854ee643a4e4d0b7a202fce237ee76b6930315ec
|
/arcemu_svn/src/sun/src/QuestScripts/RedridgeMountains.cpp
|
f2718f1975fd624d2ceb861578467944eea71b7f
|
[] |
no_license
|
miklasiak/projekt
|
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
|
064402da950555bf88609e98b7256d4dc0af248a
|
refs/heads/master
| 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,100 |
cpp
|
/*
* WEmu Scripts for WEmu MMORPG Server
* Copyright (C) 2008 WEmu 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 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
#include "Setup.h"
#include "EAS/EasyFunctions.h"
class MissingInAction : public QuestScript
{
public:
void OnQuestStart( Player * mTarget, QuestLogEntry * qLogEntry)
{
if( mTarget == NULL || mTarget->GetMapMgr() == NULL || mTarget->GetMapMgr()->GetInterface() == NULL )
return;
float SSX = mTarget->GetPositionX();
float SSY = mTarget->GetPositionY();
float SSZ = mTarget->GetPositionZ();
Creature* creat = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 349);
if(creat == NULL)
return;
creat->m_escorter = mTarget;
creat->GetAIInterface()->setMoveType(11);
creat->GetAIInterface()->StopMovement(3000);
creat->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Okay let's do!");
creat->SetUInt32Value(UNIT_NPC_FLAGS, 0);
sEAS.CreateCustomWaypointMap(creat);
sEAS.WaypointCreate(creat,-8769.745117f, -2186.538818f, 141.841599f, 3.457182f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8783.108398f, -2197.826416f, 140.165878f, 3.597175f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8828.141602f, -2188.636963f, 138.618134f, 4.815924f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8809.825195f, -2233.663574f, 144.356613f, 5.723056f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8795.662109f, -2242.221436f, 146.450958f, 5.408901f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8775.052734f, -2261.419922f, 149.575378f, 0.355398f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8690.659180f, -2241.627930f, 153.590225f, 5.829625f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8664.609375f, -2254.313232f, 154.770416f, 4.164592f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8675.779297f, -2278.719482f, 155.470612f, 4.643681f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8679.915039f, -2324.837646f, 155.916428f, 3.819015f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8760.700195f, -2386.090088f, 156.647003f, 4.206810f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8810.614258f, -2479.427246f, 133.146484f, 3.788514f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8927.923828f, -2590.238525f, 132.446716f, 3.439012f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-8992.492188f, -2607.978516f, 130.872818f, 2.472971f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-9123.129883f, -2498.676270f, 116.559822f, 1.946754f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-9165.129883f, -2376.718994f, 94.946968f, 2.406212f, 0, 256, 1826);
sEAS.WaypointCreate(creat,-9278.547852f, -2296.741699f, 68.041824f, 2.861743f, 0, 256, 1826);
}
};
class Corporal_Keeshan : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(Corporal_Keeshan);
Corporal_Keeshan(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnReachWP(uint32 iWaypointId, bool bForwards)
{
if(iWaypointId == 19)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Tell Marshal Marris. I'm outta here!");
_unit->Despawn(5000,1000);
sEAS.DeleteWaypoints(_unit);
if(_unit->m_escorter == NULL)
return;
Player* plr = _unit->m_escorter;
_unit->m_escorter = NULL;
plr->GetQuestLogForEntry(219)->SendQuestComplete();
}
}
};
void SetupRedrigeMountains(ScriptMgr * mgr)
{
mgr->register_creature_script(349, &Corporal_Keeshan::Create);
mgr->register_quest_script(219, CREATE_QUESTSCRIPT(MissingInAction));
}
|
[
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
] |
[
[
[
1,
92
]
]
] |
0b3e29c81fe3032a5ff7360061c4a69a964916e9
|
46c766a3da1fbfb390613f8d4aeaea079180d739
|
/main.cpp
|
90fea6dafe3ee7a8c8bbede295aa3d07bed09935
|
[] |
no_license
|
laosland/CSCE350_final_project
|
c72cf43905b76dbd0fd429b0f359df3cf19134b8
|
90e4a85f96497be5e3f52e1468b70e19c2679d77
|
refs/heads/master
| 2021-01-10T19:09:01.746106 | 2011-10-25T22:10:19 | 2011-10-25T22:10:19 | 2,621,820 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 159 |
cpp
|
#include <iostream>
#include "arraySort.h"
using namespace std;
arraySort test;
int main()
{
// cout << "Hello world!" << endl;
return 0;
}
|
[
"[email protected]"
] |
[
[
[
1,
12
]
]
] |
b3194c5f39e4bf5475e2f342f72d58080391be31
|
79cbdf99590cb47e7b8020da2db7fd400b028c4c
|
/include/mt/lock.h
|
d031e020db552e01f87bfca6d668059688473a45
|
[] |
no_license
|
jmckaskill/mt
|
af1b471478d03d554fb84b4f0bd0887575c78507
|
485a786c49ea7d2995eada4f1ccb230ed155a18a
|
refs/heads/master
| 2020-06-09T01:03:41.579618 | 2011-02-26T05:26:14 | 2011-02-26T05:26:14 | 1,413,794 | 2 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 5,247 |
h
|
/* vim: ts=4 sw=4 sts=4 et tw=78
*
* Copyright (c) 2009 James R. McKaskill
*
* This software is licensed under the stock MIT license:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* ----------------------------------------------------------------------------
*/
#pragma once
#include <mt/common.h>
#include <mt/atomic.h>
/* Lock flags */
#define MT_LOCK_RECURSIVE 0x01
/* ------------------------------------------------------------------------- */
#if defined _WIN32
struct MT_Mutex {
void* DebugInfo;
long LockCount;
long RecursionCount;
MT_Handle OwningThread;
MT_Handle LockSemaphore;
uint32_t SpinCount;
};
struct _RTL_CRITICAL_SECTION;
MT_EXTERN_C
__declspec(dllimport)
void
__stdcall
EnterCriticalSection (
struct _RTL_CRITICAL_SECTION* pcsCriticalSection
);
MT_EXTERN_C
__declspec(dllimport)
void
__stdcall
LeaveCriticalSection (
struct _RTL_CRITICAL_SECTION* pcsCriticalSection
);
MT_EXTERN_C
__declspec(dllimport)
void
__stdcall
InitializeCriticalSection (
struct _RTL_CRITICAL_SECTION* pcsCriticalSection
);
MT_EXTERN_C
__declspec(dllimport)
void
__stdcall
DeleteCriticalSection (
struct _RTL_CRITICAL_SECTION* pcsCriticalSection
);
#define MT_MUTEX_INITIALIZER \
{ \
NULL, /* DebugInfo */ \
-1, /* LockCount */ \
0, /* RecursionCount */ \
NULL, /* OwningThread */ \
NULL, /* LockSemaphore */ \
0 /* SpinCount */ \
}
MT_INLINE void MT_InitMutex(MT_Mutex* lock)
{
InitializeCriticalSection((struct _RTL_CRITICAL_SECTION*) lock);
}
MT_INLINE void MT_InitMutex2(MT_Mutex* lock, int flags)
{
(void) flags;
InitializeCriticalSection((struct _RTL_CRITICAL_SECTION*) lock);
}
MT_INLINE void MT_DestroyMutex(MT_Mutex* lock)
{
DeleteCriticalSection((struct _RTL_CRITICAL_SECTION*) lock);
}
MT_INLINE void MT_Lock(MT_Mutex* lock)
{
EnterCriticalSection((struct _RTL_CRITICAL_SECTION*) lock);
}
MT_INLINE void MT_Unlock(MT_Mutex* lock)
{
LeaveCriticalSection((struct _RTL_CRITICAL_SECTION*) lock);
}
/* ------------------------------------------------------------------------- */
#else
#include <pthread.h>
struct MT_Mutex {
pthread_mutex_t lock;
};
#define MT_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER}
MT_INLINE void MT_InitMutex(MT_Mutex* lock)
{
pthread_mutex_init(&lock->lock, NULL);
}
MT_API void MT_InitMutex2(MT_Mutex* lock, int flags);
MT_INLINE void MT_DestroyMutex(MT_Mutex* lock)
{
pthread_mutex_destroy(&lock->lock);
}
MT_INLINE void MT_Lock(MT_Mutex* lock)
{
pthread_mutex_lock(&lock->lock);
}
MT_INLINE void MT_Unlock(MT_Mutex* lock)
{
pthread_mutex_unlock(&lock->lock);
}
/* ------------------------------------------------------------------------- */
#endif
#ifdef __cplusplus
namespace MT
{
/* ------------------------------------------------------------------------- */
class Mutex
{
public:
Mutex() {
MT_InitMutex(&m_Lock);
}
Mutex(int flags) {
MT_InitMutex2(&m_Lock, flags);
}
~Mutex() {
MT_DestroyMutex(&m_Lock);
}
void Lock() {
MT_Lock(&m_Lock);
}
void Unlock() {
MT_Unlock(&m_Lock);
}
private:
MT_Mutex m_Lock;
};
/* ------------------------------------------------------------------------- */
class ScopedLock
{
public:
ScopedLock(MT::Mutex* lock) : m_Lock(lock) {
m_Lock->Lock();
}
~ScopedLock() {
m_Lock->Unlock();
}
private:
MT::Mutex* m_Lock;
};
/* ------------------------------------------------------------------------- */
}
#endif
|
[
"[email protected]"
] |
[
[
[
1,
208
]
]
] |
e54d3e7d358786710275980e47a09a3d02aa8d77
|
a1dfee66d86d341858093480adfde387fa38a3eb
|
/src/DdsFileType/Squish/alpha.cpp
|
6eb4ffac53e77e7189b80ccabff5b262ee538202
|
[
"MIT"
] |
permissive
|
Ashokkumar-RV/OpenPDN
|
db35bec8bb90ca1a7ed3ca5e19c68fa585af22d8
|
cca476b0df2a2f70996e6b9486ec45327631568c
|
refs/heads/master
| 2020-09-02T17:18:53.679159 | 2009-12-04T22:47:21 | 2009-12-04T22:47:21 | 219,267,634 | 1 | 0 |
NOASSERTION
| 2019-11-03T07:45:30 | 2019-11-03T07:45:30 | null |
UTF-8
|
C++
| false | false | 8,551 |
cpp
|
/* -----------------------------------------------------------------------------
Copyright (c) 2006 Simon Brown [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.
-------------------------------------------------------------------------- */
#include "alpha.h"
#include <algorithm>
namespace squish {
static int FloatToInt( float a, int limit )
{
// use ANSI round-to-zero behaviour to get round-to-nearest
int i = ( int )( a + 0.5f );
// clamp to the limit
if( i < 0 )
i = 0;
else if( i > limit )
i = limit;
// done
return i;
}
void CompressAlphaDxt3( u8 const* rgba, int mask, void* block )
{
u8* bytes = reinterpret_cast< u8* >( block );
// quantise and pack the alpha values pairwise
for( int i = 0; i < 8; ++i )
{
// quantise down to 4 bits
float alpha1 = ( float )rgba[8*i + 3] * ( 15.0f/255.0f );
float alpha2 = ( float )rgba[8*i + 7] * ( 15.0f/255.0f );
int quant1 = FloatToInt( alpha1, 15 );
int quant2 = FloatToInt( alpha2, 15 );
// set alpha to zero where masked
int bit1 = 1 << ( 2*i );
int bit2 = 1 << ( 2*i + 1 );
if( ( mask & bit1 ) == 0 )
quant1 = 0;
if( ( mask & bit2 ) == 0 )
quant2 = 0;
// pack into the byte
bytes[i] = ( u8 )( quant1 | ( quant2 << 4 ) );
}
}
void DecompressAlphaDxt3( u8* rgba, void const* block )
{
u8 const* bytes = reinterpret_cast< u8 const* >( block );
// unpack the alpha values pairwise
for( int i = 0; i < 8; ++i )
{
// quantise down to 4 bits
u8 quant = bytes[i];
// unpack the values
u8 lo = quant & 0x0f;
u8 hi = quant & 0xf0;
// convert back up to bytes
rgba[8*i + 3] = lo | ( lo << 4 );
rgba[8*i + 7] = hi | ( hi >> 4 );
}
}
static void FixRange( int& min, int& max, int steps )
{
if( max - min < steps )
max = std::min( min + steps, 255 );
if( max - min < steps )
min = std::max( 0, max - steps );
}
static int FitCodes( u8 const* rgba, int mask, u8 const* codes, u8* indices )
{
// fit each alpha value to the codebook
int err = 0;
for( int i = 0; i < 16; ++i )
{
// check this pixel is valid
int bit = 1 << i;
if( ( mask & bit ) == 0 )
{
// use the first code
indices[i] = 0;
continue;
}
// find the least error and corresponding index
int value = rgba[4*i + 3];
int least = INT_MAX;
int index = 0;
for( int j = 0; j < 8; ++j )
{
// get the squared error from this code
int dist = ( int )value - ( int )codes[j];
dist *= dist;
// compare with the best so far
if( dist < least )
{
least = dist;
index = j;
}
}
// save this index and accumulate the error
indices[i] = ( u8 )index;
err += least;
}
// return the total error
return err;
}
static void WriteAlphaBlock( int alpha0, int alpha1, u8 const* indices, void* block )
{
u8* bytes = reinterpret_cast< u8* >( block );
// write the first two bytes
bytes[0] = ( u8 )alpha0;
bytes[1] = ( u8 )alpha1;
// pack the indices with 3 bits each
u8* dest = bytes + 2;
u8 const* src = indices;
for( int i = 0; i < 2; ++i )
{
// pack 8 3-bit values
int value = 0;
for( int j = 0; j < 8; ++j )
{
int index = *src++;
value |= ( index << 3*j );
}
// store in 3 bytes
for( int j = 0; j < 3; ++j )
{
int byte = ( value >> 8*j ) & 0xff;
*dest++ = ( u8 )byte;
}
}
}
static void WriteAlphaBlock5( int alpha0, int alpha1, u8 const* indices, void* block )
{
// check the relative values of the endpoints
if( alpha0 > alpha1 )
{
// swap the indices
u8 swapped[16];
for( int i = 0; i < 16; ++i )
{
u8 index = indices[i];
if( index == 0 )
swapped[i] = 1;
else if( index == 1 )
swapped[i] = 0;
else if( index <= 5 )
swapped[i] = 7 - index;
else
swapped[i] = index;
}
// write the block
WriteAlphaBlock( alpha1, alpha0, swapped, block );
}
else
{
// write the block
WriteAlphaBlock( alpha0, alpha1, indices, block );
}
}
static void WriteAlphaBlock7( int alpha0, int alpha1, u8 const* indices, void* block )
{
// check the relative values of the endpoints
if( alpha0 < alpha1 )
{
// swap the indices
u8 swapped[16];
for( int i = 0; i < 16; ++i )
{
u8 index = indices[i];
if( index == 0 )
swapped[i] = 1;
else if( index == 1 )
swapped[i] = 0;
else
swapped[i] = 9 - index;
}
// write the block
WriteAlphaBlock( alpha1, alpha0, swapped, block );
}
else
{
// write the block
WriteAlphaBlock( alpha0, alpha1, indices, block );
}
}
void CompressAlphaDxt5( u8 const* rgba, int mask, void* block )
{
// get the range for 5-alpha and 7-alpha interpolation
int min5 = 255;
int max5 = 0;
int min7 = 255;
int max7 = 0;
for( int i = 0; i < 16; ++i )
{
// check this pixel is valid
int bit = 1 << i;
if( ( mask & bit ) == 0 )
continue;
// incorporate into the min/max
int value = rgba[4*i + 3];
if( value < min7 )
min7 = value;
if( value > max7 )
max7 = value;
if( value != 0 && value < min5 )
min5 = value;
if( value != 255 && value > max5 )
max5 = value;
}
// handle the case that no valid range was found
if( min5 > max5 )
min5 = max5;
if( min7 > max7 )
min7 = max7;
// fix the range to be the minimum in each case
FixRange( min5, max5, 5 );
FixRange( min7, max7, 7 );
// set up the 5-alpha code book
u8 codes5[8];
codes5[0] = ( u8 )min5;
codes5[1] = ( u8 )max5;
for( int i = 1; i < 5; ++i )
codes5[1 + i] = ( u8 )( ( ( 5 - i )*min5 + i*max5 )/5 );
codes5[6] = 0;
codes5[7] = 255;
// set up the 7-alpha code book
u8 codes7[8];
codes7[0] = ( u8 )min7;
codes7[1] = ( u8 )max7;
for( int i = 1; i < 7; ++i )
codes7[1 + i] = ( u8 )( ( ( 7 - i )*min7 + i*max7 )/7 );
// fit the data to both code books
u8 indices5[16];
u8 indices7[16];
int err5 = FitCodes( rgba, mask, codes5, indices5 );
int err7 = FitCodes( rgba, mask, codes7, indices7 );
// save the block with least error
if( err5 <= err7 )
WriteAlphaBlock5( min5, max5, indices5, block );
else
WriteAlphaBlock7( min7, max7, indices7, block );
}
void DecompressAlphaDxt5( u8* rgba, void const* block )
{
// get the two alpha values
u8 const* bytes = reinterpret_cast< u8 const* >( block );
int alpha0 = bytes[0];
int alpha1 = bytes[1];
// compare the values to build the codebook
u8 codes[8];
codes[0] = ( u8 )alpha0;
codes[1] = ( u8 )alpha1;
if( alpha0 <= alpha1 )
{
// use 5-alpha codebook
for( int i = 1; i < 5; ++i )
codes[1 + i] = ( u8 )( ( ( 5 - i )*alpha0 + i*alpha1 )/5 );
codes[6] = 0;
codes[7] = 255;
}
else
{
// use 7-alpha codebook
for( int i = 1; i < 7; ++i )
codes[1 + i] = ( u8 )( ( ( 7 - i )*alpha0 + i*alpha1 )/7 );
}
// decode the indices
u8 indices[16];
u8 const* src = bytes + 2;
u8* dest = indices;
for( int i = 0; i < 2; ++i )
{
// grab 3 bytes
int value = 0;
for( int j = 0; j < 3; ++j )
{
int byte = *src++;
value |= ( byte << 8*j );
}
// unpack 8 3-bit values from it
for( int j = 0; j < 8; ++j )
{
int index = ( value >> 3*j ) & 0x7;
*dest++ = ( u8 )index;
}
}
// write out the indexed codebook values
for( int i = 0; i < 16; ++i )
rgba[4*i + 3] = codes[indices[i]];
}
} // namespace squish
|
[
"benpicco@rechenknecht2k7"
] |
[
[
[
1,
348
]
]
] |
c94b7aa6b2cd034e81a7530425e68be0da05d5ed
|
44d499cacf286b033ce08eeceec1002e5ce782c9
|
/hardware/lm3s/uart_lm3s.cpp
|
ce199f5dbda7a9b440ea1d48b1ee5cd1a82657c2
|
[] |
no_license
|
thumbos/tmos
|
ef134ecc57b44e029ded14f957d7a23c982a4fae
|
756c2bc513288bfe1be96331a9e388ed0d744c83
|
refs/heads/master
| 2021-03-12T22:56:14.235818 | 2010-12-04T16:25:26 | 2010-12-04T16:25:26 | 1,137,841 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 32,338 |
cpp
|
/**************************************************************************//**
* @ingroup lm3s_uart
* @{
* @file uart_lm3s.cpp
* @brief UART class methods
* @version V3.00
* @date 15. March 2010
* @author Miroslav Kostadinov
*
*
******************************************************************************/
#include <tmos.h>
#include "fam_cpp.h"
/** The system clock divider defining the maximum baud rate supported by the UART.
*
*/
#define UART_CLK_DIVIDER ((CLASS_IS_SANDSTORM || \
(CLASS_IS_FURY && REVISION_IS_A2) || \
(CLASS_IS_DUSTDEVIL && REVISION_IS_A0)) ? \
16 : 8)
/*****************************************************************************
*
* Get UART peripheral value
*
*
*
*
* NOTE: Use Driver Info instead!!
*
*
*
*
*
* return values that can be passed to the
* SysCtlPeripheralPresent(), SysCtlPeripheralEnable(),
* SysCtlPeripheralDisable(), and SysCtlPeripheralReset() APIs as the
* ulPeripheral parameter.
*
*/
//unsigned long UART_Type::UARTGetPeripheral(void)
//{
// if( this == UART0 )
// return SYSCTL_PERIPH_UART0;
// if( this == UART1 )
// return SYSCTL_PERIPH_UART1;
// if( this == UART2 )
// return SYSCTL_PERIPH_UART2;
// return 0;
//}
/**
* DMA_GetRxChannel
* @return
*/
unsigned long UART_Type::DMA_GetRxChannel(void)
{
if( this == UART0 )
return UDMA_CHANNEL_UART0RX;
if( this == UART1 )
return UDMA_CHANNEL_UART1RX;
if( this == UART2 )
return UDMA_CHANNEL_UART2RX;
return 0;
}
/**DMA_GetTxChannel
*
* @return
*/
unsigned long UART_Type::DMA_GetTxChannel(void)
{
if( this == UART0 )
return UDMA_CHANNEL_UART0TX;
if( this == UART1 )
return UDMA_CHANNEL_UART1TX;
if( this == UART2 )
return UDMA_CHANNEL_UART2TX;
return 0;
}
/*
*
* Reset UART peripheral
*
*/
//void UART_Type::UARTReset(void)
//{
// SYSCTL->SysCtlPeripheralReset(this->UARTGetPeripheral());
//}
/**
*
* Sets the type of parity.
*
* \param ulParity specifies the type of parity to use.
*
* Sets the type of parity to use for transmitting and expect when receiving.
* The \e ulParity parameter must be one of \b UART_CONFIG_PAR_NONE,
* \b UART_CONFIG_PAR_EVEN, \b UART_CONFIG_PAR_ODD, \b UART_CONFIG_PAR_ONE,
* or \b UART_CONFIG_PAR_ZERO. The last two allow direct control of the
* parity bit; it will always be either be one or zero based on the mode.
*
* \return None.
*
*/
void UART_Type::UARTParityModeSet(unsigned long ulParity)
{
ASSERT((ulParity == UART_CONFIG_PAR_NONE) ||
(ulParity == UART_CONFIG_PAR_EVEN) ||
(ulParity == UART_CONFIG_PAR_ODD) ||
(ulParity == UART_CONFIG_PAR_ONE) ||
(ulParity == UART_CONFIG_PAR_ZERO));
this->LCRH = ((this->LCRH & ~(UART_LCRH_SPS|UART_LCRH_EPS|UART_LCRH_PEN)) | ulParity);
}
/**
*
* Gets the type of parity currently being used.
*
* This function gets the type of parity used for transmitting data, and
* expected when receiving data.
*
* \return Returns the current parity settings, specified as one of
* \b UART_CONFIG_PAR_NONE, \b UART_CONFIG_PAR_EVEN, \b UART_CONFIG_PAR_ODD,
* \b UART_CONFIG_PAR_ONE, or \b UART_CONFIG_PAR_ZERO.
*
*/
unsigned long UART_Type::UARTParityModeGet(void)
{
return(this->LCRH & (UART_LCRH_SPS | UART_LCRH_EPS | UART_LCRH_PEN));
}
/**
*
* Sets the FIFO level at which interrupts are generated.
*
* \param ulTxLevel is the transmit FIFO interrupt level, specified as one of
* \b UART_FIFO_TX1_8, \b UART_FIFO_TX2_8, \b UART_FIFO_TX4_8,
* \b UART_FIFO_TX6_8, or \b UART_FIFO_TX7_8.
* \param ulRxLevel is the receive FIFO interrupt level, specified as one of
* \b UART_FIFO_RX1_8, \b UART_FIFO_RX2_8, \b UART_FIFO_RX4_8,
* \b UART_FIFO_RX6_8, or \b UART_FIFO_RX7_8.
*
* This function sets the FIFO level at which transmit and receive interrupts
* will be generated.
*
* \return None.
*
*/
void UART_Type::UARTFIFOLevelSet(unsigned long ulTxLevel, unsigned long ulRxLevel)
{
ASSERT((ulTxLevel == UART_FIFO_TX1_8) ||
(ulTxLevel == UART_FIFO_TX2_8) ||
(ulTxLevel == UART_FIFO_TX4_8) ||
(ulTxLevel == UART_FIFO_TX6_8) ||
(ulTxLevel == UART_FIFO_TX7_8));
ASSERT((ulRxLevel == UART_FIFO_RX1_8) ||
(ulRxLevel == UART_FIFO_RX2_8) ||
(ulRxLevel == UART_FIFO_RX4_8) ||
(ulRxLevel == UART_FIFO_RX6_8) ||
(ulRxLevel == UART_FIFO_RX7_8));
this->IFLS = ulTxLevel | ulRxLevel;
}
/**
*
* Gets the FIFO level at which interrupts are generated.
*
* \param pulTxLevel is a pointer to storage for the transmit FIFO level,
* returned as one of \b UART_FIFO_TX1_8, \b UART_FIFO_TX2_8,
* \b UART_FIFO_TX4_8, \b UART_FIFO_TX6_8, or UART_FIFO_TX7_8.
* \param pulRxLevel is a pointer to storage for the receive FIFO level,
* returned as one of \b UART_FIFO_RX1_8, \b UART_FIFO_RX2_8,
* \b UART_FIFO_RX4_8, \b UART_FIFO_RX6_8, or \b UART_FIFO_RX7_8.
*
* This function gets the FIFO level at which transmit and receive interrupts
* will be generated.
*
* \return None.
*
*/
void UART_Type::UARTFIFOLevelGet( unsigned long *pulTxLevel, unsigned long *pulRxLevel )
{
unsigned long ulTemp;
ulTemp = this->IFLS;
*pulTxLevel = ulTemp & UART_IFLS_TX_M;
*pulRxLevel = ulTemp & UART_IFLS_RX_M;
}
/**
*
* Sets the configuration of a UART.
*
* \param ulUARTClk is the rate of the clock supplied to the UART module.
* \param ulBaud is the desired baud rate.
* \param ulConfig is the data format for the port (number of data bits,
* number of stop bits, and parity).
*
* This function will configure the UART for operation in the specified data
* format. The baud rate is provided in the \e ulBaud parameter and the data
* format in the \e ulConfig parameter.
*
* The \e ulConfig parameter is the logical OR of three values: the number of
* data bits, the number of stop bits, and the parity. \b UART_CONFIG_WLEN_8,
* \b UART_CONFIG_WLEN_7, \b UART_CONFIG_WLEN_6, and \b UART_CONFIG_WLEN_5
* select from eight to five data bits per byte (respectively).
* \b UART_CONFIG_STOP_ONE and \b UART_CONFIG_STOP_TWO select one or two stop
* bits (respectively). \b UART_CONFIG_PAR_NONE, \b UART_CONFIG_PAR_EVEN,
* \b UART_CONFIG_PAR_ODD, \b UART_CONFIG_PAR_ONE, and \b UART_CONFIG_PAR_ZERO
* select the parity mode (no parity bit, even parity bit, odd parity bit,
* parity bit always one, and parity bit always zero, respectively).
*
* The peripheral clock will be the same as the processor clock. This will be
* the value returned by SysCtlClockGet(), or it can be explicitly hard coded
* if it is constant and known (to save the code/execution overhead of a call
* to SysCtlClockGet()).
*
* This function replaces the original UARTConfigSet() API and performs the
* same actions. A macro is provided in <tt>uart.h</tt> to map the original
* API to this API.
*
* \return None.
*
*/
void UART_Type::UARTConfigSetExpClk(unsigned long ulUARTClk, unsigned long ulBaud, unsigned long ulConfig)
{
unsigned long ulDiv;
ASSERT(ulBaud != 0);
ASSERT(ulUARTClk >= (ulBaud * UART_CLK_DIVIDER));
this->UARTDisable();
if((ulBaud * 16) > ulUARTClk)
{
this->CTL |= UART_CTL_HSE;
ulBaud /= 2;
}
else
{
this->CTL &= ~(UART_CTL_HSE);
}
ulDiv = (((ulUARTClk * 8) / ulBaud) + 1) / 2;
this->IBRD = ulDiv / 64;
this->FBRD = ulDiv % 64;
this->LCRH = ulConfig;
// this->FR = 0;
this->UARTEnable();
}
/**
*
* Gets the current configuration of a UART.
*
* \param ulUARTClk is the rate of the clock supplied to the UART module.
* \param pulBaud is a pointer to storage for the baud rate.
* \param pulConfig is a pointer to storage for the data format.
*
* The baud rate and data format for the UART is determined, given an
* explicitly provided peripheral clock (hence the ExpClk suffix). The
* returned baud rate is the actual baud rate; it may not be the exact baud
* rate requested or an ``official'' baud rate. The data format returned in
* \e pulConfig is enumerated the same as the \e ulConfig parameter of
* UARTConfigSetExpClk().
*
* The peripheral clock will be the same as the processor clock. This will be
* the value returned by SysCtlClockGet(), or it can be explicitly hard coded
* if it is constant and known (to save the code/execution overhead of a call
* to SysCtlClockGet()).
*
* This function replaces the original UARTConfigGet() API and performs the
* same actions. A macro is provided in <tt>uart.h</tt> to map the original
* API to this API.
*
* \return None.
*
*/
void UART_Type::UARTConfigGetExpClk(unsigned long ulUARTClk, unsigned long *pulBaud, unsigned long *pulConfig)
{
unsigned long ulInt, ulFrac;
ulInt = this->IBRD;
ulFrac = this->FBRD;
*pulBaud = (ulUARTClk * 4) / ((64 * ulInt) + ulFrac);
if(this->CTL & UART_CTL_HSE)
*pulBaud *= 2;
*pulConfig = (this->LCRH &
(UART_LCRH_SPS | UART_LCRH_WLEN_M | UART_LCRH_STP2 |
UART_LCRH_EPS | UART_LCRH_PEN));
}
/**
*
* Enables transmitting and receiving.
*
* Sets the UARTEN, TXE, and RXE bits, and enables the transmit and receive
* FIFOs.
*
* \return None.
*
*/
void UART_Type::UARTEnable(void)
{
this->LCRH |= UART_LCRH_FEN;
this->CTL |= (UART_CTL_UARTEN | UART_CTL_TXE | UART_CTL_RXE);
}
/**
* RxEnable
*/
void UART_Type::RxEnable(void)
{
this->CTL |= UART_CTL_RXE;
}
/**
* RxDisable
*/
void UART_Type::RxDisable(void)
{
this->CTL &= ~UART_CTL_RXE;
}
/** TxEnable
*
*/
void UART_Type::TxEnable(void)
{
this->CTL |= UART_CTL_TXE;
}
/** TxDisable
*
*/
void UART_Type::TxDisable(void)
{
this->CTL &= ~UART_CTL_TXE;
}
/**
*
* Disables transmitting and receiving.
*
* Clears the UARTEN, TXE, and RXE bits, then waits for the end of
* transmission of the current character, and flushes the transmit FIFO.
*
* \return None.
*
*/
void UART_Type::UARTDisable(void)
{
while(this->FR & UART_FR_BUSY)
{
}
this->LCRH &= ~(UART_LCRH_FEN);
this->CTL &= ~(UART_CTL_UARTEN | UART_CTL_TXE |UART_CTL_RXE);
}
/**
*
* Enables the transmit and receive FIFOs.
*
* This functions enables the transmit and receive FIFOs in the UART.
*
* \return None.
*
*/
void UART_Type::UARTFIFOEnable(void)
{
this->LCRH |= UART_LCRH_FEN;
}
/**
*
* Disables the transmit and receive FIFOs.
*
* This functions disables the transmit and receive FIFOs in the UART.
*
* \return None.
*
*/
void UART_Type::UARTFIFODisable(void)
{
this->LCRH &= ~(UART_LCRH_FEN);
}
/**
*
* Enables SIR (IrDA) mode on the specified UART.
*
* \param bLowPower indicates if SIR Low Power Mode is to be used.
*
* Enables the SIREN control bit for IrDA mode on the UART. If the
* \e bLowPower flag is set, then SIRLP bit will also be set.
*
* \note SIR (IrDA) operation is not supported on Sandstorm-class devices.
*
* \return None.
*
*/
void UART_Type::UARTEnableSIR(int bLowPower)
{
if(bLowPower)
{
this->CTL |= (UART_CTL_SIREN | UART_CTL_SIRLP);
}
else
{
this->CTL |= (UART_CTL_SIREN);
}
}
/**
*
* Disables SIR (IrDA) mode on the specified UART.
*
* Clears the SIREN (IrDA) and SIRLP (Low Power) bits.
*
* \note SIR (IrDA) operation is not supported on Sandstorm-class devices.
*
* \return None.
*
*/
void UART_Type::UARTDisableSIR(void)
{
this->CTL &= ~(UART_CTL_SIREN | UART_CTL_SIRLP);
}
/**
*
* Enables ISO 7816 smart card mode on the specified UART.
*
* Enables the SMART control bit for ISO 7816 smart card mode on the UART.
* This call also sets 8 bit word length and even parity as required by ISO
* 7816.
*
* \note The availability of ISO 7816 smart card mode varies with the
* Stellaris part and UART in use. Please consult the datasheet for the part
* you are using to determine whether this support is available.
*
* \return None.
*
*/
void UART_Type::UARTSmartCardEnable(void)
{
unsigned long ulVal;
ASSERT(!CLASS_IS_SANDSTORM && !CLASS_IS_FURY && !CLASS_IS_DUSTDEVIL);
// Set 8 bit word length, even parity, 2 stop bits (even though the STP2
// bit is ignored when in smartcard mode, this lets the caller read back
// the actual setting in use).
ulVal = this->LCRH;
ulVal &= ~(UART_LCRH_SPS | UART_LCRH_EPS | UART_LCRH_PEN |
UART_LCRH_WLEN_M);
ulVal |= UART_LCRH_WLEN_8 | UART_LCRH_PEN | UART_LCRH_EPS | UART_LCRH_STP2;
this->LCRH = ulVal;
// Enable SMART mode.
this->CTL |= UART_CTL_SMART;
}
/**
*
* Disables ISO 7816 smart card mode on the specified UART.
*
* Clears the SMART (ISO 7816 smart card) bits in the UART control register.
*
* \note The availability of ISO 7816 smart card mode varies with the
* Stellaris part and UART in use. Please consult the datasheet for the part
* you are using to determine whether this support is available.
*
* \return None.
*
*/
void UART_Type::UARTSmartCardDisable(void)
{
ASSERT(!CLASS_IS_SANDSTORM && !CLASS_IS_FURY && !CLASS_IS_DUSTDEVIL);
this->CTL &= ~UART_CTL_SMART;
}
/**
*
* Sets the states of the DTR and/or RTS modem control signals.
*
* \param ulControl is a bit-mapped flag indicating which modem control bits
* should be set.
*
* Sets the states of the DTR or RTS modem handshake outputs from the UART.
*
* The \e ulControl parameter is the logical OR of any of the following:
*
* - \b UART_OUTPUT_DTR - The Modem Control DTR signal
* - \b UART_OUTPUT_RTS - The Modem Control RTS signal
*
* \note The availability of hardware modem handshake signals varies with the
* Stellaris part and UART in use. Please consult the datasheet for the part
* you are using to determine whether this support is available.
*
* \return None.
*
*/
void UART_Type::UARTModemControlSet(unsigned long ulControl)
{
unsigned long ulTemp;
ASSERT(!CLASS_IS_SANDSTORM && !CLASS_IS_FURY && !CLASS_IS_DUSTDEVIL);
ASSERT((ulControl & ~(UART_OUTPUT_RTS | UART_OUTPUT_DTR)) == 0);
// Set the appropriate modem control output bits.
ulTemp = this->CTL;
ulTemp |= (ulControl & (UART_OUTPUT_RTS | UART_OUTPUT_DTR));
this->CTL = ulTemp;
}
/**
*
* Clears the states of the DTR and/or RTS modem control signals.
*
* \param ulControl is a bit-mapped flag indicating which modem control bits
* should be set.
*
* Clears the states of the DTR or RTS modem handshake outputs from the UART.
*
* The \e ulControl parameter is the logical OR of any of the following:
*
* - \b UART_OUTPUT_DTR - The Modem Control DTR signal
* - \b UART_OUTPUT_RTS - The Modem Control RTS signal
*
* \note The availability of hardware modem handshake signals varies with the
* Stellaris part and UART in use. Please consult the datasheet for the part
* you are using to determine whether this support is available.
*
* \return None.
*
*/
void UART_Type::UARTModemControlClear(unsigned long ulControl)
{
unsigned long ulTemp;
ASSERT(!CLASS_IS_SANDSTORM && !CLASS_IS_FURY && !CLASS_IS_DUSTDEVIL);
ASSERT((ulControl & ~(UART_OUTPUT_RTS | UART_OUTPUT_DTR)) == 0);
// Clear the appropriate modem control output bits.
ulTemp = this->CTL;
ulTemp &= ~(ulControl & (UART_OUTPUT_RTS | UART_OUTPUT_DTR));
this->CTL = ulTemp;
}
/**
*
* Gets the states of the DTR and RTS modem control signals.
*
* Returns the current states of each of the two UART modem control signals,
* DTR and RTS.
*
* \note The availability of hardware modem handshake signals varies with the
* Stellaris part and UART in use. Please consult the datasheet for the part
* you are using to determine whether this support is available.
*
* \return Returns the states of the handshake output signals. This will be a
* logical logical OR combination of values \b UART_OUTPUT_RTS and
* \b UART_OUTPUT_DTR where the presence of each flag indicates that the
* associated signal is asserted.
*
*/
unsigned long UART_Type::UARTModemControlGet(void)
{
ASSERT(!CLASS_IS_SANDSTORM && !CLASS_IS_FURY && !CLASS_IS_DUSTDEVIL);
return(this->CTL & (UART_OUTPUT_RTS | UART_OUTPUT_DTR));
}
/**
*
* Gets the states of the RI, DCD, DSR and CTS modem status signals.
*
* Returns the current states of each of the four UART modem status signals,
* RI, DCD, DSR and CTS.
*
* \note The availability of hardware modem handshake signals varies with the
* Stellaris part and UART in use. Please consult the datasheet for the part
* you are using to determine whether this support is available.
*
* \return Returns the states of the handshake output signals. This will be a
* logical logical OR combination of values \b UART_INPUT_RI, \b
* UART_INPUT_DCD, \b UART_INPUT_CTS and \b UART_INPUT_DSR where the
* presence of each flag indicates that the associated signal is asserted.
*
*/
unsigned long UART_Type::UARTModemStatusGet(void)
{
ASSERT(!CLASS_IS_SANDSTORM && !CLASS_IS_FURY && !CLASS_IS_DUSTDEVIL);
return(this->FR & (UART_INPUT_RI | UART_INPUT_DCD | UART_INPUT_CTS | UART_INPUT_DSR));
}
/**
*
* Sets the UART hardware flow control mode to be used.
*
* \param ulMode indicates the flow control modes to be used. This is a
* logical OR combination of values \b UART_FLOWCONTROL_TX and \b
* UART_FLOWCONTROL_RX to enable hardware transmit (CTS) and receive (RTS)
* flow control or \b UART_FLOWCONTROL_NONE to disable hardware flow control.
*
* Sets the required hardware flow control modes. If \e ulMode contains
* flag \b UART_FLOWCONTROL_TX, data is only transmitted if the incoming CTS
* signal is asserted. If \e ulMode contains flag \b UART_FLOWCONTROL_RX,
* the RTS output is controlled by the hardware and is asserted only when
* there is space available in the receive FIFO. If no hardware flow control
* is required, UART_FLOWCONTROL_NONE should be passed.
*
* \note The availability of hardware flow control varies with the Stellaris
* part and UART in use. Please consult the datasheet for the part you are
* using to determine whether this support is available.
*
* \return None.
*
*/
void UART_Type::UARTFlowControlSet(unsigned long ulMode)
{
ASSERT(!CLASS_IS_SANDSTORM && !CLASS_IS_FURY && !CLASS_IS_DUSTDEVIL);
ASSERT((ulMode & ~(UART_FLOWCONTROL_TX | UART_FLOWCONTROL_RX)) == 0);
// Set the flow control mode as requested.
this->CTL = ((this->CTL & ~(UART_FLOWCONTROL_TX |UART_FLOWCONTROL_RX)) | ulMode);
}
/**
*
* Returns the UART hardware flow control mode currently in use.
*
* Returns the current hardware flow control mode.
*
* \note The availability of hardware flow control varies with the Stellaris
* part and UART in use. Please consult the datasheet for the part you are
* using to determine whether this support is available.
*
* \return Returns the current flow control mode in use. This is a
* logical OR combination of values \b UART_FLOWCONTROL_TX if transmit
* (CTS) flow control is enabled and \b UART_FLOWCONTROL_RX if receive (RTS)
* flow control is in use. If hardware flow control is disabled, \b
* UART_FLOWCONTROL_NONE will be returned.
*
*/
unsigned long UART_Type::UARTFlowControlGet(void)
{
ASSERT(!CLASS_IS_SANDSTORM && !CLASS_IS_FURY && !CLASS_IS_DUSTDEVIL);
return(this->CTL & (UART_FLOWCONTROL_TX | UART_FLOWCONTROL_RX));
}
/**
*
* Sets the operating mode for the UART transmit interrupt.
*
* \param ulMode is the operating mode for the transmit interrupt. It may be
* \b UART_TXINT_MODE_EOT to trigger interrupts when the transmitter is idle
* or \b UART_TXINT_MODE_FIFO to trigger based on the current transmit FIFO
* level.
*
* This function allows the mode of the UART transmit interrupt to be set. By
* default, the transmit interrupt is asserted when the FIFO level falls past
* a threshold set via a call to UARTFIFOLevelSet(). Alternatively, if this
* function is called with \e ulMode set to \b UART_TXINT_MODE_EOT, the
* transmit interrupt will only be asserted once the transmitter is completely
* idle - the transmit FIFO is empty and all bits, including any stop bits,
* have cleared the transmitter.
*
* \note The availability of end-of-transmission mode varies with the
* Stellaris part in use. Please consult the datasheet for the part you are
* using to determine whether this support is available.
*
* \return None.
*
*/
void UART_Type::UARTTxIntModeSet(unsigned long ulMode)
{
ASSERT((ulMode == UART_TXINT_MODE_EOT) ||
(ulMode == UART_TXINT_MODE_FIFO));
this->CTL = ((this->CTL & ~(UART_TXINT_MODE_EOT | UART_TXINT_MODE_FIFO)) | ulMode);
}
/**
*
* Returns the current operating mode for the UART transmit interrupt.
*
* This function returns the current operating mode for the UART transmit
* interrupt. The return value will be \b UART_TXINT_MODE_EOT if the
* transmit interrupt is currently set to be asserted once the transmitter is
* completely idle - the transmit FIFO is empty and all bits, including any
* stop bits, have cleared the transmitter. The return value will be \b
* UART_TXINT_MODE_FIFO if the interrupt is set to be asserted based upon the
* level of the transmit FIFO.
*
* \note The availability of end-of-transmission mode varies with the
* Stellaris part in use. Please consult the datasheet for the part you are
* using to determine whether this support is available.
*
* \return Returns \b UART_TXINT_MODE_FIFO or \b UART_TXINT_MODE_EOT.
*
*/
unsigned long UART_Type::UARTTxIntModeGet(void)
{
return(this->CTL & (UART_TXINT_MODE_EOT | UART_TXINT_MODE_FIFO));
}
/**
*
* Determines if there are any characters in the receive FIFO.
*
* This function returns a flag indicating whether or not there is data
* available in the receive FIFO.
*
* \return Returns \b true if there is data in the receive FIFO, and \b false
* if there is no data in the receive FIFO.
*
*/
int UART_Type::UARTCharsAvail(void)
{
return((this->FR & UART_FR_RXFE) ? false : true);
}
/**
*
* Determines if there is any space in the transmit FIFO.
*
* This function returns a flag indicating whether or not there is space
* available in the transmit FIFO.
*
* \return Returns \b true if there is space available in the transmit FIFO,
* and \b false if there is no space available in the transmit FIFO.
*
*/
int UART_Type::UARTSpaceAvail(void)
{
return((this->FR & UART_FR_TXFF) ? false : true);
}
/**
*
* Receives a character from the specified port.
*
* Gets a character from the receive FIFO for the specified port.
*
* This function replaces the original UARTCharNonBlockingGet() API and
* performs the same actions. A macro is provided in <tt>uart.h</tt> to map
* the original API to this API.
*
* \return Returns the character read from the specified port, cast as a
* \e long. A \b -1 will be returned if there are no characters present in
* the receive FIFO. The UARTCharsAvail() function should be called before
* attempting to call this function.
*
*/
long UART_Type::UARTCharGetNonBlocking(void)
{
if(!(this->FR & UART_FR_RXFE))
return(this->DR);
return(-1);
}
/**
*
* Waits for a character from the specified port.
*
* Gets a character from the receive FIFO for the specified port. If there
* are no characters available, this function will wait until a character is
* received before returning.
*
* \return Returns the character read from the specified port, cast as an
* \e long.
*
*/
long UART_Type::UARTCharGet(void)
{
while(this->FR & UART_FR_RXFE)
{
}
return(this->DR);
}
/**
*
* Sends a character to the specified port.
*
* \param ucData is the character to be transmitted.
*
* Writes the character \e ucData to the transmit FIFO for the specified port.
* This function does not block, so if there is no space available, then a
* \b false is returned, and the application will have to retry the function
* later.
*
* This function replaces the original UARTCharNonBlockingPut() API and
* performs the same actions. A macro is provided in <tt>uart.h</tt> to map
* the original API to this API.
*
* \return Returns \b true if the character was successfully placed in the
* transmit FIFO, and \b false if there was no space available in the transmit
* FIFO.
*/
int UART_Type::UARTCharPutNonBlocking(unsigned char ucData)
{
if(!(this->FR & UART_FR_TXFF))
{
this->DR = ucData;
return(true);
}
return(false);
}
/**
*
* Waits to send a character from the specified port.
*
* \param ucData is the character to be transmitted.
*
* Sends the character \e ucData to the transmit FIFO for the specified port.
* If there is no space available in the transmit FIFO, this function will
* wait until there is space available before returning.
*
* \return None.
*
*/
void UART_Type::UARTCharPut(unsigned char ucData)
{
while(this->FR & UART_FR_TXFF)
{
}
this->DR = ucData;
}
/**
*
* Causes a BREAK to be sent.
*
* \param bBreakState controls the output level.
*
* Calling this function with \e bBreakState set to \b true will assert a
* break condition on the UART. Calling this function with \e bBreakState set
* to \b false will remove the break condition. For proper transmission of a
* break command, the break must be asserted for at least two complete frames.
*
* \return None.
*
*/
void UART_Type::UARTBreakCtl(int bBreakState)
{
this->LCRH = (bBreakState ?
(this->LCRH | UART_LCRH_BRK) :
(this->LCRH & ~(UART_LCRH_BRK)));
}
/**
*
* Determines whether the UART transmitter is busy or not.
*
* Allows the caller to determine whether all transmitted bytes have cleared
* the transmitter hardware. If \b false is returned, the transmit FIFO is
* empty and all bits of the last transmitted character, including all stop
* bits, have left the hardware shift register.
*
* \return Returns \b true if the UART is transmitting or \b false if all
* transmissions are complete.
*
*/
int UART_Type::UARTBusy(void)
{
return((this->FR & UART_FR_BUSY) ? true : false);
}
/**
*
* Enables individual UART interrupt sources.
*
* \param ulIntFlags is the bit mask of the interrupt sources to be enabled.
*
* Enables the indicated UART interrupt sources. Only the sources that are
* enabled can be reflected to the processor interrupt; disabled sources have
* no effect on the processor.
*
* The \e ulIntFlags parameter is the logical OR of any of the following:
*
* - \b UART_INT_OE - Overrun Error interrupt
* - \b UART_INT_BE - Break Error interrupt
* - \b UART_INT_PE - Parity Error interrupt
* - \b UART_INT_FE - Framing Error interrupt
* - \b UART_INT_RT - Receive Timeout interrupt
* - \b UART_INT_TX - Transmit interrupt
* - \b UART_INT_RX - Receive interrupt
* - \b UART_INT_DSR - DSR interrupt
* - \b UART_INT_DCD - DCD interrupt
* - \b UART_INT_CTS - CTS interrupt
* - \b UART_INT_RI - RI interrupt
*
* \return None.
*
*/
void UART_Type::UARTIntEnable(unsigned long ulIntFlags)
{
this->IM |= ulIntFlags;
}
/**
*
* Disables individual UART interrupt sources.
*
* \param ulIntFlags is the bit mask of the interrupt sources to be disabled.
*
* Disables the indicated UART interrupt sources. Only the sources that are
* enabled can be reflected to the processor interrupt; disabled sources have
* no effect on the processor.
*
* The \e ulIntFlags parameter has the same definition as the \e ulIntFlags
* parameter to UARTIntEnable().
*
* \return None.
*
*/
void UART_Type::UARTIntDisable(unsigned long ulIntFlags)
{
this->IM &= ~(ulIntFlags);
}
/**
*
* Gets the current interrupt status.
*
* \param bMasked is false if the raw interrupt status is required and true
* if the masked interrupt status is required.
*
* This returns the interrupt status for the specified UART. Either the raw
* interrupt status or the status of interrupts that are allowed to reflect to
* the processor can be returned.
*
* \return Returns the current interrupt status, enumerated as a bit field of
* values described in UARTIntEnable().
*
*/
unsigned long UART_Type::UARTIntStatus(int bMasked)
{
if(bMasked)
return(this->MIS);
return(this->RIS);
}
/**
*
* Clears UART interrupt sources.
*
* \param ulIntFlags is a bit mask of the interrupt sources to be cleared.
*
* The specified UART interrupt sources are cleared, so that they no longer
* assert. This must be done in the interrupt handler to keep it from being
* called again immediately upon exit.
*
* The \e ulIntFlags parameter has the same definition as the \e ulIntFlags
* parameter to UARTIntEnable().
*
* \note Since there is a write buffer in the Cortex-M3 processor, it may take
* several clock cycles before the interrupt source is actually cleared.
* Therefore, it is recommended that the interrupt source be cleared early in
* the interrupt handler (as opposed to the very last action) to avoid
* returning from the interrupt handler before the interrupt source is
* actually cleared. Failure to do so may result in the interrupt handler
* being immediately reentered (since NVIC still sees the interrupt source
* asserted).
*
* \return None.
*
*/
void UART_Type::UARTIntClear(unsigned long ulIntFlags)
{
this->ICR = ulIntFlags;
}
/**
*
* Enable UART DMA operation.
*
* \param ulDMAFlags is a bit mask of the DMA features to enable.
*
* The specified UART DMA features are enabled. The UART can be
* configured to use DMA for transmit or receive, and to disable
* receive if an error occurs. The \e ulDMAFlags parameter is the
* logical OR of any of the following values:
*
* - UART_DMA_RX - enable DMA for receive
* - UART_DMA_TX - enable DMA for transmit
* - UART_DMA_ERR_RXSTOP - disable DMA receive on UART error
*
* \note The uDMA controller must also be set up before DMA can be used
* with the UART.
*
* \return None.
*
*/
void UART_Type::UARTDMAEnable(unsigned long ulDMAFlags)
{
this->DMACTL |= ulDMAFlags;
}
/**
*
* Disable UART DMA operation.
*
* \param ulDMAFlags is a bit mask of the DMA features to disable.
*
* This function is used to disable UART DMA features that were enabled
* by UARTDMAEnable(). The specified UART DMA features are disabled. The
* \e ulDMAFlags parameter is the logical OR of any of the following values:
*
* - UART_DMA_RX - disable DMA for receive
* - UART_DMA_TX - disable DMA for transmit
* - UART_DMA_ERR_RXSTOP - do not disable DMA receive on UART error
*
* \return None.
*
*/
void UART_Type::UARTDMADisable(unsigned long ulDMAFlags)
{
this->DMACTL &= ~ulDMAFlags;
}
/**
*
* Gets current receiver errors.
*
* This function returns the current state of each of the 4 receiver error
* sources. The returned errors are equivalent to the four error bits
* returned via the previous call to UARTCharGet() or UARTCharGetNonBlocking()
* with the exception that the overrun error is set immediately the overrun
* occurs rather than when a character is next read.
*
* \return Returns a logical OR combination of the receiver error flags,
* \b UART_RXERROR_FRAMING, \b UART_RXERROR_PARITY, \b UART_RXERROR_BREAK
* and \b UART_RXERROR_OVERRUN.
*
*/
unsigned long UART_Type::UARTRxErrorGet(void)
{
return(this->RSR & 0x0000000F);
}
/**
*
* Clears all reported receiver errors.
*
* This function is used to clear all receiver error conditions reported via
* UARTRxErrorGet(). If using the overrun, framing error, parity error or
* break interrupts, this function must be called after clearing the interrupt
* to ensure that later errors of the same type trigger another interrupt.
*
* \return None.
*
*/
void UART_Type::UARTRxErrorClear(void)
{
this->ECR = 0;
}
/** @} ingroup lm3s_uart */
|
[
"[email protected]"
] |
[
[
[
1,
1068
]
]
] |
c2fc26a47627f85d3d354763522bd96be688d68e
|
6e5c32618b28d2c7a6175d2921e0baeb530183c1
|
/lvl_edit/random_class.h
|
9c7da0077681cad11bdbef727455903ba04c0164
|
[] |
no_license
|
RoestVrijStaal/warehousepanic
|
79a26e97026b0184a10c4a631dff5df0be8918dc
|
16eeba14c7e38b2b0eeddd90e5ac6970b0bff9a9
|
refs/heads/master
| 2020-05-20T08:04:19.112773 | 2010-06-09T19:03:54 | 2010-06-09T19:03:54 | 35,184,762 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 500 |
h
|
class random_class
{
public:
random_class() : change(false), active(false), dir(0), dir_amo(0) {}
sf::Sprite sprite;
sf::Sprite arrow_0;
sf::Sprite arrow_1;
sf::Sprite arrow_2;
bool change;
bool active;
short dir;
short dir_amo;
short speed;
int value;
int intervalmax;
int interval;
int delay;
std::vector<std::string> colors;
std::string color;
};
|
[
"[email protected]@03d7b61e-2572-11df-92c5-9faf7978932a",
"[email protected]@03d7b61e-2572-11df-92c5-9faf7978932a"
] |
[
[
[
1,
2
],
[
5,
20
]
],
[
[
3,
4
]
]
] |
81d79bbc27887db45af39e067a542dc3020c21aa
|
6dac9369d44799e368d866638433fbd17873dcf7
|
/src/branches/win32networkcode/PTHelper.h
|
2b8280cbf81695c92755b306b98da5bd15ad9709
|
[] |
no_license
|
christhomas/fusionengine
|
286b33f2c6a7df785398ffbe7eea1c367e512b8d
|
95422685027bb19986ba64c612049faa5899690e
|
refs/heads/master
| 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,569 |
h
|
#ifndef _PTHELPER_H_
#define _PTHELPER_H_
#include <pthread.h>
// Only need this function on win32
#ifdef _WIN32
#include <winsock2.h>
int _gettimeofday(struct timeval *tp, void *not_used);
#endif
/*
* Wrapper functions for pthread events (wraps up the ugliness)
*/
class Event{
public:
pthread_cond_t cond;
pthread_mutex_t mutex;
timeval now;
timespec time;
bool trigger;
inline Event(bool t)
{
trigger = t;
pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex,NULL);
}
inline ~Event()
{
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
}
inline void signal()
{
pthread_mutex_lock(&mutex);
trigger = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
inline int wait()
{
int result = 0;
pthread_mutex_lock(&mutex);
if(trigger == false) result = pthread_cond_wait(&cond,&mutex);
trigger = false;
pthread_mutex_unlock(&mutex);
return result;
}
inline int timedwait(int milliseconds)
{
if(milliseconds == INFINITE) return wait();
int result = 0;
pthread_mutex_lock(&mutex);
if(trigger == false){
// Create a timespec object with the time+waittime
_gettimeofday(&now, NULL);
time.tv_sec = now.tv_sec + (milliseconds/1000);
time.tv_nsec = (now.tv_usec*1000) + ((milliseconds % 1000) * 1000);
result = pthread_cond_timedwait(&cond,&mutex,&time);
}
trigger = false;
pthread_mutex_unlock(&mutex);
return result;
}
};
#endif // #ifndef _PTHELPER_H_
|
[
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] |
[
[
[
1,
80
]
]
] |
d8ec21124e220c439deb8bb47989d072dada2396
|
019f72b2dde7d0b9ab0568dc23ae7a0f4a41b2d1
|
/jot/Editor.h
|
5e4cbefe7558af2ffc947096cd09e47e49e503df
|
[] |
no_license
|
beketa/jot-for-X01SC
|
7bb74051f494172cb18b0f6afa5df055646eed25
|
5158fde188bec3aea4f5495da0dc5dfcd4c1663b
|
refs/heads/master
| 2020-04-05T06:29:04.125514 | 2010-07-10T05:36:49 | 2010-07-10T05:36:49 | 1,416,589 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,973 |
h
|
//
// jot - Text Editor for Windows Mobile
// Copyright (C) 2007-2008, Aquamarine Networks. <http://pandora.sblo.jp/>
//
// This program is EveryOne's ware; you can redistribute it and/or modify it
// under the terms of the NYSL version 0.9982 or later. <http://www.kmonos.net/nysl/>
//
#pragma once
// CEditor
#define EDITOR_INISTR_MAX 64
#define EDITOR_SELSTR_MAX 1024*1024
class CEditor : public CEdit
{
DECLARE_DYNAMIC(CEditor)
public:
CEditor();
virtual ~CEditor();
protected:
DECLARE_MESSAGE_MAP()
BOOL m_lastmodify;
bool m_bXscrawl;
TCHAR m_inistr[EDITOR_INISTR_MAX+1];
bool m_bRegex;
bool m_bNoCase;
UINT m_modeXscrawl;
void DoXscrawl( bool up );
unsigned int m_wordwrap_pos_p;
unsigned int m_wordwrap_pos_l;
TCHAR * m_buffer;
int m_bufferLen;
TCHAR * GetBuffer();
BOOL SetBuffer( const TCHAR * buff, int size );
protected:
afx_msg LRESULT OnEnterMenuLoop(WPARAM wp, LPARAM lp);
afx_msg LRESULT OnExitMenuLoop(WPARAM wp, LPARAM lp);
afx_msg void OnContextMenu(CWnd* /*pWnd*/, CPoint /*point*/);
afx_msg void OnEditCopy();
afx_msg void OnEditCut();
afx_msg void OnEditPaste();
afx_msg void OnEditUndo();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnEnChange();
afx_msg void OnShiftLock();
virtual BOOL PreTranslateMessage(MSG* pMsg);
afx_msg void OnSelectall();
afx_msg void OnJumpEnd();
afx_msg void OnJumpHome();
afx_msg void OnJumpNext();
afx_msg void OnJumpPrev();
afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
afx_msg void OnSetFocus(CWnd* pOldWnd);
public:
BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID);
void SetXscrawl( UINT mode )
{
m_modeXscrawl = mode;
}
void SetModify(BOOL bModified = 1){
m_lastmodify = bModified;
__super::SetModify( bModified );
}
void SetWordwrap( BOOL wrap );
void SetWordwrapPos( unsigned int portrait ,unsigned int landscape );
BOOL SetMemory( const TCHAR *buff , int size );
const TCHAR *GetMemory( );
void JumpLineNo(int lineno);
void FindString( CString str , bool down , bool first );
void Replace( CString str ,CString rep , bool down );
void ReplaceAll( CString str ,CString rep );
void SetDrawSymbol( DWORD flags );
const TCHAR * GetFindInistr();
CString GetSelectedStr();
void SetRegex( bool b ){ m_bRegex = b; }
void SetNoCase( bool b ){m_bNoCase = b; }
void SetColor( int code , DWORD color );
void SetSpacing(int spacing);
void SetUnderline( BOOL value );
void SetNotFocusIme( BOOL value );
void SetBsWmChar( BOOL value );
void SetDrawLineNumber( BOOL value );
void Relocate();
};
enum XscrawlMode {
None = 0,
line05,
line10,
line15,
line20,
page,
line01,
line02,
};
#ifndef DS_LINEBREAK
#define DS_LINEBREAK (0x00000001)
#define DS_TAB (0x00000002)
#define DS_SPACE (0x00000004)
#define DS_WIDESPACE (0x00000008)
#endif
|
[
"[email protected]"
] |
[
[
[
1,
118
]
]
] |
489e219b1d9daa6ded700a73c33fed9d4e57279e
|
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
|
/pyplusplus_dev/unittests/data/ctypes/circular_references/circular_references.cpp
|
e0859863387a567f5be65d825b3f3e16a80e1275
|
[
"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 | 64 |
cpp
|
#include "circular_references.h"
void use_bar( bar_t* ){
}
|
[
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] |
[
[
[
1,
4
]
]
] |
4c0ad843fd5dbbaa04977ae6293cde95a240fe55
|
ee2f2896bed8455be9564b88666b18ad5eaf9386
|
/Server/Emu-CV/Emgu.CV.SourceAndExample-1.5.0.1/src/Emgu.CV.Extern/cvANN_MLP.cpp
|
059508b16f28ef96661459b2c60b9edb84553e85
|
[] |
no_license
|
ajdabiya/Pikling
|
512b190f0e810818ad9f1b68c2001a2b2095d6e9
|
f58082b0be767994ea09e64613b83eea3e9b1497
|
refs/heads/master
| 2023-03-18T18:08:40.528800 | 2011-06-08T03:46:53 | 2011-06-08T03:46:53 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 834 |
cpp
|
#include "cvextern.h"
CvANN_MLP* CvANN_MLPCreate(const CvMat* _layer_sizes,
int _activ_func,
double _f_param1, double _f_param2 )
{
return new CvANN_MLP(_layer_sizes, _activ_func, _f_param1, _f_param2);
}
void CvANN_MLPRelease(CvANN_MLP* model)
{
model->~CvANN_MLP();
}
int CvANN_MLPTrain(CvANN_MLP* model, const CvMat* _inputs, const CvMat* _outputs,
const CvMat* _sample_weights, const CvMat* _sample_idx,
CvANN_MLP_TrainParams _params,
int flags)
{
return model->train(_inputs, _outputs, _sample_weights, _sample_idx, _params, flags);
}
float CvANN_MLPPredict(CvANN_MLP* model, const CvMat* _inputs,
CvMat* _outputs )
{
return model->predict(_inputs, _outputs);
}
|
[
"[email protected]"
] |
[
[
[
1,
27
]
]
] |
9eec69fe2782a7bd5cd3ca97fedd6f8658a0368c
|
b88e3fe619adf0d3c56251f63afb63aba25fceaa
|
/casting.cpp
|
2aa65248b354a9f2895325df9550c1acde2ffdc5
|
[] |
no_license
|
pads/cplusplus-scratchpad
|
e4bfac971ab00cb9d95d3f0d1f01fe4f3224dca3
|
1deeac43c8d341ad1661c09b9aab22cf5c1ab9df
|
refs/heads/master
| 2020-05-18T11:56:56.037725 | 2011-03-30T17:24:38 | 2011-03-30T17:24:38 | 1,537,188 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 125 |
cpp
|
int main() {
int a = 5;
double b;
// easier to search for casts than using ()
b = static_cast<double>(a + 10) / 7;
}
|
[
"[email protected]"
] |
[
[
[
1,
6
]
]
] |
8fd1c7a4de70d61acf6e7339c331969659b3dba6
|
ef23e388061a637f82b815d32f7af8cb60c5bb1f
|
/src/mame/includes/matmania.h
|
f0244c4c477076c90b9fbe2c232906d96b55c609
|
[] |
no_license
|
marcellodash/psmame
|
76fd877a210d50d34f23e50d338e65a17deff066
|
09f52313bd3b06311b910ed67a0e7c70c2dd2535
|
refs/heads/master
| 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,038 |
h
|
class matmania_state : public driver_device
{
public:
matmania_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT8 * m_videoram;
UINT8 * m_videoram2;
UINT8 * m_videoram3;
UINT8 * m_colorram;
UINT8 * m_colorram2;
UINT8 * m_colorram3;
UINT8 * m_scroll;
UINT8 * m_pageselect;
UINT8 * m_spriteram;
UINT8 * m_paletteram;
size_t m_videoram_size;
size_t m_videoram2_size;
size_t m_videoram3_size;
size_t m_spriteram_size;
/* video-related */
bitmap_t *m_tmpbitmap;
bitmap_t *m_tmpbitmap2;
/* mcu */
/* maniach 68705 protection */
UINT8 m_port_a_in;
UINT8 m_port_a_out;
UINT8 m_ddr_a;
UINT8 m_port_b_in;
UINT8 m_port_b_out;
UINT8 m_ddr_b;
UINT8 m_port_c_in;
UINT8 m_port_c_out;
UINT8 m_ddr_c;
UINT8 m_from_main;
UINT8 m_from_mcu;
int m_mcu_sent;
int m_main_sent;
/* devices */
device_t *m_maincpu;
device_t *m_audiocpu;
device_t *m_mcu;
};
/*----------- defined in machine/maniach.c -----------*/
READ8_HANDLER( maniach_68705_port_a_r );
WRITE8_HANDLER( maniach_68705_port_a_w );
READ8_HANDLER( maniach_68705_port_b_r );
WRITE8_HANDLER( maniach_68705_port_b_w );
READ8_HANDLER( maniach_68705_port_c_r );
WRITE8_HANDLER( maniach_68705_port_c_w );
WRITE8_HANDLER( maniach_68705_ddr_a_w );
WRITE8_HANDLER( maniach_68705_ddr_b_w );
WRITE8_HANDLER( maniach_68705_ddr_c_w );
WRITE8_HANDLER( maniach_mcu_w );
READ8_HANDLER( maniach_mcu_r );
READ8_HANDLER( maniach_mcu_status_r );
/*----------- defined in video/matmania.c -----------*/
WRITE8_HANDLER( matmania_paletteram_w );
PALETTE_INIT( matmania );
SCREEN_UPDATE( maniach );
VIDEO_START( matmania );
SCREEN_UPDATE( matmania );
|
[
"Mike@localhost"
] |
[
[
[
1,
72
]
]
] |
9db69b3e91ce58f089fc3d69ddfc551f1f3c8289
|
faa30f88bd88c37ad26aeda4571668db572a140d
|
/Geometry.cpp
|
ce125b820ee343bfc7ce1d6c719162a6828808ad
|
[] |
no_license
|
simophin/remotevision
|
88fa6ea7183c79c239474d330c05b2879836735b
|
2f28b9fbb82a5b92a36e0a2b1ead067dbf0e55ab
|
refs/heads/master
| 2016-09-05T18:07:42.069906 | 2011-06-16T08:42:31 | 2011-06-16T08:42:31 | 1,744,350 | 2 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 887 |
cpp
|
/*
* Geometry.cpp
*
* Created on: 2011-5-14
* Author: simophin
*/
#include "Geometry.h"
#include "RString.h"
#include <vector>
#include "utils/String.hpp"
Geometry Geometry::
fromString (const String & str) {
Geometry ret;
std::vector<String> gargs;
gargs = Utils::split< std::vector<String> >(str,',');
if (gargs.size() != 2) return ret;
ret.width = Utils::stringToInteger(gargs.at(0));
ret.height = Utils::stringToInteger(gargs.at(1));
return ret;
}
String Geometry::
toString () const {
std::stringstream ret;
ret << width << "," << height;
return ret.str();
}
bool Geometry::
isValid() const {
return (width > 0 && height > 0);
}
void Geometry::
invalid() {
width = height = -1;
}
bool Geometry::operator ==(const Geometry & rhs) const
{
return (width == rhs.width && height == rhs.height);
}
|
[
"[email protected]",
"simophin@localhost",
"Fanchao [email protected]",
"[email protected]"
] |
[
[
[
1,
9
],
[
14,
15
],
[
17,
18
],
[
21,
23
],
[
26,
29
],
[
31,
31
],
[
33,
33
],
[
35,
35
],
[
37,
47
]
],
[
[
10,
10
],
[
12,
13
],
[
24,
25
]
],
[
[
11,
11
],
[
16,
16
],
[
19,
20
],
[
30,
30
]
],
[
[
32,
32
],
[
34,
34
],
[
36,
36
],
[
48,
54
]
]
] |
3351d3f1e29472fbbd291c37d231462f18b65cc5
|
45c0d7927220c0607531d6a0d7ce49e6399c8785
|
/GlobeFactory/src/gfx/material_mng.cc
|
feaeb05c7fd08e7199905ca6c82314137f2f3aee
|
[] |
no_license
|
wavs/pfe-2011-scia
|
74e0fc04e30764ffd34ee7cee3866a26d1beb7e2
|
a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a
|
refs/heads/master
| 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,082 |
cc
|
#include "material_mng.hh"
#include "../useful/xml_loader.hh"
#include "material_def/all.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
const unsigned MATERIAL_PREPARED_SPACE = 64;
const std::string MATERIAL_ERROR_FILENAME = "error.txt";
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
MaterialMng::MaterialMng()
: MMaterials(MATERIAL_PREPARED_SPACE)
{
for (unsigned i = 0; i < MaterialEnum::COUNT; ++i)
MMaterialLoaders[i] = NULL;
MMaterialLoaders[MaterialEnum::NONE] = new NoneMaterialDescriptor();
MMaterialLoaders[MaterialEnum::INTERFACE2D] = new Interface2DMaterialDescriptor();
MMaterialLoaders[MaterialEnum::WATER] = new WaterMaterialDescriptor();
MMaterialLoaders[MaterialEnum::SIMPLE_COLOR] = new SimpleColorMaterialDescriptor();
MMaterialLoaders[MaterialEnum::SIMPLE_TEXTURE] = new SimpleTextureMaterialDescriptor();
MMaterialLoaders[MaterialEnum::TEXT] = new TextMaterialDescriptor();
MMaterialLoaders[MaterialEnum::ANIMATED] = new AnimatedMaterialDescriptor();
for (unsigned i = 1; i < MaterialEnum::COUNT; ++i)
LOG_ASSERT_WITH_DESC(MMaterialLoaders[i] != NULL, "Material Descriptor not linker in the MaterialMng");
for (unsigned i = 0; i < MATERIAL_PREPARED_SPACE; ++i)
MMaterials[i] = NULL;
LoadMaterial(MATERIAL_ERROR_FILENAME);
MMaterials[NONE_ID] = new NoneMaterial();
LOG_ASSERT(MMaterials[ERROR_ID] != NULL);
LOG_ASSERT(MMaterials[NONE_ID] != NULL);
LOG_RESUME("MaterialMng", "NoneMaterial(1) loaded");
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
MaterialMng::~MaterialMng()
{
for (unsigned i = 0; i < MaterialEnum::COUNT; ++i)
delete MMaterialLoaders[i];
delete MMaterials[ERROR_ID];
delete MMaterials[NONE_ID];
unsigned size = MMaterials.size();
for (unsigned i = 2; i < size; ++i)
{
LOG_ASSERT(MMaterials[i] == NULL);
delete MMaterials[i];
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
unsigned MaterialMng::LoadMaterial(const std::string& parFilename)
{
LOG_ASSERT(!parFilename.empty());
unsigned size = MMaterials.size();
for (unsigned i = 0; i < size; ++i)
{
Material* material = MMaterials[i];
if (material != NULL && material->GetFilename() == parFilename)
{
material->IncRefCount();
return i;
}
}
ConfigMng* cfgMng = ConfigMng::get();
unsigned fileId = cfgMng->Load(std::string("material/") + parFilename);
const std::string* type = cfgMng->GetOptionStr(fileId, "type");
if (type == NULL)
{
LOG_ERROR("Material Mng", "Unable to open the material " + parFilename);
cfgMng->Unload(fileId);
return 0;
}
MaterialEnum::Type materialType = MaterialEnum::COUNT;
for (unsigned i = 0; i < MaterialEnum::COUNT; ++i)
if (MaterialEnum::ToString[i] == *type)
{
materialType = static_cast<MaterialEnum::Type>(i);
break;
}
if (materialType == MaterialEnum::COUNT)
{
LOG_ERROR("Material Mng", "The type of the material " + parFilename + " is unknow.");
return 0;
}
Material* material = MMaterialLoaders[materialType]->Load(fileId);
if (material == NULL)
{
LOG_ERROR("Material Mng", "Invalid material " + parFilename);
cfgMng->Unload(fileId);
return 0;
}
cfgMng->Unload(fileId);
size = MMaterials.size();
for (unsigned i = 0; i < size; ++i)
if (MMaterials[i] == NULL)
{
MMaterials[i] = material;
LOG_RESUME("MaterialMng", "New material(" + misc::ToString(i) + ") loaded : " + parFilename);
return i;
}
MMaterials.push_back(material);
LOG_RESUME("MaterialMng", "New material(" + misc::ToString(size) + ") loaded : " + parFilename);
return size;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void MaterialMng::UnloadMaterial(unsigned parId)
{
LOG_ASSERT(parId < MMaterials.size());
if (parId <= 1)
return;
LOG_ASSERT(MMaterials[parId] != NULL);
MMaterials[parId]->DecRefCount();
if (MMaterials[parId]->GetRefCount() == 0)
{
delete MMaterials[parId];
MMaterials[parId] = NULL;
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void MaterialMng::AddUserOnMaterial(unsigned parId)
{
LOG_ASSERT(parId < MMaterials.size());
LOG_ASSERT(MMaterials[parId] != NULL);
if (parId <= 1)
return;
MMaterials[parId]->IncRefCount();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
unsigned MaterialMng::LoadTextMaterial(Font* parFont, const std::string& parText, Vector2i& parSize, int parStyle)
{
TextMaterial* textMaterial = new TextMaterial(parFont, parText, parSize, parStyle);
unsigned size = MMaterials.size();
for (unsigned i = 0; i < size; ++i)
if (MMaterials[i] == NULL)
{
MMaterials[i] = textMaterial;
return i;
}
MMaterials.push_back(textMaterial);
LOG_RESUME("MaterialMng", "New TextMaterial(" + misc::ToString(size) + ") loaded : " + parText);
return size;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void MaterialMng::PreRenderForMaterial(unsigned parId)
{
LOG_ASSERT(parId <= MMaterials.size());
if (MMaterials[parId] != NULL)
MMaterials[parId]->PreRender();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void MaterialMng::PostRenderForMaterial(unsigned parId)
{
LOG_ASSERT(parId <= MMaterials.size());
if (MMaterials[parId] != NULL)
MMaterials[parId]->PostRender();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
MaterialEnum::Type MaterialMng::GetMaterialType(unsigned parId) const
{
LOG_ASSERT(parId <= MMaterials.size());
LOG_ASSERT(MMaterials[parId] != NULL);
return MMaterials[parId]->GetType();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
|
[
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
] |
[
[
[
1,
212
]
]
] |
71890625b896592173304523aeadaf432e790a4c
|
e3e5243690bd626c79678fdf287ef23c99060263
|
/opensteer/include/OpenSteer/SimpleVehicle.h
|
a317f5c67fe09bbe7e9c9c53553b2e22c547787b
|
[
"MIT"
] |
permissive
|
Shulander/steeringfluid
|
a6e6c62b719cdfe2f071eec33dfec2f32e3095a1
|
3712b0fc4f00b7c0da563ee887f55229af50d741
|
refs/heads/master
| 2021-01-25T08:38:09.460551 | 2009-05-27T02:14:24 | 2009-05-27T02:14:24 | 40,906,080 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 10,498 |
h
|
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// SimpleVehicle
//
// A steerable point mass with a velocity-aligned local coordinate system.
// SimpleVehicle is useful for developing prototype vehicles in OpenSteerDemo,
// it is the base class for vehicles in the PlugIns supplied with OpenSteer.
// Note that SimpleVehicle is intended only as sample code. Your application
// can use the OpenSteer library without using SimpleVehicle, as long as you
// implement the AbstractVehicle protocol.
//
// SimpleVehicle makes use of the "mixin" concept from OOP. To quote
// "Mixin-Based Programming in C++" a clear and helpful paper by Yannis
// Smaragdakis and Don Batory (http://citeseer.nj.nec.com/503808.html):
//
// ...The idea is simple: we would like to specify an extension without
// predetermining what exactly it can extend. This is equivalent to
// specifying a subclass while leaving its superclass as a parameter to be
// determined later. The benefit is that a single class can be used to
// express an incremental extension, valid for a variety of classes...
//
// In OpenSteer, vehicles are defined by an interface: an abstract base class
// called AbstractVehicle. Implementations of that interface, and related
// functionality (like steering behaviors and vehicle physics) are provided as
// template-based mixin classes. The intent of this design is to allow you to
// reuse OpenSteer code with your application's own base class.
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 01-29-03 cwr: created
//
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_SIMPLEVEHICLE_H
#define OPENSTEER_SIMPLEVEHICLE_H
#include "OpenSteer/AbstractVehicle.h"
#include "OpenSteer/SteerLibrary.h"
#include "OpenSteer/Annotation.h"
namespace OpenSteer {
// ----------------------------------------------------------------------------
// SimpleVehicle_1 adds concrete LocalSpace methods to AbstractVehicle
typedef LocalSpaceMixin<AbstractVehicle> SimpleVehicle_1;
// SimpleVehicle_2 adds concrete annotation methods to SimpleVehicle_1
typedef AnnotationMixin<SimpleVehicle_1> SimpleVehicle_2;
// SimpleVehicle_3 adds concrete steering methods to SimpleVehicle_2
typedef SteerLibraryMixin<SimpleVehicle_2> SimpleVehicle_3;
// SimpleVehicle adds concrete vehicle methods to SimpleVehicle_3
class SimpleVehicle : public SimpleVehicle_3
{
public:
// constructor
SimpleVehicle ();
// destructor
~SimpleVehicle ();
// reset vehicle state
void reset (void)
{
// reset LocalSpace state
resetLocalSpace ();
// reset SteerLibraryMixin state
// (XXX this seems really fragile, needs to be redesigned XXX)
SimpleVehicle_3::reset ();
setMass (1); // mass (defaults to 1 so acceleration=force)
setSpeed (0); // speed along Forward direction.
setRadius (0.5f); // size of bounding sphere
setMaxForce (0.1f); // steering force is clipped to this magnitude
setMaxSpeed (1.0f); // velocity is clipped to this magnitude
// reset bookkeeping to do running averages of these quanities
resetSmoothedPosition ();
resetSmoothedCurvature ();
resetSmoothedAcceleration ();
}
// get/set mass
float mass (void) const {return _mass;}
float setMass (float m) {return _mass = m;}
// get velocity of vehicle
Vec3 velocity (void) const {return forward() * _speed;}
// get/set speed of vehicle (may be faster than taking mag of velocity)
float speed (void) const {return _speed;}
float setSpeed (float s) {return _speed = s;}
// size of bounding sphere, for obstacle avoidance, etc.
float radius (void) const {return _radius;}
float setRadius (float m) {return _radius = m;}
// get/set maxForce
float maxForce (void) const {return _maxForce;}
float setMaxForce (float mf) {return _maxForce = mf;}
// get/set maxSpeed
float maxSpeed (void) const {return _maxSpeed;}
float setMaxSpeed (float ms) {return _maxSpeed = ms;}
// apply a given steering force to our momentum,
// adjusting our orientation to maintain velocity-alignment.
void applySteeringForce (const Vec3& force, const float deltaTime);
// the default version: keep FORWARD parallel to velocity, change
// UP as little as possible.
virtual void regenerateLocalSpace (const Vec3& newVelocity,
const float elapsedTime);
// alternate version: keep FORWARD parallel to velocity, adjust UP
// according to a no-basis-in-reality "banking" behavior, something
// like what birds and airplanes do. (XXX experimental cwr 6-5-03)
void regenerateLocalSpaceForBanking (const Vec3& newVelocity,
const float elapsedTime);
// adjust the steering force passed to applySteeringForce.
// allows a specific vehicle class to redefine this adjustment.
// default is to disallow backward-facing steering at low speed.
// xxx experimental 8-20-02
virtual Vec3 adjustRawSteeringForce (const Vec3& force,
const float deltaTime);
// apply a given braking force (for a given dt) to our momentum.
// xxx experimental 9-6-02
void applyBrakingForce (const float rate, const float deltaTime);
// predict position of this vehicle at some time in the future
// (assumes velocity remains constant)
Vec3 predictFuturePosition (const float predictionTime) const;
// get instantaneous curvature (since last update)
float curvature (void) const {return _curvature;}
// get/reset smoothedCurvature, smoothedAcceleration and smoothedPosition
float smoothedCurvature (void) {return _smoothedCurvature;}
float resetSmoothedCurvature (float value = 0)
{
_lastForward = Vec3::zero;
_lastPosition = Vec3::zero;
return _smoothedCurvature = _curvature = value;
}
Vec3 smoothedAcceleration (void) {return _smoothedAcceleration;}
Vec3 resetSmoothedAcceleration (const Vec3& value = Vec3::zero)
{
return _smoothedAcceleration = value;
}
Vec3 smoothedPosition (void) {return _smoothedPosition;}
Vec3 resetSmoothedPosition (const Vec3& value = Vec3::zero)
{
return _smoothedPosition = value;
}
// give each vehicle a unique number
int serialNumber;
static int serialNumberCounter;
// draw lines from vehicle's position showing its velocity and acceleration
void annotationVelocityAcceleration (float maxLengthA, float maxLengthV);
void annotationVelocityAcceleration (float maxLength)
{annotationVelocityAcceleration (maxLength, maxLength);}
void annotationVelocityAcceleration (void)
{annotationVelocityAcceleration (3, 3);}
// set a random "2D" heading: set local Up to global Y, then effectively
// rotate about it by a random angle (pick random forward, derive side).
void randomizeHeadingOnXZPlane (void)
{
setUp (Vec3::up);
setForward (RandomUnitVectorOnXZPlane ());
setSide (localRotateForwardToSide (forward()));
}
private:
float _mass; // mass (defaults to unity so acceleration=force)
float _radius; // size of bounding sphere, for obstacle avoidance, etc.
float _speed; // speed along Forward direction. Because local space
// is velocity-aligned, velocity = Forward * Speed
float _maxForce; // the maximum steering force this vehicle can apply
// (steering force is clipped to this magnitude)
float _maxSpeed; // the maximum speed this vehicle is allowed to move
// (velocity is clipped to this magnitude)
float _curvature;
Vec3 _lastForward;
Vec3 _lastPosition;
Vec3 _smoothedPosition;
float _smoothedCurvature;
Vec3 _smoothedAcceleration;
// measure path curvature (1/turning-radius), maintain smoothed version
void measurePathCurvature (const float elapsedTime);
};
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_SIMPLEVEHICLE_H
|
[
"shulander@85a90f13-b34b-0410-994f-f76cd5410383"
] |
[
[
[
1,
252
]
]
] |
6e4a6e6f5de92a0e5a2b0a27ce63dfa01e0c2fb5
|
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
|
/libproject/Apputility/stdafx.h
|
067c73c12845f0aa7ce4d86fe88fe5b7a18dddd2
|
[] |
no_license
|
weimingtom/httpcontentparser
|
4d5ed678f2b38812e05328b01bc6b0c161690991
|
54554f163b16a7c56e8350a148b1bd29461300a0
|
refs/heads/master
| 2021-01-09T21:58:30.326476 | 2009-09-23T08:05:31 | 2009-09-23T08:05:31 | 48,733,304 | 3 | 0 | null | null | null | null |
GB18030
|
C++
| false | false | 962 |
h
|
// stdafx.h : 标准系统包含文件的包含文件,
// 或是常用但不常更改的项目特定的包含文件
//
#pragma once
#define WIN32_LEAN_AND_MEAN // 从 Windows 头中排除极少使用的资料
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // 某些 CString 构造函数将为显式的
#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN // 从 Windows 头中排除极少使用的资料
#endif
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <conio.h>
#include <process.h>
#include <assert.h>
#include <winsock2.h>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <aclapi.h>
#pragma comment(lib, "strsafe.lib")
#pragma comment(lib, "Version.lib")
#pragma comment(lib, "Advapi32.lib")
#pragma comment(lib, "ws2_32.lib")
#ifdef _DEBUG
# pragma comment(lib, "utilityd.lib")
#else
# pragma comment(lib, "utility.lib")
#endif
|
[
"ynkhpp@1a8edc88-4151-0410-b40c-1915dda2b29b",
"[email protected]"
] |
[
[
[
1,
14
],
[
16,
16
],
[
24,
24
]
],
[
[
15,
15
],
[
17,
23
],
[
25,
40
]
]
] |
d195a9119b2d58d8667ddd4f41c51f58684e7066
|
45c0d7927220c0607531d6a0d7ce49e6399c8785
|
/GlobeFactory/src/game/state_change_listener.hh
|
416e4aaabace7fa881055917a2366e91c435b06d
|
[] |
no_license
|
wavs/pfe-2011-scia
|
74e0fc04e30764ffd34ee7cee3866a26d1beb7e2
|
a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a
|
refs/heads/master
| 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,337 |
hh
|
////////////////////////////////////////////////////////////////////////////////
// Filename : state_change_listener.hh
// Authors : Creteur Clement
// Last edit : 11/11/09 - 16h30
// Comment :
////////////////////////////////////////////////////////////////////////////////
#ifndef GAME_STATE_CHANGE_LISTENER_HH
#define GAME_STATE_CHANGE_LISTENER_HH
#include "../useful/auto_listener.hh"
#include "state_handler.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class StateChangeListener : public AutoListener<StateChangeListener, StateHandler>
{
public:
StateChangeListener() {}
virtual ~StateChangeListener() {}
inline virtual void OnLeaveMenu() {}
inline virtual void OnLeaveIngame() {}
inline virtual void OnLeaveCinematic() {}
inline virtual void OnLeaveLoading() {}
inline virtual void OnLaunchMenu() {}
inline virtual void OnLaunchIngame() {}
inline virtual void OnLaunchCinematic() {}
inline virtual void OnLaunchLoading() {}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#endif
|
[
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
] |
[
[
[
1,
36
]
]
] |
4993f920e331152eb0cc60a1352b3b8ea3809fec
|
01fadae9f2a6d3f19bc843841a7faa9c40fc4a20
|
/CG/code_CG/EX06_05.CPP
|
53ea7604b3ad1450071503638de51ae56c8c0a09
|
[] |
no_license
|
passzenith/passzenithproject
|
9999da29ac8df269c41d280137113e1e2638542d
|
67dd08f4c3a046889319170a89b45478bfd662d2
|
refs/heads/master
| 2020-12-24T14:36:46.389657 | 2010-09-05T02:34:42 | 2010-09-05T02:34:42 | 32,310,266 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 2,271 |
cpp
|
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#define ESCAPE 27
GLint window;
void init (void)
{
glClearColor (1.0, 1.0, 1, 0.0);
glLineWidth(1.0);
glColor3f (1.0, 0.0, 0.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho(-6,6,-6,6,-6,6);
}
void myDisplay (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glPushMatrix();
glBegin (GL_LINES); // Draw x-axis
glVertex2f (-5.5, 0.0);
glVertex2f ( 5.5, 0.0);
glEnd ( );
glBegin (GL_LINES); // Draw y-axis
glVertex2f (0.0,-5.5);
glVertex2f (0.0, 5.5);
glEnd ( );
glBegin (GL_LINES); // Draw y=x
glVertex2f (-5.5,-5.5);
glVertex2f ( 5.5, 5.5);
glEnd ( );
glBegin (GL_POLYGON);
glVertex2f (2.0, 3.0);
glVertex2f (1.0, 5.0);
glVertex2f (0.0, 4.0);
glEnd ( );
glBegin (GL_POLYGON);
glVertex2f (-1.0, -5.0);
glVertex2f (-2.0, -3.0);
glVertex2f (-4.0, -5.0);
glEnd ( );
glPopMatrix();
glutSwapBuffers();
glFlush ( );
}
void KeyboardAssign (GLubyte key, GLint x, GLint y)
{
switch ( key )
{
case ESCAPE :
printf("escape pressed. exit.\n");
glutDestroyWindow(window);
exit(0);
break;
case 'x':
glColor3f (0.0, 0.0, 1.0);
glPopMatrix();
glRotatef(-45, 1.0, 1.0, 0.0);
glRotatef(180, 1.0, 1.0, 0.0);
glRotatef( 45, 1.0, 1.0, 0.0);
glPopMatrix();
glBegin (GL_POLYGON);
glVertex2f (2.0, 3.0);
glVertex2f (1.0, 5.0);
glVertex2f (0.0, 4.0);
glEnd ( );
glBegin (GL_POLYGON);
glVertex2f (-1.0, -5.0);
glVertex2f (-2.0, -3.0);
glVertex2f (-4.0, -5.0);
glEnd ( );
glutSwapBuffers();
glutPostRedisplay();
break;
default:
break;
}
}
int main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (50, 50);
glutInitWindowSize(500, 500);
glutCreateWindow("Reflect y=x : Press x for reflect y=x");
init();
glutDisplayFunc(myDisplay);
glutIdleFunc(myDisplay);
glutKeyboardFunc(KeyboardAssign);
glutMainLoop();
return 0;
}
|
[
"passzenith@00fadc5f-a3f2-dbaa-0561-d91942954633"
] |
[
[
[
1,
110
]
]
] |
45c9dab17b83ec3d3f40157835e50a31d36989e4
|
11da90929ba1488c59d25c57a5fb0899396b3bb2
|
/Src/HistoryCache.cpp
|
fbc967726540b08988586d3f3424dde8ae3a0caf
|
[] |
no_license
|
danste/ars-framework
|
5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6
|
90f99d43804d3892432acbe622b15ded6066ea5d
|
refs/heads/master
| 2022-11-11T15:31:02.271791 | 2005-10-17T15:37:36 | 2005-10-17T15:37:36 | 263,623,421 | 0 | 0 | null | 2020-05-13T12:28:22 | 2020-05-13T12:28:21 | null |
UTF-8
|
C++
| false | false | 11,959 |
cpp
|
#include <HistoryCache.hpp>
#include <Serializer.hpp>
#include <SysUtils.hpp>
#include <DataStore.hpp>
#include <Text.hpp>
#include <Logging.hpp>
#ifdef __MWERKS__
using std::memcpy;
#endif
//#define DEBUG_URLS
#define HISTORY_CACHE_INDEX_STREAM "_History Cache Index"
enum {
serialIdIndexVersion,
serialIdItemsCount
};
HistoryCache::HistoryCache():
indexEntries_(NULL),
indexEntriesCount_(0),
indexCapacity_(0),
dataStore(NULL),
dataStoreOwner_(false)
{
}
HistoryCache::~HistoryCache()
{
close();
}
void HistoryCache::close()
{
if (NULL != indexEntries_)
{
if (NULL != dataStore)
writeIndex();
delete [] indexEntries_;
indexEntries_ = NULL;
indexEntriesCount_ = 0;
indexCapacity_ = 0;
}
if (dataStoreOwner_)
delete dataStore;
dataStore = NULL;
dataStoreOwner_ = false;
}
status_t HistoryCache::open(DataStore& ds)
{
close();
dataStore = &ds;
return readIndex();
}
status_t HistoryCache::open(const char_t* dsName)
{
close();
dataStore = new_nt DataStore();
if (NULL == dataStore)
return memErrNotEnoughSpace;
dataStoreOwner_ = true;
status_t err = dataStore->open(dsName, DataStore::createAsNeeded);
if (errNone != err)
return err;
return readIndex();
}
HistoryCache::IndexEntry::IndexEntry()
{
memzero(this, sizeof(*this));
}
status_t HistoryCache::readIndex()
{
assert(NULL != dataStore);
DataStoreReader reader(*dataStore);
status_t err = reader.open(HISTORY_CACHE_INDEX_STREAM);
if (errNone != err)
{
FreshIndex:
indexCapacity_ = 0;
indexEntriesCount_ = 0;
delete [] indexEntries_;
indexEntries_ = new_nt IndexEntry[maxCacheEntries];
if (NULL == indexEntries_)
return memErrNotEnoughSpace;
indexCapacity_ = maxCacheEntries;
return errNone;
}
Serializer serialize(reader);
err = serializeIndexIn(serialize);
if (errNone != err)
{
LogStrUlong(eLogError, _T("HistoryCache::readIndex(): serializeIndexIn() returned error: "), err);
goto FreshIndex;
}
return err;
}
status_t HistoryCache::serializeIndexIn(Serializer& serialize)
{
ErrTry {
ulong_t cap = maxCacheEntries;
ulong_t count;
serialize(count, serialIdIndexVersion);
serialize(count, serialIdItemsCount);
if (count > maxCacheEntries)
cap = count;
indexEntries_ = new_nt IndexEntry[cap];
if (NULL == indexEntries_)
ErrReturn(memErrNotEnoughSpace);
indexCapacity_ = cap;
for (ulong_t i = 0; i < count; ++i)
{
IndexEntry& entry = indexEntries_[i];
serialize.narrowBuffer(entry.url, maxCacheEntryUrlLength + 1);
#ifdef DEBUG_URLS
assert('s' == *entry.url);
#endif
serialize.narrowBuffer(entry.streamName, DataStore::maxStreamNameLength + 1);
serialize.textBuffer(entry.title, maxCacheEntryTitleLength + 1);
serialize(entry.onlyLink);
}
indexEntriesCount_ = count;
}
ErrCatch(ex) {
return ex;
} ErrEndCatch
return errNone;
}
status_t HistoryCache::writeIndex()
{
assert(NULL != dataStore);
DataStoreWriter writer(*dataStore);
status_t err = writer.open(HISTORY_CACHE_INDEX_STREAM);
if (errNone != err)
return err;
Serializer serialize(writer);
return serializeIndexOut(serialize);
}
status_t HistoryCache::serializeIndexOut(Serializer& serialize)
{
ErrTry {
ulong_t indexVersion = 1;
serialize(indexVersion, serialIdIndexVersion);
serialize(indexEntriesCount_, serialIdItemsCount);
for (ulong_t i = 0; i < indexEntriesCount_; ++i)
{
IndexEntry& entry = indexEntries_[i];
#ifdef DEBUG_URLS
assert('s' == *entry.url);
#endif
serialize.narrowOut(entry.url);
#ifdef DEBUG_URLS
assert('s' == *entry.url);
#endif
serialize.narrowOut(entry.streamName);
serialize.textOut(entry.title);
serialize(entry.onlyLink);
}
}
ErrCatch(ex) {
return ex;
} ErrEndCatch
return errNone;
}
ulong_t HistoryCache::entryIndex(const char* entry) const
{
for (long i = long(indexEntriesCount_) - 1; i >= 0; --i)
{
if (StrEquals(entry, indexEntries_[i].url))
return ulong_t(i);
}
return entryNotFound;
}
const char* HistoryCache::entryUrl(ulong_t index) const
{
assert(index < indexEntriesCount_);
return indexEntries_[index].url;
}
const char_t* HistoryCache::entryTitle(ulong_t index) const
{
assert(index < indexEntriesCount_);
return indexEntries_[index].title;
}
bool HistoryCache::entryIsOnlyLink(ulong_t index) const
{
assert(index < indexEntriesCount_);
return indexEntries_[index].onlyLink;
}
void HistoryCache::setEntryTitle(ulong_t index, const char_t* str)
{
assert(index < indexEntriesCount_);
size_t len = Len(str);
if (len > maxCacheEntryTitleLength)
len = maxCacheEntryTitleLength;
IndexEntry& entry = indexEntries_[index];
memmove(entry.title, str, len * sizeof(char_t));
entry.title[len] = _T('\0');
#ifdef DEBUG_URLS
assert('s' == *entry.url);
#endif
}
status_t HistoryCache::removeEntry(ulong_t index)
{
assert(index < indexEntriesCount_);
assert(NULL != dataStore);
const char* streamName = indexEntries_[index].streamName;
status_t err = dataStore->removeStream(streamName);
if (errNone != err)
return err;
memmove(indexEntries_ + index, indexEntries_ + index + 1, (indexEntriesCount_ - (index + 1)) * sizeof(IndexEntry));
--indexEntriesCount_;
return errNone;
}
status_t HistoryCache::removeEntriesAfter(ulong_t from)
{
status_t err;
while (indexEntriesCount_ > from)
{
if (errNone != (err = removeEntry(indexEntriesCount_ - 1)))
return err;
}
return errNone;
}
status_t HistoryCache::appendEntry(const char* url, ulong_t& index)
{
assert(0 != Len(url));
status_t err;
if (indexEntriesCount_ == indexCapacity_)
if (errNone != (err = removeEntry(0UL)))
return err;
ulong_t len = Len(url);
if (len > maxCacheEntryUrlLength)
len = maxCacheEntryUrlLength;
IndexEntry& entry = indexEntries_[indexEntriesCount_];
memmove(entry.url, url, len);
entry.url[len] = '\0';
StrPrintF(entry.streamName, "_History %lx%lx", ticks(), random(ULONG_MAX));
#ifdef DEBUG_URLS
assert('s' == *entry.url);
#endif
DataStoreWriter writer(*dataStore);
if (errNone != (err = writer.open(entry.streamName)))
return err;
index = indexEntriesCount_++;
return errNone;
}
status_t HistoryCache::appendLink(const char* url, const char_t* title)
{
assert(0 != Len(url));
ulong_t index;
status_t err = appendEntry(url, index);
if (errNone != err)
return err;
setEntryTitle(index, title);
indexEntries_[index].onlyLink = true;
#ifdef DEBUG_URLS
assert('s' == *indexEntries_[index].url);
#endif
return errNone;
}
status_t HistoryCache::insertLink(ulong_t index, const char* url, const char_t* title)
{
assert(0 != Len(url));
status_t err = appendLink(url, title);
if (errNone != err)
return err;
IndexEntry* tmp = new_nt IndexEntry();
if (NULL == tmp)
return memErrNotEnoughSpace;
ulong_t count = indexEntriesCount_ - (index + 1);
memmove(tmp, indexEntries_ + (indexEntriesCount_ - 1), sizeof(IndexEntry));
memmove(indexEntries_ + (index + 1), indexEntries_ + index, count * sizeof(IndexEntry));
memmove(indexEntries_ + index, tmp, sizeof(IndexEntry));
delete tmp;
#ifdef DEBUG_URLS
assert('s' == *indexEntries_[index].url);
#endif
return errNone;
}
status_t HistoryCache::replaceEntries(ulong_t from, const char* newEntryUrl)
{
status_t err = removeEntriesAfter(from);
if (errNone != err)
return err;
return appendEntry(newEntryUrl, from);
}
DataStoreReader* HistoryCache::readerForEntry(ulong_t index)
{
assert(index < indexEntriesCount_);
assert(!indexEntries_[index].onlyLink);
DataStoreReader* reader = new_nt DataStoreReader(*dataStore);
if (NULL == reader)
return NULL;
status_t err = reader->open(indexEntries_[index].streamName);
if (errNone != err)
{
delete reader;
return NULL;
}
#ifdef DEBUG_URLS
assert('s' == *indexEntries_[index].url);
#endif
return reader;
}
DataStoreWriter* HistoryCache::writerForEntry(ulong_t index)
{
assert(index < indexEntriesCount_);
assert(!indexEntries_[index].onlyLink);
DataStoreWriter* writer = new_nt DataStoreWriter(*dataStore);
if (NULL == writer)
return NULL;
status_t err = writer->open(indexEntries_[index].streamName);
if (errNone != err)
{
delete writer;
return NULL;
}
#ifdef DEBUG_URLS
assert('s' == *indexEntries_[index].url);
#endif
return writer;
}
status_t HistoryCache::moveEntryToEnd(ulong_t& index)
{
assert(index < indexEntriesCount_);
if (index == indexEntriesCount_ - 1)
return errNone;
// IndexEntry is quite big, so better not to use stack to allocate it.
IndexEntry* tmp = new_nt IndexEntry;
if (NULL == tmp)
return memErrNotEnoughSpace;
memmove(tmp, indexEntries_ + index, sizeof(*tmp));
memmove(indexEntries_ + index, indexEntries_ + (index + 1), (indexEntriesCount_ - (index + 1)) * sizeof(*tmp));
memmove(indexEntries_ + (indexEntriesCount_ - 1), tmp, sizeof(*tmp));
delete tmp;
index = (indexEntriesCount_ - 1);
#ifdef DEBUG_URLS
assert('s' == *indexEntries_[index].url);
#endif
return errNone;
}
status_t HistoryCache::removeEntry(const char* url)
{
ulong_t index = entryIndex(url);
if (entryNotFound == index)
return errNone;
return removeEntry(index);
}
#ifndef NDEBUG
#ifdef _WIN32
static const char_t* unitTestCacheName = _T("UnitTest HistoryCache.dat");
#endif
#ifdef _PALM_OS
static const char_t* unitTestCacheName = _T("UnitTest HistoryCache");
#endif
static void test_HistoryCacheWrite()
{
HistoryCache cache;
status_t err = cache.open(unitTestCacheName);
assert(errNone == err);
assert(0 == cache.entriesCount());
char buffer[33];
ulong_t index;
for (int i = 0; i < 11; ++i)
{
StrPrintF(buffer, "test %d", i);
cache.appendEntry(buffer, index);
}
assert(HistoryCache::maxCacheEntries == cache.entriesCount());
assert(0 == cache.entryIndex("test 1"));
cache.replaceEntries(0, "test 11");
assert(0 == cache.entryIndex("test 11"));
}
static void test_HistoryCacheRead()
{
HistoryCache cache;
status_t err = cache.open(unitTestCacheName);
assert(errNone == err);
assert(1 == cache.entriesCount());
assert(0 == cache.entryIndex("test 11"));
cache.removeEntry(0UL);
assert(0 == cache.entriesCount());
}
void test_HistoryCache()
{
#ifndef DEBUG_URLS
test_HistoryCacheWrite();
test_HistoryCacheRead();
test_HistoryCacheWrite();
test_HistoryCacheRead();
#endif
}
#endif
|
[
"andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9",
"kjk@10a9aba9-86da-0310-ac04-a2df2cc00fd9"
] |
[
[
[
1,
74
],
[
76,
462
]
],
[
[
75,
75
]
]
] |
49cb7aa5830771570a5c0e0e5fa987f3421e20d0
|
c13ef26a8b4b1e196c6c593a73520787a7c15b80
|
/samples_atistream/SobelFilter/SobelFilter.hpp
|
1417970ed29ea72b5c923adcd8613b14956949e6
|
[] |
no_license
|
ajaykumarkannan/simulation-opencl
|
73072dcdacf5f3c93e0c038caedb60b479839327
|
53d00629358d3a2b1135f4daf0c327436fd9ed79
|
refs/heads/master
| 2021-01-23T08:39:00.347158 | 2010-03-09T15:43:50 | 2010-03-09T15:43:50 | 37,275,925 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 10,606 |
hpp
|
/* ============================================================
Copyright (c) 2009 Advanced Micro Devices, Inc. All rights reserved.
Redistribution and use of this material is permitted under the following
conditions:
Redistributions must retain the above copyright notice and all terms of this
license.
In no event shall anyone redistributing or accessing or using this material
commence or participate in any arbitration or legal action relating to this
material against Advanced Micro Devices, Inc. or any copyright holders or
contributors. The foregoing shall survive any expiration or termination of
this license or any agreement or access or use related to this material.
ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION
OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL.
THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT
HOLDERS AND CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY
REPRESENTATIONS, GUARANTEE, OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO
SUPPORT, INDEMNITY, ERROR FREE OR UNINTERRUPTED OPERA TION, OR THAT IT IS FREE
FROM DEFECTS OR VIRUSES. ALL OBLIGATIONS ARE HEREBY DISCLAIMED - WHETHER
EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT.
IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED OR BASED ON ANY THEORY OF LIABILITY
ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED MICRO DEVICES,
INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS
(US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS
THIS ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND
ANY COPYRIGHT HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES,
OBLIGATIONS, CLAIMS, OR DEMANDS IN EXCESS OF TEN DOLLARS (US $10.00). THE
FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, IF ANY OF THESE TERMS ARE
CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME VOID OR
DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR
CONTRIBUTORS FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE
THIS MATERIAL SHALL TERMINATE IMMEDIATELY. MOREOVER, THE FOREGOING SHALL
SURVIVE ANY EXPIRATION OR TERMINATION OF THIS LICENSE OR ANY AGREEMENT OR
ACCESS OR USE RELATED TO THIS MATERIAL.
NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS
MATERIAL SUCH NOTICE IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO
RESTRICTIONS UNDER THE LAWS AND REGULATIONS OF THE UNITED STATES OR OTHER
COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT CONTROL LAWS SUCH
AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS
DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S.
MUNITIONS LIST. THIS MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED,
EXPORTED AND/OR RE-EXPORTED IN ANY MANNER PROHIBITED UNDER ANY APPLICABLE LAWS,
INCLUDING U.S. EXPORT CONTROL LAWS REGARDING SPECIFICALLY DESIGNATED PERSONS,
COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY CONTROLS.
MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY
LICENSE OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL.
NOTICE REGARDING THE U.S. GOVERNMENT AND DOD AGENCIES: This material is
provided with "RESTRICTED RIGHTS" and/or "LIMITED RIGHTS" as applicable to
computer software and technical data, respectively. Use, duplication,
distribution or disclosure by the U.S. Government and/or DOD agencies is
subject to the full extent of restrictions in all applicable regulations,
including those found at FAR52.227 and DFARS252.227 et seq. and any successor
regulations thereof. Use of this material by the U.S. Government and/or DOD
agencies is acknowledgment of the proprietary rights of any copyright holders
and contributors, including those of Advanced Micro Devices, Inc., as well as
the provisions of FAR52.227-14 through 23 regarding privately developed and/or
commercial computer software.
This license forms the entire agreement regarding the subject matter hereof and
supersedes all proposals and prior discussions and writings between the parties
with respect thereto. This license does not affect any ownership, rights, title,
or interest in, or relating to, this material. No terms of this license can be
modified or waived, and no breach of this license can be excused, unless done
so in a writing signed by all affected parties. Each term of this license is
separately enforceable. If any term of this license is determined to be or
becomes unenforceable or illegal, such term shall be reformed to the minimum
extent necessary in order for this license to remain in effect in accordance
with its terms as modified by such reformation. This license shall be governed
by and construed in accordance with the laws of the State of Texas without
regard to rules on conflicts of law of any state or jurisdiction or the United
Nations Convention on the International Sale of Goods. All disputes arising out
of this license shall be subject to the jurisdiction of the federal and state
courts in Austin, Texas, and all defenses are hereby waived concerning personal
jurisdiction and venue of these courts.
============================================================ */
#ifndef SOBEL_FILTER_H_
#define SOBEL_FILTER_H_
#include <CL/cl.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <SDKUtil/SDKCommon.hpp>
#include <SDKUtil/SDKApplication.hpp>
#include <SDKUtil/SDKFile.hpp>
#include <SDKUtil/SDKBitMap.hpp>
#define INPUT_IMAGE "SobelFilter_Input.bmp"
#define OUTPUT_IMAGE "SobelFilter_Output.bmp"
/**
* SobelFilter
* Class implements OpenCL Sobel Filter sample
* Derived from SDKSample base class
*/
class SobelFilter : public SDKSample
{
cl_double setupTime; /**< time taken to setup OpenCL resources and building kernel */
cl_double kernelTime; /**< time taken to run kernel and read result back */
cl_uchar* inputImageData; /**< Input bitmap data to device */
cl_uchar* outputImageData; /**< Output from device */
cl_context context; /**< CL context */
cl_device_id *devices; /**< CL device list */
cl_mem inputImageBuffer; /**< CL memory buffer for input Image*/
cl_mem outputImageBuffer; /**< CL memory buffer for Output Image*/
cl_uchar* verificationOutput; /**< Output array for reference implementation */
cl_command_queue commandQueue; /**< CL command queue */
cl_program program; /**< CL program */
cl_kernel kernel; /**< CL kernel */
streamsdk::SDKBitMap inputBitmap; /**< Bitmap class object */
streamsdk::uchar4* pixelData; /**< Pointer to image data */
cl_uint pixelSize; /**< Size of a pixel in BMP format> */
cl_uint width; /**< Width of image */
cl_uint height; /**< Height of image */
cl_bool byteRWSupport;
public:
/**
* Read bitmap image and allocate host memory
* @param inputImageName name of the input file
* @return 1 on success and 0 on failure
*/
int readInputImage(std::string inputImageName);
/**
* Write to an image file
* @param outputImageName name of the output file
* @return 1 on success and 0 on failure
*/
int writeOutputImage(std::string outputImageName);
/**
* Constructor
* Initialize member variables
* @param name name of sample (string)
*/
SobelFilter(std::string name)
: SDKSample(name),
inputImageData(NULL),
outputImageData(NULL),
verificationOutput(NULL),
byteRWSupport(true)
{
pixelSize = sizeof(streamsdk::uchar4);
pixelData = NULL;
}
/**
* Constructor
* Initialize member variables
* @param name name of sample (const char*)
*/
SobelFilter(const char* name)
: SDKSample(name),
inputImageData(NULL),
outputImageData(NULL),
verificationOutput(NULL),
byteRWSupport(true)
{
pixelSize = sizeof(streamsdk::uchar4);
pixelData = NULL;
}
~SobelFilter()
{
}
/**
* Allocate image memory and Load bitmap file
* @return 1 on success and 0 on failure
*/
int setupSobelFilter();
/**
* OpenCL related initialisations.
* Set up Context, Device list, Command Queue, Memory buffers
* Build CL kernel program executable
* @return 1 on success and 0 on failure
*/
int setupCL();
/**
* Set values for kernels' arguments, enqueue calls to the kernels
* on to the command queue, wait till end of kernel execution.
* Get kernel start and end time if timing is enabled
* @return 1 on success and 0 on failure
*/
int runCLKernels();
/**
* Reference CPU implementation of Binomial Option
* for performance comparison
*/
void sobelFilterCPUReference();
/**
* Override from SDKSample. Print sample stats.
*/
void printStats();
/**
* Override from SDKSample. Initialize
* command line parser, add custom options
*/
int initialize();
/**
* Override from SDKSample, adjust width and height
* of execution domain, perform all sample setup
*/
int setup();
/**
* Override from SDKSample
* Run OpenCL Sobel Filter
*/
int run();
/**
* Override from SDKSample
* Cleanup memory allocations
*/
int cleanup();
/**
* Override from SDKSample
* Verify against reference implementation
*/
int verifyResults();
};
#endif // SOBEL_FILTER_H_
|
[
"juergen.broder@c62875e2-cac2-11de-a9c8-2fbcfba63733"
] |
[
[
[
1,
254
]
]
] |
98d7db21800026d451753b78a3de99ffc2caf45a
|
1a6318d90dc640836dafbc38f0fb08710ae675fe
|
/ interfazcontroller --username alejandro.lavagnino/test.ipp
|
2fc3f02f6c6ae7c833e280619a26c936af9779b9
|
[] |
no_license
|
linxpsoft/interfazcontroller
|
6a927eb195087231e2dcefe537bd3027ba87dccf
|
778240d979685ac08d790d45dfdb368c415d8466
|
refs/heads/master
| 2021-01-21T10:12:56.878302 | 2010-05-01T17:38:42 | 2010-05-01T17:38:42 | 33,361,249 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,447 |
ipp
|
unit test;
interface
uses
Controls,
StdCtrls,
Graphics,
Forms;
type
Tfrm = class(TForm)
Button1: TButton;
CheckBox1: TCheckBox;
constructor Create(AOwner: TComponent);
procedure Button1Click(Sender: TObject);
end;
var
frm: Tfrm;
implementation
constructor Tfrm.Create(AOwner: TComponent);
begin
inherited;
Button1 := TButton.Create(Self);
Button1.Name := 'Button1';
Button1.Parent := Self;
Button1.Caption := '';
with Button1 do
begin
Left := 376;
Top := 240;
Width := 75;
Height := 25;
Caption := 'Button1';
onClick := Button1Click;
TabOrder := 8;
end;
CheckBox1 := TCheckBox.Create(Self);
CheckBox1.Name := 'CheckBox1';
CheckBox1.Parent := Self;
CheckBox1.Caption := '';
with CheckBox1 do
begin
Left := 584;
Top := 120;
Width := 97;
Height := 17;
Caption := 'CheckBox1';
TabOrder := 9;
end;
Left := -1387;
Top := 238;
Caption := '[no selected components]';
ClientHeight := 529;
ClientWidth := 952;
Color := clBtnFace;
Font.Charset := DEFAULT_CHARSET;
Font.Color := clWindowText;
Font.Height := -11;
Font.Name := 'Tahoma';
Font.Style := [];
OldCreateOrder := True;
Position := poDesigned;
ShowHint := True;
Visible := True;
PixelsPerInch := 96;
end;
procedure Tfrm.Button1Click(Sender: TObject);
begin
Print('holas');
end;
end.
|
[
"alejandro.lavagnino@2dd3ba9f-24ed-f996-982a-a3d3b69f1727"
] |
[
[
[
1,
74
]
]
] |
f7f4f33347e21c772c4535d61e4d77c4eec2ce7b
|
914791f0d412fdcd67f9bc5e0a757899b7a48ecb
|
/src/main/RenderWidget0.cpp
|
b0770d87acbbf59e728336cf3bdf28b060c37dff
|
[] |
no_license
|
hchapman/graphics-projects
|
39af28a5daf426cd2b3a050d3faa8aed935a32da
|
ede6ad4f44f2002d66fa7f6be5cbfde9829c655c
|
refs/heads/master
| 2021-03-12T22:49:37.126498 | 2010-03-30T03:08:43 | 2010-03-30T03:08:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 7,976 |
cpp
|
#include "RenderWidget0.h"
#include "Vector3.h"
#include "Matrix4.h"
#include "Camera.h"
#include "GLWidget.h"
#include "GLRenderContext.h"
#include "VertexData.h"
#include "Shapes.h"
#include <stdio.h>
#include <iostream>
#include <QtOpenGL>
RenderWidget0::RenderWidget0()
{
RenderContext *rs = new SWRenderContext();
sceneManager = 0;
tracking = false;
sceneCreated = false;
camera = false;
HOUSE = "house";
}
RenderWidget0::~RenderWidget0()
{
if(sceneManager)
{
delete sceneManager;
}
}
void RenderWidget0::initSceneEvent()
{
sceneManager = new SceneManager();
//create and position the camera
setupCamera();
//create and position and objects in scene
setupObjects();
// Trigger timer event every 5ms.
timerId = startTimer(5);
}
void RenderWidget0::toDecimal(int num_colors, float color_list[][3])
{
for (int i = 0; i < num_colors; i++) {
color_list[i][0] = color_list[i][0] / 255;
color_list[i][1] = color_list[i][1] / 255;
color_list[i][2] = color_list[i][2] / 255;
}
}
void RenderWidget0::setupCamera()
{
const int CAMERA_POSITION = 3;
// Camera
camera = sceneManager->createCamera();
if (CAMERA_POSITION == 1)
{
// First camera test setting
camera->createViewMatrix(
Vector4<float>(0,0,40,1),
Vector4<float>(0,0,0,1),
Vector4<float>(0,1,0,0));
camera->createProjectionMatrix(
1, 100, 1, 60.0/180.0*M_PI);
}
else if (CAMERA_POSITION == 2)
{
// Second camera test setting
camera->createViewMatrix(
Vector4<float>(-10,40,40,1),
Vector4<float>(-5,0,0,1),
Vector4<float>(0,1,0,0));
camera->createProjectionMatrix(
1, 100, 1, 60.0/180.0*M_PI);
}
else if (CAMERA_POSITION == 3)
{
// First camera test setting for p3
camera->createViewMatrix(
Vector4<float>(20,20,20,1),
Vector4<float>(0,0,0,1),
Vector4<float>(0,1,0,0));
camera->createProjectionMatrix(
1, 100, 1, 60.0/180.0*M_PI);
}
else if (CAMERA_POSITION == 4)
{
// First camera test setting for p3
camera->createViewMatrix(
Vector4<float>(-10,20,200,1),
Vector4<float>(-5,0,0,1),
Vector4<float>(0,1,0,0));
camera->createProjectionMatrix(
1, 100, 1, 60.0/180.0*M_PI);
}
sceneCreated = true;
}
void RenderWidget0::setupObjects()
{
objects[HOUSE] = Shapes::createColorfulHouse(sceneManager);
//objects["rect"] = Shapes::createRect(sceneManager, 10, 10);
//objects["bunny"] = Shapes::readObject(sceneManager, "buddha.obj");
}
void RenderWidget0::renderSceneEvent()
{
sceneManager->renderScene();
}
void RenderWidget0::resizeRenderWidgetEvent(const QSize &s)
{
// If we have a camera and are resizing the widget, be sure to
// update the aspect ratio!
if (camera)
camera->setAspectRatio((float)s.width()/(float)s.height());
}
void RenderWidget0::timerEvent(QTimerEvent *t)
{
updateScene();
}
void RenderWidget0::mousePressEvent(QMouseEvent *e)
{
// If we're pressing the left button, then we should start tracking
if (e->buttons() & Qt::LeftButton)
{
tracking = true;
// Store the initial mouse position
track_start = e->pos();
}
}
void RenderWidget0::mouseMoveEvent(QMouseEvent *e)
{
if (tracking && e->buttons() & Qt::LeftButton && e->pos() != track_start)
{
Vector3<float> start, stop; // Temporary vectors representing
// points on the virtual trackball
float _x, _y, _z; // Temporary 3-points
const float diameter = (float)(width() < height() ? width() : height());
// x coord of the start point on the virtual ball
_x = ((float)track_start.x()*2.f - (float)width())/diameter;
// y coord of the start point on the virtual ball
_y = -(((float)track_start.y()*2.f - (float)height())/diameter);
if (RenderWidget0::USE_COMPOSITE)
{
// Use a composite sphere/hyperbolic sheet for the trackball
// as suggested by http://www.opengl.org/wiki/Trackball
if (_x*_x + _y*_y <= 1.f/2.f) {
_z = sqrt(1 - _x*_x - _y*_y);
} else {
_z = 1.f/(2*sqrt(_x*_x + _y*_y));
}
} else
{
// Make sure we're not clicking outside of the sphere
// (There should be a better way to handle this)
if (_x*_x + _y*_y > 1) {
_z = 0;
} else {
// z coord of the start point on the virtual ball
_z = sqrt(1 - _x*_x - _y*_y);
}
}
// Create the starting point vector
start = Vector3<float>(_x, _y, _z).normalize();
// x coord of the stop point on the virtual ball
_x = ((float)e->pos().x()*2.f - (float)width())/diameter;
// y coord of the stop point on the virtual ball
_y = -(((float)e->pos().y()*2.f - (float)height())/diameter);
if (RenderWidget0::USE_COMPOSITE)
{
// Use a composite sphere/hyperbolic sheet for the trackball
// as suggested by http://www.opengl.org/wiki/Trackball
if (_x*_x + _y*_y <= 1.f/2.f) {
_z = sqrt(1 - _x*_x - _y*_y);
} else {
_z = 1.f/(2*sqrt(_x*_x + _y*_y));
}
} else
{
// Make sure we're not clicking outside of the sphere
// (There should be a better way to handle this)
if (_x*_x + _y*_y > 1) {
_z = 0;
} else {
// z coord of the stop point on the virtual ball
_z = sqrt(1 - _x *_x - _y*_y);
}
}
// Create the stopping point vector
stop = Vector3<float>(_x, _y, _z).normalize();
// Make sure that the vectors aren't equal (if they are,
// the cross product doesn't exist!)
// Also, make sure that the cross product isn't 1, as acos(1) = nan
if (start != stop &&
!(1 - (start^stop)) < EPSILON & (1 - (start^stop)) > -EPSILON) {
// Prep the trackball rotation matrix
Matrix4<float> trackRotation =
Matrix4<float>::rotateA(start*stop,
acos(start^stop));
// rotates all objects in scene via iteration
for (it = objects.begin(); it != objects.end(); it++ )
{
// dereferencing 'it' returns pair from objects map
// second value of pair is ptr to object
(*it).second->setTransformation(trackRotation *
(*it).second->getTransformation());
}
// Update the (now old) mouse position
track_start = e->pos();
}
} else if (tracking && !(e->buttons() & Qt::LeftButton))
{
// If we're tracking but somehow not clicking, then we shouldn't
// actually still be tracking
tracking = false;
}
}
void RenderWidget0::mouseReleaseEvent(QMouseEvent *e)
{
// If we've released the left mouse button, then we shouldn't be tracking
if (!(e->buttons() & Qt::LeftButton))
{
tracking = false;
}
}
void RenderWidget0::startAnimation()
{
if(!timerId)
{
timerId = startTimer(5);
}
}
void RenderWidget0::stopAnimation()
{
if(timerId)
{
killTimer(timerId);
timerId = 0;
}
}
|
[
"[email protected]",
"[email protected]",
"[email protected]"
] |
[
[
[
1,
2
],
[
4,
7
],
[
9,
9
],
[
11,
11
],
[
13,
18
],
[
20,
22
],
[
24,
27
],
[
46,
47
],
[
49,
49
],
[
56,
56
],
[
59,
60
],
[
63,
63
],
[
66,
73
],
[
76,
107
],
[
110,
112
],
[
115,
116
],
[
118,
129
],
[
131,
135
],
[
138,
147
],
[
150,
159
],
[
162,
168
],
[
171,
188
],
[
191,
197
],
[
200,
205
],
[
207,
215
],
[
217,
222
],
[
231,
234
],
[
236,
238
],
[
240,
245
],
[
247,
247
],
[
249,
252
],
[
257,
260
],
[
266,
266
]
],
[
[
3,
3
],
[
8,
8
],
[
10,
10
],
[
12,
12
],
[
113,
114
]
],
[
[
19,
19
],
[
23,
23
],
[
28,
45
],
[
48,
48
],
[
50,
55
],
[
57,
58
],
[
61,
62
],
[
64,
65
],
[
74,
75
],
[
108,
109
],
[
117,
117
],
[
130,
130
],
[
136,
137
],
[
148,
149
],
[
160,
161
],
[
169,
170
],
[
189,
190
],
[
198,
199
],
[
206,
206
],
[
216,
216
],
[
223,
230
],
[
235,
235
],
[
239,
239
],
[
246,
246
],
[
248,
248
],
[
253,
256
],
[
261,
265
]
]
] |
fa548dd7d936416980810ea16ddcc2f1d22b2667
|
ea12fed4c32e9c7992956419eb3e2bace91f063a
|
/zombie/code/zombie/nscene/src/nscene/nlightnode_cmds.cc
|
42a6350fdda6aece3e013725d1877feca8e196da
|
[] |
no_license
|
ugozapad/TheZombieEngine
|
832492930df28c28cd349673f79f3609b1fe7190
|
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
|
refs/heads/master
| 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 3,153 |
cc
|
#include "precompiled/pchnscene.h"
//------------------------------------------------------------------------------
// nlightnode_cmds.cc
// (C) 2004 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "nscene/nlightnode.h"
#include "kernel/npersistserver.h"
static void n_settype(void* slf, nCmd* cmd);
static void n_gettype(void* slf, nCmd* cmd);
static void n_setcastshadows(void* slf, nCmd* cmd);
static void n_getcastshadows(void* slf, nCmd* cmd);
//------------------------------------------------------------------------------
/**
@scriptclass
nlightnode
@cppclass
nLightNode
@superclass
nlightnode
@classinfo
Implements a generic light node.
*/
void
n_initcmds_nLightNode(nClass* cl)
{
cl->BeginCmds();
cl->AddCmd("v_settype_s", 'STYP', n_settype);
cl->AddCmd("s_gettype_v", 'GTYP', n_gettype);
cl->AddCmd("v_setcastshadows_b", 'STCS', n_setcastshadows);
cl->AddCmd("b_getcastshadows_v", 'GTCS', n_getcastshadows);
cl->EndCmds();
}
//------------------------------------------------------------------------------
/**
@cmd
settype
@input
s(light type)
@output
v
@info
Set light type.
*/
static void
n_settype(void* slf, nCmd* cmd)
{
nLightNode *self = (nLightNode*) slf;
self->SetType(nLight::StringToType(cmd->In()->GetS()));
}
//------------------------------------------------------------------------------
/**
@cmd
gettype
@input
v
@output
s(light type)
@info
Get light type.
*/
static void
n_gettype(void* slf, nCmd* cmd)
{
nLightNode *self = (nLightNode*) slf;
cmd->Out()->SetS(nLight::TypeToString(self->GetType()));
}
//------------------------------------------------------------------------------
/**
@cmd
setcastshadows
@input
b
@output
v
@info
Set the light to cast shadows or not.
*/
static void
n_setcastshadows(void* slf, nCmd* cmd)
{
nLightNode* self = (nLightNode*) slf;
self->SetCastShadows(cmd->In()->GetB());
}
//------------------------------------------------------------------------------
/**
@cmd
getcastshadows
@input
v
@output
b
@info
Check if light cast shadows.
*/
static void
n_getcastshadows(void* slf, nCmd* cmd)
{
nLightNode* self = (nLightNode*) slf;
cmd->Out()->SetB(self->GetCastShadows());
}
//------------------------------------------------------------------------------
/**
*/
bool
nLightNode::SaveCmds(nPersistServer* ps)
{
if (nAbstractShaderNode::SaveCmds(ps))
{
nCmd* cmd;
vector4 c;
//--- settype ---
cmd = ps->GetCmd(this, 'STYP');
cmd->In()->SetS(nLight::TypeToString(this->GetType()));
ps->PutCmd(cmd);
//--- setcastshadows ---
cmd = ps->GetCmd(this, 'STCS');
cmd->In()->SetB(this->GetCastShadows());
ps->PutCmd(cmd);
return true;
}
return false;
}
|
[
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] |
[
[
[
1,
135
]
]
] |
146854363c17014a2ac84b6d13f38ba4cc2dea7f
|
5fb9b06a4bf002fc851502717a020362b7d9d042
|
/developertools/GumpEditor-0.32/colorpicker/ColourPickerXP.h
|
3cbb1fd1ec4e291d0f8c6d52f3ca3b8cede0b2a8
|
[] |
no_license
|
bravesoftdz/iris-svn
|
8f30b28773cf55ecf8951b982370854536d78870
|
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
|
refs/heads/master
| 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 21,676 |
h
|
// CColourPickerXP & CColourPopupXP version 1.4
//
// Copyright ?2002-2003 Zorglab
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !! You are not allowed to use these classes in a commercial project !!
// !! without the permission of the author ! !!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// Feel free to remove or otherwise mangle any part.
// Please report any bug, comment, suggestion, etc. to the following address :
// mailto:[email protected]
//
// These classes are based on work by Chris Maunder, Alexander Bischofberger,
// James White and Descartes Systems Sciences, Inc.
// http://www.codeproject.com/miscctrl/colour_picker.asp
// http://www.codeproject.com/miscctrl/colorbutton.asp
// http://www.codeproject.com/wtl/wtlcolorbutton.asp
//
// Thanks to Keith Rule for his CMemDC class (see MemDC.h).
// Thanks to P? Kristian T?der for his CXPTheme class, which is based on
// the CVisualStyleXP class of David Yuheng Zhao (see XPTheme.cpp).
//
// Other people who have contributed to the improvement of the ColourPickerXP,
// by sending a bug report, by solving a bug, by submitting a suggestion, etc.
// are mentioned in the history-section (see below).
//
// Many thanks to them all.
//
// === HISTORY ===
//
// version 1.4 - fixed : "A required resource was"-dialog due to not
// restoring the DC after drawing pop-up (thanks to
// Kris Wojtas, KRI Software)
// - using old style selection rectangle in pop-up when
// flat menus are disabled
// - pop-up will now raise when user hit F4-key or down-arrow
// - modified : moving around in the pop-up with arrow keys
// when no colour is selected
//
// version 1.3 - parent window stays active when popup is up on screen
// (thanks to Damir Valiulin)
// - when using track-selection, the initial colour is shown
// for an invalid selection instead of black
// - added bTranslateDefault parameter in GetColor
//
// version 1.2 - fixed : in release configuration, with neither
// 'Automatic' nor 'Custom' labels, the pop-up won't work
// - diasbled combo-box is drawn correctly
// - combo-box height depends on text size
// - font support : use SetFont() and GetFont(), for combo-
// box style call SetStyle() after changing font
//
// version 1.1 - fixed some compile errors in VC6
// - no need anymore to change the defines in stdafx.h
// except for multi-monitor support
//
// version 1.0 first release
//
// === ORIGINAL COPYRIGHT STATEMENTS ===
//
// ------------------- Descartes Systems Sciences, Inc. --------------------
//
// Copyright (c) 2000-2002 - Descartes Systems Sciences, Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Neither the name of Descartes Systems Sciences, Inc nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------- Chris Maunder & Alexander Bischofberger ----------------
//
// Written by Chris Maunder ([email protected])
// Extended by Alexander Bischofberger ([email protected])
// Copyright (c) 1998.
//
// Updated 30 May 1998 to allow any number of colours, and to
// make the appearance closer to Office 97.
// Also added "Default" text area. (CJM)
//
// 13 June 1998 Fixed change of focus bug (CJM)
// 30 June 1998 Fixed bug caused by focus bug fix (D'oh!!)
// Solution suggested by Paul Wilkerson.
//
// ColourPopup is a helper class for the colour picker control
// CColourPicker. Check out the header file or the accompanying
// HTML doc file for details.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to you or your
// computer whatsoever. It's free, so don't hassle me about it.
//
// Expect bugs.
//
// Please use and enjoy. Please let me know of any bugs/mods/improvements
// that you have found/implemented and I will fix/incorporate them into this
// file.
//
// -------------------------------------------------------------------------
//
// === END OF COPYRIGHT STATEMENTS ===
//
//-----------------------------------------------------------------------------
//
// Instructions on how to add CColourPickerXP to your application:
//
// 1. Copy ColourPickerXP.h, ColourPickerXP.cpp, XPTheme.h, XPTheme.cpp and
// MemDC.h into your application directory.
//
// 2. Add the five files into your project.
//
// 3. If you want to have multi-monitor support, set the WINVER definition in
// stdafx.h to at least 0x0500.
//
// 4. If you don't want XP theme support, comment out the '#include "XPTheme.h"'
// statement below.
//
// 5. Add a button to the dialog in question using the resource editor.
// You don't have to make and style adjustments to the button.
//
// 6. Add a variable for that button.
//
// 7. Add '#include "ColourPickerXP.h"' in the dialog's header file and
// change the definition of the button from 'CButton ...' to
// 'CColourPickerXP ...'.
//
// 8. Inside your OnInitDialog for the dialog, you can change the style into
// a combobox and/or modifie the properties of the picker.
//
// 9. Compile and enjoy.
//
//-----------------------------------------------------------------------------
#ifndef COLOURPICKERXP_INCLUDED
#define COLOURPICKERXP_INCLUDED
#pragma once
// Comment this line out if you don't want XP theme support.
#include "XPTheme.h"
// CColourPopupXP messages
#define CPN_SELCHANGE WM_USER + 1001 // Colour Picker Selection change
#define CPN_DROPDOWN WM_USER + 1002 // Colour Picker drop down
#define CPN_CLOSEUP WM_USER + 1003 // Colour Picker close up
#define CPN_SELENDOK WM_USER + 1004 // Colour Picker end OK
#define CPN_SELENDCANCEL WM_USER + 1005 // Colour Picker end (cancelled)
void AFXAPI DDX_ColourPickerXP(CDataExchange *pDX, int nIDC, COLORREF& crColour);
class CColourPickerXP : public CButton
{
public:
DECLARE_DYNCREATE(CColourPickerXP);
//***********************************************************************
// Name: CColourPickerXP
// Description: Default constructor.
// Parameters: None.
// Return: None.
// Notes: None.
//***********************************************************************
CColourPickerXP(void);
//***********************************************************************
// Name: CColourPickerXP
// Description: Destructor.
// Parameters: None.
// Return: None.
// Notes: None.
//***********************************************************************
virtual ~CColourPickerXP(void);
//***********************************************************************
//** Property Accessors **
//***********************************************************************
__declspec(property(get=GetColor,put=SetColor)) COLORREF Color;
__declspec(property(get=GetDefaultColor,put=SetDefaultColor)) COLORREF DefaultColor;
__declspec(property(get=GetTrackSelection,put=SetTrackSelection)) BOOL TrackSelection;
__declspec(property(put=SetCustomText)) LPCTSTR CustomText;
__declspec(property(put=SetDefaultText)) LPCTSTR DefaultText;
__declspec(property(put=SetColoursName)) UINT ColoursName;
__declspec(property(put=SetRegSection)) LPCTSTR RegSection;
__declspec(property(put=SetRegSectionStatic)) LPCTSTR RegSectionStatic;
__declspec(property(get=GetStyle,put=SetStyle)) BOOL Style;
__declspec(property(put=SetRGBText)) LPCTSTR RGBText;
__declspec(property(get=GetAlwaysRGB,put=SetAlwaysRGB)) BOOL ShowRGBAlways;
//***********************************************************************
// Name: GetColor
// Description: Returns the current color selected in the control.
// Parameters: void / BOOL bTranslateDefault
// Return: COLORREF
// Notes: None.
//***********************************************************************
virtual COLORREF GetColor(void) const;
virtual COLORREF GetColor(BOOL bTranslateDefault) const;
virtual DWORD GetHueId() const { return m_hueId; }
//***********************************************************************
// Name: SetColor
// Description: Sets the current color selected in the control.
// Parameters: COLORREF Color
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetColor(COLORREF Color);
virtual void SetHueId(DWORD hueId);
virtual void SetFontId(int fontId) { m_fontId = fontId; }
//***********************************************************************
// Name: GetDefaultColor
// Description: Returns the color associated with the 'default' selection.
// Parameters: void
// Return: COLORREF
// Notes: None.
//***********************************************************************
virtual COLORREF GetDefaultColor(void) const;
//***********************************************************************
// Name: SetDefaultColor
// Description: Sets the color associated with the 'default' selection.
// The default value is COLOR_APPWORKSPACE.
// Parameters: COLORREF Color
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetDefaultColor(COLORREF Color);
//***********************************************************************
// Name: SetCustomText
// Description: Sets the text to display in the 'Custom' selection of the
// CColourPicker control, the default text is "More Colors...".
// Parameters: LPCTSTR tszText
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetCustomText(LPCTSTR tszText);
//***********************************************************************
// Name: SetDefaultText
// Description: Sets the text to display in the 'Default' selection of the
// CColourPicker control, the default text is "Automatic". If
// this value is set to "", the 'Default' selection will not
// be shown.
// Parameters: LPCTSTR tszText
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetDefaultText(LPCTSTR tszText);
//***********************************************************************
// Name: SetColoursName
// Description: Sets the text from the resources of the tooltips to be
// displayed when the pointer is on a colour.
// Set this to 0 to use original English names.
// Parameters: UINT nFirstID (ID of Black)
// Return: None.
// Notes: None.
//***********************************************************************
static void SetColoursName(UINT nFirstID = 0);
//***********************************************************************
// Name: SetRegSection
// Description: Sets the registry section where to write custom colours.
// Set this to _T("") to disable.
// Parameters: LPCTSTR tszRegSection
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetRegSection(LPCTSTR tszRegSection = _T(""));
//***********************************************************************
// Name: SetRegSectionStatic
// Description: Sets the registry section where to write custom colours.
// Set this to _T("") to disable. This will be applied in
// all CColourPickerXPs of the application.
// Parameters: LPCTSTR tszRegSection
// Return: None.
// Notes: None.
//***********************************************************************
static void SetRegSectionStatic(LPCTSTR tszRegSection = _T(""));
//***********************************************************************
// Name: SetTrackSelection
// Description: Turns on/off the 'Track Selection' option of the control
// which shows the colors during the process of selection.
// Parameters: BOOL bTrack
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetTrackSelection(BOOL bTrack);
//***********************************************************************
// Name: GetTrackSelection
// Description: Returns the state of the 'Track Selection' option.
// Parameters: void
// Return: BOOL
// Notes: None.
//***********************************************************************
virtual BOOL GetTrackSelection(void) const;
//***********************************************************************
// Name: SetStyle
// Description: Sets the style of control to show.
// Parameters: BOOL bComboBoxStyle
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetStyle(BOOL bComboBoxStyle);
//***********************************************************************
// Name: GetTrackSelection
// Description: Returns TRUE if the style is set on ComboBox and FALSE if
// it is set on Button.
// Parameters: void
// Return: BOOL
// Notes: None.
//***********************************************************************
virtual BOOL GetStyle(void) const;
//***********************************************************************
// Name: SetRGBText
// Description: Sets the 3 letters used to display the RGB-value.
// Parameters: LPCTSTR tszRGB
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetRGBText(LPCTSTR tszRGB = _T("RGB"));
//***********************************************************************
// Name: SetAlwaysRGB
// Description: If this is set to TRUE the RGB-value of the colour will
// be shown even if the colour is a base colour.
// Parameters: BOOL bShow
// Return: None.
// Notes: None.
//***********************************************************************
virtual void SetAlwaysRGB(BOOL bShow);
//***********************************************************************
// Name: GetAlwaysRGB
// Description: Returns TRUE if the RGB-value is always shown.
// Parameters: void
// Return: BOOL
// Notes: None.
//***********************************************************************
virtual BOOL GetAlwaysRGB(void) const;
//{{AFX_VIRTUAL(CColourPickerXP)
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
protected:
virtual void PreSubclassWindow();
virtual BOOL PreTranslateMessage(MSG* pMsg);
//}}AFX_VIRTUAL
protected:
//{{AFX_MSG(CColourPickerXP)
afx_msg BOOL OnClicked();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg LONG OnSelEndOK(UINT lParam, LONG wParam);
afx_msg LONG OnSelEndCancel(UINT lParam, LONG wParam);
afx_msg LONG OnSelChange(UINT lParam, LONG wParam);
afx_msg void OnNMThemeChanged(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg LRESULT OnMouseLeave(WPARAM wParam, LPARAM lParam);
//}}AFX_MSG
//***********************************************************************
// Name: DrawArrow
// Description: None.
// Parameters: CDC* pDC
// RECT* pRect
// int iDirection
// 0 - Down
// 1 - Up
// 2 - Left
// 3 - Right
// Return: static None.
// Notes: None.
//***********************************************************************
static void DrawArrow(CDC* pDC,
RECT* pRect,
int iDirection = 0,
COLORREF clrArrow = RGB(0,0,0));
virtual void DrawHotArrow(BOOL bHot);
DECLARE_MESSAGE_MAP()
int m_fontId;
DWORD m_hueId;
COLORREF m_Color;
COLORREF m_DefaultColor;
CString m_strDefaultText;
CString m_strCustomText;
BOOL m_bPopupActive;
BOOL m_bTrackSelection;
BOOL m_bMouseOver;
BOOL m_bFlatMenus;
BOOL m_bComboBoxStyle;
BOOL m_bAlwaysRGB;
CString m_strRGBText;
CString m_strRegSection;
static CString m_strRegSectionStatic;
#ifdef _THEME_H_
CXPTheme m_xpButton, m_xpEdit, m_xpCombo;
#endif
private:
typedef CButton _Inherited;
};
//***********************************************************************
//** CColourPopupXP class definition **
//***********************************************************************
// To hold the colours and their names
/////////////////////////////////////////////////////////////////////////////
// CColourPopupXP window
class CColourPopupXP : public CWnd
{
// Construction
public:
CColourPopupXP();
CColourPopupXP(CPoint p, COLORREF crColour, DWORD hueId, int fontId, CWnd* pParentWnd,
LPCTSTR szDefaultText = NULL, LPCTSTR szCustomText = NULL,
LPCTSTR szRegSection = NULL);
void Initialise();
// Attributes
public:
// Operations
public:
BOOL Create(CPoint p, COLORREF crColour, DWORD hueId, CWnd* pParentWnd,
LPCTSTR szDefaultText = NULL, LPCTSTR szCustomText = NULL);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CColourPopupXP)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CColourPopupXP();
protected:
BOOL GetCellRect(int nIndex, const LPRECT& rect);
void FindCellFromColour(COLORREF crColour);
void SetWindowSize();
void CreateToolTips();
void ChangeSelection(int nIndex);
void EndSelection(int nMessage);
void DrawCell(CDC* pDC, int nIndex);
int GetIndex(int row, int col) const;
int GetRow(int nIndex) const;
int GetColumn(int nIndex) const;
void DrawBorder(CDC* pDC, CRect rect, UINT nEdge, UINT nBorder);
void SetFontId(int fontId) { m_fontId = fontId; }
// public attributes
public:
static DWORD m_crColours[];
//static TCHAR m_strInitNames[][256];
static int m_nNumColours;
static COLORREF GetColour(int nIndex, int fontId);
static CString GetColourName(int nIndex);
// protected attributes
protected:
int m_nNumColumns, m_nNumRows;
int m_nBoxSize, m_nMargin;
int m_nCurrentSel;
int m_nChosenColourSel;
CString m_strDefaultText;
CString m_strCustomText;
CRect m_CustomTextRect, m_DefaultTextRect, m_WindowRect, m_BoxesRect;
CFont m_Font;
CPalette m_Palette;
COLORREF m_crInitialColour, m_crColour;
DWORD m_hueIdInitial, m_hueId;
int m_fontId;
CToolTipCtrl m_ToolTip;
CWnd* m_pParent;
BOOL m_bChildWindowVisible;
BOOL m_bIsXP, m_bFlatmenus;
COLORREF m_clrBackground,
m_clrHiLightBorder,
m_clrHiLight,
m_clrHiLightText,
m_clrText,
m_clrLoLight;
CString m_strRegSection;
// Generated message map functions
protected:
//{{AFX_MSG(CColourPopupXP)
afx_msg void OnNcDestroy();
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnPaint();
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg BOOL OnQueryNewPalette();
afx_msg void OnPaletteChanged(CWnd* pFocusWnd);
afx_msg void OnKillFocus(CWnd* pNewWnd);
#if _MFC_VER >= 0x0700
afx_msg void OnActivateApp(BOOL bActive, DWORD dwTask);
#else
afx_msg void OnActivateApp(BOOL bActive, HTASK hTask);
#endif
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#endif //!COLOURPICKERXP_INCLUDED
|
[
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
] |
[
[
[
1,
559
]
]
] |
967a869d6894d1ede3edb3282657e4fec5b2c990
|
6426b0ba09cf324c4caad8b86b74f33ef489710e
|
/src/goMidiManager.cpp
|
5a5af0a464017dea995cfebee6a1208b77a03e93
|
[] |
no_license
|
gameoverhack/iMediate
|
e619a1148ecc3f76f011e2c1a7fa9cdb32c8a290
|
9c43edf26954cbc15fb0145632fa4dbf2634fc29
|
refs/heads/master
| 2020-04-05T23:05:37.392441 | 2010-10-23T20:10:03 | 2010-10-23T20:10:03 | 1,373,120 | 1 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 22,540 |
cpp
|
#include "goMidiManager.h"
static const int ports[] = {2,3,4,5,6,7,8,9,10};
//static const int keys[] = {48,50,52,53,55,57,59,60,62,64};
static const int keys[] = {60,61,62,63,64,65,66,68};
goMidiManager::goMidiManager()
{
//ctor
}
goMidiManager::~goMidiManager()
{
//dtor
}
void goMidiManager::setup()
{
// setup arduino
ard.connect("COM5", 57600);
PLAYSOLENOIDS = bSetupArduino = false; // flag so we setup arduino when its ready, you don't need to touch this :)
// setup midi
midiFXChannel = 0;
midiIn.openPort();
midiIn.setVerbose(false);
ofAddListener(midiIn.newMessageEvent, this, &goMidiManager::newMidiMessage);
}
// --- Listen midi events -.----
void goMidiManager::newMidiMessage(ofxMidiEventArgs &args)
{
int port;
int channel;
int status;
int byteOne;
int byteTwo;
double timestamp;
if (args.channel != 15) // strange signal from the SPD-S on channel 15 - need to mask
{
cout << "MIDI message [port: " << args.port << ", channel: " << args.channel << ", status: " << args.status << ", byteOne: " << args.byteOne << ", byteTwo: " << args.byteTwo << ", timestamp: " << args.timestamp << "]" << endl;
newMidiMsg.port = args.port;
newMidiMsg.channel = args.channel;
newMidiMsg.status = args.status;
newMidiMsg.byteOne = args.byteOne;
newMidiMsg.byteTwo = args.byteTwo;
newMidiMsg.timestamp = args.timestamp;
newMSG = true;
}
}
//--------------------------------------------------------------
void goMidiManager::update()
{
if ( ard.isArduinoReady())
{
// 1st: setup the arduino if haven't already:
if (bSetupArduino == false)
{
setupArduino();
bSetupArduino = true; // only do this once
}
// auto test by using the update arduino
//updateArduino();
for (int i = 0; i < 8; i++)
{
if(ofGetElapsedTimeMillis() - ardTimer[i] > 10) ard.sendDigital(ports[i], ARD_LOW);
}
}
if(newMSG)
{
newMSG = false;
lastMidiMsg.port = newMidiMsg.port;
lastMidiMsg.channel = newMidiMsg.channel;
lastMidiMsg.status = newMidiMsg.status;
lastMidiMsg.byteOne = newMidiMsg.byteOne;
lastMidiMsg.byteTwo = newMidiMsg.byteTwo;
lastMidiMsg.timestamp = newMidiMsg.timestamp;
for(int i = 0; i < 6; i++)
{
if (lastMidiMsg.channel >= LISTENCHBEG[i] && lastMidiMsg.channel <= LISTENCHEND[i])
{
if(LEARNRANGE[i])
{
LISTENNTBEG[i] = MIN(lastMidiMsg.byteOne, LISTENNTBEG[i]);
LISTENNTEND[i] = MAX(lastMidiMsg.byteOne, LISTENNTEND[i]);
}
newMSGCH[i] ^= true;
if (lastMidiMsg.byteOne >= LISTENNTBEG[i] && LISTENNTEND[i])
{
newMSGNT[i] ^= true;
}
switch (REMAPMODE[i])
{
case SOLENOID_CONTROL:
if (ard.isArduinoReady())
{
for (int j = 0; j < NUM_SOLENOIDS; j++)
{
if(lastMidiMsg.status == 144)
{
int mapPort = (int)floor(ofMap(lastMidiMsg.byteOne, LISTENNTBEG[i], LISTENNTEND[i], 0, 9, false));
ard.sendDigital(ports[mapPort], ARD_HIGH);
ardTimer[mapPort] = ofGetElapsedTimeMillis();
}
//ard.sendDigital(ports[i], ARD_LOW);
}
}
break;
case PARTICLE_GENERATE:
cout << PARTICLEMODE[i] << endl;
if(PARTICLEMODE[i] == 0)
{
for (int j = 0; j < 8; j++)
{
PARTICLES->generate(j, (int)ofRandom(0,lastMidiMsg.byteTwo));
}
}
else
{
PARTICLES->generate(PARTICLEMODE[i]-1, lastMidiMsg.byteTwo);
}
break;
case NOTE_TO_VIDEOS:
remap(i, 0.0f, GROUPS[0].numberLoaded, 0.0f, GROUPS[1].numberLoaded);
break;
case RANDOM_VIDEO:
remap(i, GROUPS[0].numberLoaded, GROUPS[1].numberLoaded);
break;
case FX_BLUR:
remap(i, &EFFECTS[0].blurAmount, &EFFECTS[1].blurAmount, 0.0f, 20.0f, 0.0f, 20.0f);
break;
case FX_FLIP_X:
remap(i, &EFFECTS[0].doFlipX, &EFFECTS[1].doFlipX);
break;
case FX_FLIP_Y:
remap(i, &EFFECTS[0].doFlipY, &EFFECTS[1].doFlipY);
break;
case FX_GREYSCALE:
remap(i, &EFFECTS[0].doGreyscale, &EFFECTS[1].doGreyscale);
break;
case FX_INVERT:
remap(i, &EFFECTS[0].doInvert, &EFFECTS[1].doInvert);
break;
case FX_THRESHOLD:
remap(i, &EFFECTS[0].threshLevel, &EFFECTS[1].threshLevel, 0.0f, 10.0f, 0.0f, 10.0f);
break;
case FX_SATURATION:
remap(i, &EFFECTS[0].saturationLevel, &EFFECTS[1].saturationLevel, 0.0f, 10.0f, 0.0f, 10.0f);
break;
case FX_CONTRAST:
remap(i, &EFFECTS[0].contrastLevel, &EFFECTS[1].contrastLevel, 0.0f, 10.0f, 0.0f, 10.0f);
break;
case FX_BRIGHTNESS:
remap(i, &EFFECTS[0].brightnessLevel, &EFFECTS[1].brightnessLevel, 0.0f, 10.0f, 0.0f, 10.0f);
break;
case X_FADER:
remap(i, &XFADE, &XFADE, -1.0, 1.0, -1.0, 1.0);
break;
case CH_FADER:
remap(i, &EFFECTS[0].fadeLevel, &EFFECTS[1].fadeLevel, 0.0f, 1.0f, 0.0f, 1.0f);
break;
case REVERSE_CHANNELS:
remap(i, &REVERSECHANNELS, &REVERSECHANNELS);
break;
}
}
}
if (lastMidiMsg.channel == CONTROLCHANNEL)
{
if (lastMidiMsg.status == 144 || !PROTECTCONTROL)
{
// note values change video
if (lastMidiMsg.byteOne >= 48 && lastMidiMsg.byteOne <=59)
{
GROUPS[0].playVideoInGroup((int)lastMidiMsg.byteOne - 48 + 12 * SELECTIONGRP[0]);
}
if (lastMidiMsg.byteOne >= 60 && lastMidiMsg.byteOne <=72)
{
GROUPS[1].playVideoInGroup((int)lastMidiMsg.byteOne - 60 + 12 * SELECTIONGRP[1]);
}
if(lastMidiMsg.byteOne > 35 && lastMidiMsg.byteOne < 44)
{
PARTICLES->generate(lastMidiMsg.byteOne-36, lastMidiMsg.byteTwo);
}
}
if (lastMidiMsg.status == 176 || !PROTECTCONTROL)
{
// Novation control data
if(lastMidiMsg.byteOne == 17)
{
PARTICLES->pWidth = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0, 720.0, false);
}
if(lastMidiMsg.byteOne == 18)
{
PARTICLES->pDamp = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0, 40.0, false);
}
if(lastMidiMsg.byteOne == 19)
{
PARTICLES->particlePattern = ofMap(lastMidiMsg.byteTwo, 0, 16, 0, 16, false);
}
if(lastMidiMsg.byteOne == 33)
{
SELECTIONGRP[0] = 0;
}
if(lastMidiMsg.byteOne == 34)
{
SELECTIONGRP[0] = 1;
}
if(lastMidiMsg.byteOne == 35)
{
SELECTIONGRP[0] = 2;
}
if(lastMidiMsg.byteOne == 36)
{
SELECTIONGRP[1] = 0;
}
if(lastMidiMsg.byteOne == 37)
{
SELECTIONGRP[1] = 1;
}
if(lastMidiMsg.byteOne == 38)
{
SELECTIONGRP[1] = 2;
}
if(lastMidiMsg.byteOne == 49)
{
PARTICLES->sizeParticle = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 50)
{
PARTICLES->speedParticle = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 51)
{
PARTICLES->linkParticle = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 52)
{
PARTICLES->particleColors = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 53)
{
PARTICLES->eraseParticle = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 56)
{
CONTROLLER->fullScreen();
}
if(lastMidiMsg.byteOne == 41 || lastMidiMsg.byteOne == 47)
{
MUTE[0] = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 42 || lastMidiMsg.byteOne == 48)
{
MUTE[1] = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 43)
{
CHANNELADIRECT = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 44)
{
EFFECTS[0].muteAll = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 45)
{
CHANNELBDIRECT = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 46)
{
EFFECTS[1].muteAll = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 30)
{
if (lastMidiMsg.byteTwo == 127) midiFXChannel = 0;
else midiFXChannel = 1;
}
if(lastMidiMsg.byteOne == 25)
{
EFFECTS[midiFXChannel].doBlur = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 26)
{
EFFECTS[midiFXChannel].doThreshold = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 27)
{
EFFECTS[midiFXChannel].doSaturation = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 28)
{
EFFECTS[midiFXChannel].doContrast = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 29)
{
EFFECTS[midiFXChannel].doBrightness = !(bool)lastMidiMsg.byteTwo;
}
if(lastMidiMsg.byteOne == 9)
{
EFFECTS[midiFXChannel].blurAmount = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0, 20, true);
}
if(lastMidiMsg.byteOne == 10)
{
EFFECTS[midiFXChannel].threshLevel = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0.0f, 1.0f, true);
}
if(lastMidiMsg.byteOne == 11)
{
EFFECTS[midiFXChannel].saturationLevel = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0.0f, 10.0f, true);
}
if(lastMidiMsg.byteOne == 12)
{
EFFECTS[midiFXChannel].contrastLevel = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0.0f, 10.0f, true);
}
if(lastMidiMsg.byteOne == 13)
{
EFFECTS[midiFXChannel].brightnessLevel = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0.0f, 10.0f, true);
}
if(lastMidiMsg.byteOne == 41)
{
EFFECTS[0].videoSpeed = 1;
}
if(lastMidiMsg.byteOne == 42)
{
EFFECTS[1].videoSpeed = 1;
}
if(lastMidiMsg.byteOne == 7)
{
EFFECTS[0].videoSpeed = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, -5.0f, 5.0f, true);
}
if(lastMidiMsg.byteOne == 8)
{
EFFECTS[1].videoSpeed = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, -5.0f, 5.0f, true);
}
// x-fades
if (lastMidiMsg.byteOne == 1)
{
XFADE = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, -1.0f, 1.0f, true);
}
if (lastMidiMsg.byteOne == 2)
{
EFFECTS[0].fadeLevel = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0.0f, 1.0f, true);
}
if (lastMidiMsg.byteOne == 3)
{
EFFECTS[1].fadeLevel = ofMap(lastMidiMsg.byteTwo, 0.0f, 127.0f, 0.0f, 1.0f, true);
}
}
}
if (lastMidiMsg.channel == SOLENOIDCHANNEL)
{
if (lastMidiMsg.byteOne == 71)
{
if(lastMidiMsg.status == 144) PLAYSOLENOIDS ^= true;
//if(lastMidiMsg.status == 128) playSolenoids = false;
}
if (ard.isArduinoReady() && PLAYSOLENOIDS)
{
for (int i = 0; i < NUM_SOLENOIDS; i++)
{
if (keys[i] == lastMidiMsg.byteOne)
{
if(lastMidiMsg.status == 144)
{
ard.sendDigital(ports[i], ARD_HIGH);
ardTimer[i] = ofGetElapsedTimeMillis();
}
//if(lastMidiMsg.status == 128) ard.sendDigital(ports[i], ARD_LOW);
}
}
}
}
}
}
void goMidiManager::remap(int & index, bool * var0, bool * var1)
{
bool decision = (bool)floor(ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], 0, 2, true));
switch (CHANNELMODE[index])
{
case CHANNEL_BOTH:
*var0 = decision;
*var1 = decision;
break;
case CHANNEL_A:
*var0 = decision;
break;
case CHANNEL_B:
*var1 = decision;
break;
case CHANNEL_SPLIT:
if (lastMidiMsg.byteOne >= LISTENNTBEG[index] &&
lastMidiMsg.byteOne <= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f)
{
*var0 = (bool)floor(ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f, 0, 2, true));
}
if (lastMidiMsg.byteOne >= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f &&
lastMidiMsg.byteOne <= LISTENNTEND[index])
{
*var1 = (bool)floor(ofMap(lastMidiMsg.byteOne, floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f, LISTENNTEND[index], 0, 2, true));
}
break;
}
}
void goMidiManager::remap(int & index, int rBegin0, int rEnd0, int rBegin1, int rEnd1)
{
switch (CHANNELMODE[index])
{
case CHANNEL_BOTH:
GROUPS[0].playVideoInGroup(ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin0, rEnd0, true));
GROUPS[1].playVideoInGroup(ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin1, rEnd1, true));
break;
case CHANNEL_A:
GROUPS[0].playVideoInGroup(ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin0, rEnd0, true));
break;
case CHANNEL_B:
GROUPS[1].playVideoInGroup(ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin1, rEnd1, true));
break;
case CHANNEL_SPLIT:
if (lastMidiMsg.byteOne >= LISTENNTBEG[index] &&
lastMidiMsg.byteOne <= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f)
{
GROUPS[0].playVideoInGroup(ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f, rBegin0, rEnd0, true));
}
if (lastMidiMsg.byteOne >= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f &&
lastMidiMsg.byteOne <= LISTENNTEND[index])
{
GROUPS[1].playVideoInGroup(ofMap(lastMidiMsg.byteOne, floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f, LISTENNTEND[index], rBegin1, rEnd0, true));
}
break;
}
}
void goMidiManager::remap(int & index, int maxR0, int maxR1)
{
switch (CHANNELMODE[index])
{
case CHANNEL_BOTH:
GROUPS[0].playVideoInGroup(ofRandom(0, maxR0));
GROUPS[1].playVideoInGroup(ofRandom(0, maxR1));
break;
case CHANNEL_A:
GROUPS[0].playVideoInGroup(ofRandom(0, maxR0));
break;
case CHANNEL_B:
GROUPS[1].playVideoInGroup(ofRandom(0, maxR1));
break;
case CHANNEL_SPLIT:
if (lastMidiMsg.byteOne >= LISTENNTBEG[index] &&
lastMidiMsg.byteOne <= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f)
{
GROUPS[0].playVideoInGroup(ofRandom(0, maxR0));
}
if (lastMidiMsg.byteOne >= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f &&
lastMidiMsg.byteOne <= LISTENNTEND[index])
{
GROUPS[1].playVideoInGroup(ofRandom(0, maxR1));
}
break;
}
}
void goMidiManager::remap(int & index, int * var0, int * var1, float rBegin0, float rEnd0, float rBegin1, float rEnd1)
{
switch (CHANNELMODE[index])
{
case CHANNEL_BOTH:
*var0 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin0, rEnd0, true);
*var1 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin1, rEnd1, true);
break;
case CHANNEL_A:
*var0 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin0, rEnd0, true);
break;
case CHANNEL_B:
*var1 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin1, rEnd1, true);
break;
case CHANNEL_SPLIT:
if (lastMidiMsg.byteOne >= LISTENNTBEG[index] &&
lastMidiMsg.byteOne <= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f)
{
*var0 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f, rBegin0, rEnd0, true);
}
if (lastMidiMsg.byteOne >= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f &&
lastMidiMsg.byteOne <= LISTENNTEND[index])
{
*var1 = ofMap(lastMidiMsg.byteOne, floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f, LISTENNTEND[index], rBegin1, rEnd0, true);
}
break;
}
}
void goMidiManager::remap(int & index, float * var0, float * var1, float rBegin0, float rEnd0, float rBegin1, float rEnd1)
{
switch (CHANNELMODE[index])
{
case CHANNEL_BOTH:
*var0 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin0, rEnd0, true);
*var1 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin1, rEnd1, true);
break;
case CHANNEL_A:
*var0 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin0, rEnd0, true);
break;
case CHANNEL_B:
*var1 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], LISTENNTEND[index], rBegin1, rEnd1, true);
break;
case CHANNEL_SPLIT:
if (lastMidiMsg.byteOne >= LISTENNTBEG[index] &&
lastMidiMsg.byteOne <= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f)
{
*var0 = ofMap(lastMidiMsg.byteOne, LISTENNTBEG[index], floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f, rBegin0, rEnd0, true);
}
if (lastMidiMsg.byteOne >= floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f &&
lastMidiMsg.byteOne <= LISTENNTEND[index])
{
*var1 = ofMap(lastMidiMsg.byteOne, floor(LISTENNTBEG[index] + LISTENNTEND[index])/2.0f, LISTENNTEND[index], rBegin1, rEnd0, true);
}
break;
}
}
//--------------------------------------------------------------
void goMidiManager::setupArduino()
{
// this is where you setup all the pins and pin modes, etc
for (int i = 0; i < NUM_SOLENOIDS; i++)
{
ard.sendDigitalPinMode(ports[i], ARD_OUTPUT);
}
}
//--------------------------------------------------------------
void goMidiManager::updateArduino()
{
// update the arduino, get any data or messages:
ard.update();
if(ofGetFrameNum()%2 == 1)
{
for (int i = 0; i < NUM_SOLENOIDS; i++) ard.sendDigital(ports[i], ARD_LOW);
}
else
{
for (int i = 0; i < NUM_SOLENOIDS; i++) ard.sendDigital(ports[i], ARD_HIGH);
}
}
goMidiManager::goMidiManager(const goMidiManager& other)
{
//copy ctor
}
goMidiManager& goMidiManager::operator=(const goMidiManager& rhs)
{
if (this == &rhs) return *this; // handle self assignment
//assignment operator
return *this;
}
|
[
"gameover@4bdaed08-0356-49c7-8fa1-902f09de843b"
] |
[
[
[
1,
607
]
]
] |
44c5bf18f7a4b1bd23e049f72d9e86c5d5178869
|
62874cd4e97b2cfa74f4e507b798f6d5c7022d81
|
/src/PropertiesEditor/PropertyWidgetReal.h
|
0f7bf6573a1f7399a1c4bb1afb5c85c448769a44
|
[] |
no_license
|
rjaramih/midi-me
|
6a4047e5f390a5ec851cbdc1b7495b7fe80a4158
|
6dd6a1a0111645199871f9951f841e74de0fe438
|
refs/heads/master
| 2021-03-12T21:31:17.689628 | 2011-07-31T22:42:05 | 2011-07-31T22:42:05 | 36,944,802 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 1,141 |
h
|
#ifndef PROPERTIESEDITOR_PROPERTYWIDGETREAL_H
#define PROPERTIESEDITOR_PROPERTYWIDGETREAL_H
// Includes
#include "PropertyWidget.h"
#include "PropertyWidgetCreator.h"
// Forward declarations
class QDoubleSpinBox;
namespace MidiMe
{
// Forward declarations
class RealProperty;
class PROPERTIESEDITOR_API PropertyWidgetReal : public PropertyWidget
{
Q_OBJECT
public:
// Constructors and destructor
PropertyWidgetReal(RealProperty *pProperty, QWidget *parent = NULL);
virtual ~PropertyWidgetReal();
// PropertyWidget functions
void updateFromProperty();
private slots:
void changed(double value);
private:
// Member variables
QDoubleSpinBox *m_pDoubleSpinBox;
};
class PROPERTIESEDITOR_API PropertyWidgetCreatorReal : public PropertyWidgetCreator
{
public:
PropertyWidgetCreatorReal() : PropertyWidgetCreator("real") {}
// PropertyWidgetCreator functions
PropertyWidget * createWidget(Property *pProperty) { return new PropertyWidgetReal((RealProperty *) pProperty); }
void destroyWidget(PropertyWidget *pWidget) { delete pWidget; }
};
}
#endif // PROPERTIESEDITOR_PROPERTYWIDGETREAL_H
|
[
"Jeroen.Dierckx@d8a2fbcc-2753-0410-82a0-8bc2cd85795f"
] |
[
[
[
1,
47
]
]
] |
26eda82e33439c060738b955532fdf3b7a0b6d46
|
0468c65f767387da526efe03b37e1d6e8ddd1815
|
/source/drivers/win/window.cpp
|
28fdadf9cc34ba032ce38c5c2b8c967e3e6aa68d
|
[] |
no_license
|
arntsonl/fc2x
|
aadc4e1a6c4e1d5bfcc76a3815f1f033b2d7e2fd
|
57ffbf6bcdf0c0b1d1e583663e4466adba80081b
|
refs/heads/master
| 2021-01-13T02:22:19.536144 | 2011-01-11T22:48:58 | 2011-01-11T22:48:58 | 32,103,729 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 86,450 |
cpp
|
/* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2002 Xodnizel
*
* 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.
*f
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// File description: Everything relevant for the main window should go here. This
// does not include functions relevant for dialog windows.
#include "../../input.h"
#include "../../state.h"
#include "../../cheat.h" //adelikat: For FCEU_LoadGameCheats()
#include "../../version.h"
#include "../../video.h" //adelikat: For ScreenshotAs Get/Set functions
#include "window.h"
#include "main.h"
#include "state.h"
#include "sound.h"
#include "wave.h"
#include "input.h"
#include "video.h"
#include "input.h"
#include "fceu.h"
#include "ram_search.h"
#include "ramwatch.h"
#include "memwatch.h"
#include "ppuview.h"
#include "debugger.h"
#include "cheat.h"
#include "debug.h"
#include "ntview.h"
#include "memview.h"
#include "tracer.h"
#include "cdlogger.h"
#include "throttle.h"
#include "monitor.h"
#include "tasedit.h"
#include "keyboard.h"
#include "joystick.h"
#include "oldmovie.h"
#include "movie.h"
#include "texthook.h"
#include "guiconfig.h"
#include "timing.h"
#include "palette.h"
#include "directories.h"
#include "gui.h"
#include "help.h"
#include "movie.h"
//#include "fceulua.h"
#include "utils/xstring.h"
#include "file.h"
#include "mapinput.h"
#include "movieoptions.h"
#include "config.h" //adelikat: For SaveConfigFile()
#include <fstream>
#include <sstream>
#include <cmath>
using namespace std;
//----Context Menu - Some dynamically added menu items
#define FCEUX_CONTEXT_UNHIDEMENU 60000
#define FCEUX_CONTEXT_LOADLASTLUA 60001
#define FCEUX_CONTEXT_CLOSELUAWINDOWS 60002
#define FCEUX_CONTEXT_TOGGLESUBTITLES 60003
#define FCEUX_CONTEXT_DUMPSUBTITLES 60004
//********************************************************************************
//Globals
//********************************************************************************
//Handles----------------------------------------------
static HMENU fceumenu = 0; //Main menu.
HWND pwindow; //Client Area
static HMENU recentmenu; //Recent Menu
static HMENU recentluamenu; //Recent Lua Files Menu
static HMENU recentmoviemenu; //Recent Movie Files Menu
HMENU hfceuxcontext; //Handle to context menu
HMENU hfceuxcontextsub; //Handle to context sub menu
HWND MainhWnd; //Main FCEUX(Parent) window Handle. Dialogs should use GetMainHWND() to get this
//Extern variables-------------------------------------
extern bool movieSubtitles;
extern FCEUGI *GameInfo;
extern int EnableAutosave;
extern bool frameAdvanceLagSkip;
extern bool turbo;
extern bool movie_readonly;
extern bool AutoSS; //flag for whether an auto-save has been made
extern int newppu;
extern BOOL CALLBACK ReplayMetadataDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); //Metadata dialog
extern bool CheckFileExists(const char* filename); //Receives a filename (fullpath) and checks to see if that file exists
extern bool oldInputDisplay;
//AutoFire-----------------------------------------------
void ShowNetplayConsole(void); //mbg merge 7/17/06 YECH had to add
void MapInput(void);
void SetAutoFirePattern(int onframes, int offframes);
void SetAutoFireOffset(int offset);
static int CheckedAutoFirePattern = MENU_AUTOFIRE_PATTERN_1;
static int CheckedAutoFireOffset = MENU_AUTOFIRE_OFFSET_1;
int GetCheckedAutoFirePattern();
int GetCheckedAutoFireOffset();
//Internal variables-------------------------------------
bool AVIdisableMovieMessages = false;
char *md5_asciistr(uint8 digest[16]);
static int winwidth, winheight;
static volatile int nofocus = 0;
static int tog = 0; //Toggle for Hide Menu
static bool loggingSound = false;
static LONG WindowXC=1<<30,WindowYC;
int MainWindow_wndx, MainWindow_wndy;
static uint32 mousex,mousey,mouseb;
static int vchanged = 0;
int menuYoffset = 0;
bool wasPausedByCheats = false; //For unpausing the emulator if paused by the cheats dialog
bool rightClickEnabled = true; //If set to false, the right click context menu will be disabled.
//Function Prototypes
void ChangeMenuItemText(int menuitem, string text); //Alters a menu item name
void ChangeContextMenuItemText(int menuitem, string text, HMENU menu); //Alters a context menu item name
void SaveMovieAs(); //Gets a filename for Save Movie As...
void OpenRamSearch();
void OpenRamWatch();
void SaveSnapshotAs();
//Recent Menu Strings ------------------------------------
char *recent_files[] = { 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 };
const unsigned int MENU_FIRST_RECENT_FILE = 600;
const unsigned int MAX_NUMBER_OF_RECENT_FILES = sizeof(recent_files)/sizeof(*recent_files);
//Lua Console --------------------------------------------
//TODO: these need to be in a header file instead
//extern HWND LuaConsoleHWnd;
//extern INT_PTR CALLBACK DlgLuaScriptDialog(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam);
//extern void UpdateLuaConsole(const char* fname);
//Recent Lua Menu ----------------------------------------
//char *recent_lua[] = {0,0,0,0,0};
//const unsigned int LUA_FIRST_RECENT_FILE = 50000;
//const unsigned int MAX_NUMBER_OF_LUA_RECENT_FILES = sizeof(recent_lua)/sizeof(*recent_lua);
//Recent Movie Menu -------------------------------------
char *recent_movie[] = {0,0,0,0,0};
const unsigned int MOVIE_FIRST_RECENT_FILE = 51000;
const unsigned int MAX_NUMBER_OF_MOVIE_RECENT_FILES = sizeof(recent_movie)/sizeof(*recent_movie);
//Exported variables ------------------------------------
int EnableBackgroundInput = 0;
int ismaximized = 0;
//Help Menu subtopics
string moviehelp = "{695C964E-B83F-4A6E-9BA2-1A975387DB55}"; //Movie Recording
string gettingstartedhelp = "{C76AEBD9-1E27-4045-8A37-69E5A52D0F9A}";//Getting Started
//********************************************************************************
void SetMainWindowText()
{
if (GameInfo)
{
//Add the filename to the window caption
extern char FileBase[];
string str = FCEU_NAME_AND_VERSION;
str.append(": ");
str.append(FileBase);
if (FCEUMOV_IsLoaded())
{
str.append(" Playing: ");
str.append(StripPath(FCEUI_GetMovieName()));
}
SetWindowText(hAppWnd, str.c_str());
}
else
SetWindowText(hAppWnd, FCEU_NAME_AND_VERSION);
}
bool HasRecentFiles()
{
for (int x = 0; x < MAX_NUMBER_OF_RECENT_FILES; x++)
{
if (recent_files[x])
return true;
}
return false;
}
HWND GetMainHWND()
{
return MainhWnd;
}
int GetCheckedAutoFirePattern()
{
//adelikat: sorry, I'm sure there is an easier way to accomplish this.
//This function allows the proper check to be displayed on the auto-fire pattern offset at start up when another autofire pattern is saved in config
if (AFon == 1 && AFoff == 2) return MENU_AUTOFIRE_PATTERN_2;
if (AFon == 1 && AFoff == 3) return MENU_AUTOFIRE_PATTERN_3;
if (AFon == 1 && AFoff == 4) return MENU_AUTOFIRE_PATTERN_4;
if (AFon == 1 && AFoff == 5) return MENU_AUTOFIRE_PATTERN_5;
if (AFon == 2 && AFoff == 1) return MENU_AUTOFIRE_PATTERN_6;
if (AFon == 2 && AFoff == 2) return MENU_AUTOFIRE_PATTERN_7;
if (AFon == 2 && AFoff == 3) return MENU_AUTOFIRE_PATTERN_8;
if (AFon == 2 && AFoff == 4) return MENU_AUTOFIRE_PATTERN_9;
if (AFon == 3 && AFoff == 1) return MENU_AUTOFIRE_PATTERN_10;
if (AFon == 3 && AFoff == 2) return MENU_AUTOFIRE_PATTERN_11;
if (AFon == 3 && AFoff == 3) return MENU_AUTOFIRE_PATTERN_12;
if (AFon == 4 && AFoff == 1) return MENU_AUTOFIRE_PATTERN_13;
if (AFon == 4 && AFoff == 2) return MENU_AUTOFIRE_PATTERN_14;
if (AFon == 5 && AFoff == 1) return MENU_AUTOFIRE_PATTERN_15;
return MENU_AUTOFIRE_PATTERN_1;
}
int GetCheckedAutoFireOffset()
{
if (AutoFireOffset == 1) return MENU_AUTOFIRE_OFFSET_2;
if (AutoFireOffset == 2) return MENU_AUTOFIRE_OFFSET_3;
if (AutoFireOffset == 3) return MENU_AUTOFIRE_OFFSET_4;
if (AutoFireOffset == 4) return MENU_AUTOFIRE_OFFSET_5;
if (AutoFireOffset == 5) return MENU_AUTOFIRE_OFFSET_6;
return MENU_AUTOFIRE_OFFSET_1;
}
// Internal functions
static void ConvertFCM(HWND hwndOwner)
{
std::string initdir = FCEU_GetPath(FCEUMKF_MOVIE);
OPENFILENAME ofn;
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwndOwner;
ofn.lpstrFilter = "FCEU <2.0 Movie Files (*.fcm)\0*.fcm\0All Files (*.*)\0*.*\0\0";
ofn.lpstrFile = new char[640*1024]; //640K should be enough for anyone
ofn.lpstrFile[0] = 0;
ofn.nMaxFile = 640*1024;
ofn.lpstrInitialDir = initdir.c_str();
ofn.Flags = OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT | OFN_EXPLORER;
ofn.lpstrDefExt = "fcm";
ofn.lpstrTitle = "Select old movie(s) for conversion";
if(GetOpenFileName(&ofn))
{
std::vector<std::string> todo;
//build a list of movies to convert. this might be one, or it might be many, depending on what the user selected
if(ofn.nFileExtension==0)
{
//multiselect
std::string dir = ofn.lpstrFile;
char* cp = ofn.lpstrFile + dir.size() + 1;
while(*cp)
{
std::string fname = cp;
todo.push_back(dir + "/" + fname);
cp += fname.size() + 1;
}
}
else
{
todo.push_back(ofn.lpstrFile);
}
SetCursor(LoadCursor(0,IDC_WAIT));
//convert each movie
int okcount = 0;
for(uint32 i=0;i<todo.size();i++)
{
std::string infname = todo[i];
//produce output filename
std::string outname;
size_t dot = infname.find_last_of(".");
if(dot == std::string::npos)
outname = infname + ".fm2";
else
outname = infname.substr(0,dot) + ".fm2";
MovieData md;
EFCM_CONVERTRESULT result = convert_fcm(md, infname);
if(result==FCM_CONVERTRESULT_SUCCESS)
{
okcount++;
EMUFILE_FILE* outf = FCEUD_UTF8_fstream(outname, "wb");
md.dump(outf,false);
delete outf;
} else {
std::string msg = "Failure converting " + infname + "\r\n\r\n" + EFCM_CONVERTRESULT_message(result);
MessageBox(hwndOwner,msg.c_str(),"Failure converting fcm", 0);
}
}
std::string okmsg = "Converted " + stditoa(okcount) + " movie(s). There were " + stditoa(todo.size()-okcount) + " failure(s).";
MessageBox(hwndOwner,okmsg.c_str(),"FCM Conversion results", 0);
}
delete[] ofn.lpstrFile;
}
void CalcWindowSize(RECT *al)
{
al->left = 0;
al->right = VNSWID * winsizemulx;
al->top = 0;
al->bottom = (FSettings.TotalScanlines() * winsizemuly) + menuYoffset;
AdjustWindowRectEx(al,
GetWindowLong(hAppWnd, GWL_STYLE),
GetMenu(hAppWnd) != NULL,
GetWindowLong(hAppWnd, GWL_EXSTYLE)
);
al->right -= al->left;
al->left = 0;
al->bottom -= al->top;
al->top=0;
}
/// Updates the menu items that should only be enabled if a game is loaded.
/// @param enable Flag that indicates whether the menus should be enabled (1) or disabled (0).
void updateGameDependentMenus(unsigned int enable)
{
const int menu_ids[]= {
MENU_CLOSE_FILE,
MENU_RESET,
MENU_POWER,
MENU_INSERT_COIN,
MENU_SWITCH_DISK,
MENU_EJECT_DISK,
MENU_RECORD_AVI,
MENU_STOP_AVI,
MENU_RECORD_WAV,
MENU_STOP_WAV,
MENU_HIDE_MENU,
//MENU_DEBUGGER,
MENU_PPUVIEWER,
MENU_NAMETABLEVIEWER,
MENU_HEXEDITOR,
MENU_TRACELOGGER,
MENU_CDLOGGER,
MENU_GAMEGENIEDECODER,
MENU_CHEATS,
ID_RAM_SEARCH,
ID_RAM_WATCH,
ID_TOOLS_TEXTHOOKER
};
for (unsigned int i = 0; i < sizeof(menu_ids) / sizeof(*menu_ids); i++)
{
/*
adelikat: basicbot is gone
#ifndef _USE_SHARED_MEMORY_
if(simpled[x] == MENU_BASIC_BOT)
EnableMenuItem(fceumenu,menu_ids[i],MF_BYCOMMAND| MF_GRAYED);
else
#endif
*/
EnableMenuItem(fceumenu, menu_ids[i], MF_BYCOMMAND | (enable ? MF_ENABLED : MF_GRAYED));
}
}
//Updates menu items which need to be checked or unchecked.
void UpdateCheckedMenuItems()
{
bool spr, bg;
FCEUI_GetRenderPlanes(spr,bg);
static int *polo[] = { &genie, &pal_emulation, &status_icon};
static int polo2[]={ MENU_GAME_GENIE, MENU_PAL, MENU_SHOW_STATUS_ICON };
int x;
// Check or uncheck the necessary menu items
for(x = 0; x < sizeof(polo) / sizeof(*polo); x++)
{
CheckMenuItem(fceumenu, polo2[x], *polo[x] ? MF_CHECKED : MF_UNCHECKED);
}
//File Menu
CheckMenuItem(fceumenu, ID_FILE_MOVIE_TOGGLEREAD, movie_readonly ? MF_CHECKED : MF_UNCHECKED);
//CheckMenuItem(fceumenu, ID_FILE_OPENLUAWINDOW, LuaConsoleHWnd ? MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, ID_AVI_DISMOVIEMESSAGE, AVIdisableMovieMessages ? MF_CHECKED : MF_UNCHECKED);
//NES Menu
CheckMenuItem(fceumenu, ID_NES_PAUSE, EmulationPaused ? MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, ID_NES_TURBO, turbo ? MF_CHECKED : MF_UNCHECKED);
//Config Menu
// CheckMenuItem(fceumenu, MENU_PAUSEAFTERPLAYBACK, pauseAfterPlayback ? MF_CHECKED : MF_UNCHECKED); // no more
CheckMenuItem(fceumenu, MENU_RUN_IN_BACKGROUND, eoptions & EO_BGRUN ? MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_BACKGROUND_INPUT, EnableBackgroundInput ? MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_ENABLE_AUTOSAVE, EnableAutosave ? MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_DISPLAY_FA_LAGSKIP, frameAdvanceLagSkip?MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_CONFIG_BINDSAVES, bindSavestate?MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, ID_ENABLE_BACKUPSAVESTATES, backupSavestates?MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, ID_ENABLE_COMPRESSSAVESTATES, compressSavestates?MF_CHECKED : MF_UNCHECKED);
//Config - Display SubMenu
CheckMenuItem(fceumenu, MENU_DISPLAY_LAGCOUNTER, lagCounterDisplay?MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, ID_DISPLAY_FRAMECOUNTER, frame_display ? MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_DISPLAY_BG, bg?MF_CHECKED:MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_DISPLAY_OBJ, spr?MF_CHECKED:MF_UNCHECKED);
CheckMenuItem(fceumenu, ID_INPUTDISPLAY_OLDSTYLEDISP, oldInputDisplay?MF_CHECKED:MF_UNCHECKED);
//Config - Movie Options, no longer in menu
//CheckMenuItem(fceumenu, ID_DISPLAY_MOVIESUBTITLES, movieSubtitles?MF_CHECKED:MF_UNCHECKED);
//CheckMenuItem(fceumenu, ID_DISPLAY_MOVIESUBTITLES_AVI, subtitlesOnAVI?MF_CHECKED:MF_UNCHECKED);
//Tools Menu
CheckMenuItem(fceumenu, MENU_ALTERNATE_AB, GetAutoFireDesynch() ? MF_CHECKED : MF_UNCHECKED);
//AutoFire Patterns
int AutoFirePatternIDs[] = {
MENU_AUTOFIRE_PATTERN_1,
MENU_AUTOFIRE_PATTERN_2,
MENU_AUTOFIRE_PATTERN_3,
MENU_AUTOFIRE_PATTERN_4,
MENU_AUTOFIRE_PATTERN_5,
MENU_AUTOFIRE_PATTERN_6,
MENU_AUTOFIRE_PATTERN_7,
MENU_AUTOFIRE_PATTERN_8,
MENU_AUTOFIRE_PATTERN_9,
MENU_AUTOFIRE_PATTERN_10,
MENU_AUTOFIRE_PATTERN_11,
MENU_AUTOFIRE_PATTERN_12,
MENU_AUTOFIRE_PATTERN_13,
MENU_AUTOFIRE_PATTERN_14,
MENU_AUTOFIRE_PATTERN_15,
0};
int AutoFireOffsetIDs[] = {
MENU_AUTOFIRE_OFFSET_1,
MENU_AUTOFIRE_OFFSET_2,
MENU_AUTOFIRE_OFFSET_3,
MENU_AUTOFIRE_OFFSET_4,
MENU_AUTOFIRE_OFFSET_5,
MENU_AUTOFIRE_OFFSET_6,
0};
x = 0;
CheckedAutoFirePattern = GetCheckedAutoFirePattern();
CheckedAutoFireOffset = GetCheckedAutoFireOffset();
while(AutoFirePatternIDs[x])
{
CheckMenuItem(fceumenu, AutoFirePatternIDs[x],
AutoFirePatternIDs[x] == CheckedAutoFirePattern ? MF_CHECKED : MF_UNCHECKED);
x++;
}
x = 0;
while(AutoFireOffsetIDs[x])
{
CheckMenuItem(fceumenu, AutoFireOffsetIDs[x],
AutoFireOffsetIDs[x] == CheckedAutoFireOffset ? MF_CHECKED : MF_UNCHECKED);
x++;
}
//Check input display
CheckMenuItem(fceumenu, MENU_INPUTDISPLAY_0, MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_INPUTDISPLAY_1, MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_INPUTDISPLAY_2, MF_UNCHECKED);
CheckMenuItem(fceumenu, MENU_INPUTDISPLAY_4, MF_UNCHECKED);
switch (input_display)
{
case 0: //Off
CheckMenuItem(fceumenu, MENU_INPUTDISPLAY_0, MF_CHECKED);
break;
case 1: //1 player
CheckMenuItem(fceumenu, MENU_INPUTDISPLAY_1, MF_CHECKED);
break;
case 2: //2 player
CheckMenuItem(fceumenu, MENU_INPUTDISPLAY_2, MF_CHECKED);
break;
//note: input display can actually have a 3 player display option but is skipped in the hotkey toggle so it is skipped here as well
case 4: //4 player
CheckMenuItem(fceumenu, MENU_INPUTDISPLAY_4, MF_CHECKED);
break;
default:
break;
}
}
void UpdateContextMenuItems(HMENU context, int whichContext)
{
string undoLoadstate = "Undo loadstate";
string redoLoadstate = "Redo loadstate";
string undoSavestate = "Undo savestate";
string redoSavestate = "Redo savestate";
CheckMenuItem(context,ID_CONTEXT_FULLSAVESTATES,MF_BYCOMMAND | fullSaveStateLoads?MF_CHECKED:MF_UNCHECKED);
//Undo Loadstate
if (CheckBackupSaveStateExist() && (undoLS || redoLS))
EnableMenuItem(context,FCEUX_CONTEXT_UNDOLOADSTATE,MF_BYCOMMAND | MF_ENABLED);
else
EnableMenuItem(context,FCEUX_CONTEXT_UNDOLOADSTATE,MF_BYCOMMAND | MF_GRAYED);
if (redoLS)
ChangeContextMenuItemText(FCEUX_CONTEXT_UNDOLOADSTATE, redoLoadstate, context);
else
ChangeContextMenuItemText(FCEUX_CONTEXT_UNDOLOADSTATE, undoLoadstate, context);
//Undo Savestate
if (undoSS || redoSS) //If undo or redo, enable Undo savestate, else keep it gray
EnableMenuItem(context,FCEUX_CONTEXT_UNDOSAVESTATE,MF_BYCOMMAND | MF_ENABLED);
else
EnableMenuItem(context,FCEUX_CONTEXT_UNDOSAVESTATE,MF_BYCOMMAND | MF_GRAYED);
if (redoSS)
ChangeContextMenuItemText(FCEUX_CONTEXT_UNDOSAVESTATE, redoSavestate, context);
else
ChangeContextMenuItemText(FCEUX_CONTEXT_UNDOSAVESTATE, undoSavestate, context);
//Rewind to last auto-save
if(EnableAutosave && AutoSS)
EnableMenuItem(context,FCEUX_CONTEXT_REWINDTOLASTAUTO,MF_BYCOMMAND | MF_ENABLED);
else
EnableMenuItem(context,FCEUX_CONTEXT_REWINDTOLASTAUTO,MF_BYCOMMAND | MF_GRAYED);
//Load last ROM
if (recent_files[0])
EnableMenuItem(context,FCEUX_CONTEXT_RECENTROM1,MF_BYCOMMAND | MF_ENABLED);
else
EnableMenuItem(context,FCEUX_CONTEXT_RECENTROM1,MF_BYCOMMAND | MF_GRAYED);
//Add Lua separator if either lua condition is true (yeah, a little ugly but it works)
#ifdef _S9XLUA_H
if (recent_lua[0] || FCEU_LuaRunning())
InsertMenu(context, 0xFFFF, MF_SEPARATOR, 0, "");
//If a recent lua file exists, add Load Last Lua
if (recent_lua[0])
InsertMenu(context, 0xFFFF, MF_BYCOMMAND, FCEUX_CONTEXT_LOADLASTLUA, "Load last Lua");
//If lua is loaded, add a stop lua item
if (FCEU_LuaRunning())
InsertMenu(context, 0xFFFF, MF_BYCOMMAND, FCEUX_CONTEXT_CLOSELUAWINDOWS, "Close All Script Windows");
#endif
//If menu is hidden, add an Unhide menu option
if (tog)
{
InsertMenu(context, 0xFFFF, MF_SEPARATOR, 0, "");
InsertMenu(context,0xFFFF, MF_BYCOMMAND, FCEUX_CONTEXT_UNHIDEMENU, "Unhide Menu");
}
if ( ( (whichContext == 0) || (whichContext == 3) ) && (currMovieData.subtitles.size()) ){
// At position 3 is "View comments and subtitles". Insert this there:
InsertMenu(context,0x3, MF_BYPOSITION, FCEUX_CONTEXT_TOGGLESUBTITLES, movieSubtitles ? "Subtitle Display: On" : "Subtitle Display: Off");
// At position 4(+1) is after View comments and subtitles. Insert this there:
InsertMenu(context,0x5, MF_BYPOSITION, FCEUX_CONTEXT_DUMPSUBTITLES, "Dump Subtitles to SRT file");
}
}
//adelikat: This removes a recent menu item from any recent menu, and shrinks the list accordingly
//The update recent menu function will need to be run after this
void RemoveRecentItem(unsigned int which, char**bufferArray, const unsigned int MAX)
{
//which = array item to remove
//buffer = char array of the recent menu
//MAX = max number of array items
//Just in case
if (which >= MAX)
return;
//Remove the item
if(bufferArray[which])
{
free(bufferArray[which]);
}
//If the item is not the last one in the list, shift the remaining ones up
if (which < (MAX-1))
{
//Move the remaining items up
for(unsigned int x = which+1; x < MAX; x++)
{
bufferArray[x-1] = bufferArray[x]; //Shift each remaining item up by 1
}
}
bufferArray[MAX-1] = 0; //Clear out the last item since it is empty now no matter what
}
/// Updates recent files / recent directories menu
/// @param menu Menu handle of the main window's menu
/// @param strs Strings to add to the menu
/// @param mitem Menu ID of the recent files / directory menu
/// @param baseid Menu ID of the first subitem
void UpdateRMenu(HMENU menu, char **strs, unsigned int mitem, unsigned int baseid)
{
// UpdateRMenu(recentmenu, recent_files, MENU_RECENT_FILES, MENU_FIRST_RECENT_FILE);
MENUITEMINFO moo;
int x;
moo.cbSize = sizeof(moo);
moo.fMask = MIIM_SUBMENU | MIIM_STATE;
GetMenuItemInfo(GetSubMenu(fceumenu, 0), mitem, FALSE, &moo);
moo.hSubMenu = menu;
moo.fState = strs[0] ? MFS_ENABLED : MFS_GRAYED;
SetMenuItemInfo(GetSubMenu(fceumenu, 0), mitem, FALSE, &moo);
// Remove all recent files submenus
for(x = 0; x < MAX_NUMBER_OF_RECENT_FILES; x++)
{
RemoveMenu(menu, baseid + x, MF_BYCOMMAND);
}
// Recreate the menus
for(x = MAX_NUMBER_OF_RECENT_FILES - 1; x >= 0; x--)
{
// Skip empty strings
if(!strs[x])
continue;
std::string tmp = strs[x];
std::string archiveName, fileName, fileToOpen;
FCEU_SplitArchiveFilename(tmp,archiveName,fileName,fileToOpen);
if(archiveName != "")
tmp = archiveName + " <" + fileName + ">";
//clamp this string to 128 chars
if(tmp.size()>128)
tmp = tmp.substr(0,128);
moo.cbSize = sizeof(moo);
moo.fMask = MIIM_DATA | MIIM_ID | MIIM_TYPE;
//// Fill in the menu text.
//if(strlen(strs[x]) < 128)
//{
// sprintf(tmp, "&%d. %s", ( x + 1 ) % 10, strs[x]);
//}
//else
//{
// sprintf(tmp, "&%d. %s", ( x + 1 ) % 10, strs[x] + strlen( strs[x] ) - 127);
//}
// Insert the menu item
moo.cch = tmp.size();
moo.fType = 0;
moo.wID = baseid + x;
moo.dwTypeData = (LPSTR)tmp.c_str();
InsertMenuItem(menu, 0, 1, &moo);
}
DrawMenuBar(hAppWnd);
}
/// Helper function to populate the recent directories and recent files arrays.
/// @param addString String to add to the array.
/// @param bufferArray Array where the string will be added.
/// @param arrayLen Length of the bufferArray.
/// @param menu Menu handle of the main menu.
/// @param menuItem
/// @param baseID
void UpdateRecentArray(const char* addString, char** bufferArray, unsigned int arrayLen, HMENU menu, unsigned int menuItem, unsigned int baseId)
{
// Try to find out if the filename is already in the recent files list.
for(unsigned int x = 0; x < arrayLen; x++)
{
if(bufferArray[x])
{
if(!strcmp(bufferArray[x], addString)) // Item is already in list.
{
// If the filename is in the file list don't add it again.
// Move it up in the list instead.
int y;
char *tmp;
// Save pointer.
tmp = bufferArray[x];
for(y = x; y; y--)
{
// Move items down.
bufferArray[y] = bufferArray[y - 1];
}
// Put item on top.
bufferArray[0] = tmp;
// Update the recent files menu
UpdateRMenu(menu, bufferArray, menuItem, baseId);
return;
}
}
}
// The filename wasn't found in the list. That means we need to add it.
// If there's no space left in the recent files list, get rid of the last
// item in the list.
if(bufferArray[arrayLen - 1])
{
free(bufferArray[arrayLen - 1]);
}
// Move the other items down.
for(unsigned int x = arrayLen - 1; x; x--)
{
bufferArray[x] = bufferArray[x - 1];
}
// Add the new item.
bufferArray[0] = (char*)malloc(strlen(addString) + 1); //mbg merge 7/17/06 added cast
strcpy(bufferArray[0], addString);
// Update the recent files menu
UpdateRMenu(menu, bufferArray, menuItem, baseId);
}
/// Add a filename to the recent files list.
/// @param filename Name of the file to add.
void AddRecentFile(const char *filename)
{
UpdateRecentArray(filename, recent_files, MAX_NUMBER_OF_RECENT_FILES, recentmenu, MENU_RECENT_FILES, MENU_FIRST_RECENT_FILE);
}
void UpdateLuaRMenu(HMENU menu, char **strs, unsigned int mitem, unsigned int baseid)
{
MENUITEMINFO moo;
int x;
moo.cbSize = sizeof(moo);
moo.fMask = MIIM_SUBMENU | MIIM_STATE;
GetMenuItemInfo(GetSubMenu(fceumenu, 0), mitem, FALSE, &moo);
moo.hSubMenu = menu;
moo.fState = strs[0] ? MFS_ENABLED : MFS_GRAYED;
SetMenuItemInfo(GetSubMenu(fceumenu, 0), mitem, FALSE, &moo);
// Remove all recent files submenus
/* for(x = 0; x < MAX_NUMBER_OF_LUA_RECENT_FILES; x++)
{
RemoveMenu(menu, baseid + x, MF_BYCOMMAND);
}
// Recreate the menus
for(x = MAX_NUMBER_OF_LUA_RECENT_FILES - 1; x >= 0; x--)
{
// Skip empty strings
if(!strs[x])
continue;
string tmp = strs[x];
//clamp this string to 128 chars
if(tmp.size()>128)
tmp = tmp.substr(0,128);
moo.cbSize = sizeof(moo);
moo.fMask = MIIM_DATA | MIIM_ID | MIIM_TYPE;
// Insert the menu item
moo.cch = tmp.size();
moo.fType = 0;
moo.wID = baseid + x;
moo.dwTypeData = (LPSTR)tmp.c_str();
InsertMenuItem(menu, 0, 1, &moo);
}
*/
DrawMenuBar(hAppWnd);
}
void UpdateRecentLuaArray(const char* addString, char** bufferArray, unsigned int arrayLen, HMENU menu, unsigned int menuItem, unsigned int baseId)
{
// Try to find out if the filename is already in the recent files list.
for(unsigned int x = 0; x < arrayLen; x++)
{
if(bufferArray[x])
{
if(!strcmp(bufferArray[x], addString)) // Item is already in list.
{
// If the filename is in the file list don't add it again.
// Move it up in the list instead.
int y;
char *tmp;
// Save pointer.
tmp = bufferArray[x];
for(y = x; y; y--)
{
// Move items down.
bufferArray[y] = bufferArray[y - 1];
}
// Put item on top.
bufferArray[0] = tmp;
// Update the recent files menu
UpdateLuaRMenu(menu, bufferArray, menuItem, baseId);
return;
}
}
}
// The filename wasn't found in the list. That means we need to add it.
// If there's no space left in the recent files list, get rid of the last
// item in the list.
if(bufferArray[arrayLen - 1])
{
free(bufferArray[arrayLen - 1]);
}
// Move the other items down.
for(unsigned int x = arrayLen - 1; x; x--)
{
bufferArray[x] = bufferArray[x - 1];
}
// Add the new item.
bufferArray[0] = (char*)malloc(strlen(addString) + 1); //mbg merge 7/17/06 added cast
strcpy(bufferArray[0], addString);
// Update the recent files menu
UpdateLuaRMenu(menu, bufferArray, menuItem, baseId);
}
void AddRecentLuaFile(const char *filename)
{
// UpdateRecentLuaArray(filename, recent_lua, MAX_NUMBER_OF_LUA_RECENT_FILES, recentluamenu, MENU_LUA_RECENT, LUA_FIRST_RECENT_FILE);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void UpdateMovieRMenu(HMENU menu, char **strs, unsigned int mitem, unsigned int baseid)
{
MENUITEMINFO moo;
int x;
moo.cbSize = sizeof(moo);
moo.fMask = MIIM_SUBMENU | MIIM_STATE;
GetMenuItemInfo(GetSubMenu(fceumenu, 0), mitem, FALSE, &moo);
moo.hSubMenu = menu;
moo.fState = strs[0] ? MFS_ENABLED : MFS_GRAYED;
SetMenuItemInfo(GetSubMenu(fceumenu, 0), mitem, FALSE, &moo);
// Remove all recent files submenus
for(x = 0; x < MAX_NUMBER_OF_MOVIE_RECENT_FILES; x++)
{
RemoveMenu(menu, baseid + x, MF_BYCOMMAND);
}
// Recreate the menus
for(x = MAX_NUMBER_OF_MOVIE_RECENT_FILES - 1; x >= 0; x--)
{
// Skip empty strings
if(!strs[x])
continue;
string tmp = strs[x];
//clamp this string to 128 chars
if(tmp.size()>128)
tmp = tmp.substr(0,128);
moo.cbSize = sizeof(moo);
moo.fMask = MIIM_DATA | MIIM_ID | MIIM_TYPE;
// Insert the menu item
moo.cch = tmp.size();
moo.fType = 0;
moo.wID = baseid + x;
moo.dwTypeData = (LPSTR)tmp.c_str();
InsertMenuItem(menu, 0, 1, &moo);
}
DrawMenuBar(hAppWnd);
}
void UpdateRecentMovieArray(const char* addString, char** bufferArray, unsigned int arrayLen, HMENU menu, unsigned int menuItem, unsigned int baseId)
{
// Try to find out if the filename is already in the recent files list.
for(unsigned int x = 0; x < arrayLen; x++)
{
if(bufferArray[x])
{
if(!strcmp(bufferArray[x], addString)) // Item is already in list.
{
// If the filename is in the file list don't add it again.
// Move it up in the list instead.
int y;
char *tmp;
// Save pointer.
tmp = bufferArray[x];
for(y = x; y; y--)
{
// Move items down.
bufferArray[y] = bufferArray[y - 1];
}
// Put item on top.
bufferArray[0] = tmp;
// Update the recent files menu
UpdateMovieRMenu(menu, bufferArray, menuItem, baseId);
return;
}
}
}
// The filename wasn't found in the list. That means we need to add it.
// If there's no space left in the recent files list, get rid of the last
// item in the list.
if(bufferArray[arrayLen - 1])
{
free(bufferArray[arrayLen - 1]);
}
// Move the other items down.
for(unsigned int x = arrayLen - 1; x; x--)
{
bufferArray[x] = bufferArray[x - 1];
}
// Add the new item.
bufferArray[0] = (char*)malloc(strlen(addString) + 1); //mbg merge 7/17/06 added cast
strcpy(bufferArray[0], addString);
// Update the recent files menu
UpdateMovieRMenu(menu, bufferArray, menuItem, baseId);
}
void AddRecentMovieFile(const char *filename)
{
UpdateRecentMovieArray(filename, recent_movie, MAX_NUMBER_OF_MOVIE_RECENT_FILES, recentmoviemenu, MENU_MOVIE_RECENT, MOVIE_FIRST_RECENT_FILE);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hides the main menu.
//@param hide_menu Flag to turn the main menu on (0) or off (1)
void HideMenu(unsigned int hide_menu)
{
if(hide_menu)
{
SetMenu(hAppWnd, 0);
}
else
{
SetMenu(hAppWnd, fceumenu);
}
}
void HideFWindow(int h)
{
LONG desa;
if(h) /* Full-screen. */
{
RECT bo;
GetWindowRect(hAppWnd, &bo);
WindowXC = bo.left;
WindowYC = bo.top;
SetMenu(hAppWnd, 0);
desa=WS_POPUP | WS_CLIPSIBLINGS;
}
else
{
desa = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS;
HideMenu(tog);
/* Stupid DirectDraw bug(I think?) requires this. Need to investigate it. */
SetWindowPos(hAppWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOREPOSITION | SWP_NOSIZE);
}
SetWindowLong(hAppWnd, GWL_STYLE ,desa | ( GetWindowLong(hAppWnd, GWL_STYLE) & WS_VISIBLE ));
SetWindowPos(hAppWnd, 0 ,0 ,0 ,0 ,0 ,SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
}
//Toggles the display status of the main menu.
void ToggleHideMenu(void)
{
if(!fullscreen && (GameInfo || tog))
{
tog ^= 1;
HideMenu(tog);
SetMainWindowStuff();
}
}
//Toggles the display status of the main menu.
//TODO: We could get rid of this one.
void FCEUD_HideMenuToggle(void)
{
ToggleHideMenu();
}
void CloseGame()
{
if (GameInfo)
{
FCEUI_CloseGame();
KillMemView();
updateGameDependentMenus(GameInfo != 0);
updateGameDependentMenusDebugger(GameInfo != 0);
SetMainWindowText();
}
}
bool ALoad(char *nameo, char* innerFilename)
{
if (GameInfo) FCEUI_CloseGame();
if(FCEUI_LoadGameVirtual(nameo, 1))
{
pal_emulation = FCEUI_GetCurrentVidSystem(0, 0);
UpdateCheckedMenuItems();
PushCurrentVideoSettings();
std::string recentFileName = nameo;
if(GameInfo->archiveFilename && GameInfo->archiveCount>1)
recentFileName = (std::string)GameInfo->archiveFilename + "|" + GameInfo->filename;
else
recentFileName = nameo;
AddRecentFile(recentFileName.c_str());
RefreshThrottleFPS();
if(eoptions & EO_HIDEMENU && !tog)
{
ToggleHideMenu();
}
if(eoptions & EO_FSAFTERLOAD)
{
SetFSVideoMode();
}
if (AutoRWLoad)
{
OpenRWRecentFile(0); //adelikat: TODO: This command should be called internally from the RamWatch dialog in order for it to be more portable
OpenRamWatch();
}
if (debuggerAutoload)
{
DoDebug(0);
}
}
else
{
SetWindowText(hAppWnd, FCEU_NAME_AND_VERSION); //adelikat: If game fails to load while a previous one was open, the previous would have been closed, so reflect that in the window caption
return false;
}
SetMainWindowText();
ParseGIInput(GameInfo);
updateGameDependentMenus(GameInfo != 0);
updateGameDependentMenusDebugger(GameInfo != 0);
return true;
}
/// Shows an Open File dialog and opens the ROM if the user selects a ROM file.
/// @param hParent Handle of the main window
/// @param initialdir Directory that's pre-selected in the Open File dialog.
void LoadNewGamey(HWND hParent, const char *initialdir)
{
const char filter[] = "All usable files (*.nes,*.nsf,*.fds,*.unf,*.zip,*.rar,*.7z,*.gz)\0*.nes;*.nsf;*.fds;*.unf;*.zip;*.rar;*.7z;*.gz\0All non-compressed usable files (*.nes,*.nsf,*.fds,*.unf)\0*.nes;*.nsf;*.fds;*.unf\0All Files (*.*)\0*.*\0\0";
char nameo[2048];
// Create the Open File dialog
OPENFILENAME ofn;
memset(&ofn,0,sizeof(ofn));
ofn.lStructSize=sizeof(ofn);
ofn.hInstance=fceu_hInstance;
ofn.lpstrTitle=FCEU_NAME" Open File...";
ofn.lpstrFilter=filter;
nameo[0]=0;
ofn.hwndOwner=hParent;
ofn.lpstrFile=nameo;
ofn.nMaxFile=256;
ofn.Flags=OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_HIDEREADONLY; //OFN_EXPLORER|OFN_ENABLETEMPLATE|OFN_ENABLEHOOK;
string stdinitdir =FCEU_GetPath(FCEUMKF_ROMS);
if (initialdir) //adelikat: If a directory is specified in the function parameter, it should take priority
ofn.lpstrInitialDir = initialdir;
else //adelikat: Else just use the override, if no override it will default to 0 - last directory used.
ofn.lpstrInitialDir = stdinitdir.c_str();
// Show the Open File dialog
if(GetOpenFileName(&ofn))
{
ALoad(nameo);
}
}
void GetMouseData(uint32 (&md)[3])
{
md[0] = mousex;
md[1] = mousey;
if(!fullscreen)
{
if(ismaximized)
{
RECT t;
GetClientRect(hAppWnd, &t);
md[0] = md[0] * VNSWID / (t.right ? t.right : 1);
md[1] = md[1] * FSettings.TotalScanlines() / (t.bottom ? t.bottom : 1);
}
else
{
md[0] /= winsizemulx;
md[1] /= winsizemuly;
}
md[0] += VNSCLIP;
}
md[1] += FSettings.FirstSLine;
md[2] = ((mouseb == MK_LBUTTON) ? 1 : 0) | (( mouseb == MK_RBUTTON ) ? 2 : 0);
}
void DumpSubtitles(HWND hWnd)
{
const char filter[]="Subtitles files (*.srt)\0*.srt\0All Files (*.*)\0*.*\0\0";
char nameo[2048];
OPENFILENAME ofn;
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrTitle="Save Subtitles as...";
ofn.lpstrFilter = filter;
strcpy(nameo,GetRomName());
ofn.lpstrFile = nameo;
ofn.nMaxFile = 256;
ofn.Flags = OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_HIDEREADONLY;
ofn.lpstrDefExt = "srt";
if (GetSaveFileName(&ofn))
{
FILE *srtfile;
srtfile = fopen(nameo, "w");
if (srtfile)
{
extern std::vector<int> subtitleFrames;
extern std::vector<std::string> subtitleMessages;
float fps = (currMovieData.palFlag == 0 ? 60.0988 : 50.0069); // NTSC vs PAL
float subduration = 3; // seconds for the subtitles to be displayed
for (unsigned int i = 0; i < subtitleFrames.size(); i++)
{
fprintf(srtfile, "%i\n", i+1); // starts with 1, not 0
double seconds, ms, endseconds, endms;
seconds = subtitleFrames[i]/fps;
if (i+1 < subtitleFrames.size()) // there's another subtitle coming after this one
{
if (subtitleFrames[i+1]-subtitleFrames[i] < subduration*fps) // avoid two subtitles at the same time
{
endseconds = (subtitleFrames[i+1]-1)/fps; // frame x: subtitle1; frame x+1 subtitle2
} else {
endseconds = seconds+subduration;
}
} else {
endseconds = seconds+subduration;
}
ms = modf(seconds, &seconds);
endms = modf(endseconds, &endseconds);
// this is just beyond ugly, don't show it to your kids
fprintf(srtfile,
"%02.0f:%02d:%02d,%03d --> %02.0f:%02d:%02d,%03d\n", // hh:mm:ss,ms --> hh:mm:ss,ms
floor(seconds/3600), (int)floor(seconds/60 ) % 60, (int)floor(seconds) % 60, (int)(ms*1000),
floor(endseconds/3600), (int)floor(endseconds/60) % 60, (int)floor(endseconds) % 60, (int)(endms*1000));
fprintf(srtfile, "%s\n\n", subtitleMessages[i].c_str()); // new line for every subtitle
}
}
fclose(srtfile);
}
return;
}
//Message loop of the main window
LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
MainhWnd = hWnd;
int whichContext = 0;
POINT pt;
RECT file_rect;
RECT help_rect;
int x = 0;
char TempArray[2048];
PCOPYDATASTRUCT pcData;
switch(msg)
{
case WM_COPYDATA:
pcData = (PCOPYDATASTRUCT) lParam;
switch ( pcData->dwData )
{
case 1: //cData.dwData = 1; (can use for other types as well)
if (!ALoad((LPSTR) ( (DATA *) (pcData->lpData) )-> strFilePath))
MessageBox(hWnd,"File from second instance failed to open", "Failed to open file", MB_OK);
break;
}
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
mouseb=wParam;
goto proco;
case WM_RBUTTONUP:
{
if (rightClickEnabled)
{
hfceuxcontext = LoadMenu(fceu_hInstance,"FCEUCONTEXTMENUS");
//If There is a movie loaded in read only
if (GameInfo && FCEUMOV_Mode(MOVIEMODE_PLAY|MOVIEMODE_RECORD|MOVIEMODE_FINISHED) && movie_readonly)
{
hfceuxcontextsub = GetSubMenu(hfceuxcontext,0);
whichContext = 0; // Game+Movie+readonly
}
//If there is a movie loaded in read+write
else if (GameInfo && FCEUMOV_Mode(MOVIEMODE_PLAY|MOVIEMODE_RECORD|MOVIEMODE_FINISHED) && !movie_readonly)
{
hfceuxcontextsub = GetSubMenu(hfceuxcontext,3);
whichContext = 3; // Game+Movie+readwrite
}
//If there is a ROM loaded but no movie
else if (GameInfo)
{
hfceuxcontextsub = GetSubMenu(hfceuxcontext,1);
whichContext = 1; // Game+NoMovie
}
//Else no ROM
else
{
hfceuxcontextsub = GetSubMenu(hfceuxcontext,2);
whichContext = 2; // NoGame
}
UpdateContextMenuItems(hfceuxcontextsub, whichContext);
pt.x = LOWORD(lParam); //Get mouse x in terms of client area
pt.y = HIWORD(lParam); //Get mouse y in terms of client area
ClientToScreen(hAppWnd, (LPPOINT) &pt); //Convert client area x,y to screen x,y
TrackPopupMenu(hfceuxcontextsub,0,(pt.x),(pt.y),TPM_RIGHTBUTTON,hWnd,0); //Create menu
}
}
case WM_MOVE:
{
if (!IsIconic(hWnd)) {
RECT wrect;
GetWindowRect(hWnd,&wrect);
MainWindow_wndx = wrect.left;
MainWindow_wndy = wrect.top;
#ifdef WIN32
WindowBoundsCheckNoResize(MainWindow_wndx,MainWindow_wndy,wrect.right);
#endif
}
}
case WM_MOUSEMOVE:
{
mousex=LOWORD(lParam);
mousey=HIWORD(lParam);
}
goto proco;
case WM_ERASEBKGND:
if(xbsave)
return(0);
else
goto proco;
case WM_PAINT:
if(xbsave)
{
PAINTSTRUCT ps;
BeginPaint(hWnd,&ps);
FCEUD_BlitScreen(xbsave);
EndPaint(hWnd,&ps);
return(0);
}
goto proco;
case WM_SIZE:
if(!fullscreen && !changerecursive)
switch(wParam)
{
case SIZE_MAXIMIZED:
ismaximized = 1;
SetMainWindowStuff();
break;
case SIZE_RESTORED:
ismaximized = 0;
SetMainWindowStuff();
break;
}
break;
case WM_SIZING:
{
RECT *wrect=(RECT *)lParam;
RECT srect;
int h=wrect->bottom-wrect->top;
int w=wrect->right-wrect->left;
int how = 0;
if(wParam == WMSZ_BOTTOM || wParam == WMSZ_TOP)
how = 2;
else if(wParam == WMSZ_LEFT || wParam == WMSZ_RIGHT)
how = 1;
else if(wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT
|| wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
how = 3;
if(how & 1)
winsizemulx*= (double)w/winwidth;
if(how & 2)
winsizemuly*= (double)h/winheight;
if(how & 1) FixWXY(0);
else FixWXY(1);
CalcWindowSize(&srect);
winwidth=srect.right;
winheight=srect.bottom;
wrect->right = wrect->left + srect.right;
wrect->bottom = wrect->top + srect.bottom;
GetMenuItemRect(hWnd, fceumenu, 0, &file_rect);
GetMenuItemRect(hWnd, fceumenu, 5, &help_rect);
menuYoffset = help_rect.top-file_rect.top;
}
//sizchange=1;
//break;
goto proco;
case WM_DISPLAYCHANGE:
if(!fullscreen && !changerecursive)
vchanged=1;
goto proco;
case WM_DROPFILES:
{
UINT len;
char *ftmp;
len=DragQueryFile((HDROP)wParam,0,0,0)+1;
if((ftmp=(char*)malloc(len)))
{
DragQueryFile((HDROP)wParam,0,ftmp,len);
string fileDropped = ftmp;
//adelikat: Drag and Drop only checks file extension, the internal functions are responsible for file error checking
//-------------------------------------------------------
//Check if a cheats (.cht) file
//-------------------------------------------------------
if (!(fileDropped.find(".cht") == string::npos) && (fileDropped.find(".cht") == fileDropped.length()-4))
{
FILE* file = FCEUD_UTF8fopen(fileDropped.c_str(),"rb");
FCEU_LoadGameCheats(file);
}
//-------------------------------------------------------
//Check if .fcm file, if so, convert it and play the resulting .fm2
//-------------------------------------------------------
else if (!(fileDropped.find(".fcm") == string::npos) && (fileDropped.find(".fcm") == fileDropped.length()-4))
{
//produce output filename
std::string outname;
size_t dot = fileDropped.find_last_of(".");
if(dot == std::string::npos)
outname = fileDropped + ".fm2";
else
outname = fileDropped.substr(0,dot) + ".fm2";
MovieData md;
EFCM_CONVERTRESULT result = convert_fcm(md, fileDropped.c_str());
if(result==FCM_CONVERTRESULT_SUCCESS)
{
EMUFILE* outf = FCEUD_UTF8_fstream(outname, "wb");
md.dump(outf,false);
delete outf;
if (!GameInfo) //If no game is loaded, load the Open Game dialog
LoadNewGamey(hWnd, 0);
FCEUI_LoadMovie(outname.c_str(), 1, false, false);
FCEUX_LoadMovieExtras(outname.c_str());
} else {
std::string msg = "Failure converting " + fileDropped + "\r\n\r\n" + EFCM_CONVERTRESULT_message(result);
MessageBox(hWnd,msg.c_str(),"Failure converting fcm", 0);
}
}
//-------------------------------------------------------
//Check if Palette file
//-------------------------------------------------------
else if (!(fileDropped.find(".pal") == string::npos) && (fileDropped.find(".pal") == fileDropped.length()-4))
{
SetPalette(fileDropped.c_str());
}
//-------------------------------------------------------
//Check if Movie file
//-------------------------------------------------------
else if (!(fileDropped.find(".fm2") == string::npos) && (fileDropped.find(".fm2") == fileDropped.length()-4)) //ROM is already loaded and .fm2 in filename
{
if (!GameInfo) //If no game is loaded, load the Open Game dialog
LoadNewGamey(hWnd, 0);
if (GameInfo && !(fileDropped.find(".fm2") == string::npos)) { //.fm2 is at the end of the filename so that must be the extension
FCEUI_LoadMovie(ftmp, 1, false, false); //We are convinced it is a movie file, attempt to load it
FCEUX_LoadMovieExtras(ftmp);
}
}
//-------------------------------------------------------
//Check if Savestate file
//-------------------------------------------------------
else if (!(fileDropped.find(".fc") == string::npos))
{
if (fileDropped.find(".fc") == fileDropped.length()-4) //Check to see it is both at the end (file extension) and there is on more character
{
if (fileDropped[fileDropped.length()-1] >= '0' && fileDropped[fileDropped.length()-1] <= '9') //If last character is 0-9 (making .fc0 - .fc9)
{
FCEUI_LoadState(fileDropped.c_str());
}
}
}
//-------------------------------------------------------
//Check if Lua file
//-------------------------------------------------------
#ifdef _S9XLUA_H
else if (!(fileDropped.find(".lua") == string::npos) && (fileDropped.find(".lua") == fileDropped.length()-4))
{
FCEU_LoadLuaCode(ftmp);
UpdateLuaConsole(fileDropped.c_str());
}
#endif
//-------------------------------------------------------
//Check if Ram Watch file
//-------------------------------------------------------
else if (!(fileDropped.find(".wch") == string::npos) && (fileDropped.find(".wch") == fileDropped.length()-4)) {
if (GameInfo) {
SendMessage(hWnd, WM_COMMAND, (WPARAM)ID_RAM_WATCH,(LPARAM)(NULL));
Load_Watches(true, fileDropped.c_str());
}
}
//-------------------------------------------------------
//If not a movie, Load it as a ROM file
//-------------------------------------------------------
else
{
ALoad(ftmp);
free(ftmp);
}
}
}
break;
case WM_COMMAND:
if(HIWORD(wParam) == 0 || HIWORD(wParam) == 1)
{
wParam &= 0xFFFF;
// A menu item from the recent files menu was clicked.
if(wParam >= MENU_FIRST_RECENT_FILE && wParam <= MENU_FIRST_RECENT_FILE + MAX_NUMBER_OF_RECENT_FILES - 1)
{
char*& fname = recent_files[wParam - MENU_FIRST_RECENT_FILE];
if(fname)
{
if (!ALoad(fname))
{
int result = MessageBox(hWnd,"Remove from list?", "Could Not Open Recent File", MB_YESNO);
if (result == IDYES)
{
RemoveRecentItem((wParam - MENU_FIRST_RECENT_FILE), recent_files, MAX_NUMBER_OF_RECENT_FILES);
UpdateRMenu(recentmenu, recent_files, MENU_RECENT_FILES, MENU_FIRST_RECENT_FILE);
}
}
}
}
// A menu item for the recent lua files menu was clicked.
#ifdef _S9XLUA_H
if(wParam >= LUA_FIRST_RECENT_FILE && wParam <= LUA_FIRST_RECENT_FILE + MAX_NUMBER_OF_LUA_RECENT_FILES - 1)
{
char*& fname = recent_lua[wParam - LUA_FIRST_RECENT_FILE];
if(fname)
{
if (!FCEU_LoadLuaCode(fname))
{
//int result = MessageBox(hWnd,"Remove from list?", "Could Not Open Recent File", MB_YESNO);
//if (result == IDYES)
//{
// RemoveRecentItem((wParam - LUA_FIRST_RECENT_FILE), recent_lua, MAX_NUMBER_OF_LUA_RECENT_FILES);
// UpdateLuaRMenu(recentluamenu, recent_lua, MENU_LUA_RECENT, LUA_FIRST_RECENT_FILE);
//}
//adelikat: Commenting this code out because it is annoying in context lua scripts since lua scripts will frequently give errors to those developing them. It is frustrating for this to pop up every time.
}
UpdateLuaConsole(fname);
}
}
#endif
// A menu item for the recent movie files menu was clicked.
if(wParam >= MOVIE_FIRST_RECENT_FILE && wParam <= MOVIE_FIRST_RECENT_FILE + MAX_NUMBER_OF_MOVIE_RECENT_FILES - 1)
{
char*& fname = recent_movie[wParam - MOVIE_FIRST_RECENT_FILE];
if(fname)
{
if (!FCEUI_LoadMovie(fname, 1, false, false))
{
int result = MessageBox(hWnd,"Remove from list?", "Could Not Open Recent File", MB_YESNO);
if (result == IDYES)
{
RemoveRecentItem((wParam - MOVIE_FIRST_RECENT_FILE), recent_movie, MAX_NUMBER_OF_MOVIE_RECENT_FILES);
UpdateMovieRMenu(recentmoviemenu, recent_movie, MENU_MOVIE_RECENT, MOVIE_FIRST_RECENT_FILE);
}
} else {
FCEUX_LoadMovieExtras(fname);
}
}
}
switch(LOWORD(wParam))
{
//File Menu-------------------------------------------------------------
case FCEU_CONTEXT_OPENROM:
case MENU_OPEN_FILE:
LoadNewGamey(hWnd, 0);
break;
case FCEU_CONTEXT_CLOSEROM:
case MENU_CLOSE_FILE:
CloseGame();
break;
//Savestate Submenu
case MENU_SAVESTATE: //Save State
FCEUI_SaveState(0);
break;
case MENU_LOADSTATE: //Load State
FCEUI_LoadState(0);
break;
case MENU_SAVE_STATE: //Save state as
FCEUD_SaveStateAs();
break;
case MENU_LOAD_STATE: //Load state as
FCEUD_LoadStateFrom();
break;
case MENU_NEXTSAVESTATE: //Next Save slot
FCEUI_SelectStateNext(1);
break;
case MENU_PREVIOUSSAVESTATE: //Previous Save slot
FCEUI_SelectStateNext(-1);
break;
case MENU_VIEWSAVESLOTS: //View save slots
FCEUI_SelectState(CurrentState, 1);
break;
//Movie submenu
case FCEUX_CONTEXT_RECORDMOVIE:
case MENU_RECORD_MOVIE:
FCEUD_MovieRecordTo();
break;
case FCEUX_CONTEXT_REPLAYMOVIE:
case MENU_REPLAY_MOVIE:
// Replay movie menu was selected
FCEUD_MovieReplayFrom();
break;
case FCEU_CONTEXT_STOPMOVIE:
case MENU_STOP_MOVIE:
FCEUI_StopMovie();
break;
case FCEU_CONTEXT_PLAYMOVIEFROMBEGINNING:
case ID_FILE_PLAYMOVIEFROMBEGINNING:
FCEUI_MoviePlayFromBeginning();
break;
case FCEUX_CONTEXT_READONLYTOGGLE:
case ID_FILE_MOVIE_TOGGLEREAD:
FCEUI_MovieToggleReadOnly();
break;
//Record Avi/Wav submenu
case MENU_RECORD_AVI:
FCEUD_AviRecordTo();
break;
case MENU_STOP_AVI:
FCEUD_AviStop();
break;
case MENU_RECORD_WAV:
loggingSound = CreateSoundSave();
break;
case MENU_STOP_WAV:
CloseWave();
loggingSound = false;
break;
case ID_AVI_DISMOVIEMESSAGE:
AVIdisableMovieMessages ^= 1;
FCEUI_SetAviDisableMovieMessages(AVIdisableMovieMessages);
break;
case FCEUX_CONTEXT_SCREENSHOT:
case ID_FILE_SCREENSHOT:
FCEUI_SaveSnapshot();
break;
case ID_FILE_SAVESCREENSHOTAS:
SaveSnapshotAs();
break;
/*
//Lua submenu
case ID_FILE_OPENLUAWINDOW:
if(!LuaConsoleHWnd)
LuaConsoleHWnd = CreateDialog(fceu_hInstance, MAKEINTRESOURCE(IDD_LUA), hWnd, (DLGPROC) DlgLuaScriptDialog);
else
SetForegroundWindow(LuaConsoleHWnd);
break;
case FCEUX_CONTEXT_CLOSELUAWINDOWS:
case ID_FILE_CLOSELUAWINDOWS:
if(LuaConsoleHWnd)
PostMessage(LuaConsoleHWnd, WM_CLOSE, 0, 0);
break;
//Recent Lua 1
#ifdef _S9XLUA_H
case FCEUX_CONTEXT_LOADLASTLUA:
if(recent_lua[0])
{
if (!FCEU_LoadLuaCode(recent_lua[0]))
{
//int result = MessageBox(hWnd,"Remove from list?", "Could Not Open Recent File", MB_YESNO);
//if (result == IDYES)
//{
// RemoveRecentItem(0, recent_lua, MAX_NUMBER_OF_LUA_RECENT_FILES);
// UpdateLuaRMenu(recentluamenu, recent_lua, MENU_LUA_RECENT, LUA_FIRST_RECENT_FILE);
//}
//adelikat: Forgot to comment this out for 2.1.2 release. FCEUX shouldn't ask in this case because it is too likely that lua script will error many times for a user developing a lua script.
}
}
break;
#endif
*/
case MENU_EXIT:
DoFCEUExit();
break;
//NES Menu--------------------------------------------------------------
case MENU_RESET:
FCEUI_ResetNES();
break;
case MENU_POWER:
FCEUI_PowerNES();
break;
case MENU_EJECT_DISK:
FCEUI_FDSInsert();
break;
case MENU_SWITCH_DISK:
FCEUI_FDSSelect();
break;
case MENU_INSERT_COIN:
FCEUI_VSUniCoin();
break;
//Emulation submenu
case ID_NES_PAUSE:
FCEUI_ToggleEmulationPause();
UpdateCheckedMenuItems();
break;
case ID_NES_TURBO:
FCEUD_TurboToggle();
break;
//Emulation speed submenu
case ID_NES_SPEEDUP:
FCEUD_SetEmulationSpeed(3);
break;
case ID_NES_SLOWDOWN:
FCEUD_SetEmulationSpeed(1);
break;
case ID_NES_SLOWESTSPEED:
FCEUD_SetEmulationSpeed(0);
break;
case ID_NES_NORMALSPEED:
FCEUD_SetEmulationSpeed(2);
break;
//Config Menu-----------------------------------------------------------
case FCEUX_CONTEXT_UNHIDEMENU:
case MENU_HIDE_MENU:
ToggleHideMenu();
break;
case MENU_RUN_IN_BACKGROUND:
eoptions ^= EO_BGRUN;
if((eoptions & EO_BGRUN) == 0)
{
EnableBackgroundInput = 0;
KeyboardSetBackgroundAccess(EnableBackgroundInput!=0);
JoystickSetBackgroundAccess(EnableBackgroundInput!=0);
}
UpdateCheckedMenuItems();
break;
case MENU_BACKGROUND_INPUT:
EnableBackgroundInput ^= 1;
eoptions |= EO_BGRUN * EnableBackgroundInput;
KeyboardSetBackgroundAccess(EnableBackgroundInput!=0);
JoystickSetBackgroundAccess(EnableBackgroundInput!=0);
UpdateCheckedMenuItems();
break;
case MENU_ENABLE_AUTOSAVE:
EnableAutosave ^= 1;
UpdateCheckedMenuItems();
break;
case MENU_DISPLAY_FA_LAGSKIP:
frameAdvanceLagSkip ^= 1;
UpdateCheckedMenuItems();
break;
case ID_ENABLE_BACKUPSAVESTATES:
backupSavestates ^=1;
UpdateCheckedMenuItems();
break;
case ID_ENABLE_COMPRESSSAVESTATES:
compressSavestates ^=1;
UpdateCheckedMenuItems();
break;
//Display submenu
case MENU_INPUTDISPLAY_0: //Input display off
input_display = 0;
UpdateCheckedMenuItems();
break;
case MENU_INPUTDISPLAY_1: //Input display - 1 player
input_display = 1;
UpdateCheckedMenuItems();
break;
case MENU_INPUTDISPLAY_2: //Input display - 2 player
input_display = 2;
UpdateCheckedMenuItems();
break;
case MENU_INPUTDISPLAY_4: //Input display - 4 player
input_display = 4;
UpdateCheckedMenuItems();
break;
case ID_INPUTDISPLAY_OLDSTYLEDISP:
oldInputDisplay ^= 1;
UpdateCheckedMenuItems();
break;
case MENU_DISPLAY_LAGCOUNTER:
lagCounterDisplay ^= 1;
UpdateCheckedMenuItems();
break;
case ID_DISPLAY_FRAMECOUNTER:
FCEUI_MovieToggleFrameDisplay();
UpdateCheckedMenuItems();
break;
case MENU_DISPLAY_BG:
case MENU_DISPLAY_OBJ:
{
bool spr, bg;
FCEUI_GetRenderPlanes(spr,bg);
if(LOWORD(wParam)==MENU_DISPLAY_BG)
bg = !bg;
else
spr = !spr;
FCEUI_SetRenderPlanes(spr,bg);
}
break;
case ID_NEWPPU:
case ID_OLDPPU:
FCEU_TogglePPU();
break;
case MENU_GAME_GENIE:
genie ^= 1;
FCEUI_SetGameGenie(genie!=0);
UpdateCheckedMenuItems();
break;
case MENU_PAL:
pal_emulation ^= 1;
FCEUI_SetVidSystem(pal_emulation);
RefreshThrottleFPS();
UpdateCheckedMenuItems();
PushCurrentVideoSettings();
break;
case MENU_DIRECTORIES:
ConfigDirectories();
break;
case MENU_GUI_OPTIONS:
ConfigGUI();
break;
case MENU_INPUT:
ConfigInput(hWnd);
break;
case MENU_NETWORK:
ShowNetplayConsole();
break;
case MENU_PALETTE:
ConfigPalette();
break;
case MENU_SOUND:
ConfigSound();
break;
case MENU_TIMING:
ConfigTiming();
break;
case MENU_VIDEO:
ConfigVideo();
break;
case MENU_HOTKEYS:
MapInput();
break;
case MENU_MOVIEOPTIONS:
OpenMovieOptions();
break;
case ID_CONFIG_SAVECONFIGFILE:
{
extern string cfgFile;
sprintf(TempArray, "%s/%s", BaseDirectory.c_str(),cfgFile.c_str());
SaveConfig(TempArray);
break;
}
//Tools Menu---------------------------------------------------------------
case MENU_CHEATS:
ConfigCheats(hWnd);
break;
case MENU_MEMORY_WATCH:
CreateMemWatch();
break;
case ID_RAM_SEARCH:
if(!RamSearchHWnd)
{
OpenRamSearch();
}
else
SetForegroundWindow(RamSearchHWnd);
break;
case ID_RAM_WATCH:
if(!RamWatchHWnd)
{
OpenRamWatch();
}
else
SetForegroundWindow(RamWatchHWnd);
break;
//case MENU_RAMFILTER:
// DoByteMonitor();
// break;
// Removing this tool since it is redundant to both
case ACCEL_CTRL_E:
case MENU_TASEDIT:
DoTasEdit();
break;
case MENU_CONVERT_MOVIE:
ConvertFCM(hWnd);
break;
//AutoFire Pattern submenu
case MENU_AUTOFIRE_PATTERN_1:
SetAutoFirePattern(1,1);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_2:
SetAutoFirePattern(1,2);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_3:
SetAutoFirePattern(1,3);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_4:
SetAutoFirePattern(1,4);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_5:
SetAutoFirePattern(1,5);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_6:
SetAutoFirePattern(2,1);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_7:
SetAutoFirePattern(2,2);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_8:
SetAutoFirePattern(2,3);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_9:
SetAutoFirePattern(2,4);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_10:
SetAutoFirePattern(3,1);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_11:
SetAutoFirePattern(3,2);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_12:
SetAutoFirePattern(3,3);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_13:
SetAutoFirePattern(4,1);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_14:
SetAutoFirePattern(4,2);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
case MENU_AUTOFIRE_PATTERN_15:
SetAutoFirePattern(5,1);
CheckedAutoFirePattern = wParam;
UpdateCheckedMenuItems();
break;
//Autofire Offset submenu
case MENU_AUTOFIRE_OFFSET_1:
case MENU_AUTOFIRE_OFFSET_2:
case MENU_AUTOFIRE_OFFSET_3:
case MENU_AUTOFIRE_OFFSET_4:
case MENU_AUTOFIRE_OFFSET_5:
case MENU_AUTOFIRE_OFFSET_6:
SetAutoFireOffset(wParam - MENU_AUTOFIRE_OFFSET_1);
CheckedAutoFireOffset = wParam;
UpdateCheckedMenuItems();
break;
case MENU_ALTERNATE_AB:
SetAutoFireDesynch(GetAutoFireDesynch()^1);
UpdateCheckedMenuItems();
break;
case ID_TOOLS_TEXTHOOKER:
DoTextHooker();
break;
//Debug Menu-------------------------------------------------------------
case MENU_DEBUGGER:
DoDebug(0);
break;
case MENU_PPUVIEWER:
DoPPUView();
break;
case MENU_NAMETABLEVIEWER:
DoNTView();
break;
case MENU_HEXEDITOR:
DoMemView();
break;
case MENU_TRACELOGGER:
DoTracer();
break;
case MENU_CDLOGGER:
DoCDLogger();
break;
case MENU_GAMEGENIEDECODER:
DoGGConv();
break;
//Help Menu--------------------------------------------------------------
case MENU_HELP:
OpenHelpWindow();
break;
case MENU_MSGLOG:
MakeLogWindow();
break;
case MENU_ABOUT:
ShowAboutBox();
break;
//Context Menus------------------------------------------------------
//Recent ROM 1
case FCEUX_CONTEXT_RECENTROM1:
if(recent_files[0])
{
if (!ALoad(recent_files[0]))
{
int result = MessageBox(hWnd,"Remove from list?", "Could Not Open Recent File", MB_YESNO);
if (result == IDYES)
{
RemoveRecentItem(0, recent_files, MAX_NUMBER_OF_RECENT_FILES);
UpdateRMenu(recentmenu, recent_files, MENU_RECENT_FILES, MENU_FIRST_RECENT_FILE);
}
}
}
break;
//Recent Movie 1
case FCEUX_CONTEXT_LOADLASTMOVIE:
if(recent_movie[0])
{
if (!FCEUI_LoadMovie(recent_movie[0], 1, false, false))
{
int result = MessageBox(hWnd,"Remove from list?", "Could Not Open Recent File", MB_YESNO);
if (result == IDYES)
{
RemoveRecentItem(0, recent_movie, MAX_NUMBER_OF_MOVIE_RECENT_FILES);
UpdateMovieRMenu(recentmoviemenu, recent_movie, MENU_MOVIE_RECENT, MOVIE_FIRST_RECENT_FILE);
}
} else {
FCEUX_LoadMovieExtras(recent_movie[0]);
}
}
break;
//Toggle subtitles
case FCEUX_CONTEXT_TOGGLESUBTITLES:
movieSubtitles ^= 1;
break;
case FCEUX_CONTEXT_DUMPSUBTITLES:
DumpSubtitles(hWnd);
break;
//View comments and subtitles
case FCEUX_CONTEXT_VIEWCOMMENTSSUBTITLES:
CreateDialog(fceu_hInstance, "IDD_REPLAY_METADATA", hWnd, ReplayMetadataDialogProc);
break;
//Undo Savestate
case FCEUX_CONTEXT_UNDOSAVESTATE:
if (undoSS || redoSS)
SwapSaveState();
break;
//Undo Loadstate
case FCEUX_CONTEXT_UNDOLOADSTATE:
if (CheckBackupSaveStateExist() && redoLS)
RedoLoadState();
else if (CheckBackupSaveStateExist() && undoLS)
LoadBackup();
break;
//Load last auto-save
case FCEUX_CONTEXT_REWINDTOLASTAUTO:
FCEUI_Autosave();
break;
//Create a backup movie file
case FCEUX_CONTEXT_MAKEBACKUP:
FCEUI_MakeBackupMovie(true);
break;
//Create a backup based on user entering a filename
case FCEUX_CONTEXT_SAVEMOVIEAS:
SaveMovieAs();
break;
//Game + Movie - Help
case FCEU_CONTEXT_MOVIEHELP:
OpenHelpWindow(moviehelp);
break;
case ID_CONTEXT_FULLSAVESTATES:
fullSaveStateLoads ^= 1;
break;
//No Game - Help
case FCEU_CONTEXT_FCEUHELP:
OpenHelpWindow(gettingstartedhelp);
break;
}
}
break;
case WM_SYSCOMMAND:
if(GameInfo && wParam == SC_SCREENSAVE && (goptions & GOO_DISABLESS))
return(0);
//adelikat: If we are going to disable screensave, we should disable monitor off as well
if(GameInfo && wParam == SC_MONITORPOWER && (goptions & GOO_DISABLESS))
return(0);
if(wParam==SC_KEYMENU)
{
if(GameInfo && ((InputType[2]==SIFC_FKB) || (InputType[2]==SIFC_SUBORKB)) && cidisabled)
break;
if(lParam == VK_RETURN || fullscreen || tog) break;
}
goto proco;
case WM_SYSKEYDOWN:
if(GameInfo && ((InputType[2]==SIFC_FKB) || (InputType[2]==SIFC_SUBORKB)) && cidisabled)
break; // Hopefully this won't break DInput...
if(fullscreen || tog)
{
if(wParam==VK_MENU)
break;
}
if(wParam==VK_F10)
break; // 11.12.08 CH4 Disable F10 as System Key dammit
/*
if(wParam == VK_RETURN)
{
if(!(lParam&(1<<30)))
{
UpdateCheckedMenuItems();
changerecursive=1;
if(!SetVideoMode(fullscreen^1))
SetVideoMode(fullscreen);
changerecursive=0;
}
break;
}
adelikat: Outsourced this to a remappable hotkey
*/
goto proco;
case WM_KEYDOWN:
if(GameInfo)
{
//Only disable command keys if a game is loaded(and the other conditions are right, of course).
if(InputType[2]==SIFC_FKB)
{
if(wParam==VK_SCROLL)
{
cidisabled^=1;
FCEUI_DispMessage("Family Keyboard %sabled.",0,cidisabled?"en":"dis");
}
if(cidisabled)
break; // Hopefully this won't break DInput...
}
if(InputType[2]==SIFC_SUBORKB)
{
if(wParam==VK_SCROLL)
{
cidisabled^=1;
FCEUI_DispMessage("Subor Keyboard %sabled.",0,cidisabled?"en":"dis");
}
if(cidisabled)
break;
}
}
goto proco;
case WM_CLOSE:
case WM_DESTROY:
case WM_QUIT:
DoFCEUExit();
break;
case WM_SETFOCUS:
if (wasPausedByCheats)
{
EmulationPaused = 0;
wasPausedByCheats = false;
}
break;
case WM_ACTIVATEAPP:
if((BOOL)wParam)
{
nofocus=0;
}
else
{
nofocus=1;
}
goto proco;
case WM_ENTERMENULOOP:
UpdateCheckedMenuItems();
UpdateMenuHotkeys();
EnableMenuItem(fceumenu,MENU_RESET,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_RESET)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_POWER,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_POWER)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_TASEDIT,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_TASEDIT)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_CLOSE_FILE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_CLOSEGAME) && GameInfo ?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_RECENT_FILES,MF_BYCOMMAND | ((FCEU_IsValidUI(FCEUI_OPENGAME) && HasRecentFiles()) ?MF_ENABLED:MF_GRAYED)); //adelikat - added && recent_files, otherwise this line prevents recent from ever being gray when tasedit is not engaged
EnableMenuItem(fceumenu,MENU_OPEN_FILE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_OPENGAME)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_RECORD_MOVIE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_RECORDMOVIE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_REPLAY_MOVIE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_PLAYMOVIE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_MOVIE_RECENT,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_PLAYMOVIE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_STOP_MOVIE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_STOPMOVIE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,ID_FILE_PLAYMOVIEFROMBEGINNING,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_PLAYFROMBEGINNING)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_SAVESTATE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_QUICKSAVE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_LOADSTATE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_QUICKLOAD)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_SAVE_STATE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_SAVESTATE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_LOAD_STATE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_LOADSTATE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_NEXTSAVESTATE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_NEXTSAVESTATE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_PREVIOUSSAVESTATE,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_PREVIOUSSAVESTATE)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_VIEWSAVESLOTS,MF_BYCOMMAND | (FCEU_IsValidUI(FCEUI_VIEWSLOTS)?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_STOP_AVI,MF_BYCOMMAND | (FCEUI_AviIsRecording()?MF_ENABLED:MF_GRAYED));
EnableMenuItem(fceumenu,MENU_STOP_WAV,MF_BYCOMMAND | (loggingSound?MF_ENABLED:MF_GRAYED));
// EnableMenuItem(fceumenu,ID_FILE_CLOSELUAWINDOWS,MF_BYCOMMAND | (LuaConsoleHWnd?MF_ENABLED:MF_GRAYED));
CheckMenuItem(fceumenu, ID_NEWPPU, newppu ? MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(fceumenu, ID_OLDPPU, !newppu ? MF_CHECKED : MF_UNCHECKED);
default:
proco:
return DefWindowProc(hWnd,msg,wParam,lParam);
}
return 0;
}
void FixWXY(int pref)
{
if(eoptions&EO_FORCEASPECT)
{
/* First, make sure the ratio is valid, and if it's not, change
it so that it doesn't break everything.
*/
if(saspectw < 0.01) saspectw = 0.01;
if(saspecth < 0.01) saspecth = 0.01;
if((saspectw / saspecth) > 100) saspecth = saspectw;
if((saspecth / saspectw) > 100) saspectw = saspecth;
if((saspectw / saspecth) < 0.1) saspecth = saspectw;
if((saspecth / saspectw) > 0.1) saspectw = saspecth;
if(!pref)
{
winsizemuly = winsizemulx * 256 / FSettings.TotalScanlines() * 3 / 4 * saspectw / saspecth;
}
else
{
winsizemulx = winsizemuly * FSettings.TotalScanlines() / 256 * 4 / 3 * saspecth / saspectw;
}
}
if(winspecial)
{
// -Video Modes Tag-
int mult;
if(winspecial >= 1 && winspecial <= 3) mult = 2;
else mult = 3;
if(winsizemulx < mult)
{
if(eoptions&EO_FORCEASPECT)
winsizemuly *= mult / winsizemulx;
if (winsizemulx < mult)
winsizemulx = mult;
}
if(winsizemuly < mult && mult < 3) //11/14/2008, adelikat: added && mult < 3 and extra code to meet mult >=3 conditions
{
if(eoptions&EO_FORCEASPECT)
winsizemulx *= mult / winsizemuly;
if (winsizemuly < mult)
winsizemuly = mult;
}
else if (winsizemuly < mult&& mult >= 3) { //11/14/2008, adelikat: This was probably a hacky solution. But when special scalar = 3 and aspect correction is on,
if(eoptions&EO_FORCEASPECT) //then x is corrected to a wider ratio (.5 of what this code seems to expect) so I added a special circumstance for these 2 situations
winsizemulx *= (mult+0.5) / winsizemuly; //And adjusted the special scaling by .5
if (winsizemuly < mult)
winsizemuly = mult;
}
}
if(winsizemulx<0.1)
winsizemulx=0.1;
if(winsizemuly<0.1)
winsizemuly=0.1;
if(eoptions & EO_FORCEISCALE)
{
int x,y;
x = winsizemulx * 2;
y = winsizemuly * 2;
x = (x>>1) + (x&1);
y = (y>>1) + (y&1);
if(!x) x=1;
if(!y) y=1;
winsizemulx = x;
winsizemuly = y;
}
if(winsizemulx > 100) winsizemulx = 100;
if(winsizemuly > 100) winsizemuly = 100;
}
void UpdateFCEUWindow(void)
{
if(vchanged && !fullscreen && !changerecursive && !nofocus)
{
SetVideoMode(0);
vchanged = 0;
}
BlockingCheck();
if(!(eoptions & EO_BGRUN))
{
while(nofocus)
{
Sleep(75);
BlockingCheck();
}
}
}
//Destroys the main window
void ByebyeWindow()
{
SetMenu(hAppWnd, 0);
DestroyMenu(fceumenu);
DestroyWindow(hAppWnd);
}
/// reates the main window.
/// @return Flag that indicates failure (0) or success (1)
int CreateMainWindow()
{
WNDCLASSEX winclass;
RECT tmp;
// Create and register the window class
memset(&winclass, 0, sizeof(winclass));
winclass.cbSize = sizeof(WNDCLASSEX);
winclass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW | CS_SAVEBITS;
winclass.lpfnWndProc = AppWndProc;
winclass.cbClsExtra = 0;
winclass.cbWndExtra = 0;
winclass.hInstance = fceu_hInstance;
winclass.hIcon = LoadIcon(fceu_hInstance, "ICON_1");
winclass.hIconSm = LoadIcon(fceu_hInstance, "ICON_1");
winclass.hCursor = LoadCursor(NULL, IDC_ARROW);
winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); //mbg merge 7/17/06 added cast
winclass.lpszClassName = "FCEUXWindowClass";
if(!RegisterClassEx(&winclass))
{
return FALSE;
}
AdjustWindowRectEx(&tmp, WS_OVERLAPPEDWINDOW, 1, 0);
fceumenu = LoadMenu(fceu_hInstance,"FCEUMENU");
recentmenu = CreateMenu();
recentluamenu = CreateMenu();
recentmoviemenu = CreateMenu();
// Update recent files menu
UpdateRMenu(recentmenu, recent_files, MENU_RECENT_FILES, MENU_FIRST_RECENT_FILE);
//UpdateLuaRMenu(recentluamenu, recent_lua, MENU_LUA_RECENT, LUA_FIRST_RECENT_FILE);
UpdateMovieRMenu(recentmoviemenu, recent_movie, MENU_MOVIE_RECENT, MOVIE_FIRST_RECENT_FILE);
updateGameDependentMenus(0);
updateGameDependentMenusDebugger(0);
if (MainWindow_wndx==-32000) MainWindow_wndx=0; //Just in case
if (MainWindow_wndy==-32000) MainWindow_wndy=0;
hAppWnd = CreateWindowEx(
0,
"FCEUXWindowClass",
FCEU_NAME_AND_VERSION,
WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS, /* Style */
MainWindow_wndx,
MainWindow_wndy,
256,
FSettings.TotalScanlines(), /* X,Y ; Width, Height */
NULL,
fceumenu,
fceu_hInstance,
NULL );
//CenterWindowOnScreen(hAppWnd);
DragAcceptFiles(hAppWnd, 1);
SetMainWindowStuff();
return 1;
}
void SetMainWindowStuff()
{
RECT tmp;
GetWindowRect(hAppWnd, &tmp);
if(ismaximized)
{
winwidth = tmp.right - tmp.left;
winheight = tmp.bottom - tmp.top;
ShowWindow(hAppWnd, SW_SHOWMAXIMIZED);
}
else
{
RECT srect;
if(WindowXC != ( 1 << 30 ))
{
/* Subtracting and adding for if(eoptions&EO_USERFORCE) below. */
tmp.bottom -= tmp.top;
tmp.bottom += WindowYC;
tmp.right -= tmp.left;
tmp.right += WindowXC;
tmp.left = WindowXC;
tmp.top = WindowYC;
WindowXC = 1 << 30;
}
CalcWindowSize(&srect);
SetWindowPos(
hAppWnd,
HWND_TOP,
tmp.left,
tmp.top,
srect.right,
srect.bottom,
SWP_SHOWWINDOW
);
winwidth = srect.right;
winheight = srect.bottom;
ShowWindow(hAppWnd, SW_SHOWNORMAL);
}
}
/// @return Flag that indicates failure (0) or success (1).
int GetClientAbsRect(LPRECT lpRect)
{
POINT point;
point.x = point.y = 0;
if(!ClientToScreen(hAppWnd, &point))
{
return 0;
}
lpRect->top = point.y;
lpRect->left = point.x;
if(ismaximized)
{
RECT al;
GetClientRect(hAppWnd, &al);
lpRect->right = point.x + al.right;
lpRect->bottom = point.y + al.bottom;
}
else
{
lpRect->right = point.x + VNSWID * winsizemulx;
lpRect->bottom = point.y + FSettings.TotalScanlines() * winsizemuly;
}
return 1;
}
//Shows an Open File menu and starts recording an AVI
void FCEUD_AviRecordTo(void)
{
OPENFILENAME ofn;
char szChoice[MAX_PATH];
string tempFilename, aviFilename;
std::string aviDirectory = FCEU_GetPath(21); //21 = FCEUMKF_AVI
if (aviDirectory.find_last_of("\\") != (aviDirectory.size()-1))
aviDirectory.append("\\"); //if directory override has no \ then add one
//if we are playing a movie, construct the filename from the current movie.
if(FCEUMOV_Mode(MOVIEMODE_PLAY|MOVIEMODE_RECORD)) //adelikat: TOOD: Think about this. I think MOVIEMODE_FINISHED shouldn't not be included here. Am I wrong?
{
tempFilename = GetMfn(); //get movie filename
tempFilename.erase(0,1); //remove dot
}
//else construct it from the ROM name.
else
tempFilename = GetRomName();
aviFilename = aviDirectory + tempFilename; //concate avi directory and movie filename
strcpy(szChoice, aviFilename.c_str());
char* dot = strrchr(szChoice,'.');
if (dot) *dot='\0';
strcat(szChoice, ".avi");
// avi record file browser
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hAppWnd;
ofn.lpstrFilter = "AVI Files (*.avi)\0*.avi\0All Files (*.*)\0*.*\0\0";
ofn.lpstrFile = szChoice;
ofn.lpstrDefExt = "avi";
ofn.lpstrTitle = "Save AVI as";
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
if(GetSaveFileName(&ofn))
FCEUI_AviBegin(szChoice);
}
//Stop AVI recording
void FCEUD_AviStop(void)
{
FCEUI_AviEnd();
}
void FCEUD_CmdOpen(void)
{
LoadNewGamey(hAppWnd, 0);
}
bool FCEUD_PauseAfterPlayback()
{
return pauseAfterPlayback!=0;
}
void ChangeContextMenuItemText(int menuitem, string text, HMENU menu)
{
MENUITEMINFO moo;
moo.cbSize = sizeof(moo);
moo.fMask = MIIM_TYPE;
moo.cch = NULL;
GetMenuItemInfo(menu, menuitem, FALSE, &moo);
moo.dwTypeData = (LPSTR)text.c_str();
SetMenuItemInfo(menu, menuitem, FALSE, &moo);
}
void ChangeMenuItemText(int menuitem, string text)
{
MENUITEMINFO moo;
moo.cbSize = sizeof(moo);
moo.fMask = MIIM_TYPE;
moo.cch = NULL;
GetMenuItemInfo(fceumenu, menuitem, FALSE, &moo);
moo.dwTypeData = (LPSTR)text.c_str();
SetMenuItemInfo(fceumenu, menuitem, FALSE, &moo);
}
void UpdateMenuHotkeys()
{
//Update all menu items that can be called from a hotkey to include the current hotkey assignment
string combo, combined;
//-------------------------------FILE---------------------------------------
//Open ROM
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_OPENROM]);
combined = "&Open ROM...\t" + combo;
ChangeMenuItemText(MENU_OPEN_FILE, combined);
//Close ROM
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_CLOSEROM]);
combined = "&Close\t" + combo;
ChangeMenuItemText(MENU_CLOSE_FILE, combined);
//Load State
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_LOAD_STATE]);
combined = "&Load State\t" + combo;
ChangeMenuItemText(MENU_LOADSTATE, combined);
//Save State
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SAVE_STATE]);
combined = "&Save State\t" + combo;
ChangeMenuItemText(MENU_SAVESTATE, combined);
//Loadstate from
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_LOAD_STATE_FROM]);
combined = "Load State &From...\t" + combo;
ChangeMenuItemText(MENU_LOAD_STATE, combined);
//Savestate as
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SAVE_STATE_AS]);
combined = "Save State &As...\t" + combo;
ChangeMenuItemText(MENU_SAVE_STATE, combined);
//Next Save Slot
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SAVE_SLOT_NEXT]);
combined = "&Next save slot\t" + combo;
ChangeMenuItemText(MENU_NEXTSAVESTATE, combined);
//Previous Save Slot
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SAVE_SLOT_PREV]);
combined = "&Previous save slot\t" + combo;
ChangeMenuItemText(MENU_PREVIOUSSAVESTATE, combined);
//View Save Slots
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MISC_SHOWSTATES]);
combined = "&View save slots\t" + combo;
ChangeMenuItemText(MENU_VIEWSAVESLOTS, combined);
//Record Movie
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MOVIE_RECORD_TO]);
combined = "&Record Movie...\t" + combo;
ChangeMenuItemText(MENU_RECORD_MOVIE, combined);
//Play movie
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MOVIE_REPLAY_FROM]);
combined = "&Play Movie...\t" + combo;
ChangeMenuItemText(MENU_REPLAY_MOVIE, combined);
//Stop movie
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MOVIE_STOP]);
combined = "&Stop Movie\t" + combo;
ChangeMenuItemText(MENU_STOP_MOVIE, combined);
//Play Movie from Beginning
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MOVIE_PLAY_FROM_BEGINNING]);
combined = "Play from &Beginning\t" + combo;
ChangeMenuItemText(ID_FILE_PLAYMOVIEFROMBEGINNING, combined);
//Read only
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MOVIE_READONLY_TOGGLE]);
combined = "&Read only\t" + combo;
ChangeMenuItemText(ID_FILE_MOVIE_TOGGLEREAD, combined);
//Screenshot
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SCREENSHOT]);
combined = "&Screenshot\t" + combo;
ChangeMenuItemText(ID_FILE_SCREENSHOT, combined);
//Record AVI
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_AVI_RECORD_AS]);
combined = "&Record AVI...\t" + combo;
ChangeMenuItemText(MENU_RECORD_AVI, combined);
//Stop AVI
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_AVI_STOP]);
combined = "&Stop AVI\t" + combo;
ChangeMenuItemText(MENU_STOP_AVI, combined);
//-------------------------------NES----------------------------------------
//Reset
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_RESET]);
combined = "&Reset\t" + combo;
ChangeMenuItemText(MENU_RESET, combined);
//Power
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_POWER]);
combined = "&Power\t" + combo;
ChangeMenuItemText(MENU_POWER, combined);
//Eject/Insert Disk
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_FDS_EJECT_INSERT]);
combined = "&Eject/Insert Disk\t" + combo;
ChangeMenuItemText(MENU_EJECT_DISK, combined);
//Switch Disk Side
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_FDS_SIDE_SELECT]);
combined = "&Switch Disk Side\t" + combo;
ChangeMenuItemText(MENU_SWITCH_DISK, combined);
//Insert Coin
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_VSUNI_COIN]);
combined = "&Insert Coin\t" + combo;
ChangeMenuItemText(MENU_INSERT_COIN, combined);
//Speed Up
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SPEED_FASTER]);
combined = "Speed &Up\t" + combo;
ChangeMenuItemText(ID_NES_SPEEDUP, combined);
//Slow Down
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SPEED_SLOWER]);
combined = "Slow &Down\t" + combo;
ChangeMenuItemText(ID_NES_SLOWDOWN, combined);
//Pause
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_PAUSE]);
combined = "&Pause\t" + combo;
ChangeMenuItemText(ID_NES_PAUSE, combined);
//Slowest Speed
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SPEED_SLOWEST]);
combined = "&Slowest Speed\t" + combo;
ChangeMenuItemText(ID_NES_SLOWESTSPEED, combined);
//Normal Speed
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SPEED_NORMAL]);
combined = "&Normal Speed\t" + combo;
ChangeMenuItemText(ID_NES_NORMALSPEED, combined);
//Turbo
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_SPEED_TURBO_TOGGLE]);
combined = "&Turbo\t" + combo;
ChangeMenuItemText(ID_NES_TURBO, combined);
//-------------------------------Config-------------------------------------
//Hide Menu
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_HIDE_MENU_TOGGLE]);
combined = "&Hide Menu\t" + combo;
ChangeMenuItemText(MENU_HIDE_MENU, combined);
//Frame Adv. skip lag
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_FRAMEADV_SKIPLAG]);
combined = "&Frame Adv. - Skip Lag\t" + combo;
ChangeMenuItemText(MENU_DISPLAY_FA_LAGSKIP, combined);
//Lag Counter
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MISC_DISPLAY_LAGCOUNTER_TOGGLE]);
combined = "&Lag Counter\t" + combo;
ChangeMenuItemText(MENU_DISPLAY_LAGCOUNTER, combined);
//Frame Counter
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MOVIE_FRAME_DISPLAY_TOGGLE]);
combined = "&Frame Counter\t" + combo;
ChangeMenuItemText(ID_DISPLAY_FRAMECOUNTER, combined);
//Graphics: BG
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MISC_DISPLAY_BG_TOGGLE]);
combined = "Graphics: &BG\t" + combo;
ChangeMenuItemText(MENU_DISPLAY_BG, combined);
//Graphics: OBJ
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_MISC_DISPLAY_OBJ_TOGGLE]);
combined = "Graphics: &OBJ\t" + combo;
ChangeMenuItemText(MENU_DISPLAY_OBJ, combined);
//-------------------------------Tools--------------------------------------
//Open Cheats
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_TOOL_OPENCHEATS]);
combined = "&Cheats...\t" + combo;
ChangeMenuItemText(MENU_CHEATS, combined);
//Open Memory Watch
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_TOOL_OPENMEMORYWATCH]);
combined = "&Memory Watch...\t" + combo;
ChangeMenuItemText(MENU_MEMORY_WATCH, combined);
//-------------------------------Debug--------------------------------------
//Open Debugger
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_TOOL_OPENDEBUGGER]);
combined = "&Debugger...\t" + combo;
ChangeMenuItemText(MENU_DEBUGGER, combined);
//Open PPU Viewer
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_TOOL_OPENPPU]);
combined = "&PPU Viewer...\t" + combo;
ChangeMenuItemText(MENU_PPUVIEWER, combined);
//Open Hex editor
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_TOOL_OPENHEX]);
combined = "&Hex Editor...\t" + combo;
ChangeMenuItemText(MENU_HEXEDITOR, combined);
//Open Trace Logger
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_TOOL_OPENTRACELOGGER]);
combined = "&Trace Logger...\t" + combo;
ChangeMenuItemText(MENU_TRACELOGGER, combined);
//Open Code/Data Logger
combo = GetKeyComboName(FCEUD_CommandMapping[EMUCMD_TOOL_OPENCDLOGGER]);
combined = "&Code/Data Logger...\t" + combo;
ChangeMenuItemText(MENU_CDLOGGER, combined);
}
//This function is for the context menu item Save Movie As...
//It gets a filename from the user then calls CreateMovie()
void SaveMovieAs()
{
const char filter[]="NES Movie file (*.fm2)\0*.fm2\0All Files (*.*)\0*.*\0\0";
char nameo[2048];
std::string tempName;
OPENFILENAME ofn;
memset(&ofn,0,sizeof(ofn));
ofn.lStructSize=sizeof(ofn);
ofn.hInstance=fceu_hInstance;
ofn.lpstrTitle="Save Movie as...";
ofn.lpstrFilter=filter;
strcpy(nameo,curMovieFilename);
ofn.lpstrFile=nameo;
ofn.lpstrDefExt="fm2";
ofn.nMaxFile=256;
ofn.Flags=OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_HIDEREADONLY;
ofn.hwndOwner = hMemView;
if (GetSaveFileName(&ofn))
{
tempName = nameo;
FCEUI_CreateMovieFile(tempName);
}
}
void OpenRamSearch()
{
reset_address_info();
RamSearchHWnd = CreateDialog(fceu_hInstance, MAKEINTRESOURCE(IDD_RAMSEARCH), MainhWnd, (DLGPROC) RamSearchProc);
}
void OpenRamWatch()
{
RamWatchHWnd = CreateDialog(fceu_hInstance, MAKEINTRESOURCE(IDD_RAMWATCH), MainhWnd, (DLGPROC) RamWatchProc);
}
void SaveSnapshotAs()
{
const char filter[] = "Snapshot (*.png)\0*.png\0All Files (*.*)\0*.*\0\0";
char nameo[512];
OPENFILENAME ofn;
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hInstance = fceu_hInstance;
ofn.lpstrTitle = "Save Snapshot As...";
ofn.lpstrFilter = filter;
strcpy(nameo,FCEU_MakeFName(FCEUMKF_SNAP,0,"png").c_str());
nameo[strlen(nameo)-6] = '\0';
ofn.lpstrFile = nameo;
ofn.lpstrDefExt = "fcs";
std::string initdir = FCEU_GetPath(FCEUMKF_SNAP);
ofn.lpstrInitialDir = initdir.c_str();
ofn.nMaxFile = 256;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = "png";
if(GetSaveFileName(&ofn))
FCEUI_SetSnapshotAsName(nameo);
FCEUI_SaveSnapshotAs();
}
|
[
"Cthulhu32@e9098629-9c10-95be-0fa9-336bad66c20b"
] |
[
[
[
1,
2889
]
]
] |
fa541b507b6a6fe1f9cedc166b03f75ae2d65f92
|
c2abb873c8b352d0ec47757031e4a18b9190556e
|
/src/MyGUIEngine/src/MyGUI_TileRect.cpp
|
1a32ab343ee0e4db3870c2dbd738f0b008aae681
|
[] |
no_license
|
twktheainur/vortex-ee
|
70b89ec097cd1c74cde2b75f556448965d0d345d
|
8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6
|
refs/heads/master
| 2021-01-10T02:26:21.913972 | 2009-01-30T12:53:21 | 2009-01-30T12:53:21 | 44,046,528 | 0 | 0 | null | null | null | null |
WINDOWS-1251
|
C++
| false | false | 11,349 |
cpp
|
/*!
@file
@author Albert Semenov
@date 05/2008
@module
*/
#include "MyGUI_TileRect.h"
#include "MyGUI_RenderItem.h"
#include "MyGUI_LayerManager.h"
namespace MyGUI
{
const size_t TILERECT_COUNT_VERTEX = 16 * VERTEX_IN_QUAD;
TileRect::TileRect(const SubWidgetInfo &_info, CroppedRectanglePtr _parent) :
CroppedRectangleInterface(_info.coord, _info.align, _parent),
mEmptyView(false),
mRenderItem(null),
mCurrentCoord(_info.coord),
mCurrentAlpha(0xFFFFFFFF),
mTileSize(_info.coord.size()),
mCountVertex(TILERECT_COUNT_VERTEX)
{
mManager = LayerManager::getInstancePtr();
updateTextureData();
}
TileRect::~TileRect()
{
}
void TileRect::show()
{
if (mShow) return;
mShow = true;
if (null != mRenderItem) mRenderItem->outOfDate();
}
void TileRect::hide()
{
if (false == mShow) return;
mShow = false;
if (null != mRenderItem) mRenderItem->outOfDate();
}
void TileRect::setAlpha(float _alpha)
{
mCurrentAlpha = 0x00FFFFFF | ((uint8)(_alpha*255) << 24);
if (null != mRenderItem) mRenderItem->outOfDate();
}
void TileRect::_correctView()
{
if (null != mRenderItem) mRenderItem->outOfDate();
}
void TileRect::_setAlign(const IntCoord& _coord, bool _update)
{
_setAlign(_coord.size(), _update);
}
void TileRect::_setAlign(const IntSize& _size, bool _update)
{
// необходимо разобраться
bool need_update = true;//_update;
// первоначальное выравнивание
if (IS_ALIGN_RIGHT(mAlign)) {
if (IS_ALIGN_LEFT(mAlign)) {
// растягиваем
mCoord.width = mCoord.width + (mParent->getWidth() - _size.width);
need_update = true;
mIsMargin = true; // при изменении размеров все пересчитывать
}
else {
// двигаем по правому краю
mCoord.left = mCoord.left + (mParent->getWidth() - _size.width);
need_update = true;
}
}
else if (false == IS_ALIGN_LEFT(mAlign)) {
// выравнивание по горизонтали без растяжения
mCoord.left = (mParent->getWidth() - mCoord.width) / 2;
need_update = true;
}
if (IS_ALIGN_BOTTOM(mAlign)) {
if (IS_ALIGN_TOP(mAlign)) {
// растягиваем
mCoord.height = mCoord.height + (mParent->getHeight() - _size.height);
need_update = true;
mIsMargin = true; // при изменении размеров все пересчитывать
}
else {
mCoord.top = mCoord.top + (mParent->getHeight() - _size.height);
need_update = true;
}
}
else if (false == IS_ALIGN_TOP(mAlign)) {
// выравнивание по вертикали без растяжения
mCoord.top = (mParent->getHeight() - mCoord.height) / 2;
need_update = true;
}
if (need_update) {
mCurrentCoord = mCoord;
_updateView();
}
// растягиваем
/*mCoord.width = mCoord.width + (mParent->getWidth() - _size.width);
mCoord.height = mCoord.height + (mParent->getHeight() - _size.height);
mIsMargin = true; // при изменении размеров все пересчитывать
mCurrentCoord = mCoord;
_updateView();*/
}
void TileRect::_updateView()
{
bool margin = _checkMargin();
mEmptyView = ((0 >= getViewWidth()) || (0 >= getViewHeight()));
mCurrentCoord.left = mCoord.left + mMargin.left;
mCurrentCoord.top = mCoord.top + mMargin.top;
mCurrentCoord.width = getViewWidth();
mCurrentCoord.height = getViewHeight();
// подсчитываем необходимое колличество тайлов
if (false == mEmptyView) {
size_t count_x = mCoord.width / mTileSize.width;
if ((mCoord.width % mTileSize.width) > 0) count_x ++;
size_t count = mCoord.height / mTileSize.height;
if ((mCoord.height % mTileSize.height) > 0) count ++;
count = count * count_x * VERTEX_IN_QUAD;
// нужно больше вершин
if (count > mCountVertex) {
mCountVertex = count + TILERECT_COUNT_VERTEX;
if (null != mRenderItem) mRenderItem->reallockDrawItem(this, mCountVertex);
}
}
// вьюпорт стал битым
if (margin) {
// проверка на полный выход за границу
if (_checkOutside()) {
// запоминаем текущее состояние
mIsMargin = margin;
// обновить перед выходом
if (null != mRenderItem) mRenderItem->outOfDate();
return;
}
}
// запоминаем текущее состояние
mIsMargin = margin;
if (null != mRenderItem) mRenderItem->outOfDate();
}
void TileRect::_setUVSet(const FloatRect& _rect)
{
mCurrentTexture = _rect;
updateTextureData();
if (null != mRenderItem) mRenderItem->outOfDate();
}
size_t TileRect::_drawItem(Vertex * _vertex, bool _update)
{
if ((false == mShow) || mEmptyView) return 0;
//if (_update)
updateTextureData();
float vertex_z = mManager->getMaximumDepth();
// абсолютный размер окна
float window_left = ((mManager->getPixScaleX() * (float)(mCoord.left + mParent->getAbsoluteLeft()) + mManager->getHOffset()) * 2) - 1;
float window_right = window_left + (mManager->getPixScaleX() * (float)mCoord.width * 2);
float window_top = -(((mManager->getPixScaleY() * (float)(mCoord.top + mParent->getAbsoluteTop()) + mManager->getVOffset()) * 2) - 1);
float window_bottom = window_top - (mManager->getPixScaleY() * (float)mCoord.height * 2);
// размер вьюпорта
float real_left = ((mManager->getPixScaleX() * (float)(mCurrentCoord.left + mParent->getAbsoluteLeft()) + mManager->getHOffset()) * 2) - 1;
float real_right = real_left + (mManager->getPixScaleX() * (float)mCurrentCoord.width * 2);
float real_top = -(((mManager->getPixScaleY() * (float)(mCurrentCoord.top + mParent->getAbsoluteTop()) + mManager->getVOffset()) * 2) - 1);
float real_bottom = real_top - (mManager->getPixScaleY() * (float)mCurrentCoord.height * 2);
size_t count = 0;
float left = window_left;
float right = window_left;
float top = window_top;
float bottom = window_top;
for (int y=0; y<mCoord.height; y+=mTileSize.height) {
top = bottom;
bottom -= mRealTileHeight;
right = window_left;
float vertex_top = top;
float vertex_bottom = bottom;
bool texture_crop_height = false;
if (vertex_top > real_top) {
// проверка на полный выход
if (vertex_bottom > real_top) {
continue;
}
// обрезаем
vertex_top = real_top;
texture_crop_height = true;
}
if (vertex_bottom < real_bottom) {
// вообще вниз ушли
if (vertex_top < real_bottom) {
continue;
}
// обрезаем
vertex_bottom = real_bottom;
texture_crop_height = true;
}
for (int x=0; x<mCoord.width; x+=mTileSize.width) {
left = right;
right += mRealTileWidth;
float vertex_left = left;
float vertex_right = right;
bool texture_crop_width = false;
if (vertex_left < real_left) {
// проверка на полный выход
if (vertex_right < real_left) {
continue;
}
// обрезаем
vertex_left = real_left;
texture_crop_width = true;
}
if (vertex_right > real_right) {
// вообще строку до конца не нуна
if (vertex_left > real_right) {
continue;
}
// обрезаем
vertex_right = real_right;
texture_crop_width = true;
}
// текущие текстурные координаты
float texture_left = mCurrentTexture.left;
float texture_right = mCurrentTexture.right;
float texture_top = mCurrentTexture.top;
float texture_bottom = mCurrentTexture.bottom;
// смещение текстуры по вертикили
if (texture_crop_height) {
// прибавляем размер смещения в текстурных координатах
texture_top += (top - vertex_top) * mTextureHeightOne;
// отнимаем размер смещения в текстурных координатах
texture_bottom -= (vertex_bottom - bottom) * mTextureHeightOne;
}
// смещение текстуры по горизонтали
if (texture_crop_width) {
// прибавляем размер смещения в текстурных координатах
texture_left += (vertex_left - left) * mTextureWidthOne;
// отнимаем размер смещения в текстурных координатах
texture_right -= (right - vertex_right) * mTextureWidthOne;
}
// first triangle - left top
_vertex[count].x = vertex_left;
_vertex[count].y = vertex_top;
_vertex[count].z = vertex_z;
_vertex[count].colour = mCurrentAlpha;
_vertex[count].u = texture_left;
_vertex[count].v = texture_top;
count++;
// first triangle - left bottom
_vertex[count].x = vertex_left;
_vertex[count].y = vertex_bottom;
_vertex[count].z = vertex_z;
_vertex[count].colour = mCurrentAlpha;
_vertex[count].u = texture_left;
_vertex[count].v = texture_bottom;
count++;
// first triangle - right top
_vertex[count].x = vertex_right;
_vertex[count].y = vertex_top;
_vertex[count].z = vertex_z;
_vertex[count].colour = mCurrentAlpha;
_vertex[count].u = texture_right;
_vertex[count].v = texture_top;
count++;
// second triangle - right top
_vertex[count].x = vertex_right;
_vertex[count].y = vertex_top;
_vertex[count].z = vertex_z;
_vertex[count].colour = mCurrentAlpha;
_vertex[count].u = texture_right;
_vertex[count].v = texture_top;
count++;
// second triangle = left bottom
_vertex[count].x = vertex_left;
_vertex[count].y = vertex_bottom;
_vertex[count].z = vertex_z;
_vertex[count].colour = mCurrentAlpha;
_vertex[count].u = texture_left;
_vertex[count].v = texture_bottom;
count++;
// second triangle - right botton
_vertex[count].x = vertex_right;
_vertex[count].y = vertex_bottom;
_vertex[count].z = vertex_z;
_vertex[count].colour = mCurrentAlpha;
_vertex[count].u = texture_right;
_vertex[count].v = texture_bottom;
count++;
}
}
return count;
}
void TileRect::_createDrawItem(LayerItemKeeper * _keeper, RenderItem * _item)
{
mRenderItem = _item;
mRenderItem->addDrawItem(this, mCountVertex);
}
void TileRect::_destroyDrawItem()
{
mRenderItem->removeDrawItem(this);
}
void TileRect::updateTextureData()
{
// размер одного тайла
mRealTileWidth = mManager->getPixScaleX() * (float)(mTileSize.width) * 2;
mRealTileHeight = mManager->getPixScaleY() * (float)(mTileSize.height) * 2;
mTextureHeightOne = (mCurrentTexture.bottom - mCurrentTexture.top) / mRealTileHeight;
mTextureWidthOne = (mCurrentTexture.right - mCurrentTexture.left) / mRealTileWidth;
}
} // namespace MyGUI
|
[
"twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83"
] |
[
[
[
1,
366
]
]
] |
18c6dac7836b0c02aef3a50ee4414beba7aade22
|
3533c9f37def95dcc9d6b530c59138f7570ca239
|
/guCORE/src/guCORE_CProductInfo.cpp
|
497ac29ae129e0e988beca73c78fb7df4d051dfd
|
[] |
no_license
|
LiberatorUSA/GU
|
7e8af0dccede7edf5fc9c96c266b9888cff6d76e
|
2493438447e5cde3270e1c491fe2a6094dc0b4dc
|
refs/heads/master
| 2021-01-01T18:28:53.809051 | 2011-06-04T00:12:42 | 2011-06-04T00:12:42 | 41,840,823 | 0 | 0 | null | null | null | null |
UTF-8
|
C++
| false | false | 13,853 |
cpp
|
/*
* guCORE: Main module of the Galaxy Unlimited system
* Copyright (C) 2002 - 2008. Dinand Vanvelzen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*-------------------------------------------------------------------------//
// //
// INCLUDE //
// //
//-------------------------------------------------------------------------*/
#ifndef GUCEF_CORE_CDATANODE_H
#include "CDataNode.h"
#define GUCEF_CORE_CDATANODE_H
#endif /* GUCEF_CORE_CDATANODE_H ? */
#ifndef GUCEF_CORE_DVCPPSTRINGUTILS_H
#include "dvcppstringutils.h"
#define GUCEF_CORE_DVCPPSTRINGUTILS_H
#endif /* GUCEF_CORE_DVCPPSTRINGUTILS_H ? */
#include "guCORE_CProductInfo.h"
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GU {
namespace CORE {
/*-------------------------------------------------------------------------//
// //
// UTILITIES //
// //
//-------------------------------------------------------------------------*/
CProductInfo::CProductInfo( void )
: CIConfigurable() ,
m_name() ,
m_description() ,
m_infoURL() ,
m_patchListURL() ,
m_version() ,
m_deploymentState( DEPLOYMENTSTATE_UNKNOWN ) ,
m_productType( PRODUCTTYPE_UNKNOWN )
{GU_TRACE;
}
/*-------------------------------------------------------------------------*/
CProductInfo::~CProductInfo()
{GU_TRACE;
}
/*-------------------------------------------------------------------------*/
CProductInfo::CProductInfo( const CProductInfo& src )
: CIConfigurable() ,
m_name( src.m_name ) ,
m_description( src.m_description ) ,
m_infoURL( src.m_infoURL ) ,
m_patchListURL( src.m_patchListURL ) ,
m_version( src.m_version ) ,
m_deploymentState( src.m_deploymentState ) ,
m_productType( src.m_productType )
{GU_TRACE;
}
/*-------------------------------------------------------------------------*/
CProductInfo&
CProductInfo::operator=( const CProductInfo& src )
{GU_TRACE;
if ( &src != this )
{
m_name = src.m_name;
m_description = src.m_description;
m_infoURL = src.m_infoURL;
m_patchListURL = src.m_patchListURL;
m_version = src.m_version;
m_deploymentState = src.m_deploymentState;
m_productType = src.m_productType;
}
return *this;
}
/*-------------------------------------------------------------------------*/
void
CProductInfo::SetName( const CString& name )
{GU_TRACE;
m_name = name;
}
/*-------------------------------------------------------------------------*/
const CString&
CProductInfo::GetName( void ) const
{GU_TRACE;
return m_name;
}
/*-------------------------------------------------------------------------*/
void
CProductInfo::SetParentName( const CString& name )
{GU_TRACE;
m_parentName = name;
}
/*-------------------------------------------------------------------------*/
const CString&
CProductInfo::GetParentName( void ) const
{GU_TRACE;
return m_parentName;
}
/*-------------------------------------------------------------------------*/
void
CProductInfo::SetDescription( const CString& description )
{GU_TRACE;
m_description = description;
}
/*-------------------------------------------------------------------------*/
const CString&
CProductInfo::GetDescription( void ) const
{GU_TRACE;
return m_description;
}
/*-------------------------------------------------------------------------*/
void
CProductInfo::SetInfoURL( const CString& infoURL )
{GU_TRACE;
m_infoURL = infoURL;
}
/*-------------------------------------------------------------------------*/
const CString&
CProductInfo::GetInfoURL( void ) const
{GU_TRACE;
return m_infoURL;
}
/*-------------------------------------------------------------------------*/
void
CProductInfo::SetPatchListURL( const CString& patchListURL )
{GU_TRACE;
m_patchListURL = patchListURL;
}
/*-------------------------------------------------------------------------*/
const CString&
CProductInfo::GetPatchListURL( void ) const
{GU_TRACE;
return m_patchListURL;
}
/*-------------------------------------------------------------------------*/
void
CProductInfo::SetDeploymentState( const TDeploymentStatus deploymentState )
{GU_TRACE;
m_deploymentState = deploymentState;
}
/*-------------------------------------------------------------------------*/
const CProductInfo::TDeploymentStatus
CProductInfo::GetDeploymentState( void ) const
{GU_TRACE;
return m_deploymentState;
}
/*-------------------------------------------------------------------------*/
void
CProductInfo::SetProductType( const TProductType productType )
{GU_TRACE;
m_productType = productType;
}
/*-------------------------------------------------------------------------*/
const CProductInfo::TProductType
CProductInfo::GetProductType( void ) const
{GU_TRACE;
return m_productType;
}
/*-------------------------------------------------------------------------*/
void
CProductInfo::SetVersion( const GUCEF::CORE::TVersion& version )
{GU_TRACE;
m_version = version;
}
/*-------------------------------------------------------------------------*/
const GUCEF::CORE::TVersion&
CProductInfo::GetVersion( void ) const
{GU_TRACE;
return m_version;
}
/*-------------------------------------------------------------------------*/
bool
CProductInfo::operator<( const CProductInfo& other ) const
{GU_TRACE;
return GetCombinedProductString() < other.GetCombinedProductString();
}
/*-------------------------------------------------------------------------*/
CString
CProductInfo::ProductTypeToString( const TProductType productType )
{GU_TRACE;
switch ( productType )
{
case PRODUCTTYPE_INDEPENDANT :
{
return "Independent";
}
case PRODUCTTYPE_MODIFICATION :
{
return "Modification";
}
case PRODUCTTYPE_EXPANSION :
{
return "Expansion";
}
case PRODUCTTYPE_PLUGIN :
{
return "Plugin";
}
default:
{
return "Unknown";
}
}
}
/*-------------------------------------------------------------------------*/
const CProductInfo::TProductType
CProductInfo::StringToProductType( const CString& productType )
{GU_TRACE;
if ( productType.Equals( "Independent", false ) )
{
return PRODUCTTYPE_INDEPENDANT;
}
if ( productType.Equals( "Modification", false ) )
{
return PRODUCTTYPE_MODIFICATION;
}
if ( productType.Equals( "Expansion", false ) )
{
return PRODUCTTYPE_EXPANSION;
}
if ( productType.Equals( "Plugin", false ) )
{
return PRODUCTTYPE_PLUGIN;
}
return PRODUCTTYPE_UNKNOWN;
}
/*-------------------------------------------------------------------------*/
CString
CProductInfo::DeploymentStateToString( TDeploymentStatus deploymentState )
{GU_TRACE;
switch ( deploymentState )
{
case DEPLOYMENTSTATE_INSTALLED :
{
return "Installed";
}
case DEPLOYMENTSTATE_UPDATING :
{
return "Updating";
}
case DEPLOYMENTSTATE_DOWNLOADING :
{
return "Downloading";
}
case DEPLOYMENTSTATE_AVAILABLEFORDOWNLOAD :
{
return "AvailableForDownload";
}
default :
{
return "Unknown";
}
}
}
/*-------------------------------------------------------------------------*/
const CProductInfo::TDeploymentStatus
CProductInfo::StringToDeploymentState( const CString& deploymentState )
{GU_TRACE;
if ( deploymentState.Equals( "Installed", false ) )
{
return DEPLOYMENTSTATE_INSTALLED;
}
if ( deploymentState.Equals( "Updating", false ) )
{
return DEPLOYMENTSTATE_UPDATING;
}
if ( deploymentState.Equals( "Downloading", false ) )
{
return DEPLOYMENTSTATE_DOWNLOADING;
}
if ( deploymentState.Equals( "AvailableForDownload", false ) )
{
return DEPLOYMENTSTATE_AVAILABLEFORDOWNLOAD;
}
return DEPLOYMENTSTATE_UNKNOWN;
}
/*-------------------------------------------------------------------------*/
bool
CProductInfo::SaveConfig( GUCEF::CORE::CDataNode& node )
{GU_TRACE;
GUCEF::CORE::CDataNode newNode( "ProductInfo" );
newNode.SetAttribute( "Name", m_name );
newNode.SetAttribute( "Description", m_description );
newNode.SetAttribute( "Version", GUCEF::CORE::VersionToString( m_version ) );
newNode.SetAttribute( "ProductType", ProductTypeToString( m_productType ) );
newNode.SetAttribute( "DeploymentState", DeploymentStateToString( m_deploymentState ) );
newNode.SetAttribute( "PatchListURL", m_patchListURL );
newNode.SetAttribute( "InfoURL", m_infoURL );
node.AddChild( newNode );
return true;
}
/*-------------------------------------------------------------------------*/
bool
CProductInfo::LoadConfig( const GUCEF::CORE::CDataNode& node )
{GU_TRACE;
const GUCEF::CORE::CDataNode* infoNode = node.Find( "ProductInfo" );
if ( NULL != infoNode )
{
const GUCEF::CORE::CDataNode::TKeyValuePair* att = NULL;
att = infoNode->GetAttribute( "Name" );
if ( NULL != att )
{
m_name = att->second;
}
att = infoNode->GetAttribute( "Version" );
if ( NULL != att )
{
m_version = GUCEF::CORE::StringToVersion( att->second );
}
att = infoNode->GetAttribute( "Description" );
if ( NULL != att )
{
m_name = att->second;
}
att = infoNode->GetAttribute( "ProductType" );
if ( NULL != att )
{
m_name = StringToProductType( att->second );
}
att = infoNode->GetAttribute( "DeploymentState" );
if ( NULL != att )
{
m_name = StringToDeploymentState( att->second );
}
att = infoNode->GetAttribute( "PatchListURL" );
if ( NULL != att )
{
m_patchListURL = att->second;
}
att = infoNode->GetAttribute( "InfoURL" );
if ( NULL != att )
{
m_infoURL = att->second;
}
return true;
}
return false;
}
/*-------------------------------------------------------------------------*/
CString
CProductInfo::GetCombinedProductString( void ) const
{GU_TRACE;
const CString& mainName = m_parentName.Length() > 0 ? m_parentName : m_name;
CString path = mainName + '/' + GUCEF::CORE::VersionToString( m_version ) + '/';
if ( ( m_productType != CProductInfo::PRODUCTTYPE_UNKNOWN ) &&
( m_productType != CProductInfo::PRODUCTTYPE_INDEPENDANT ) )
{
path += CProductInfo::ProductTypeToString( m_productType ) + "s/";
if ( m_productType != CProductInfo::PRODUCTTYPE_PLUGIN )
{
path += GUCEF::CORE::VersionToString( m_version ) + '/';
}
if ( m_parentName.Length() > 0 )
{
path += m_name;
}
}
return path;
}
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace CORE */
}; /* namespace GU */
/*-------------------------------------------------------------------------*/
|
[
"[email protected]"
] |
[
[
[
1,
474
]
]
] |
b721a99f4f40a114a45fec3d38b9831351267b63
|
9e4b72c504df07f6116b2016693abc1566b38310
|
/back/ArcBall.cpp
|
92aa3535f37c9af761fae42e1e0ae14740b92732
|
[
"MIT"
] |
permissive
|
mmeeks/rep-snapper
|
73311cadd3d8753462cf87a7e279937d284714aa
|
3a91de735dc74358c0bd2259891f9feac7723f14
|
refs/heads/master
| 2016-08-04T08:56:55.355093 | 2010-12-05T19:03:03 | 2010-12-05T19:03:03 | 704,101 | 0 | 1 | null | null | null | null |
UTF-8
|
C++
| false | false | 4,733 |
cpp
|
/** KempoApi: The Turloc Toolkit *****************************/
/** * * **/
/** ** ** Filename: ArcBall.cpp **/
/** ** Version: Common **/
/** ** **/
/** **/
/** Arcball class for mouse manipulation. **/
/** **/
/** **/
/** **/
/** **/
/** (C) 1999-2003 Tatewake.com **/
/** History: **/
/** 08/17/2003 - (TJG) - Creation **/
/** 09/23/2003 - (TJG) - Bug fix and optimization **/
/** 09/25/2003 - (TJG) - Version for NeHe Basecode users **/
/** **/
/*************************************************************/
#include "stdafx.h"
//#include <windows.h> // Header File For Windows
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
//#include <gl\glaux.h> // Header File For The GLaux Library
#include "math.h" // Needed for sqrtf
#include "ArcBall.h" // ArcBall header
//Arcball sphere constants:
//Diameter is 2.0f
//Radius is 1.0f
//Radius squared is 1.0f
void ArcBall_t::_mapToSphere(const Point2fT* NewPt, Vector3fT* NewVec) const
{
Point2fT TempPt;
GLfloat length;
//Copy paramter into temp point
TempPt = *NewPt;
//Adjust point coords and scale down to range of [-1 ... 1]
TempPt.s.X = (TempPt.s.X * this->AdjustWidth) - 1.0f;
TempPt.s.Y = 1.0f - (TempPt.s.Y * this->AdjustHeight);
//Compute the square of the length of the vector to the point from the center
length = (TempPt.s.X * TempPt.s.X) + (TempPt.s.Y * TempPt.s.Y);
//If the point is mapped outside of the sphere... (length > radius squared)
if (length > 1.0f)
{
GLfloat norm;
//Compute a normalizing factor (radius / sqrt(length))
norm = 1.0f / FuncSqrt(length);
//Return the "normalized" vector, a point on the sphere
NewVec->s.X = TempPt.s.X * norm;
NewVec->s.Y = TempPt.s.Y * norm;
NewVec->s.Z = 0.0f;
}
else //Else it's on the inside
{
//Return a vector to a point mapped inside the sphere sqrt(radius squared - length)
NewVec->s.X = TempPt.s.X;
NewVec->s.Y = TempPt.s.Y;
NewVec->s.Z = FuncSqrt(1.0f - length);
}
}
//Create/Destroy
ArcBall_t::ArcBall_t(GLfloat NewWidth, GLfloat NewHeight)
{
//Clear initial values
this->StVec.s.X =
this->StVec.s.Y =
this->StVec.s.Z =
this->EnVec.s.X =
this->EnVec.s.Y =
this->EnVec.s.Z = 0.0f;
//Set initial bounds
this->setBounds(NewWidth, NewHeight);
}
//Mouse down
void ArcBall_t::click(const Point2fT* NewPt)
{
//Map the point to the sphere
this->_mapToSphere(NewPt, &this->StVec);
}
//Mouse drag, calculate rotation
void ArcBall_t::drag(const Point2fT* NewPt, Quat4fT* NewRot)
{
//Map the point to the sphere
this->_mapToSphere(NewPt, &this->EnVec);
//Return the quaternion equivalent to the rotation
if (NewRot)
{
Vector3fT Perp;
//Compute the vector perpendicular to the begin and end vectors
Vector3fCross(&Perp, &this->StVec, &this->EnVec);
//Compute the length of the perpendicular vector
if (Vector3fLength(&Perp) > Epsilon) //if its non-zero
{
//We're ok, so return the perpendicular vector as the transform after all
NewRot->s.X = Perp.s.X;
NewRot->s.Y = Perp.s.Y;
NewRot->s.Z = Perp.s.Z;
//In the quaternion values, w is cosine (theta / 2), where theta is rotation angle
NewRot->s.W= Vector3fDot(&this->StVec, &this->EnVec);
}
else //if its zero
{
//The begin and end vectors coincide, so return an identity transform
NewRot->s.X =
NewRot->s.Y =
NewRot->s.Z =
NewRot->s.W = 0.0f;
}
}
}
|
[
"[email protected]"
] |
[
[
[
1,
129
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.