blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d0e50f07d472219d88c640377c409bf3a932101d | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/GumpEditor-0.32/diagram/DiagramControlFactory.cpp | c841ddbd0257ac360c1133d1663b6c118883c956 | [] | 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 | 2,863 | cpp | /* ==========================================================================
CDiagramControlFactory
Author : Johan Rosengren, Abstrakt Mekanik AB
Date : 2004-03-31
Purpose : CDiagramControlFactory is a factory-class with one
single member, allowing the creation of CDiagramEntity-
derived objects from a string.
Description : CreateFromString tries to instantiate one of the control
objects by testing the control object static function
CreateFromString until it hits a valid one. The
resulting pointer is then returned and can be added to
the application data.
Usage : This is an example on how to handle loading from a text
file to a CDiagramEditor. Just call
CDiagramControlFactory::CreateFromString and if a non-
NULL pointer is returned, add it to the CDiagramEditor
data.
========================================================================*/
#include "stdafx.h"
#include "DiagramControlFactory.h"
/*
#include "DiagramButton.h"
#include "DiagramEdit.h"
#include "DiagramStatic.h"
#include "DiagramCheckbox.h"
#include "DiagramRadiobutton.h"
#include "DiagramCombobox.h"
#include "DiagramListbox.h"
#include "DiagramGroupbox.h"
*/
#include "../GumpEditor.h"
#include "../GumpStatic.h"
#include "../GumpPicture.h"
#include "../GumpButton.h"
#include "../GumpEdit.h"
#include "../GumpBorder.h"
#include "../GumpCheckbox.h"
#include "../GumpRadio.h"
#include "../GumpPaperdoll.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDiagramControlFactory
CDiagramEntity* CDiagramControlFactory::CreateFromString(XML::Node* node)
{
CDiagramEntity* obj;
obj = CGumpPicture::CreateFromString( node );
if( !obj )
obj = CGumpButton::CreateFromString( node );
if( !obj )
obj = CGumpStatic::CreateFromString(node);
if( !obj )
obj = CGumpEdit::CreateFromString( node );
if( !obj )
obj = CGumpCheckbox::CreateFromString( node );
if( !obj )
obj = CGumpRadio::CreateFromString( node );
if( !obj )
obj = CGumpBorder::CreateFromString( node );
if( !obj )
obj = CGumpPaperdoll::CreateFromString( node );
/*
if( !obj )
obj = CDiagramButton::CreateFromString( node );
if( !obj )
obj = CDiagramEdit::CreateFromString( node );
if( !obj )
obj = CDiagramStatic::CreateFromString( node );
if( !obj )
obj = CDiagramCheckbox::CreateFromString( node );
if( !obj )
obj = CDiagramRadiobutton::CreateFromString( node );
if( !obj )
obj = CDiagramCombobox::CreateFromString( node );
if( !obj )
obj = CDiagramListbox::CreateFromString( node );
if( !obj )
obj = CDiagramGroupbox::CreateFromString( node );
*/
return obj;
} | [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
] | [
[
[
1,
99
]
]
] |
a13bd70e9b654f78ef8613abb197934e1d22b848 | 191d4160cba9d00fce9041a1cc09f17b4b027df5 | /ZeroLag/ZeroLag/PeInfoDlg.cpp | 8a126df13e55a72d0fd5fc02da2936944e93bf5f | [] | no_license | zapline/zero-lag | f71d35efd7b2f884566a45b5c1dc6c7eec6577dd | 1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4 | refs/heads/master | 2021-01-22T16:45:46.430952 | 2011-05-07T13:22:52 | 2011-05-07T13:22:52 | 32,774,187 | 3 | 2 | null | null | null | null | GB18030 | C++ | false | false | 1,552 | cpp | // PeInfoDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "ZeroLag.h"
#include "PeInfoDlg.h"
// CPeInfoDlg 对话框
IMPLEMENT_DYNAMIC(CPeInfoDlg, CDialog)
CPeInfoDlg::CPeInfoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CPeInfoDlg::IDD, pParent)
, m_eFileSize(_T(""))
, m_eFileName(_T(""))
{
}
CPeInfoDlg::~CPeInfoDlg()
{
}
void CPeInfoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST_PEINFOLIST, m_SecList);
DDX_Text(pDX, IDC_EDIT_PEINFOFILESIZE, m_eFileSize);
DDX_Text(pDX, IDC_EDIT_PEINFOFILENAME, m_eFileName);
}
BEGIN_MESSAGE_MAP(CPeInfoDlg, CDialog)
END_MESSAGE_MAP()
// CPeInfoDlg 消息处理程序
BOOL CPeInfoDlg::OnInitDialog()
{
CDialog::OnInitDialog();
PeInfo.zInit(PathName);
m_SecList.InsertColumn(0, L"區段名", LVCFMT_LEFT, 80);
m_SecList.InsertColumn(1, L"區段大小", LVCFMT_LEFT,120);
m_eFileName = FileName;
m_eFileSize.Format(L"%d字節", PeInfo.zGetFileSize());
UpdateData(FALSE);
for (int n=0;n<PeInfo.zGetSecNum();n++)
{
CString temp;
PIMAGE_SECTION_HEADER p = PeInfo.zGetSecHeader(n);
temp.Format(L"%c%c%c%c%c%c%c%c",p->Name[0],p->Name[1],p->Name[2],p->Name[3],p->Name[4],p->Name[5],p->Name[6],p->Name[7]);
m_SecList.InsertItem(n,L"");
m_SecList.SetItemText(n,0,temp);
temp.Format(L"0x%08X",p->SizeOfRawData);
m_SecList.SetItemText(n,1,temp);
}
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
| [
"Administrator@PC-200201010241"
] | [
[
[
1,
67
]
]
] |
dafb9b6fe1dddd97daad33cc0dfa463a1cfae3cc | 6b9505c5313d161f9763b5d454c06818d407c8fa | /mmo-game-server/client.h | 1c09080bb00c95eb28baa6349237401121408c2d | [] | no_license | itsnotlupus/webgl-mmo | 09426fdf368e7448fd84475b4a60f19a9818b699 | b3349a38ed09a3ab536517d1be05951958ef98df | refs/heads/master | 2020-07-21T23:12:46.125284 | 2011-05-15T15:55:10 | 2011-05-15T15:55:10 | 3,181,876 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 644 | h | #ifndef CLIENT_H
#define CLIENT_H
#include <QObject>
#include <QTcpSocket>
#include <QTimer>
#include <QTime>
class Client : public QObject
{
Q_OBJECT
public:
Client(int n, QTcpSocket *s);
void sendMessage(QByteArray ba);
int getN();
float px, py, pz, pd;
int n, ps;
QTime lh;
signals:
void handshaked(int i);
void disconnected(int i);
void gotMessage(int i, QByteArray ba);
private slots:
void tcpSocketReadyRead();
void tcpSocketDisconnected();
void handshakeTimeOut();
private:
QTcpSocket *s;
QTimer *timer;
};
#endif // CLIENT_H
| [
"KaUgnius@0b165116-7a41-ded5-cf4d-4fbad8ecb400"
] | [
[
[
1,
40
]
]
] |
4342a85b219528f78c71f68c49190814ee0709a9 | 937c59bea84dfe14cac07ed2e3a706ac765d965e | /PictureClass/StatLink.h | d9cc11980506efd59eaa461ce789c2561987d556 | [] | no_license | IDA-RE-things/dvsatucsd | 1b73b21644ffa869a0b5dbd36ac1c0cbfa37bce0 | dff552ac9c29bca8f5b20b46342fbb6887857915 | refs/heads/master | 2016-09-05T16:17:08.013350 | 2010-04-03T22:17:49 | 2010-04-03T22:17:49 | 40,741,625 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,283 | h | ////////////////////////////////////////////////////////////////
// MSDN Magazine -- October 2001
// If this code works, it was written by Paul DiLascia.
// If not, I don't know who wrote it.
// Compiles with Visual C++ 6.0 for Windows 98 and probably Windows 2000 too.
// Set tabsize = 3 in your editor.
//
#pragma once
//////////////////
// Simple text hyperlink derived from CString
//
class CHyperlink : public CString {
public:
CHyperlink(LPCTSTR lpLink = NULL) : CString(lpLink) { }
~CHyperlink() { }
const CHyperlink& operator=(LPCTSTR lpsz) {
CString::operator=(lpsz);
return *this;
}
operator LPCTSTR() {
return CString::operator LPCTSTR();
}
HINSTANCE Navigate() {
return IsEmpty() ? NULL :
ShellExecute(0, _T("open"), *this, 0, 0, SW_SHOWNORMAL);
}
};
class CStaticLink : public CStatic {
public:
DECLARE_DYNAMIC(CStaticLink)
CStaticLink(LPCTSTR lpText = NULL, BOOL bDeleteOnDestroy=FALSE);
~CStaticLink() { }
// Use this if you want to subclass and also set different URL
BOOL SubclassDlgItem(UINT nID, CWnd* pParent, LPCTSTR lpszLink=NULL) {
m_link = lpszLink;
return CStatic::SubclassDlgItem(nID, pParent);
}
void SetNoLink(BOOL bNoLink) {
m_bNoLink = bNoLink;
}
// Hyperlink contains URL/filename. If NULL, I will use the window text.
// (GetWindowText) to get the target.
CHyperlink m_link;
COLORREF m_color;
// Default colors you can change
// These are global, so they're the same for all links.
static COLORREF g_colorUnvisited;
static COLORREF g_colorVisited;
// Cursor used when mouse is on a link--you can set, or
// it will default to the standard hand with pointing finger.
// This is global, so it's the same for all links.
static HCURSOR g_hCursorLink;
protected:
CFont m_font; // underline font for text control
BOOL m_bDeleteOnDestroy; // delete object when window destroyed?
BOOL m_bNoLink;
BOOL TryNavigate();
virtual void PostNcDestroy();
// message handlers
DECLARE_MESSAGE_MAP()
afx_msg UINT OnNcHitTest(CPoint point);
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
};
| [
"rishmish@bd9eb85a-b20e-11dd-9381-bf584fb1fa83"
] | [
[
[
1,
75
]
]
] |
36c97aeab9931cd36f199faa08e1b22971602a8f | 9738ebb36adfaa6f06fe2ba452aec6fcb8a06a5e | /heimdall-frontend/Source/main.cpp | 78336663e2410bdcbff28aee00cb5fc02b27cef7 | [] | no_license | superweapons/Heimdall-fc | 9f4ea33e4da6ffd209a7fb7afa51616eb2007832 | 73d77ddbf2f26c2d416b0ef4a57040e64ad86df2 | refs/heads/master | 2021-01-15T19:39:54.452631 | 2011-11-16T02:54:26 | 2011-11-16T02:54:26 | 2,785,073 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,403 | cpp | /* Copyright (c) 2010-2011 Benjamin Dobell, Glass Echidna
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.*/
// Qt
#include <QtGui/QApplication>
// Heimdall Frontend
#include "mainwindow.h"
using namespace HeimdallFrontend;
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
MainWindow window;
window.show();
return (application.exec());
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
24,
26
],
[
31,
31
],
[
33,
34
],
[
36,
36
]
],
[
[
2,
23
],
[
27,
30
],
[
32,
32
],
[
35,
35
],
[
37,
37
]
]
] |
82c98905e5436f24336bacd5cde0ea951b4d3640 | 110f8081090ba9591d295d617a55a674467d127e | /tests/CommandLineTest.cpp | 05c5c3ad31c63bca2f9016a0b99072f5f4b0c2e2 | [] | no_license | rayfill/cpplib | 617bcf04368a2db70aea8b9418a45d7fd187d8c2 | bc37fbf0732141d0107dd93bcf5e0b31f0d078ca | refs/heads/master | 2021-01-25T03:49:26.965162 | 2011-07-17T15:19:11 | 2011-07-17T15:19:11 | 783,979 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,387 | cpp | #include <cppunit/extensions/HelperMacros.h>
#include <util/CommandLine.hpp>
class CommandLineTest : public CppUnit::TestFixture
{
private:
CPPUNIT_TEST_SUITE(CommandLineTest);
CPPUNIT_TEST(parseTest);
CPPUNIT_TEST(functionTest);
CPPUNIT_TEST_SUITE_END();
public:
void parseTest()
{
std::vector<std::string> result =
CommandLine::parseArguments(" aaaaaa bbbbbbb ddddd ");
CPPUNIT_ASSERT(result.size() == 3);
CPPUNIT_ASSERT_MESSAGE(result[0], result[0] == "aaaaaa");
CPPUNIT_ASSERT_MESSAGE(result[1], result[1] == "bbbbbbb");
CPPUNIT_ASSERT_MESSAGE(result[2], result[2] == "ddddd");
const char* args[] = { "cccccc", "hogehoge", "fugafuga" };
result = CommandLine::parseArguments(3, args);
}
void functionTest()
{
CommandLine cmdline("a bb ccc dddd eeeee ");
CPPUNIT_ASSERT(cmdline.arguments.size() == 5);
CPPUNIT_ASSERT(cmdline.size() == 5);
std::vector<std::string> result;
for (CommandLine::iterator itor = cmdline.begin();
itor != cmdline.end(); ++itor)
result.push_back(*itor);
CPPUNIT_ASSERT(result.size() == 5);
CPPUNIT_ASSERT(result[0] == "a");
CPPUNIT_ASSERT(result[1] == "bb");
CPPUNIT_ASSERT(result[2] == "ccc");
CPPUNIT_ASSERT(result[3] == "dddd");
CPPUNIT_ASSERT(result[4] == "eeeee");
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( CommandLineTest );
| [
"alfeim@287b3242-7fab-264f-8401-8509467ab285"
] | [
[
[
1,
48
]
]
] |
60aae33ec47467234d872e246520c68c7f91ec8d | 3eae8bea68fd2eb7965cca5afca717b86700adb5 | /HiroCat/Source/GLoadingScene.cpp | 9548aea58f57490638ee1ea5ade7d6d5afa215d8 | [] | no_license | mujige77/WebGame | c0a218ee7d23609076859e634e10e29c92bb595b | 73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd | refs/heads/master | 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 992 | cpp | #include "GamePCH.h"
#include "GLoadingScene.h"
GLoadingLayer* GLoadingLayer::CreateLoadingLayer(guint32 uiLoadingBgIndex)
{
float width = GetGameState()->GetGameWidth();
float height = GetGameState()->GetGameHeight();
GLoadingLayer* loadingLayer = new GLoadingLayer();
gchar fileName[GN_MAX_PATH] = { 0, };
GnSprintf( fileName, sizeof( fileName ), "loading%d.png", uiLoadingBgIndex );
gstring fullFileName;
GetFullPathFromWorkPath( fileName, fullFileName );
CCSprite* bg = CCSprite::spriteWithFile( fullFileName.c_str() );
bg->setPosition( CCPointMake( width / 2, height / 2 ) );
loadingLayer->addChild( bg );
return loadingLayer;
}
GLoadingScene* GLoadingScene::CreateLoadingScene()
{
GLoadingScene* loadingScene = new GLoadingScene();
GLoadingLayer* loadingLayer = GLoadingLayer::CreateLoadingLayer( ( GnRand() % 3 ) + 1 );
loadingScene->addChild( loadingLayer );
loadingLayer->release();
return loadingScene;
}
| [
"[email protected]"
] | [
[
[
1,
33
]
]
] |
84042866e3932e4d3d6189e6618e13db754801d8 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/Window.h | 27e4e9584a0b5b99d67f8f313d45d0780fa11930 | [] | 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,720 | h | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: Window.h
Version: 0.12
---------------------------------------------------------------------------
*/
#pragma once
#ifndef __INC_WINDOW_H_
#define __INC_WINDOW_H_
#include "Prerequisities.h"
#include "TypeInfo.h"
namespace nGENE
{
/// Window descriptor class.
typedef struct nGENEDLL SWindowDesc
{
uint width; ///< Width of the client area
uint height; ///< Height of the client area
wstring name; ///< Caption of the window
} WINDOW_DESC;
/** Interface representing application window.
*/
class nGENEDLL Window
{
EXPOSE_TYPE
private:
// Hide assignment operator and copy constructor to prevent
// it from being used.
Window(const Window& src);
Window& operator=(const Window& rhs);
protected:
/// Descriptor of the window
WINDOW_DESC m_WndDesc;
public:
Window();
Window(const WINDOW_DESC& _desc);
virtual ~Window();
/// Creates new window.
virtual void createWindow()=0;
/** Shows/hides window.
@param
value when true window is showed, otherwise it is
hidden.
*/
virtual void showWindow(bool _value)=0;
/// Closes the window.
virtual void closeWindow()=0;
/// Returns the name of the window
virtual const wstring& getWindowName() const {return m_WndDesc.name;}
/// Sets window caption.
virtual void setWindowCaption(const wstring& _caption)=0;
/// How many windows are being used throughout the application
static dword s_nWindowsNum;
};
}
#endif | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
78
]
]
] |
4bfd034fc43dcf8ca427c8ff575a77e4470f16fb | 1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50 | /xpr/exploring_machine.cpp | fa5351550cc318c950d29e063833c4668738dd68 | [] | 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 | IBM852 | C++ | false | false | 10,771 | cpp | #include "exploring_machine.h"
//-----------------------------------------------------------------------++
///experimental
#include "alcor/core/pixel_traits.h"
#include "alcor/core/depth_image_utils.hpp"
//---------------------------------------------------------------------------
namespace all { namespace xpr {
//---------------------------------------------------------------------------
//ctor
exploring_machine::exploring_machine()
{
//Idling ... default
fire_callback = boost::bind
(&exploring_machine::idled_cb, this);
//Task Listener
tasklistener.reset(new task_listener("config/xpr_service.ini"));
tasklistener->notify_evt = boost::bind(&exploring_machine::taskreceived, this, ::_1);
tasklistener->run_async();
//bumblebee
bee.reset(new sense::bumblebee_driver_t());
bee->open("config/bumblebeeB.ini");
//PTU
ptu.reset (new act::directed_perception_ptu_t);
ptu->open("config/dpptu_conf.ini");
//PINHOLE
pinhole.focal = bee->focal();
pinhole.ncols = bee->ncols();
pinhole.nrows = bee->nrows();
//P3AT
p3at.reset(new act::p3_gateway());
///
if (p3at->open("config/p3_conf.ini"))
printf("Robot connected!\n");
///P3AT server
p3at_server.reset(new act::p3_server_t("config/p3_conf.ini"));
p3at_server->set_gateway_ptr(p3at);
p3at_server->run_async();
//STREAMING
rgb_stream_source_ptr.reset(new all::core::memory_stream_source_t( bee->nrows(), bee->ncols() ) );
rgb_stream_server_ptr = new all::core::stream_server_t(rgb_stream_source_ptr,"config/bumblebee_stream_server.ini");
rgb_stream_server_ptr->run_async();
///SPLAM STREAMING
splam_stream_source_ptr.reset(new all::core::memory_stream_source_t( splam.get_row(), splam.get_col() ) );
splam_stream_server_ptr = new all::core::stream_server_t(splam_stream_source_ptr,"config/.....ini");
splam_stream_server_ptr->run_async();
///Streaming OPen GL outside???
//Initiate thread
thisthread.reset(
new boost::thread
(
boost::bind(&exploring_machine::threadloop, this)
)
);
}
//---------------------------------------------------------------------------
///
void exploring_machine::taskreceived(int evt)
{
printf("TASK RECEIVED\n");
boost::mutex::scoped_lock lock(process_guard);
switch (evt)
{
case etag::RESET :
process_event(exploring_machine::reset_evt() );
break;
case etag::IDLE :
process_event(exploring_machine::idle_evt() );
break;
case etag::EXPLORE :
process_event(exploring_machine::explore_evt() );
break;
case etag::RESUME :
process_event(exploring_machine::resume_evt() );
break;
case etag::VISIT :
process_event(exploring_machine::visit_evt() );
break;
default:
break;
}
}
//---------------------------------------------------------------------------
void exploring_machine::threadloop()
{
///
workspace.reset( new matlab::matlab_engine_t);
///
workspace->command_line("cd explore");
///
while (running_)
{
{
boost::mutex::scoped_lock lock(process_guard);
if(!fire_callback.empty())
fire_callback();
}
boost::thread::yield();
core::BOOST_SLEEP(50);
}
}
//---------------------------------------------------------------------------
//[FIRE callbacks]
//---------------------------------------------------------------------------
//idled
void exploring_machine::idled_cb()
{
if (bee->grab())
{
rightim = bee->get_color_buffer(core::right_img);
rgb_stream_source_ptr->update_image(rightim);
}
}
//---------------------------------------------------------------------------
///
void exploring_machine::exploring_cb()
{
math::angle pana_;
math::angle tilta_;
//center pantilt, depending on last glo_theta_target and theta_rob
splam.get_splam_data(splamdata);
//
math::pose2d robotpose = splamdata.get_current_position();
//to compensate
pana_.set_deg(glo_theta_target.deg() - robotpose.getTh().deg());
//compensate!!
ptu->set_pan(pana_.deg());
if (bee->grab())
{
rightim = bee->get_color_buffer(core::right_img);
rgb_stream_source_ptr->update_image(rightim);
}
}
//---------------------------------------------------------------------------
///
void exploring_machine::observing_cb()
{
//
splam.get_splam_data(splamdata);
//
math::pose2d robotpose = splamdata.get_current_position();
//
core::pantilt_angle_t currentptu = ptu->get_fast_pantilt();
//GRAB
if (bee->grab())
{
///GET
rightim =
bee->get_color_buffer(core::right_img);
///
depthim =
bee->get_depth_buffer();
//ADAPT
///transform
mxArray* mx_rimage =
matlab::buffer2array<core::uint8_t>::create_from_planar(rightim.get()
,matlab::row_major
,bee->nrows()
,bee->ncols());
//XYZ
mxArray* mx_xyz =
matlab::buffer2array<core::single_t>::create_from_planar(
depthim.get()
, matlab::row_major
,bee->nrows()
,bee->ncols());
//WORKSPACE
//Push into Workspace
workspace->put_array("xyz", mx_xyz);
//Push into Workspace
workspace->put_array("rgb", mx_rimage);
///COMMANDs
workspace->command_line
("[valX, valY, prob, odimX, odimY] = fair_attention_wrap(rgb, xyz)");
//***GATHER***
valX =
static_cast<int> (workspace->get_scalar_double("valX") );
valY =
static_cast<int> (workspace->get_scalar_double("valY") );
prob =
static_cast<int> (workspace->get_scalar_double("prob") );
odimX =
static_cast<int> (workspace->get_scalar_double("odimX") );
odimY =
static_cast<int> (workspace->get_scalar_double("odimY") );
//first, center the ptu on the target/roi
move_ptu_to_screen_rc(valX, valY );
//ProfonditÓ 3D
core::depth_image_t mydepthim;
mydepthim.assign(bee->nrows(), bee->ncols(), depthim.get());
//centro dell'intorno
core::pixelcoord_t center;
center.row = valX;
center.col = valY;
//raggio dell'intorno
size_t hsize = (odimX > odimY) ? (odimX):(odimY);
//
core::mystat vstat
= core::estimate_depth(mydepthim, center, hsize);
//---------------------------
double distanza = vstat.mean;
//angolo (all::math::angle) rispetto il centro dell'immagine dell'oggetto visto
math::angle th ( pinhole.delta_pan_from_pixel(valY) , math::deg_tag) ;
////local offset (that is respect to robot nose)
double loc_theta_target = currentptu.get_pan_deg() + th.deg();
////theta globale (useful for next iteration)
glo_theta_target.set_deg( loc_theta_target + robotpose.get_th(math::deg_tag) );
// relative_goal = goal relativo... costruttore con modulo ed angolo
all::math::point2d relative_goal(distanza/2.0, glo_theta_target);
//SETPOINT NAVIGAZIONE
p3at->set_relative_goto(math::point2d(0,0) , 0);
//
rgb_stream_source_ptr->update_image(rightim);
///SWITCH TO EXPLORE ...mmmmm
//fire_callback = boost::bind
// (&exploring_machine::exploring_cb, this);
printf("Navigate with setpoint\n");
process_event(exploring_machine::explore_evt());
}
else
{
printf("cannot grab!\n");
process_event(exploring_machine::reset_evt());
}
}
///
void exploring_machine::visiting_cb()
{
}
//---------------------------------------------------------------------------
//[TRANSITION FUNCTIONS]
//
bool exploring_machine::go_explore (explore_evt const&)
{
//
p3at->enable_goto_mode();
//
p3at->set_relative_goto(math::point2d(0,0) , 0);
//
boost::mutex::scoped_lock lock(process_guard);
///PROVVISORIO
fire_callback = boost::bind
(&exploring_machine::observing_cb, this);
return true;
}
//---------------------------------------------------------------------------
///
bool exploring_machine::go_explore (resume_evt const&)
{
//
boost::mutex::scoped_lock lock(process_guard);
///
fire_callback = boost::bind
(&exploring_machine::observing_cb, this);
return true;
}
//---------------------------------------------------------------------------
//
bool exploring_machine::go_idle (idle_evt const&)
{
//
p3at->enable_stop_mode();
//
boost::mutex::scoped_lock lock(process_guard);
///
fire_callback = boost::bind
(&exploring_machine::idled_cb, this);
return true;
}
//---------------------------------------------------------------------------
//
bool exploring_machine::go_idle (reset_evt const&)
{
//
p3at->enable_stop_mode();
//
boost::mutex::scoped_lock lock(process_guard);
///
fire_callback = boost::bind
(&exploring_machine::idled_cb, this);
return true;
}
//---------------------------------------------------------------------------
//
bool exploring_machine::go_visit (visit_evt const&)
{
return true;
}
//---------------------------------------------------------------------------
//###########################################################################
void exploring_machine::move_ptu_to_screen_rc(float row, float col)
{
if(ptu)
{
//
core::pantilt_angle_t current =
ptu->get_fast_pantilt();
//
core::pantilt_angle_t delta;
//
pinhole.pantilt_from_pixel(row, col, delta);
//
float nupan = delta.get_pan_deg() + current.get_pan_deg();
float nutilt = delta.get_tilt_deg()+ current.get_tilt_deg();
//
ptu->set_pantilt(nupan, nutilt);
//printf("Row: %f Col: %f \n", row, col);
//printf("current: %.2f %.2f\n", current.get_pan_deg(),current.get_tilt_deg());
//printf("Delta: %.2f %.2f\n", delta.get_pan_deg(), delta.get_tilt_deg());
}
}
//---------------------------------------------------------------------------
}}//all::xpr
//--------------------------------------------------------------------------- | [
"andrea.carbone@1ffd000b-a628-0410-9a29-793f135cad17",
"giorgio.ugazio@1ffd000b-a628-0410-9a29-793f135cad17"
] | [
[
[
1,
248
],
[
250,
366
]
],
[
[
249,
249
]
]
] |
b56ad65a2fa2fe298e7d66916d2a9b797241e36c | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/techdemo2/engine/multimedia/include/SoundResource.h | 194375cea8e6c9c7a98da54506458452022f14d1 | [
"ClArtistic",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | 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 | ISO-8859-3 | C++ | false | false | 2,553 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 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.
*/
#ifndef SOUNDRESOURCE_H
#define SOUNDRESOURCE_H
#include "MultimediaPrerequisites.h"
#include <OgreResource.h>
#include <OgreDataStream.h>
namespace rl {
/** Diese Basisklasse kapselt eine fmod-Source fuer
* den ResourceManager von Ogre
* @author Josch
* @date 06-19-2004
* @date 07-23-2004
* @date 10-10-2004
* @date 06-26-2005
* @version 4.0
*/
class _RlMultimediaExport SoundResource: public Ogre::Resource
{
private:
/// Unsere Daten von Ogres ResourceManager.
Ogre::DataStreamPtr mDataStream;
public:
/// Der Standardkonstruktor
SoundResource(Ogre::ResourceManager* creator, const Ogre::String& name,
Ogre::ResourceHandle handle, const Ogre::String& group, bool isManual,
Ogre::ManualResourceLoader* loader);
/// Der Destruktor
virtual ~SoundResource();
/// Den Datenstrom zurückgeben
const Ogre::DataStreamPtr &getDataStream() const;
/// Groesse zurueckgeben.
int getSize() const;
protected:
/// Laedt die Soundquelle.
virtual void loadImpl();
/// Entlaedt die Soundquelle.
virtual void unloadImpl();
/// Bestimmt die Groesse im Speicher (wird erst nach dem Laden aufgerufen)
virtual size_t calculateSize() const;
};
class _RlMultimediaExport SoundResourcePtr :
public Ogre::SharedPtr<SoundResource>
{
public:
SoundResourcePtr() : Ogre::SharedPtr<SoundResource>() {}
explicit SoundResourcePtr(SoundResource* rep) : Ogre::SharedPtr<SoundResource>(rep) {}
SoundResourcePtr(const SoundResourcePtr& res) : Ogre::SharedPtr<SoundResource>(res) {}
SoundResourcePtr(const Ogre::ResourcePtr& res);
SoundResourcePtr& operator=(const Ogre::ResourcePtr& res);
protected:
void destroy();
};
}
#endif
| [
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
78
]
]
] |
d2af5dd5cc4a3cc9c26152b5e879de0ba86e106e | 8f1601062c4a5452f2bdd0f75f3d12a79b98ba62 | /examples/tankwars/Terrain.cpp | 15ae0280d1a8d6ef494aa43ef8bcb26bb69a81c9 | [] | no_license | chadaustin/isugamedev | 200a54f55a2581cd2c62c94eb96b9e238abcf3dd | d3008ada042d2dd98c6e05711773badf6f1fd85c | refs/heads/master | 2016-08-11T17:59:38.504631 | 2005-01-25T23:17:11 | 2005-01-25T23:17:11 | 36,483,500 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | cpp | // Terrain.cpp: implementation of the Terrain class.
//
//////////////////////////////////////////////////////////////////////
#include "Terrain.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Terrain::Terrain()
{
xsize = 5.0f;
zsize = 5.0f;
xPos = 0.0;
zPos = 0.0;
extents = 28.0;
}
Terrain::~Terrain()
{
}
void Terrain::draw()
{
glTranslatef(-3.0f, 0.0f, -11.0f*zsize);
glRotatef(-45.0f, 0.0f, 1.0f, 0.0f);
glBindTexture(GL_TEXTURE_2D, terrainTex[0]);
for (int x = 0; x<13; x++)
{
glTranslatef(xsize, 0.0f, 0.0f);
for (int z = 0; z<13; z++)
{
glTranslatef(0.0f, 0.0f, zsize);
glBegin(GL_QUADS); // coordinates for the square
//glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(0.02f, 0.02f); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(.98f, 0.02f); glVertex3f(xsize, 0.0f, 0.0f);
glTexCoord2f(0.98f, 0.98f); glVertex3f(xsize, 0.0f, zsize);
glTexCoord2f(0.02f, 0.98f); glVertex3f(0.0f, 0.0f, zsize);
glEnd();
}
glTranslatef(0.0f, 0.0f, -13*zsize);
}
return;
}
void Terrain::setx(GLfloat x)
{
xsize = x;
return;
}
void Terrain::setz(GLfloat z)
{
zsize = z;
return;
} | [
"viperscum@84b32ba4-53c3-423c-be69-77cca6335494"
] | [
[
[
1,
65
]
]
] |
5f1cf0c626d25b08a20b08a8d7bc29a5221430f0 | 857b85d77dfcf9d82c445ad44fedf5c83b902b7c | /source/Source/EventHandler.cpp | 8401bd56ed1dca64c23a1c418a18aefab4ae3588 | [] | no_license | TheProjecter/nintendo-ds-homebrew-framework | 7ecf88ef5b02a0b1fddc8939011adde9eabf9430 | 8ab54265516e20b69fbcbb250677557d009091d9 | refs/heads/master | 2021-01-10T15:13:28.188530 | 2011-05-19T12:24:39 | 2011-05-19T12:24:39 | 43,224,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 617 | cpp | #include "EventHandler.h"
bool EventHandler::KeyPressed(int key)
{
if(m_pressed & key)
{
return true;
}
return false;
}
bool EventHandler::KeyHeld(int key)
{
if(m_held & key)
{
return true;
}
return false;
}
bool EventHandler::StylusDown()
{
if(m_held & KEY_TOUCH)
{
return true;
}
return false;
}
float EventHandler::GetStylusX()
{
return m_touchPos.px;
}
float EventHandler::GetStylusY()
{
return m_touchPos.py;
}
void EventHandler::Update()
{
scanKeys();
touchRead(&m_touchPos);
m_held = keysHeld();
m_pressed = keysDown();
}
| [
"[email protected]"
] | [
[
[
1,
52
]
]
] |
a2f0730103fc83d3026d46a661b088b6db78655b | 48113249b9c24b965a55cd8cef98d9a6edc0bb31 | /sidescroller/player.cpp | 7ff457aa497054760be096f9c7d228f6937dd589 | [] | no_license | janww/sidescroller | f2d6e16784be5585f16334119b35be28f8e79abb | caac450f92272b8b13710236cde73322a558755c | refs/heads/master | 2020-12-24T13:28:59.400165 | 2011-10-06T18:59:13 | 2011-10-06T18:59:13 | 2,528,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | cpp | #include "player.h"
player::player(SDL_Surface* img)
{
image = img;
box.x = 0;
box.y = 0;
box.w = 50;
box.h = 100;
xvel = 0;
yvel = 0;
ground = false;
for(int i=0; i < player::FRAMES; i++)
{
frames[i].x = baseclass::TILE_BORDER_SIZE + i * 50;
frames[i].y = 0;
frames[i].w = 50;
frames[i].h = 100;
}
}
player::~player()
{
SDL_FreeSurface(image);
}
SDL_Rect* player::getRect()
{
return &box;
}
int player::getXvel()
{
return xvel;
}
void player::setXvel(int vel)
{
xvel = vel;
}
void player::show(SDL_Surface* screen)
{
SDL_BlitSurface(image, &frames[0], screen, &box);
}
void player::move(const std::vector<std::vector<int>>&map)
{
int start = (baseclass::coord.x - (baseclass::coord.x % baseclass::TILE_SIZE)) / baseclass::TILE_SIZE;
int end = (baseclass::coord.x + baseclass::coord.w + (baseclass::TILE_SIZE - (baseclass::coord.x + baseclass::coord.w) % baseclass::TILE_SIZE)) / baseclass::TILE_SIZE;
if(start < 0)
start = 0;
if(end > map[0].size())
end = map[0].size();
bool nocollision = false;
for(int i = 0; i < map.size(); i++)
for(int j = start; j < end; j++)
{
if(map[i][j] == 0)
continue;
SDL_Rect destrect = {j * 50 - baseclass::coord.x, i * 50, 50, 50};
if(collision(&box, &destrect))
{
nocollision = true;
if(destrect.y >= box.y + box.h - 11)
{
ground = true;
yvel = 0;
} else if(destrect.y + destrect.h <= box.y + 11)
{
box.x++;
yvel = 5;
}
if(box.x + box.w >= destrect.x - 5 && box.y + box.h >= destrect.y + 6 && box.x + box.w <= destrect.x + 20)
{
xvel = 0;
box.x--;
} else if(box.x <= destrect.x + destrect.w && box.y + box.h >= destrect.y + 6)
{
xvel = 0;
box.x++;
}
}
}
if(!nocollision)
{
yvel = 5;
}
box.x += xvel;
box.y += yvel;
} | [
"[email protected]"
] | [
[
[
1,
99
]
]
] |
80e07b290c8adb5e804bf972156e3a631d7f5821 | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_core/files/juce_File.cpp | 598717e5aa8e80b3b572d399f29c342b1e9db738 | [] | no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,233 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#if ! JUCE_WINDOWS
#include <pwd.h>
#endif
BEGIN_JUCE_NAMESPACE
//==============================================================================
File::File (const String& fullPathName)
: fullPath (parseAbsolutePath (fullPathName))
{
}
File File::createFileWithoutCheckingPath (const String& path)
{
File f;
f.fullPath = path;
return f;
}
File::File (const File& other)
: fullPath (other.fullPath)
{
}
File& File::operator= (const String& newPath)
{
fullPath = parseAbsolutePath (newPath);
return *this;
}
File& File::operator= (const File& other)
{
fullPath = other.fullPath;
return *this;
}
#if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
File::File (File&& other) noexcept
: fullPath (static_cast <String&&> (other.fullPath))
{
}
File& File::operator= (File&& other) noexcept
{
fullPath = static_cast <String&&> (other.fullPath);
return *this;
}
#endif
const File File::nonexistent;
//==============================================================================
String File::parseAbsolutePath (const String& p)
{
if (p.isEmpty())
return String::empty;
#if JUCE_WINDOWS
// Windows..
String path (p.replaceCharacter ('/', '\\'));
if (path.startsWithChar (File::separator))
{
if (path[1] != File::separator)
{
/* When you supply a raw string to the File object constructor, it must be an absolute path.
If you're trying to parse a string that may be either a relative path or an absolute path,
you MUST provide a context against which the partial path can be evaluated - you can do
this by simply using File::getChildFile() instead of the File constructor. E.g. saying
"File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
path if that's what was supplied, or would evaluate a partial path relative to the CWD.
*/
jassertfalse;
path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
}
}
else if (! path.containsChar (':'))
{
/* When you supply a raw string to the File object constructor, it must be an absolute path.
If you're trying to parse a string that may be either a relative path or an absolute path,
you MUST provide a context against which the partial path can be evaluated - you can do
this by simply using File::getChildFile() instead of the File constructor. E.g. saying
"File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
path if that's what was supplied, or would evaluate a partial path relative to the CWD.
*/
jassertfalse;
return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
}
#else
// Mac or Linux..
// Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
// to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
// If that's why you've ended up here, use File::getChildFile() to build your paths instead.
jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));
String path (p);
if (path.startsWithChar ('~'))
{
if (path[1] == File::separator || path[1] == 0)
{
// expand a name of the form "~/abc"
path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
+ path.substring (1);
}
else
{
// expand a name of type "~dave/abc"
const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
struct passwd* const pw = getpwnam (userName.toUTF8());
if (pw != nullptr)
path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
}
}
else if (! path.startsWithChar (File::separator))
{
/* When you supply a raw string to the File object constructor, it must be an absolute path.
If you're trying to parse a string that may be either a relative path or an absolute path,
you MUST provide a context against which the partial path can be evaluated - you can do
this by simply using File::getChildFile() instead of the File constructor. E.g. saying
"File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
path if that's what was supplied, or would evaluate a partial path relative to the CWD.
*/
jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
}
#endif
while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
path = path.dropLastCharacters (1);
return path;
}
String File::addTrailingSeparator (const String& path)
{
return path.endsWithChar (File::separator) ? path
: path + File::separator;
}
//==============================================================================
#if JUCE_LINUX
#define NAMES_ARE_CASE_SENSITIVE 1
#endif
bool File::areFileNamesCaseSensitive()
{
#if NAMES_ARE_CASE_SENSITIVE
return true;
#else
return false;
#endif
}
bool File::operator== (const File& other) const
{
#if NAMES_ARE_CASE_SENSITIVE
return fullPath == other.fullPath;
#else
return fullPath.equalsIgnoreCase (other.fullPath);
#endif
}
bool File::operator!= (const File& other) const
{
return ! operator== (other);
}
bool File::operator< (const File& other) const
{
#if NAMES_ARE_CASE_SENSITIVE
return fullPath < other.fullPath;
#else
return fullPath.compareIgnoreCase (other.fullPath) < 0;
#endif
}
bool File::operator> (const File& other) const
{
#if NAMES_ARE_CASE_SENSITIVE
return fullPath > other.fullPath;
#else
return fullPath.compareIgnoreCase (other.fullPath) > 0;
#endif
}
//==============================================================================
bool File::setReadOnly (const bool shouldBeReadOnly,
const bool applyRecursively) const
{
bool worked = true;
if (applyRecursively && isDirectory())
{
Array <File> subFiles;
findChildFiles (subFiles, File::findFilesAndDirectories, false);
for (int i = subFiles.size(); --i >= 0;)
worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
}
return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
}
bool File::deleteRecursively() const
{
bool worked = true;
if (isDirectory())
{
Array<File> subFiles;
findChildFiles (subFiles, File::findFilesAndDirectories, false);
for (int i = subFiles.size(); --i >= 0;)
worked = subFiles.getReference(i).deleteRecursively() && worked;
}
return deleteFile() && worked;
}
bool File::moveFileTo (const File& newFile) const
{
if (newFile.fullPath == fullPath)
return true;
#if ! NAMES_ARE_CASE_SENSITIVE
if (*this != newFile)
#endif
if (! newFile.deleteFile())
return false;
return moveInternal (newFile);
}
bool File::copyFileTo (const File& newFile) const
{
return (*this == newFile)
|| (exists() && newFile.deleteFile() && copyInternal (newFile));
}
bool File::copyDirectoryTo (const File& newDirectory) const
{
if (isDirectory() && newDirectory.createDirectory())
{
Array<File> subFiles;
findChildFiles (subFiles, File::findFiles, false);
int i;
for (i = 0; i < subFiles.size(); ++i)
if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
return false;
subFiles.clear();
findChildFiles (subFiles, File::findDirectories, false);
for (i = 0; i < subFiles.size(); ++i)
if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
return false;
return true;
}
return false;
}
//==============================================================================
String File::getPathUpToLastSlash() const
{
const int lastSlash = fullPath.lastIndexOfChar (separator);
if (lastSlash > 0)
return fullPath.substring (0, lastSlash);
else if (lastSlash == 0)
return separatorString;
else
return fullPath;
}
File File::getParentDirectory() const
{
File f;
f.fullPath = getPathUpToLastSlash();
return f;
}
//==============================================================================
String File::getFileName() const
{
return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
}
int File::hashCode() const
{
return fullPath.hashCode();
}
int64 File::hashCode64() const
{
return fullPath.hashCode64();
}
String File::getFileNameWithoutExtension() const
{
const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
const int lastDot = fullPath.lastIndexOfChar ('.');
if (lastDot > lastSlash)
return fullPath.substring (lastSlash, lastDot);
else
return fullPath.substring (lastSlash);
}
bool File::isAChildOf (const File& potentialParent) const
{
if (potentialParent == File::nonexistent)
return false;
const String ourPath (getPathUpToLastSlash());
#if NAMES_ARE_CASE_SENSITIVE
if (potentialParent.fullPath == ourPath)
#else
if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
#endif
{
return true;
}
else if (potentialParent.fullPath.length() >= ourPath.length())
{
return false;
}
else
{
return getParentDirectory().isAChildOf (potentialParent);
}
}
//==============================================================================
bool File::isAbsolutePath (const String& path)
{
return path.startsWithChar (separator)
#if JUCE_WINDOWS
|| (path.isNotEmpty() && path[1] == ':');
#else
|| path.startsWithChar ('~');
#endif
}
File File::getChildFile (String relativePath) const
{
if (isAbsolutePath (relativePath))
return File (relativePath);
String path (fullPath);
// It's relative, so remove any ../ or ./ bits at the start..
if (relativePath[0] == '.')
{
#if JUCE_WINDOWS
relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
#else
relativePath = relativePath.trimStart();
#endif
while (relativePath[0] == '.')
{
if (relativePath[1] == '.')
{
if (relativePath [2] == 0 || relativePath[2] == separator)
{
const int lastSlash = path.lastIndexOfChar (separator);
if (lastSlash >= 0)
path = path.substring (0, lastSlash);
relativePath = relativePath.substring (3);
}
else
{
break;
}
}
else if (relativePath[1] == separator)
{
relativePath = relativePath.substring (2);
}
else
{
break;
}
}
}
return File (addTrailingSeparator (path) + relativePath);
}
File File::getSiblingFile (const String& fileName) const
{
return getParentDirectory().getChildFile (fileName);
}
//==============================================================================
String File::descriptionOfSizeInBytes (const int64 bytes)
{
if (bytes == 1) return "1 byte";
else if (bytes < 1024) return String (bytes) + " bytes";
else if (bytes < 1024 * 1024) return String (bytes / 1024.0, 1) + " KB";
else if (bytes < 1024 * 1024 * 1024) return String (bytes / (1024.0 * 1024.0), 1) + " MB";
else return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
}
//==============================================================================
Result File::create() const
{
if (exists())
return Result::ok();
const File parentDir (getParentDirectory());
if (parentDir == *this)
return Result::fail ("Cannot create parent directory");
Result r (parentDir.createDirectory());
if (r.wasOk())
{
FileOutputStream fo (*this, 8);
r = fo.getStatus();
}
return r;
}
Result File::createDirectory() const
{
if (isDirectory())
return Result::ok();
const File parentDir (getParentDirectory());
if (parentDir == *this)
return Result::fail ("Cannot create parent directory");
Result r (parentDir.createDirectory());
if (r.wasOk())
r = createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
return r;
}
//==============================================================================
Time File::getLastModificationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (m); }
Time File::getLastAccessTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (a); }
Time File::getCreationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (c); }
bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
//==============================================================================
bool File::loadFileAsData (MemoryBlock& destBlock) const
{
if (! existsAsFile())
return false;
FileInputStream in (*this);
return getSize() == in.readIntoMemoryBlock (destBlock);
}
String File::loadFileAsString() const
{
if (! existsAsFile())
return String::empty;
FileInputStream in (*this);
return in.readEntireStreamAsString();
}
void File::readLines (StringArray& destLines) const
{
destLines.addLines (loadFileAsString());
}
//==============================================================================
int File::findChildFiles (Array<File>& results,
const int whatToLookFor,
const bool searchRecursively,
const String& wildCardPattern) const
{
DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
int total = 0;
while (di.next())
{
results.add (di.getFile());
++total;
}
return total;
}
int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
{
DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
int total = 0;
while (di.next())
++total;
return total;
}
bool File::containsSubDirectories() const
{
if (isDirectory())
{
DirectoryIterator di (*this, false, "*", findDirectories);
return di.next();
}
return false;
}
//==============================================================================
File File::getNonexistentChildFile (const String& prefix_,
const String& suffix,
bool putNumbersInBrackets) const
{
File f (getChildFile (prefix_ + suffix));
if (f.exists())
{
int num = 2;
String prefix (prefix_);
// remove any bracketed numbers that may already be on the end..
if (prefix.trim().endsWithChar (')'))
{
putNumbersInBrackets = true;
const int openBracks = prefix.lastIndexOfChar ('(');
const int closeBracks = prefix.lastIndexOfChar (')');
if (openBracks > 0
&& closeBracks > openBracks
&& prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
{
num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
prefix = prefix.substring (0, openBracks);
}
}
// also use brackets if it ends in a digit.
putNumbersInBrackets = putNumbersInBrackets
|| CharacterFunctions::isDigit (prefix.getLastCharacter());
do
{
String newName (prefix);
if (putNumbersInBrackets)
newName << '(' << num++ << ')';
else
newName << num++;
f = getChildFile (newName + suffix);
} while (f.exists());
}
return f;
}
File File::getNonexistentSibling (const bool putNumbersInBrackets) const
{
if (exists())
return getParentDirectory()
.getNonexistentChildFile (getFileNameWithoutExtension(),
getFileExtension(),
putNumbersInBrackets);
return *this;
}
//==============================================================================
String File::getFileExtension() const
{
const int indexOfDot = fullPath.lastIndexOfChar ('.');
if (indexOfDot > fullPath.lastIndexOfChar (separator))
return fullPath.substring (indexOfDot);
return String::empty;
}
bool File::hasFileExtension (const String& possibleSuffix) const
{
if (possibleSuffix.isEmpty())
return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
const int semicolon = possibleSuffix.indexOfChar (0, ';');
if (semicolon >= 0)
{
return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
|| hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
}
else
{
if (fullPath.endsWithIgnoreCase (possibleSuffix))
{
if (possibleSuffix.startsWithChar ('.'))
return true;
const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
if (dotPos >= 0)
return fullPath [dotPos] == '.';
}
}
return false;
}
File File::withFileExtension (const String& newExtension) const
{
if (fullPath.isEmpty())
return File::nonexistent;
String filePart (getFileName());
int i = filePart.lastIndexOfChar ('.');
if (i >= 0)
filePart = filePart.substring (0, i);
if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
filePart << '.';
return getSiblingFile (filePart + newExtension);
}
//==============================================================================
bool File::startAsProcess (const String& parameters) const
{
return exists() && Process::openDocument (fullPath, parameters);
}
//==============================================================================
FileInputStream* File::createInputStream() const
{
if (existsAsFile())
return new FileInputStream (*this);
return nullptr;
}
FileOutputStream* File::createOutputStream (const int bufferSize) const
{
ScopedPointer<FileOutputStream> out (new FileOutputStream (*this, bufferSize));
return out->failedToOpen() ? nullptr
: out.release();
}
//==============================================================================
bool File::appendData (const void* const dataToAppend,
const int numberOfBytes) const
{
if (numberOfBytes <= 0)
return true;
FileOutputStream out (*this, 8192);
return out.openedOk() && out.write (dataToAppend, numberOfBytes);
}
bool File::replaceWithData (const void* const dataToWrite,
const int numberOfBytes) const
{
jassert (numberOfBytes >= 0); // a negative number of bytes??
if (numberOfBytes <= 0)
return deleteFile();
TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
tempFile.getFile().appendData (dataToWrite, numberOfBytes);
return tempFile.overwriteTargetFileWithTemporary();
}
bool File::appendText (const String& text,
const bool asUnicode,
const bool writeUnicodeHeaderBytes) const
{
FileOutputStream out (*this);
if (out.failedToOpen())
return false;
out.writeText (text, asUnicode, writeUnicodeHeaderBytes);
return true;
}
bool File::replaceWithText (const String& textToWrite,
const bool asUnicode,
const bool writeUnicodeHeaderBytes) const
{
TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
return tempFile.overwriteTargetFileWithTemporary();
}
bool File::hasIdenticalContentTo (const File& other) const
{
if (other == *this)
return true;
if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
{
FileInputStream in1 (*this), in2 (other);
const int bufferSize = 4096;
HeapBlock <char> buffer1 (bufferSize), buffer2 (bufferSize);
for (;;)
{
const int num1 = in1.read (buffer1, bufferSize);
const int num2 = in2.read (buffer2, bufferSize);
if (num1 != num2)
break;
if (num1 <= 0)
return true;
if (memcmp (buffer1, buffer2, (size_t) num1) != 0)
break;
}
}
return false;
}
//==============================================================================
String File::createLegalPathName (const String& original)
{
String s (original);
String start;
if (s[1] == ':')
{
start = s.substring (0, 2);
s = s.substring (2);
}
return start + s.removeCharacters ("\"#@,;:<>*^|?")
.substring (0, 1024);
}
String File::createLegalFileName (const String& original)
{
String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
const int maxLength = 128; // only the length of the filename, not the whole path
const int len = s.length();
if (len > maxLength)
{
const int lastDot = s.lastIndexOfChar ('.');
if (lastDot > jmax (0, len - 12))
{
s = s.substring (0, maxLength - (len - lastDot))
+ s.substring (lastDot);
}
else
{
s = s.substring (0, maxLength);
}
}
return s;
}
//==============================================================================
String File::getRelativePathFrom (const File& dir) const
{
String thisPath (fullPath);
while (thisPath.endsWithChar (separator))
thisPath = thisPath.dropLastCharacters (1);
String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
: dir.fullPath));
const int len = jmin (thisPath.length(), dirPath.length());
int commonBitLength = 0;
{
String::CharPointerType thisPathIter (thisPath.getCharPointer());
String::CharPointerType dirPathIter (dirPath.getCharPointer());
for (int i = 0; i < len; ++i)
{
const juce_wchar c1 = thisPathIter.getAndAdvance();
const juce_wchar c2 = dirPathIter.getAndAdvance();
#if NAMES_ARE_CASE_SENSITIVE
if (c1 != c2)
#else
if (c1 != c2 && CharacterFunctions::toLowerCase (c1) != CharacterFunctions::toLowerCase (c2))
#endif
break;
++commonBitLength;
}
}
while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
--commonBitLength;
// if the only common bit is the root, then just return the full path..
if (commonBitLength <= 0
|| (commonBitLength == 1 && thisPath [1] == File::separator))
return fullPath;
thisPath = thisPath.substring (commonBitLength);
dirPath = dirPath.substring (commonBitLength);
while (dirPath.isNotEmpty())
{
#if JUCE_WINDOWS
thisPath = "..\\" + thisPath;
#else
thisPath = "../" + thisPath;
#endif
const int sep = dirPath.indexOfChar (separator);
if (sep >= 0)
dirPath = dirPath.substring (sep + 1);
else
dirPath = String::empty;
}
return thisPath;
}
//==============================================================================
File File::createTempFile (const String& fileNameEnding)
{
const File tempFile (getSpecialLocation (tempDirectory)
.getChildFile ("temp_" + String::toHexString (Random::getSystemRandom().nextInt()))
.withFileExtension (fileNameEnding));
if (tempFile.exists())
return createTempFile (fileNameEnding);
return tempFile;
}
//==============================================================================
#if JUCE_UNIT_TESTS
class FileTests : public UnitTest
{
public:
FileTests() : UnitTest ("Files") {}
void runTest()
{
beginTest ("Reading");
const File home (File::getSpecialLocation (File::userHomeDirectory));
const File temp (File::getSpecialLocation (File::tempDirectory));
expect (! File::nonexistent.exists());
expect (home.isDirectory());
expect (home.exists());
expect (! home.existsAsFile());
expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
expect (File::getSpecialLocation (File::currentExecutableFile).exists());
expect (File::getSpecialLocation (File::currentApplicationFile).exists());
expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
expect (home.getVolumeTotalSize() > 1024 * 1024);
expect (home.getBytesFreeOnVolume() > 0);
expect (! home.isHidden());
expect (home.isOnHardDisk());
expect (! home.isOnCDRomDrive());
expect (File::getCurrentWorkingDirectory().exists());
expect (home.setAsCurrentWorkingDirectory());
expect (File::getCurrentWorkingDirectory() == home);
{
Array<File> roots;
File::findFileSystemRoots (roots);
expect (roots.size() > 0);
int numRootsExisting = 0;
for (int i = 0; i < roots.size(); ++i)
if (roots[i].exists())
++numRootsExisting;
// (on windows, some of the drives may not contain media, so as long as at least one is ok..)
expect (numRootsExisting > 0);
}
beginTest ("Writing");
File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
expect (demoFolder.deleteRecursively());
expect (demoFolder.createDirectory());
expect (demoFolder.isDirectory());
expect (demoFolder.getParentDirectory() == temp);
expect (temp.isDirectory());
{
Array<File> files;
temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
expect (files.contains (demoFolder));
}
{
Array<File> files;
temp.findChildFiles (files, File::findDirectories, true, "*.folder");
expect (files.contains (demoFolder));
}
File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
expect (tempFile.getFileExtension() == ".txt");
expect (tempFile.hasFileExtension (".txt"));
expect (tempFile.hasFileExtension ("txt"));
expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
expect (tempFile.withFileExtension ("xyz").hasFileExtension ("abc;xyz;foo"));
expect (tempFile.withFileExtension ("xyz").hasFileExtension ("xyz;foo"));
expect (! tempFile.withFileExtension ("h").hasFileExtension ("bar;foo;xx"));
expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
expect (tempFile.hasWriteAccess());
{
FileOutputStream fo (tempFile);
fo.write ("0123456789", 10);
}
expect (tempFile.exists());
expect (tempFile.getSize() == 10);
expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
expectEquals (tempFile.loadFileAsString(), String ("0123456789"));
expect (! demoFolder.containsSubDirectories());
expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
expect (demoFolder.containsSubDirectories());
expect (tempFile.hasWriteAccess());
tempFile.setReadOnly (true);
expect (! tempFile.hasWriteAccess());
tempFile.setReadOnly (false);
expect (tempFile.hasWriteAccess());
Time t (Time::getCurrentTime());
tempFile.setLastModificationTime (t);
Time t2 = tempFile.getLastModificationTime();
expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
{
MemoryBlock mb;
tempFile.loadFileAsData (mb);
expect (mb.getSize() == 10);
expect (mb[0] == '0');
}
{
expect (tempFile.getSize() == 10);
FileOutputStream fo (tempFile);
expect (fo.openedOk());
expect (fo.setPosition (7));
expect (fo.truncate().wasOk());
expect (tempFile.getSize() == 7);
fo.write ("789", 3);
fo.flush();
expect (tempFile.getSize() == 10);
}
beginTest ("Memory-mapped files");
{
MemoryMappedFile mmf (tempFile, MemoryMappedFile::readOnly);
expect (mmf.getSize() == 10);
expect (mmf.getData() != nullptr);
expect (memcmp (mmf.getData(), "0123456789", 10) == 0);
}
{
const File tempFile2 (tempFile.getNonexistentSibling (false));
expect (tempFile2.create());
expect (tempFile2.appendData ("xxxxxxxxxx", 10));
{
MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
expect (mmf.getSize() == 10);
expect (mmf.getData() != nullptr);
memcpy (mmf.getData(), "abcdefghij", 10);
}
{
MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
expect (mmf.getSize() == 10);
expect (mmf.getData() != nullptr);
expect (memcmp (mmf.getData(), "abcdefghij", 10) == 0);
}
expect (tempFile2.deleteFile());
}
beginTest ("More writing");
expect (tempFile.appendData ("abcdefghij", 10));
expect (tempFile.getSize() == 20);
expect (tempFile.replaceWithData ("abcdefghij", 10));
expect (tempFile.getSize() == 10);
File tempFile2 (tempFile.getNonexistentSibling (false));
expect (tempFile.copyFileTo (tempFile2));
expect (tempFile2.exists());
expect (tempFile2.hasIdenticalContentTo (tempFile));
expect (tempFile.deleteFile());
expect (! tempFile.exists());
expect (tempFile2.moveFileTo (tempFile));
expect (tempFile.exists());
expect (! tempFile2.exists());
expect (demoFolder.deleteRecursively());
expect (! demoFolder.exists());
}
};
static FileTests fileUnitTests;
#endif
END_JUCE_NAMESPACE
| [
"ow3nskip"
] | [
[
[
1,
1082
]
]
] |
d3b7763565894dd5e705cf6a4c5a08484289823f | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/v0-1/engine/core/include/Animation.h | a362bb66a02a00187d20f6debe0cce1ad675a2c3 | [
"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 | ISO-8859-1 | C++ | false | false | 7,145 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 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.
*/
#ifndef __rlAnimation_H__
#define __rlAnimation_H__
#include "CorePrerequisites.h"
#include <set>
#include <map>
#include "AnimationListener.h"
namespace rl {
class MeshObject;
/**
Diese Klasse ermöglicht eine einfache Steuerung von Animationseinstellungen
und ist die Basisklasse erweiterter Animationen.
@remarks Instanzen werden über den AnimationManager erzeugt
@see AnimationManager
*/
class _RlCoreExport Animation : public virtual EventSource
{
public:
/** Der Basiskonstruktor, für MeshObject, die einen AnimationState mitbringen
@param animState AnimationState, intern
@param speed Geschwindigkeit, auch negativ
@param timesToPlay Abspielanzahl, 0 = unendlich
@mesh mesh The MeshObjekt whose Animation is played
@remarks Die Animation beginnt sofort zu spielen, bei negativer
Geschwindigkeit beginnt sie mit dem letzten Frame. Konstruktor
sollte nicht direkt aufgerufen werden, sondern vom AnimationManager.
*/
Animation(Ogre::AnimationState* animState, MeshObject* mesh, Ogre::Real speed=1.0,
unsigned int timesToPlay=0);
/** Ein Konstruktor, für eine später festlegbare Animation
@remarks Dieser Konstruktor ist für Unterklassen. Konstruktor
sollte nicht direkt aufgerufen werden, sondern vom AnimationManager.
*/
Animation();
/// Virtueller Destruktor
virtual ~Animation( );
/// Gibt zurück ob die Animation pausiert ist
bool isPaused() const;
/** Pausieren/Fortsetzen der Animation
@param isPaused Zukünftiger Status
@remarks Löst einen AnimationPaused/Unpaused Event aus
*/
void setPaused( bool isPaused );
/// Gibt zurück ob die globale Beschleunigung ignoriert wird
bool isIgnoringGlobalSpeed() const;
/** Setzt die Ignoranz
@param isIgnoringGlobalSpeed Die zukünftige Ignoranz der globalen Geschwindigkeit
@remarks Möglichkeit die globale SlowMotion zu umgehen
Nützlich für Statusanzeigen, oder ähnliche konstante Animationen
@todo TODO Eventuell das ganze auf Flags erweitern
*/
void setIgnoringGlobalSpeed( bool isIgnoringGlobalSpeed );
/// Gibt die aktuelle Geschwindigkeit zurück
Ogre::Real getSpeed() const;
/** Setzt die aktuelle Geschwindigkeit der Animation
@param speed die Geschwindigkeit
@remarks 1.0 ist die normale Geschwindigkeit der Animation
(mLength in Sekunden), negative Werte spielen die
Animation rückwärts ab. Bei 0 herrscht Stillstand.
*/
void setSpeed( Ogre::Real speed );
/// Negiert die aktuelle Geschwindigkeit
void reverseAnimation();
/** Setzt die maximalen Wiederholungszahl der Animation
@param timesToPlay Die nicht negative Anzahl der Wiederholungen
@remarks Bei 0 wird die Animation beliebig oft wiederholt
*/
void setTimesToPlay(unsigned int timesToPlay);
/// Gibt die Anzahl der bereits vollständig abgespielten Wiederholungen zurück
unsigned int getTimesPlayed() const;
/** Setzt die Abspielzeit zurück
Löst dabei auch eine mögliche Pause auf, und spult die Animation zurück
*/
void resetTimesPlayed();
/// Gibt zurück wieviel Wiederholungen insgesamt abzuspielen sind
unsigned int getTimesToPlay() const;
/// Gibt zurück wieviele Wiederholungen noch durchzuführen sind
unsigned int getTimesToPlayLeft() const;
/// Gibt die Abspieldauer zurück (intern)
Ogre::Real getTimePlayed() const;
/// Gibt das Gewicht der Animation zurück
Ogre::Real getWeight(void) const;
/** Setzt das Gewicht (Einfluss) der Animation
@param weigt Das Gewicht der Animation
*/
void setWeight( Ogre::Real weight );
/// Gibt das MeshObject
MeshObject* getMeshObject();
/// Zeit hinzufügen - wird vom AnimationManager aufgerufen
void addTime( Ogre::Real timePassed );
/** Fügt einen AnimationListener hinzu
@param listener Der hinzuzufügende Listener
@remarks Der Listener wird benachrichtigt, wenn
* die Animation pausiert/fortgesetzt wird
* die Animation ihr gesamten Wiederholungen vollendet hat
*/
void addAnimationListener( AnimationListener *listener);
/// Entfernt einen AnimationListener
void removeAnimationListener( AnimationListener *listener);
/// Gibt den erstbesten Listener wieder (nur ne Testmethode)
AnimationListener* getAnimationListener( );
/** Fügt einen AnimationFrameListener hinzu
@param listener Der hinzuzufügende Listener
@param frameNumber Die zu überwachende Zeitindex
@remarks Der Listener wird benachrichtigt, wenn der Zeitindex erreicht oder
übersprungen wird. Dabei wird, falls der Fortschritt größer als die
Länge der Animation korrekt geprüft, so dass keine Events verloren
gehen
*/
void addAnimationFrameListener( AnimationFrameListener *listener, Ogre::Real frameNumber );
/// Entfernt einen AnimationListener an allen Zeitindizes
void removeAnimationFrameListener( AnimationFrameListener *listener );
/// Entfernt einen AnimationListener an einem bestimmtem Zeitindex
void removeAnimationFrameListener( AnimationFrameListener *listener, Ogre::Real frameNumber );
/// Gibt den AnimationState zurück (intern)
Ogre::AnimationState* getAnimationState() const { return mAnimState; };
protected:
/// Der AnimationState
Ogre::AnimationState* mAnimState;
/// Das MeshObject
MeshObject* mMeshObject;
/// Pause
bool mPaused;
/// Ignoriert die globale Geschwindigkeit
bool mIgnoringGlobalSpeed;
/// Eigene Geschwindigkeit
Ogre::Real mSpeed;
/// Gesamte Abspielwiederholungen
unsigned int mTimesToPlay;
/// Bisherige Abspielzeit
Ogre::Real mTimePlayed;
/// Setzt den AnimationState
void setAnimationState( Ogre::AnimationState* animState );
/// EventCaster
EventCaster<AnimationEvent> mAnimationCaster;
typedef std::multimap<Ogre::Real,AnimationFrameListener*>
AnimationFrameListenerMap;
/// Die Multimap mit den FrameNummern und den dazugehörigen Listenern
AnimationFrameListenerMap mAnimationFrameListener;
private:
/// Überwacht das erreichen der einzelnen Frames für die Listener
void checkAnimationFrameListeners( Ogre::Real timePassed );
void removeAllListeners();
};
}
#endif
| [
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
184
]
]
] |
4a05de4be9ed81c1c3e8916585caeb607e32abc4 | 2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83 | /BasicOgreFramework/PhysxSDK/Samples/SampleCommonCode/src/DebugRenderer.cpp | d3f7ef7fdcea7eb8e1bc693607e82584f2a8c2c2 | [] | no_license | mgq812/simengines-g2-code | 5908d397ef2186e1988b1d14fa8b73f4674f96ea | 699cb29145742c1768857945dc59ef283810d511 | refs/heads/master | 2016-09-01T22:57:54.845817 | 2010-01-11T19:26:51 | 2010-01-11T19:26:51 | 32,267,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,161 | cpp |
#include "DebugRenderer.h"
#include "NxDebugRenderable.h"
#include <GL/glut.h>
void DebugRenderer::renderBuffer(float* pVertList, float* pColorList, int type, int num)
{
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3,GL_FLOAT, 0, pVertList);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, 0, pColorList);
glDrawArrays(type, 0, num);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
void DebugRenderer::renderData(const NxDebugRenderable& data) const
{
#ifndef __CELLOS_LV2__
glPushAttrib(GL_ALL_ATTRIB_BITS);
#endif
glLineWidth(1.0f);
glColor4f(0.7f,0.7f,0.7f,1.0f);
glDisable(GL_LIGHTING);
unsigned int NbPoints = data.getNbPoints();
if(NbPoints)
{
float* pVertList = new float[NbPoints*3];
float* pColorList = new float[NbPoints*4];
int vertIndex = 0;
int colorIndex = 0;
const NxDebugPoint* Points = data.getPoints();
while(NbPoints--)
{
pVertList[vertIndex++] = Points->p.x;
pVertList[vertIndex++] = Points->p.y;
pVertList[vertIndex++] = Points->p.z;
pColorList[colorIndex++] = (float)((Points->color>>16)&0xff)/255.0f;
pColorList[colorIndex++] = (float)((Points->color>>8)&0xff)/255.0f;
pColorList[colorIndex++] = (float)(Points->color&0xff)/255.0f;
pColorList[colorIndex++] = 1.0f;
Points++;
}
renderBuffer(pVertList, pColorList, GL_POINTS, data.getNbPoints());
delete[] pVertList;
delete[] pColorList;
}
unsigned int NbLines = data.getNbLines();
if(NbLines)
{
float* pVertList = new float[NbLines*3*2];
float* pColorList = new float[NbLines*4*2];
int vertIndex = 0;
int colorIndex = 0;
const NxDebugLine* Lines = data.getLines();
while(NbLines--)
{
pVertList[vertIndex++] = Lines->p0.x;
pVertList[vertIndex++] = Lines->p0.y;
pVertList[vertIndex++] = Lines->p0.z;
pColorList[colorIndex++] = (float)((Lines->color>>16)&0xff)/255.0f;
pColorList[colorIndex++] = (float)((Lines->color>>8)&0xff)/255.0f;
pColorList[colorIndex++] = (float)(Lines->color&0xff)/255.0f;
pColorList[colorIndex++] = 1.0f;
pVertList[vertIndex++] = Lines->p1.x;
pVertList[vertIndex++] = Lines->p1.y;
pVertList[vertIndex++] = Lines->p1.z;
pColorList[colorIndex++] = (float)((Lines->color>>16)&0xff)/255.0f;
pColorList[colorIndex++] = (float)((Lines->color>>8)&0xff)/255.0f;
pColorList[colorIndex++] = (float)(Lines->color&0xff)/255.0f;
pColorList[colorIndex++] = 1.0f;
Lines++;
}
renderBuffer(pVertList, pColorList, GL_LINES, data.getNbLines()*2);
delete[] pVertList;
delete[] pColorList;
}
unsigned int NbTris = data.getNbTriangles();
if(NbTris)
{
float* pVertList = new float[NbTris*3*3];
float* pColorList = new float[NbTris*4*3];
int vertIndex = 0;
int colorIndex = 0;
const NxDebugTriangle* Triangles = data.getTriangles();
while(NbTris--)
{
pVertList[vertIndex++] = Triangles->p0.x;
pVertList[vertIndex++] = Triangles->p0.y;
pVertList[vertIndex++] = Triangles->p0.z;
pVertList[vertIndex++] = Triangles->p1.x;
pVertList[vertIndex++] = Triangles->p1.y;
pVertList[vertIndex++] = Triangles->p1.z;
pVertList[vertIndex++] = Triangles->p2.x;
pVertList[vertIndex++] = Triangles->p2.y;
pVertList[vertIndex++] = Triangles->p2.z;
for(int i=0;i<3;i++)
{
pColorList[colorIndex++] = (float)((Triangles->color>>16)&0xff)/255.0f;
pColorList[colorIndex++] = (float)((Triangles->color>>8)&0xff)/255.0f;
pColorList[colorIndex++] = (float)(Triangles->color&0xff)/255.0f;
pColorList[colorIndex++] = 1.0f;
}
Triangles++;
}
renderBuffer(pVertList, pColorList, GL_TRIANGLES, data.getNbTriangles()*3);
delete[] pVertList;
delete[] pColorList;
}
#ifndef __CELLOS_LV2__
glPopAttrib();
#endif
}
| [
"erucarno@789472dc-e1c3-11de-81d3-db62269da9c1"
] | [
[
[
1,
133
]
]
] |
0534cf6a3b0bf2ac6067fc7db747b4ee447d6a1b | 14e30c5f520f0ed28117914101d9bdf2f3d5dac7 | /project/source/game/states/game_state_manager.cpp | 9e0a68dabd2468f26e23d20bc4c50a1a06f31a59 | [] | no_license | danielePiracci/arlight | f356eb5a162d0cd62a759720cbc6da41a820642f | 15a68c4c80c97f2fe7458e7ddf03f3e1063e25a4 | refs/heads/master | 2016-08-11T13:45:35.252916 | 2011-01-24T20:22:50 | 2011-01-24T20:22:50 | 44,962,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,110 | cpp | /// \file game/states/game_state_manager.cpp
/// \author Juan Carlos De Abreu ([email protected])
/// \date 2010/02/06
/// \version 1.0
///
/// \brief This file implements the DissertationProject::States::GameStateManager
/// class, declared at game/states/game_manager.h.
#include "game/states/game_state_manager.h"
BEGIN_PROJECT_NAMESPACE();
BEGIN_NAMESPACE(States);
GameStateManager::GameStateManager() {
// Load all the default game states.
Initialize();
}
GameStateManager::~GameStateManager() {
// Release all the game states resources.
Release();
}
void GameStateManager::Initialize() {
// Register all the default game states.
}
void GameStateManager::Release() {
// Release all the states stacked.
while (!states_.empty()) states_.pop();
// Iterate over all the registered states and release it's resources.
std::map<GameState::StateId, GameState*>::iterator it = game_states_.begin();
std::map<GameState::StateId, GameState*>::iterator end = game_states_.end();
for (; it != end; ++it) UnregisterState(it->first);
game_states_.clear();
}
void GameStateManager::RegisterState(GameState* game_state, GameState::StateId state) {
// Add the state to game state manager map.
game_states_[state] = game_state;
game_state->Initialize();
}
void GameStateManager::UnregisterState(GameState::StateId state) {
// Remove the state from the game state manager map.
if (game_states_[state]) delete game_states_[state];
game_states_[state] = NULL;
}
void GameStateManager::ChangeState(GameState::StateId state) {
// Check if a current game state exist and if so removed.
if (!states_.empty()) {
game_states_[states_.top()]->Exit();
states_.pop();
}
// Add the new game state.
states_.push(state);
game_states_[state]->Enter();
}
void GameStateManager::PushState(GameState::StateId state) {
// Check if a current game state exist and if so pause it's execution.
if (!states_.empty())
game_states_[states_.top()]->Pause();
// Add the new game state.
states_.push(state);
game_states_[state]->Enter();
}
void GameStateManager::PopState() {
// Check if a current game state exist and if so finish it's execution.
if (!states_.empty()) {
game_states_[states_.top()]->Exit();
states_.pop();
}
// Restore the previous game state execution.
if (!states_.empty())
game_states_[states_.top()]->Resume();
}
void GameStateManager::Update(Game& game) {
// Check if a current game state exist and if so update it.
if (!states_.empty())
game_states_[states_.top()]->Update(game);
}
void GameStateManager::Render(Game& game) {
// Check fi a current game state exist and if so render it.
if (!states_.empty())
game_states_[states_.top()]->Render(game);
}
void GameStateManager::HandleEvents(Game& game) {
// Check if a current game state exist and if so handle the event.
if (!states_.empty())
game_states_[states_.top()]->HandleEvents(game);
}
END_NAMESPACE(States);
END_PROJECT_NAMESPACE();
| [
"jcabreur@db05138c-34b8-7cfb-67b9-2db12d2e1ab0"
] | [
[
[
1,
103
]
]
] |
21f7b9e043ea7e9b1fb4dfbf5aa59712a672ea4f | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/pcsx2/x86/microVU_Clamp.inl | 6d6675fbe1285b8dc8d28abcdf8595eaaf0579c6 | [] | no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,482 | inl | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
//------------------------------------------------------------------
// Micro VU - Clamp Functions
//------------------------------------------------------------------
const __aligned16 u32 sse4_minvals[2][4] = {
{ 0xff7fffff, 0xffffffff, 0xffffffff, 0xffffffff }, //1000
{ 0xff7fffff, 0xff7fffff, 0xff7fffff, 0xff7fffff }, //1111
};
const __aligned16 u32 sse4_maxvals[2][4] = {
{ 0x7f7fffff, 0x7fffffff, 0x7fffffff, 0x7fffffff }, //1000
{ 0x7f7fffff, 0x7f7fffff, 0x7f7fffff, 0x7f7fffff }, //1111
};
// Used for Result Clamping
// Note: This function will not preserve NaN values' sign.
// The theory behind this is that when we compute a result, and we've
// gotten a NaN value, then something went wrong; and the NaN's sign
// is not to be trusted. Games like positive values better usually,
// and its faster... so just always make NaNs into positive infinity.
void mVUclamp1(const xmm& reg, const xmm& regT1, int xyzw, bool bClampE = 0) {
if ((!clampE && CHECK_VU_OVERFLOW) || (clampE && bClampE)) {
switch (xyzw) {
case 1: case 2: case 4: case 8:
xMIN.SS(reg, ptr32[mVUglob.maxvals]);
xMAX.SS(reg, ptr32[mVUglob.minvals]);
break;
default:
xMIN.PS(reg, ptr32[mVUglob.maxvals]);
xMAX.PS(reg, ptr32[mVUglob.minvals]);
break;
}
}
}
// Used for Operand Clamping
// Note 1: If 'preserve sign' mode is on, it will preserve the sign of NaN values.
// Note 2: Using regalloc here seems to contaminate some regs in certain games.
// Must be some specific case I've overlooked (or I used regalloc improperly on an opcode)
// so we just use a temporary mem location for our backup for now... (non-sse4 version only)
void mVUclamp2(microVU* mVU, const xmm& reg, const xmm& regT1in, int xyzw, bool bClampE = 0) {
if ((!clampE && CHECK_VU_SIGN_OVERFLOW) || (clampE && bClampE && CHECK_VU_SIGN_OVERFLOW)) {
if (x86caps.hasStreamingSIMD4Extensions) {
int i = (xyzw==1||xyzw==2||xyzw==4||xyzw==8) ? 0: 1;
xPMIN.SD(reg, ptr128[&sse4_maxvals[i][0]]);
xPMIN.UD(reg, ptr128[&sse4_minvals[i][0]]);
return;
}
//const xmm& regT1 = regT1b ? mVU->regAlloc->allocReg() : regT1in;
const xmm& regT1 = regT1in.IsEmpty() ? xmm((reg.Id + 1) % 8) : regT1in;
if (regT1 != regT1in) xMOVAPS(ptr128[mVU->xmmCTemp], regT1);
switch (xyzw) {
case 1: case 2: case 4: case 8:
xMOVAPS(regT1, reg);
xAND.PS(regT1, ptr128[mVUglob.signbit]);
xMIN.SS(reg, ptr128[mVUglob.maxvals]);
xMAX.SS(reg, ptr128[mVUglob.minvals]);
xOR.PS (reg, regT1);
break;
default:
xMOVAPS(regT1, reg);
xAND.PS(regT1, ptr128[mVUglob.signbit]);
xMIN.PS(reg, ptr128[mVUglob.maxvals]);
xMAX.PS(reg, ptr128[mVUglob.minvals]);
xOR.PS (reg, regT1);
break;
}
//if (regT1 != regT1in) mVU->regAlloc->clearNeeded(regT1);
if (regT1 != regT1in) xMOVAPS(regT1, ptr128[mVU->xmmCTemp]);
}
else mVUclamp1(reg, regT1in, xyzw, bClampE);
}
// Used for operand clamping on every SSE instruction (add/sub/mul/div)
void mVUclamp3(microVU* mVU, const xmm& reg, const xmm& regT1, int xyzw) {
if (clampE) mVUclamp2(mVU, reg, regT1, xyzw, 1);
}
// Used for result clamping on every SSE instruction (add/sub/mul/div)
// Note: Disabled in "preserve sign" mode because in certain cases it
// makes too much code-gen, and you get jump8-overflows in certain
// emulated opcodes (causing crashes). Since we're clamping the operands
// with mVUclamp3, we should almost never be getting a NaN result,
// but this clamp is just a precaution just-in-case.
void mVUclamp4(const xmm& reg, const xmm& regT1, int xyzw) {
if (clampE && !CHECK_VU_SIGN_OVERFLOW) mVUclamp1(reg, regT1, xyzw, 1);
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
] | [
[
[
1,
103
]
]
] |
61c77fe0cbe57b18ab9ba8a569c9905f07c9df19 | 4d01363b089917facfef766868fb2b1a853605c7 | /src/Graphics/WindowInitializer.h | fca9bc852968d79928bd44ad1f62d42be79b5b8b | [] | no_license | FardMan69420/aimbot-57 | 2bc7075e2f24dc35b224fcfb5623083edcd0c52b | 3f2b86a1f86e5a6da0605461e7ad81be2a91c49c | refs/heads/master | 2022-03-20T07:18:53.690175 | 2009-07-21T22:45:12 | 2009-07-21T22:45:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 639 | h | #ifndef windowinitializer_h
#define windowinitializer_h
#include "Glut/GraphicIncludes.h"
#include "Glut/GlutDisplay.h"
#include "../Game/GameCoordinator.h"
class WindowInitializer
{
private:
public:
WindowInitializer(int n, char** argv)
{
initializeWindow(n, argv);
GameCoordinator* coordinator = new GameCoordinator();
coordinator->initialize();
glutMainLoop();
}
~WindowInitializer()
{
}
void initializeWindow(int n, char** argv)
{
glutInit(&n, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutCreateWindow(argv[0]);
glutFullScreen();
}
};
#endif
| [
"daven.hughes@92c3b6dc-493d-11de-82d9-516ade3e46db"
] | [
[
[
1,
36
]
]
] |
50e5934be6daa15309402f1985539e7cb1a7326c | 4d58047280e0e4ef2f260d13e89136ff3a32c2cc | /utilities/PhoneSpell/trunk/PhoneSpell-C++/PhoneSpell.cpp | 85c3213ef9a078383409fe421368561f49aa851c | [] | no_license | BackupTheBerlios/dzchart-svn | 6a9a3185cd630074e2144d4cfbe4e8ab4cc09b11 | c86b3300cd16cf74ceb533e792a0e3034eb90a5a | refs/heads/master | 2020-12-24T13:20:18.535356 | 2011-11-27T18:54:47 | 2011-11-27T18:54:47 | 40,673,394 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 833 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
//---------------------------------------------------------------------------
USEFORM("w_PhoneSpell.cpp", f_PhoneSpell);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Application->CreateForm(__classid(Tf_PhoneSpell), &f_PhoneSpell);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
return 0;
}
//---------------------------------------------------------------------------
| [
"twm@ef4fdce5-35f3-0310-a5ee-fc8da0176504"
] | [
[
[
1,
33
]
]
] |
54436a3173c0315f780d8203d35c8ef91ee1a47c | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/dmc/dlls/gamerules.cpp | e950e11ba949dcff8e31fc87c460a28bebc952c7 | [] | no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,520 | cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
//=========================================================
// GameRules.cpp
//=========================================================
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "player.h"
#include "weapons.h"
#include "gamerules.h"
#include "teamplay_gamerules.h"
extern Vector g_vecTeleMins[ MAX_TELES ];
extern Vector g_vecTeleMaxs[ MAX_TELES ];
extern int g_iTeleNum;
#include "skill.h"
extern edict_t *EntSelectSpawnPoint( CBaseEntity *pPlayer );
DLL_GLOBAL CGameRules* g_pGameRules = NULL;
extern DLL_GLOBAL BOOL g_fGameOver;
extern int gmsgDeathMsg; // client dll messages
extern int gmsgScoreInfo;
extern int gmsgMOTD;
//=========================================================
//=========================================================
BOOL CGameRules::CanHaveAmmo( CBasePlayer *pPlayer, const char *pszAmmoName, int iMaxCarry )
{
int iAmmoIndex;
if ( pszAmmoName )
{
iAmmoIndex = pPlayer->GetAmmoIndex( pszAmmoName );
if ( iAmmoIndex > -1 )
{
if ( pPlayer->AmmoInventory( iAmmoIndex ) < iMaxCarry )
{
// player has room for more of this type of ammo
return TRUE;
}
}
}
return FALSE;
}
//=========================================================
//=========================================================
edict_t *CGameRules :: GetPlayerSpawnSpot( CBasePlayer *pPlayer )
{
edict_t *pentSpawnSpot = EntSelectSpawnPoint( pPlayer );
pPlayer->pev->origin = VARS(pentSpawnSpot)->origin + Vector(0,0,1);
pPlayer->pev->v_angle = g_vecZero;
pPlayer->pev->velocity = g_vecZero;
pPlayer->pev->angles = VARS(pentSpawnSpot)->angles;
pPlayer->pev->punchangle = g_vecZero;
pPlayer->pev->fixangle = TRUE;
return pentSpawnSpot;
}
//=========================================================
//=========================================================
BOOL CGameRules::CanHavePlayerItem( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon )
{
if ( pWeapon->pszAmmo1() )
{
if ( !CanHaveAmmo( pPlayer, pWeapon->pszAmmo1(), pWeapon->iMaxAmmo1() ) )
{
// we can't carry anymore ammo for this gun. We can only
// have the gun if we aren't already carrying one of this type
if ( pPlayer->HasPlayerItem( pWeapon ) )
{
return FALSE;
}
}
}
else
{
// weapon doesn't use ammo, don't take another if you already have it.
if ( pPlayer->HasPlayerItem( pWeapon ) )
{
return FALSE;
}
}
// note: will fall through to here if GetItemInfo doesn't fill the struct!
return TRUE;
}
//=========================================================
// load the SkillData struct with the proper values based on the skill level.
//=========================================================
void CGameRules::RefreshSkillData ( void )
{
int iSkill;
iSkill = (int)CVAR_GET_FLOAT("skill");
if ( iSkill < 1 )
{
iSkill = 1;
}
else if ( iSkill > 3 )
{
iSkill = 3;
}
gSkillData.iSkillLevel = iSkill;
}
//=========================================================
// instantiate the proper game rules object
//=========================================================
CGameRules *InstallGameRules( void )
{
SERVER_COMMAND( "exec game.cfg\n" );
SERVER_EXECUTE( );
//Clear all the teleporters
for ( int i = 0; i < MAX_TELES; i++ )
{
g_vecTeleMins[ i ].x = 0.0;
g_vecTeleMins[ i ].y = 0.0;
g_vecTeleMins[ i ].z = 0.0;
g_vecTeleMaxs[ i ].x = 0.0;
g_vecTeleMaxs[ i ].y = 0.0;
g_vecTeleMaxs[ i ].z = 0.0;
}
g_iTeleNum = 0;
if ( !gpGlobals->deathmatch )
{
// generic half-life
return new CHalfLifeRules;
}
else
{
if ( CVAR_GET_FLOAT( "mp_teamplay" ) > 0 )
{
// teamplay
return new CHalfLifeTeamplay;
}
if ((int)gpGlobals->deathmatch == 1)
{
// vanilla deathmatch
return new CHalfLifeMultiplay;
}
else
{
// vanilla deathmatch??
return new CHalfLifeMultiplay;
}
}
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
] | [
[
[
1,
179
]
]
] |
5fdea2a45e27ff7eb0c947c9cd6b42938e25ed22 | 0ee189afe953dc99825f55232cd52b94d2884a85 | /mlog/Logging.h | 033601941c95d135b587260f58f33825d4dba3f2 | [] | 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 | 2,091 | h | #pragma once
#include "Logger.h"
#include "Manager.h"
#include "Output.h"
namespace mlog {
#if !MLOG_NO_LOGGING
#define MLOG_DO_OUT(level, value) \
do { \
mlog::Output _mlog_output; \
logger.outputHeader(_mlog_output.out(), level); \
_mlog_output.out() << value; \
_mlog_output.send(logger.group(), level, logger.name()); \
} while(false)
#define MLOG_MESSAGE_EX(level, value) \
do { \
if(logger.enabled(level)) \
MLOG_DO_OUT(level, value); \
} while(false)
#define MLOG_MESSAGE(level, value) MLOG_MESSAGE_EX(mlog::ll##level, value)
#define MLOG_MESSAGE2(level1, value1, level2, value2) \
do { \
if(logger.enabled(mlog::ll##level1)) \
MLOG_DO_OUT(level1, value1); \
else if(logger.enabled(mlog::ll##level2)) \
MLOG_DO_OUT(level2, value2); \
} while(false)
#define MLOG_FMESSAGE(level, value) \
do { \
mlog::Logger & logger = getLogger(); \
if(logger.enabled(mlog::ll##level)) \
{ \
mlog::Output _mlog_output; \
logger.outputHeader(_mlog_output.out(), mlog::ll##level); \
_mlog_output.out() << value; \
_mlog_output.send(logger.group(), mlog::ll##level, logger.name()); \
} \
} while(false)
#else
#define MLOG_DO_OUT(level, value) \
do {} while(false)
#define MLOG_MESSAGE(level, value) \
do {} while(false)
#define MLOG_MESSAGE2(level1, value1, level2, value2) \
do {} while(false)
#define MLOG_FMESSAGE(level, value) \
do {} while(false)
#endif
#define MLOG_DEBUG(value) MLOG_MESSAGE(Debug, value)
#define MLOG_INFO(value) MLOG_MESSAGE(Info, value);
#define MLOG_NOTICE(value) MLOG_MESSAGE(Notice, value)
#define MLOG_WARNING(value) MLOG_MESSAGE(Warning, value)
#define MLOG_ERROR(value) MLOG_MESSAGE(Error, value)
#define MLOG_CRITICAL(value) MLOG_MESSAGE(Critical, value)
#define MLOG_ALERT(value) MLOG_MESSAGE(Alert, value)
#define MLOG_EMERGENCY(value) MLOG_MESSAGE(Emergency, value)
}
| [
"[email protected]"
] | [
[
[
1,
68
]
]
] |
9ccc77c43aa8a899cc5211f46718fd1b212817b2 | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /XMLTree2Geom/bin/binFronds.h | 574bf15f0e68fff5445734333cec055da1f97ddc | [] | 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 | 1,081 | h | #ifndef _BIN_FRONDS_H_
#define _BIN_FRONDS_H_
#include <vector>
#include <string>
typedef std::vector< float > tVecVertex;
typedef std::vector< unsigned short > tVecIndex;
typedef std::vector< tVecIndex > tVecVecIndex;
struct binFrondsGeom
{
binFrondsGeom() : m_fAlfa( 0.0f)
{};
//координаты вершин: 3 значения на вершину
tVecVertex m_vVertex;
//нормаль к вершине: 3 значения на вершину
tVecVertex m_vNormal;
//текстурные координаты вершины: 2 значения на вершину
tVecVertex m_vTexCoord;
//индексы вершин для режима TRIANGLE_STRIP
tVecVecIndex m_vvIndex;
//значения альфа-теста
float m_fAlfa;
};
//набор геометрий для LOD'ов
typedef std::vector< binFrondsGeom > tVecFronds;
struct binFronds
{
//LOD'ы ствола
tVecFronds m_vFronds;
//имя файла с текстурой ствола
std::string m_sTexture;
};
#endif //_BIN_FRONDS_H_ | [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
] | [
[
[
1,
44
]
]
] |
2c42d4b8f2421fadce48a2be01fd5f9cc893491e | 3c9d64d2af8cf3d5b83c7393b4ddfeba468a94f7 | /third/aam/AAM_Util.cpp | 40d9246eea3c53d66576c0f4ad45c7df5fb669a7 | [] | no_license | kod3r/cv | 0ff9f31b9b926a6f61f7e422bc69f0303a8a2de4 | 9e769c90693005b76c8a7d5305002a1feb07f096 | refs/heads/master | 2021-01-18T10:55:32.764921 | 2009-08-10T17:32:19 | 2009-08-10T17:32:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,845 | cpp | /****************************************************************************
* AAMLibrary
* http://code.google.com/p/aam-library
* Copyright (c) 2008-2009 by GreatYao, all rights reserved.
****************************************************************************/
#include <fstream>
#include "AAM_Util.h"
#include "AAM_Basic.h"
#include "AAM_IC.h"
using namespace std;
//============================================================================
std::ostream& operator<<(std::ostream &os, const CvMat* mat)
{
assert(CV_MAT_TYPE(mat->type) == CV_64FC1);
for(int i = 0; i < mat->rows; i++)
{
for(int j = 0; j < mat->cols; j++)
{
os << CV_MAT_ELEM(*mat, double, i, j) << " ";
}
os << std::endl;
}
return os;
}
//============================================================================
std::istream& operator>>(std::istream &is, CvMat* mat)
{
assert(CV_MAT_TYPE(mat->type) == CV_64FC1);
for(int i = 0; i < mat->rows; i++)
{
for(int j = 0; j < mat->cols; j++)
{
is >> CV_MAT_ELEM(*mat, double, i, j);
}
}
return is;
}
//============================================================================
// compare function for the qsort() call below
static int str_compare(const void *arg1, const void *arg2)
{
return strcmp((*(std::string*)arg1).c_str(), (*(std::string*)arg2).c_str());
}
#ifdef WIN32
file_lists AAM_Common::ScanNSortDirectory(const std::string &path, const std::string &extension)
{
WIN32_FIND_DATA wfd;
HANDLE hHandle;
string searchPath, searchFile;
file_lists vFilenames;
int nbFiles = 0;
searchPath = path + "/*" + extension;
hHandle = FindFirstFile(searchPath.c_str(), &wfd);
if (INVALID_HANDLE_VALUE == hHandle)
{
fprintf(stderr, "ERROR(%s, %d): Cannot find (*.%s)files in directory %s\n",
__FILE__, __LINE__, extension.c_str(), path.c_str());
exit(0);
}
do
{
//. or ..
if (wfd.cFileName[0] == '.')
{
continue;
}
// if exists sub-directory
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
continue;
}
else//if file
{
searchFile = path + "/" + wfd.cFileName;
vFilenames.push_back(searchFile);
nbFiles++;
}
}while (FindNextFile(hHandle, &wfd));
FindClose(hHandle);
// sort the filenames
qsort((void *)&(vFilenames[0]), (size_t)nbFiles, sizeof(string), str_compare);
return vFilenames;
}
#else
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#define MAX_PATH 1024
static int match(const char* s1, const char* s2)
{
int diff = strlen(s1) - strlen(s2);
if(diff >= 0 && !strcmp(s1+diff, s2))
return 1;
return 0;
}
file_lists AAM_Common::ScanNSortDirectory(const std::string &path, const std::string &extension)
{
struct dirent *d;
DIR* dir;
struct stat s;
char fullpath[MAX_PATH];
file_lists allfiles;
int num = 0;
dir = opendir(path.c_str());
if(dir == NULL)
{
fprintf(stderr, "Can not open directory %s\n", path.c_str());
exit(0);
}
while(d = readdir(dir))
{
sprintf(fullpath, "%s/%s", path.c_str(), d->d_name);
if(stat(fullpath, &s) != -1)
{
if(S_ISDIR(s.st_mode))
continue;
if(match(d->d_name, extension.c_str()))
{
allfiles.push_back(std::string(fullpath));
num++;
}
}
}
closedir(dir);
qsort((void*)&(allfiles[0]), size_t(num), sizeof(std::string), str_compare);
return allfiles;
}
#endif
//============================================================================
void AAM_Common::DrawPoints(IplImage* image, const AAM_Shape& Shape)
{
for(int i = 0; i < Shape.NPoints(); i++)
{
cvCircle(image, cvPointFrom32f(Shape[i]), 3, CV_RGB(255, 0, 0));
}
}
//============================================================================
void AAM_Common::DrawTriangles(IplImage* image, const AAM_Shape& Shape, const std::vector<std::vector<int> >&tris)
{
int idx1, idx2, idx3;
for(int i = 0; i < tris.size(); i++)
{
idx1 = tris[i][0];
idx2 = tris[i][1];
idx3 = tris[i][2];
cvLine(image, cvPointFrom32f(Shape[idx1]), cvPointFrom32f(Shape[idx2]),
CV_RGB(128,255,0));
cvLine(image, cvPointFrom32f(Shape[idx2]), cvPointFrom32f(Shape[idx3]),
CV_RGB(128,255,0));
cvLine(image, cvPointFrom32f(Shape[idx3]), cvPointFrom32f(Shape[idx1]),
CV_RGB(128,255,0));
}
}
//============================================================================
void AAM_Common::DrawAppearance(IplImage*image, const AAM_Shape& Shape,
const CvMat* t, const AAM_PAW& paw, const AAM_PAW& refpaw)
{
int x1, x2, y1, y2, idx1, idx2;
int xby3, idxby3;
int minx, miny, maxx, maxy;
int tri_idx, v1, v2, v3;
byte* pimg;
double* fastt = t->data.db;
int nChannel = image->nChannels;
const AAM_Shape& refShape = refpaw.__referenceshape;
const std::vector<std::vector<int> >& tri = paw.__tri;
const std::vector<std::vector<int> >& rect1 = paw.__rect;
const std::vector<std::vector<int> >& rect2 = refpaw.__rect;
const std::vector<int>& pixTri = paw.__pixTri;
const std::vector<double>& alpha = paw.__alpha;
const std::vector<double>& belta= paw.__belta;
const std::vector<double>& gamma = paw.__gamma;
minx = Shape.MinX(); miny = Shape.MinY();
maxx = Shape.MaxX(); maxy = Shape.MaxY();
for(int y = miny; y < maxy; y++)
{
y1 = y-miny;
pimg = (byte*)(image->imageData + image->widthStep*y);
for(int x = minx; x < maxx; x++)
{
x1 = x-minx;
idx1 = rect1[y1][x1];
if(idx1 >= 0)
{
tri_idx = pixTri[idx1];
v1 = tri[tri_idx][0];
v2 = tri[tri_idx][1];
v3 = tri[tri_idx][2];
x2 = alpha[idx1]*refShape[v1].x + belta[idx1]*refShape[v2].x +
gamma[idx1]*refShape[v3].x;
y2 = alpha[idx1]*refShape[v1].y + belta[idx1]*refShape[v2].y +
gamma[idx1]*refShape[v3].y;
idx2 = rect2[y2][x2];
idxby3 = idx2 + (idx2<<1); /* 3*idx2 */
if(nChannel == 3)
{
xby3 = x + (x<<1); /* 3*x */
pimg[xby3 ] = fastt[idxby3 ];
pimg[xby3+1] = fastt[idxby3+1];
pimg[xby3+2] = fastt[idxby3+2];
}
else
{
pimg[x] = (fastt[idxby3]+fastt[idxby3+1]+fastt[idxby3+2])/3;
}
}
}
}
}
//===========================================================================
void AAM_Common::CheckShape(CvMat* s, int w, int h)
{
double* fasts = s->data.db;
int npoints = s->cols / 2;
for(int i = 0; i < npoints; i++)
{
if(fasts[2*i] > w-1) fasts[2*i] = w-1;
else if(fasts[2*i] < 0) fasts[2*i] = 0;
if(fasts[2*i+1] > h-1) fasts[2*i+1] = h-1;
else if(fasts[2*i+1] < 0) fasts[2*i+1] = 0;
}
}
//============================================================================
AAM::AAM()
{
}
//============================================================================
AAM::~AAM()
{
}
//============================================================================
void AAM_Pyramid::BuildDetectMapping(const file_lists& pts_files,
const file_lists& img_files,
VJfacedetect& FaceDetect,
double refWidth)
{
printf("########################################################\n");
printf("Building Detect Mapping ...\n");
int total = 0;
__referenceWidth = refWidth;
int nPoints = GetMeanShape().NPoints();
__VJDetectShape.resize(nPoints);
for(int i = 0; i < pts_files.size(); i++)
{
printf("%i of %i\r", i, pts_files.size());
IplImage* image = cvLoadImage(img_files[i].c_str(), -1);
std::vector<AAM_Shape> DetShape;
bool flag = FaceDetect.DetectFace(DetShape, image);
if(!flag) continue;
AAM_Shape Shape;
flag = Shape.ReadAnnotations(pts_files[i]);
if(!flag) Shape.ScaleXY(image->width, image->height);
cvReleaseImage(&image);
CvPoint2D32f lt = DetShape[0][0], rb = DetShape[0][1];
double x = (lt.x+rb.x)/2., y = (lt.y+rb.y)/2.;
double w = (-lt.x+rb.x), h = (-lt.y+rb.y);
Shape.Translate(-x, -y);
Shape.ScaleXY(__referenceWidth/w, __referenceWidth/h);
__VJDetectShape += Shape;
total ++;
}
__VJDetectShape /= total;
printf("########################################################\n");
}
//============================================================================
bool AAM_Pyramid::InitShapeFromDetBox(AAM_Shape& Shape, VJfacedetect& facedetect, const IplImage* image)
{
std::vector<AAM_Shape> DetShape;
bool flag = facedetect.DetectFace(DetShape, image);
if(!flag) return false;
CvPoint2D32f lt = DetShape[0][0], RB = DetShape[0][1];
Shape = __VJDetectShape;
Shape.ScaleXY((-lt.x+RB.x)/__referenceWidth, (-lt.y+RB.y)/__referenceWidth);
Shape.Translate((lt.x+RB.x)/2., (lt.y+RB.y)/2. );
return true;
}
//============================================================================
AAM_Pyramid::AAM_Pyramid()
{
__model.resize(0);
}
//============================================================================
AAM_Pyramid::~AAM_Pyramid()
{
for(int i = 0; i < __model.size(); i++)
delete __model[i];
}
//============================================================================
void AAM_Pyramid::Build(const file_lists& pts_files,
const file_lists& img_files,
int type /* = TYPE_AAM_IC */,
int level /* = 1 */)
{
if(level <= 0)
{
fprintf(stderr, "ERROE(%s,%d): The pyramid level must be at least 1!\n",
__FILE__, __LINE__);
exit(0);
}
__model.resize(0);
for(int i = 0; i < level; i++)
{
if(type == TYPE_AAM_BASIC) __model.push_back(new AAM_Basic);
else if(type == TYPE_AAM_IC) __model.push_back(new AAM_IC);
else
{
printf("Unsupported aam type!\n");
exit(0);
}
__model[i]->Build(pts_files, img_files, 1.0/pow(2.0, i));
}
}
//============================================================================
void AAM_Pyramid::Fit(const IplImage* image,
AAM_Shape& Shape,
int max_iter /* = 30 */,
bool showprocess /* = false */)
{
// the images used during search
int w = image->width;
int h = image->height;
int startlev = __model.size() - 1;
int iter = max_iter/(startlev+1);
//double PyrScale = pow(2.0, startlev);
//Shape /= PyrScale;
// for each level in the image pyramid
for (int iLev = startlev; iLev > 0; iLev--)
{
printf("Level %d: ", iLev);
//IplImage* fitimage = cvCreateImage(cvSize(w/PyrScale, h/PyrScale), image->depth, image->nChannels);
//cvResize(image, fitimage);
__model[iLev]->Fit(/*fit*/image, Shape, iter, showprocess);
//cvReleaseImage(&fitimage);
//PyrScale /= 2.0;
//Shape *= 2.0;
}
printf("Level 0: ");
__model[0]->Fit(image, Shape, iter, showprocess);
}
//void AAM_Pyramid::SetAllParamsZero()
//{
// for(int i = 0; i < __model.size(); i++)
// __model[i]->SetAllParamsZero();
//}
//============================================================================
const AAM_Shape AAM_Pyramid::GetMeanShape()const
{
return __model[0]->GetMeanShape();
}
//============================================================================
void AAM_Pyramid::Draw(IplImage* image, const AAM_Shape& Shape, int type)
{
__model[0]->Draw(image, Shape, type);
}
//============================================================================
void AAM_Pyramid::WriteModel(const std::string& filename)
{
ofstream os(filename.c_str());
if(!os){
fprintf(stderr, "ERROR(%s, %d): CANNOT create model \"%s\"\n",
__FILE__, __LINE__, filename.c_str());
exit(0);
}
os << __model[0]->GetType() << " " << __model.size() << std::endl;
for(int i = 0; i < __model.size(); i++)
{
printf("Writing (level %d) active appearance model to file...\n", i);
__model[i]->Write(os);
}
printf("Done\n");
os << __referenceWidth << std::endl;
__VJDetectShape.Write(os);
os.close();
}
//============================================================================
void AAM_Pyramid::ReadModel(const std::string& filename)
{
ifstream is(filename.c_str());
if(!is){
fprintf(stderr, "ERROR(%s, %d): CANNOT load model \"%s\"\n",
__FILE__, __LINE__, filename.c_str());
exit(0);
}
int level, type;
is >> type >> level;
for(int i = 0; i < level; i++)
{
if(type == TYPE_AAM_BASIC) __model.push_back(new AAM_Basic);
else if(type == TYPE_AAM_IC) __model.push_back(new AAM_IC);
else {
fprintf(stderr, "Unsupported AAM type\n");
exit(0);
}
printf("Reading (level %d) active appearance model from file...\n", i);
__model[i]->Read(is);
}
printf("Done\n");
is >> __referenceWidth;
__VJDetectShape.resize(GetMeanShape().NPoints());
__VJDetectShape.Read(is);
is.close();
}
| [
"sudeep@sudeep-laptop.(none)"
] | [
[
[
1,
469
]
]
] |
55e1453098b2873c63c6aedb78514d03d9aeb843 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/trunk/engine/ai/src/DialogVariable.cpp | dc4b5564dc3c6eeb7bc5b84b9a59a1446ae7e62d | [
"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 | 3,933 | 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"
#include "DialogVariable.h"
#include "Creature.h"
#include "Dialog.h"
#include "RulesSubsystem.h"
#include "QuestBook.h"
namespace rl
{
DialogVariable::DialogVariable(const CeGuiString& type)
: mRecalculate(true), mType(type)
{
}
DialogVariable::~DialogVariable()
{
}
const CeGuiString& DialogVariable::getType()
{
return mType;
}
const Property& DialogVariable::getValue(Dialog* dialog)
{
if (mRecalculate)
{
mValue = calculateValue(dialog);
mRecalculate = false;
}
return mValue;
}
void DialogVariable::invalidate()
{
mRecalculate = true;
}
DialogPropertyVariable::DialogPropertyVariable(const Ogre::String &propertyName)
: DialogVariable("dialogvariable"), mPropertyName(propertyName)
{
}
Property DialogPropertyVariable::calculateValue(Dialog* dialog)
{
return dialog->getProperty(mPropertyName);
}
QuestStateVariable::QuestStateVariable(const Ogre::String &questId, const Ogre::String &propertyName)
: DialogVariable("queststate"), mQuestId(questId), mPropertyName(propertyName)
{
}
Property QuestStateVariable::calculateValue(Dialog* dialog)
{
return RulesSubsystem::getSingleton().getQuestBook()->getQuest(mQuestId)->getProperty(mPropertyName);
}
TalentProbeVariable::TalentProbeVariable(const rl::CeGuiString &talent, int modifier, const rl::CeGuiString& target)
: DialogVariable("talentcheck"), mTalent(talent), mTarget(target), mModifier(modifier)
{
}
Property TalentProbeVariable::calculateValue(Dialog* dialog)
{
Creature* cr = dialog->getParticipant(mTarget);
if (cr == NULL)
{
LOG_ERROR("Dialog", "No or wrong target for talent check ' " + mTalent + "'");
return Property(-1);
}
else
{
return Property(cr->doTalentprobe(mTalent, mModifier));
}
}
EigenschaftsProbeVariable::EigenschaftsProbeVariable(const rl::CeGuiString &eigenschaft, int modifier, const rl::CeGuiString& target)
: DialogVariable("attributecheck"), mEigenschaft(eigenschaft), mTarget(target), mModifier(modifier)
{
}
Property EigenschaftsProbeVariable::calculateValue(Dialog* dialog)
{
Creature* cr = dialog->getParticipant(mTarget);
// if no target was given, use the player character.
// @todo: remove this, target should be required!
if (cr == NULL)
{
LOG_ERROR("Dialog", "No or wrong target for attribute check ' " + mEigenschaft + "'");
return Property(-1);
}
else
{
return Property(cr->doEigenschaftsprobe(mEigenschaft, mModifier));
}
}
RandomVariable::RandomVariable(int maximum)
: DialogVariable("random"), mMaximum(maximum)
{
}
Property RandomVariable::calculateValue(Dialog* dialog)
{
double d = std::rand();
return Property(static_cast<int>(d * mMaximum / RAND_MAX) + 1);
}
}
| [
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013",
"iblis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
26
],
[
29,
35
],
[
41,
57
],
[
59,
67
],
[
69,
76
],
[
79,
85
],
[
87,
88
],
[
90,
90
],
[
92,
92
],
[
94,
95
],
[
98,
106
],
[
108,
109
],
[
111,
111
],
[
113,
113
],
[
115,
127
]
],
[
[
27,
28
],
[
36,
40
],
[
58,
58
],
[
68,
68
],
[
77,
78
],
[
86,
86
],
[
89,
89
],
[
91,
91
],
[
93,
93
],
[
96,
97
],
[
107,
107
],
[
110,
110
],
[
112,
112
],
[
114,
114
]
]
] |
5a300eb00463a5428da4b080dc549b25d3999473 | c034a6ffa81773a279c4cd25bdbd3b23a999d4b7 | /gmfclass/GMFClass/cGMFTypes.h | b5f1f1d7231e68f309221648c7653816c4d8491c | [] | no_license | Shima33/gmftoolkit | 08ee92bb5700af984286c71dd54dbfd1ffecd35a | 0e602d27b9b8cce83942f9624cbb892b0fd44b6b | refs/heads/master | 2021-01-10T15:45:10.838305 | 2010-06-20T19:09:19 | 2010-06-20T19:09:19 | 50,957,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,462 | h | #ifndef cGMFSceneh
#define cGMFSceneh
#define GMID_HAVOK_RBCOLLECTION 312
#define GEOMOBJECT 24
#define GMID_ATTACHMENTPT 212
#define GMID_HAVOK_SIMOBJECT 702
#include "sRGB.h"
#include <string>
using namespace std;
class cGMFScene {
public:
string name;
unsigned int firstFrame, lastFrame, frameSpeed, ticksPerFrame;
RGB backgroundStatic, ambientStatic;
};
class cGMFMaterialList;
class cGMFTextureList;
class cGMFMaterial {
public:
string name, classname;
int ref, shading, fallof, XPType, texNum, matNum;
RGB ambient, diffuse, specular;
float shine, shineStrength, transparency, wiresize, XPFallof, selfIllum;
cGMFMaterialList* materialList;
cGMFTextureList* textureList;
};
class cGMFMaterialList {
public:
int number;
cGMFMaterial** materials;
};
class cGMFTexture {
public:
string name, classname, bitmap;
float amount;
int style, type, UVWNoiseLevel, bitmapFilter, bitmapChannel;
float UO, VO, UT, VT, UVWAngle, UVWBlur, UVWBlurOffset, UVWNoiseAmount, UVWNoiseSize, UVWNoisePhase;
};
class cGMFTextureList {
public:
int number;
cGMFTexture** textures;
};
class cGMFTM {
public:
string name;
float matrix[4][3];
};
class cGMFFace {
public:
int vertex[3];
int matlid;
};
class cGMFVertexNormal {
public:
int i;
float crd[3];
};
class cGMFFaceNormal {
public:
int i;
float crd[3];
cGMFVertexNormal** vnormals;
};
class cGMFVertex {
public:
float vert[3];
};
class cGMFMeshMappingChannel {
public:
int number, numTVerts, numTFaces;
cGMFVertex** tverts;
cGMFFace** tfaces;
};
class cGMFMesh {
public:
int timeValue, numVerts, numFaces, numTVerts, numCVerts, backFace, matRef, secondMaterial, secondMaterialAmount;
cGMFVertex** verts;
cGMFVertex** tverts;
cGMFVertex** cverts;
cGMFFace** faces;
cGMFFace** tfaces;
cGMFFaceNormal** normals;
cGMFMeshMappingChannel** mappingChannel;
};
class cGMFObject {
public:
string name;
cGMFTM* tm;
virtual int getType() {
return -1;
}
};
class cGMFCollisionPair {
public:
string body1, body2;
};
class cGMFCollisionPairList {
public:
int count;
cGMFCollisionPair** cpair;
};
class cGMFRigidBody {
public:
string name, geomProxy, dispProxy;
float mass, elasticity, friction, optimisation;
int unyielding, simulationGeo, useDisplayProxy, disableCollisions, inactive, geoType, childrenNumber;
cGMFTM* tm;
};
class cGMFObjectRBCollectionList {
public:
int rbCount;
cGMFRigidBody** rbs;
};
class cGMFObjectRBCollection : public cGMFObject {
public:
int numDisabledPairs, solverType;
int hasRBList, hasDisabledCollisionsList;
cGMFObjectRBCollectionList* rblist;
cGMFCollisionPairList* cplist;
virtual int getType() {
return 312;
}
};
class cGMFObjectGeo : public cGMFObject {
public:
string parent;
int shadeVerts;
cGMFMesh* mesh;
virtual int getType() {
return 24;
}
};
class cGMFObjectAttachment : public cGMFObject {
public:
string userData;
virtual int getType() {
return 212;
}
};
class cGMFObjectSimobject : public cGMFObject {
public:
float x, y, z, worldScale, tolerance, linearDrag, angularDrag, shortFreq, longFreq, updatesPerTimeStep;
int resolver, includeDrag, includeDeactivator, useFastSubspace, collisionPairs;
virtual int getType() {
return 702;
}
};
class cGMFObjectList {
public:
int number;
cGMFObject** objects;
};
#endif
| [
"Bazanski@1d10bff2-9961-11dd-bd51-a78b85c98fae"
] | [
[
[
1,
179
]
]
] |
0256c950f2b6a86c4c4e3c91936dbfe983b0cbc4 | e6ffc738b23d185d18140f644dc9b2c736cd170c | /fuentes/enrutamiento/src/grafo/ConstructorGrafo.cpp | 0866618a3f3757dbfb3714c7d0dfc7fbd02946e4 | [] | no_license | ghuttemann/enrutamiento-demandas-unicast | 0444af6e4a5a2e68f62ea0b08286366c8a5d956f | 4a03265ab6e24cc577703f21e1023073730e7bc7 | refs/heads/master | 2021-01-03T13:19:44.629478 | 2008-09-23T13:36:24 | 2008-09-23T13:36:24 | 32,361,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,448 | cpp | #include "ConstructorGrafo.h"
#include "../utils/utils.h"
#include <fstream>
using namespace std;
ConstructorGrafo::ConstructorGrafo() {
}
ConstructorGrafo::~ConstructorGrafo() {
}
Grafo* ConstructorGrafo::leerGrafo(const char *archivo) {
ifstream stream;
double aux; // variable auxiliar
int contador; // contador de lineas leidas
int cantAristas;
int cantVertices;
int origen, destino;
double costo, capacidad;
Grafo *grafo;
// Abrimos el archivo
stream.open(archivo);
if (stream.bad()) {
string str = string("No se puede abrir \"") + archivo + "\"";
terminar(str);
}
stream >> cantVertices; // Se lee cantidad de vertices
stream >> cantAristas; // se lee cantidad de aristas
// Construimos el grafo
grafo = new Grafo(cantVertices);
contador = 0;
while (stream.good()) {
// Cargamos una linea del archivo
stream >> origen;
stream >> destino;
stream >> capacidad;
stream >> costo;
stream >> aux;
// Creamos la arista y la guardamos en el grafo
Arista *a = new Arista(origen, destino, costo, capacidad);
grafo->agregarArista(a);
contador++;
}
// Cerramos el stream
stream.close();
if (contador != cantAristas) {
string str = string("Error en el archivo \"") + archivo + "\"\n";
str += "La cantidad de vertices leidos no coincide con ";
str += "la cantidad especificada";
terminar(str);
}
return grafo;
}
| [
"ghuttemann@bd0bc703-fb3b-0410-a856-e1b9a076a7ce",
"rodas.marcelo@bd0bc703-fb3b-0410-a856-e1b9a076a7ce"
] | [
[
[
1,
4
],
[
6,
55
],
[
57,
65
]
],
[
[
5,
5
],
[
56,
56
]
]
] |
4bb745556cff8453cdeb9dfa0df434c41336f15b | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/Mir2ExCode/Mir2/CharSelectProcess/CreateChr/CreateChr.h | 683e6ada27793fff378582451be4b24a365df479 | [] | no_license | sdfwds4/fjljfatchina | 62a3bcf8085f41d632fdf83ab1fc485abd98c445 | 0503d4aa1907cb9cf47d5d0b5c606df07217c8f6 | refs/heads/master | 2021-01-10T04:10:34.432964 | 2010-03-07T09:43:28 | 2010-03-07T09:43:28 | 48,106,882 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | h | // LoginProcess.h: interface for the CCreateChrProcess class.
//
//////////////////////////////////////////////////////////////////////
#ifndef _CREATE_CHR_H
#define _CREATE_CHR_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CCreateChr : public CBMWnd
{
/////////////////////////////////////////////////////////////////////////////////////////
// Functions
public:
CCreateChr();
~CCreateChr();
virtual VOID Create(CWHWilImageData* pxImage);
virtual HRESULT OnButtonDown(WPARAM wParam, LPARAM lParam);
virtual HRESULT OnButtonDown(POINT ptMouse);
virtual HRESULT OnButtonUp(WPARAM wParam, LPARAM lParam);
virtual HRESULT OnButtonUp(POINT ptMouse);
virtual HRESULT OnKeyDown(WPARAM wParam, LPARAM lParam);
virtual LRESULT OnMouseMove(WPARAM wParam, LPARAM lParam);
virtual VOID Render(INT nLoopTime);
private:
protected:
/////////////////////////////////////////////////////////////////////////////////////////
// Variable
public:
private:
CMirButton m_xButtons[4];
BOOL m_fIsButtonDown;
protected:
CWHWilImageData *m_pxImage;
INT m_nSelectGender;
INT m_nSelectJob;
};
#endif //_CREATE_CHR_H
| [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
] | [
[
[
1,
43
]
]
] |
c5f1c2d4b8eebe4f6260f6520600568be54b1942 | 00c36cc82b03bbf1af30606706891373d01b8dca | /OpenGUI/OpenGUI_Brush_Caching.cpp | eb83d7a2624ce94f01d85b066026eba79ba61970 | [
"BSD-3-Clause"
] | permissive | VB6Hobbyst7/opengui | 8fb84206b419399153e03223e59625757180702f | 640be732a25129a1709873bd528866787476fa1a | refs/heads/master | 2021-12-24T01:29:10.296596 | 2007-01-22T08:00:22 | 2007-01-22T08:00:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,589 | cpp | // OpenGUI (http://opengui.sourceforge.net)
// This source code is released under the BSD License
// See LICENSE.TXT for details
#include "OpenGUI_Brush_Caching.h"
#include "OpenGUI_Exception.h"
#include "OpenGUI_Screen.h"
#include "OpenGUI_Renderer.h"
#include "OpenGUI_TextureManager.h"
namespace OpenGUI {
//############################################################################
Brush_Caching::Brush_Caching( Screen* parentScreen, const FVector2& size ): mScreen( parentScreen ), mDrawSize( size ) {
if ( !mScreen )
OG_THROW( Exception::ERR_INVALIDPARAMS, "Constructor requires a valid pointer to destination Screen", __FUNCTION__ );
if ( !initRTT() )
initMemory();
mHasContent = false;
}
//############################################################################
Brush_Caching::~Brush_Caching() {
if ( isRTT() )
cleanupRTT();
else
cleanupMemory();
}
//############################################################################
void Brush_Caching::emerge( Brush& targetBrush ) {
if ( isRTT() )
emergeRTT( targetBrush );
else
emergeMemory( targetBrush );
}
//############################################################################
const FVector2& Brush_Caching::getPPU_Raw() const {
if ( isRTT() ) {
static FVector2 retVal;
const IVector2& texsize = mRenderTexture->getSize();
retVal.x = ( float )texsize.x / mDrawSize.x;
retVal.y = ( float )texsize.y / mDrawSize.y;
return retVal;
} else {
return mScreen->getPPU();
}
}
//############################################################################
const FVector2& Brush_Caching::getUPI_Raw() const {
return mScreen->getUPI();
}
//############################################################################
void Brush_Caching::appendRenderOperation( RenderOperation &renderOp ) {
mHasContent = true;
if ( isRTT() )
appendRTT( renderOp );
else
appendMemory( renderOp );
}
//############################################################################
void Brush_Caching::onActivate() {
if ( isRTT() )
activateRTT();
else
activateMemory();
}
//############################################################################
void Brush_Caching::onClear() {
mHasContent = false;
if ( isRTT() )
clearRTT();
else
clearMemory();
}
//############################################################################
//############################################################################
//############################################################################
void Brush_Caching::initMemory() {
pushClippingRect( FRect( 0, 0, mDrawSize.x, mDrawSize.y ) );
_pushMarker( this );
}
//############################################################################
void Brush_Caching::cleanupMemory() {
_popMarker( this );
pop();
}
//############################################################################
void Brush_Caching::clearMemory() {
mRenderOpList.clear();
}
//############################################################################
void Brush_Caching::activateMemory() {
/* No special action required */
}
//############################################################################
void Brush_Caching::appendMemory( RenderOperation &renderOp ) {
//!\todo fix me to perform triangle list appending when renderOps are equal
mRenderOpList.push_back( renderOp );
RenderOperation& newRop = mRenderOpList.back();
newRop.triangleList = new TriangleList;
TriangleList& inList = *( renderOp.triangleList );
TriangleList& outList = *( newRop.triangleList );
outList = inList;
}
//############################################################################
void Brush_Caching::emergeMemory( Brush& targetBrush ) {
RenderOperationList::iterator iter, iterend = mRenderOpList.end();
for ( iter = mRenderOpList.begin(); iter != iterend; iter++ ) {
//!\todo Having a copy operation here makes this incredibly slow! This should be removed as part of Brush optimization
// we need to make a copy because addrenderOperation modifies the input directly
RenderOperation &thisRop = ( *iter );
RenderOperation tmp = thisRop;
tmp.triangleList = new TriangleList;
*( tmp.triangleList ) = *( thisRop.triangleList );
targetBrush._addRenderOperation( tmp );
}
}
//############################################################################
//############################################################################
//############################################################################
bool Brush_Caching::initRTT() {
if ( !TextureManager::getSingleton().supportsRenderToTexture() )
return false;
IVector2 texSize;
float xTexSize, yTexSize, xPixelSize, yPixelSize;
xPixelSize = mDrawSize.x * getPPU_Raw().x;
yPixelSize = mDrawSize.y * getPPU_Raw().y;
xTexSize = Math::Ceil( xPixelSize );
yTexSize = Math::Ceil( yPixelSize );
mMaxUV.x = xPixelSize / xTexSize;
mMaxUV.y = yPixelSize / yTexSize;
texSize.x = ( int )( xTexSize );
texSize.y = ( int )( yTexSize );
mRenderTexture = TextureManager::getSingleton().createRenderTexture( texSize );
if ( !mRenderTexture )
return false;
_clear();
return true;
}
//############################################################################
void Brush_Caching::cleanupRTT() {
/* No special action required */
}
//############################################################################
void Brush_Caching::clearRTT() {
Renderer::getSingleton().clearContents();
}
//############################################################################
void Brush_Caching::activateRTT() {
Renderer::getSingleton().selectRenderContext( mRenderTexture.get() );
}
//############################################################################
void Brush_Caching::appendRTT( RenderOperation &renderOp ) {
TriangleList::iterator iter, iterend = renderOp.triangleList->end();
for ( iter = renderOp.triangleList->begin(); iter != iterend; iter++ ) {
Triangle& t = ( *iter );
for ( int i = 0; i < 3; i++ ) {
t.vertex[i].position.x /= mDrawSize.x;
t.vertex[i].position.y /= mDrawSize.y;
}
}
Renderer::getSingleton().doRenderOperation( renderOp );
}
//############################################################################
void Brush_Caching::emergeRTT( Brush& targetBrush ) {
RenderOperation rop;
rop.texture = mRenderTexture.get();
rop.triangleList = new TriangleList;
Triangle tri;
//ul
tri.vertex[0].textureUV = FVector2( 0.0f, mMaxUV.y );
tri.vertex[0].position = FVector2( 0.0f, 0.0f );
//ll
tri.vertex[1].textureUV = FVector2( 0.0f, 0.0f );
tri.vertex[1].position = FVector2( 0.0f, mDrawSize.y );
//ur
tri.vertex[2].textureUV = FVector2( mMaxUV.x, mMaxUV.y );
tri.vertex[2].position = FVector2( mDrawSize.x, 0.0f );
rop.triangleList->push_back( tri );
//ur
tri.vertex[0] = tri.vertex[2];
//ll
// tri.vertex[1].textureUV = FVector2(0.0f,0.0f);
// tri.vertex[1].position = FVector2(0.0f,1.0f);
//lr
tri.vertex[2].textureUV = FVector2( mMaxUV.x, 0.0f );
tri.vertex[2].position = FVector2( mDrawSize.x, mDrawSize.y );
rop.triangleList->push_back( tri );
targetBrush.pushPixelAlignment();
targetBrush._addRenderOperation( rop );
targetBrush.pop();
}
//############################################################################
} // namespace OpenGUI{ | [
"zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59"
] | [
[
[
1,
199
]
]
] |
0f87726030aa16880e79263cd54763597fb7a322 | 8a2e417c772eba9cf4653d0c688dd3ac96590964 | /prop-src/lawgen.cc | c36bf480580f9c18d0f14016c4618629f37f16e5 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | romix/prop-cc | 1a190ba6ed8922428352826de38efb736e464f50 | 3f7f2e4a4d0b717f4e4f3dbd4c7f9d1f35572f8f | refs/heads/master | 2023-08-30T12:55:00.192286 | 2011-07-19T20:56:39 | 2011-07-19T20:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,840 | cc | ///////////////////////////////////////////////////////////////////////////////
// This file is generated automatically using Prop (version 2.4.0),
// last updated on Jul 1, 2011.
// The original source file is "..\..\prop-src\lawgen.pcc".
///////////////////////////////////////////////////////////////////////////////
#define PROP_TUPLE2_USED
#include <propdefs.h>
#line 1 "../../prop-src/lawgen.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Module to generate law abbreviations.
//
///////////////////////////////////////////////////////////////////////////////
#include "ir.h"
#include "ast.h"
#include "datagen.h"
#include "type.h"
#include "hashtab.h"
#include "list.h"
///////////////////////////////////////////////////////////////////////////////
//
// Law environment.
//
///////////////////////////////////////////////////////////////////////////////
HashTable DatatypeCompiler::law_env( string_hash, string_equal);
///////////////////////////////////////////////////////////////////////////////
//
// Method to lookup a pattern law.
//
///////////////////////////////////////////////////////////////////////////////
Pat DatatypeCompiler::lookup_pat( Id id)
{
HashTable::Entry * e = law_env.lookup(id);
return e ? (Pat)e->v : NOpat;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to enter a new pattern
//
///////////////////////////////////////////////////////////////////////////////
void DatatypeCompiler::add_law( LawDef law_def)
{
#line 42 "../../prop-src/lawgen.pcc"
#line 56 "../../prop-src/lawgen.pcc"
{
#line 45 "../../prop-src/lawgen.pcc"
if (lookup_pat(law_def->id) != NOpat)
{
error ("%Lduplicated definition of pattern constructor '%s'\n",law_def->id);
}
else
{
// type check pattern
Pat p = law_def->guard != NOexp ? GUARDpat( p, law_def->guard) : law_def->pat;
law_env.insert( law_def->id, POLYpat( law_def->id, length( law_def->args), law_def->args, p, law_def->guard, law_def->invert));
}
#line 56 "../../prop-src/lawgen.pcc"
}
#line 57 "../../prop-src/lawgen.pcc"
#line 57 "../../prop-src/lawgen.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Function 'invertible' checks whether a pattern is invertible into
// a pseudo constructor.
//
///////////////////////////////////////////////////////////////////////////////
#line 67 "../../prop-src/lawgen.pcc"
#line 93 "../../prop-src/lawgen.pcc"
Bool invertible (Pat x_1);
Bool invertible (a_List<Pat> * x_1);
Bool invertible (a_List<LabPat> * x_1);
Bool invertible (Pat x_1)
{
if (x_1) {
switch (x_1->tag__) {
case a_Pat::tag_APPpat: {
if (_APPpat(x_1)->_1) {
switch (_APPpat(x_1)->_1->tag__) {
case a_Pat::tag_CONSpat: {
#line 71 "../../prop-src/lawgen.pcc"
return invertible(_APPpat(x_1)->_2);
#line 71 "../../prop-src/lawgen.pcc"
} break;
default: {
L1:;
#line 86 "../../prop-src/lawgen.pcc"
bug("invertible: %p", x_1); return false;
#line 86 "../../prop-src/lawgen.pcc"
} break;
}
} else { goto L1; }
} break;
case a_Pat::tag_TYPEDpat: {
#line 72 "../../prop-src/lawgen.pcc"
return invertible(_TYPEDpat(x_1)->_1);
#line 72 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_ASpat: {
#line 73 "../../prop-src/lawgen.pcc"
return invertible(_ASpat(x_1)->_2);
#line 73 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_CONTEXTpat: {
#line 74 "../../prop-src/lawgen.pcc"
return invertible(_CONTEXTpat(x_1)->_2);
#line 74 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_TUPLEpat: {
#line 75 "../../prop-src/lawgen.pcc"
return invertible(_TUPLEpat(x_1)->TUPLEpat);
#line 75 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_EXTUPLEpat: {
#line 76 "../../prop-src/lawgen.pcc"
return invertible(_EXTUPLEpat(x_1)->EXTUPLEpat);
#line 76 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_RECORDpat: {
#line 77 "../../prop-src/lawgen.pcc"
return ! _RECORDpat(x_1)->_2 && invertible(_RECORDpat(x_1)->_1);
#line 77 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_LISTpat: {
#line 81 "../../prop-src/lawgen.pcc"
return invertible(_LISTpat(x_1)->head) && invertible(_LISTpat(x_1)->tail);
#line 81 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_VECTORpat: {
#line 83 "../../prop-src/lawgen.pcc"
return ! _VECTORpat(x_1)->head_flex && ! _VECTORpat(x_1)->tail_flex &&
invertible(_VECTORpat(x_1)->len) && invertible(_VECTORpat(x_1)->array) && invertible(_VECTORpat(x_1)->elements);
#line 85 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_GUARDpat: {
#line 78 "../../prop-src/lawgen.pcc"
return invertible(_GUARDpat(x_1)->_1);
#line 78 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_MARKEDpat: {
#line 79 "../../prop-src/lawgen.pcc"
return invertible(_MARKEDpat(x_1)->_2);
#line 79 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_WILDpat:
case a_Pat::tag_ARRAYpat:
case a_Pat::tag_APPENDpat:
case a_Pat::tag_LOGICALpat: {
#line 70 "../../prop-src/lawgen.pcc"
return false;
#line 70 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_INDpat:
case a_Pat::tag_IDpat:
case a_Pat::tag_CONSpat:
case a_Pat::tag_LITERALpat: {
L2:;
#line 68 "../../prop-src/lawgen.pcc"
return true;
#line 68 "../../prop-src/lawgen.pcc"
} break;
default: { goto L1; } break;
}
} else { goto L2; }
}
Bool invertible (a_List<Pat> * x_1)
{
if (x_1) {
#line 89 "../../prop-src/lawgen.pcc"
return invertible(x_1->_1) && invertible(x_1->_2);
#line 89 "../../prop-src/lawgen.pcc"
} else {
#line 88 "../../prop-src/lawgen.pcc"
return true;
#line 88 "../../prop-src/lawgen.pcc"
}
}
Bool invertible (a_List<LabPat> * x_1)
{
if (x_1) {
#line 92 "../../prop-src/lawgen.pcc"
return invertible(x_1->_1.pat) && invertible(x_1->_2);
#line 92 "../../prop-src/lawgen.pcc"
} else {
#line 91 "../../prop-src/lawgen.pcc"
return true;
#line 91 "../../prop-src/lawgen.pcc"
}
}
#line 93 "../../prop-src/lawgen.pcc"
#line 93 "../../prop-src/lawgen.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Function to convert a pattern into a variable creation expression.
//
///////////////////////////////////////////////////////////////////////////////
Exp mkvariable( Pat p)
{
#line 103 "../../prop-src/lawgen.pcc"
#line 111 "../../prop-src/lawgen.pcc"
{
Ty _V1 = deref_all(p->ty);
if (_V1) {
switch (_V1->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(_TYCONty(_V1)->_1)) {
switch (_TYCONty(_V1)->_1->tag__) {
case a_TyCon::tag_DATATYPEtycon: {
if (
#line 105 "../../prop-src/lawgen.pcc"
(_DATATYPEtycon(_TYCONty(_V1)->_1)->qualifiers & QUALunifiable)
#line 105 "../../prop-src/lawgen.pcc"
) {
#line 106 "../../prop-src/lawgen.pcc"
return APPexp( IDexp( _DATATYPEtycon(_TYCONty(_V1)->_1)->terms[_DATATYPEtycon(_TYCONty(_V1)->_1)->unit]->name), TUPLEexp(
#line 106 "../../prop-src/lawgen.pcc"
#line 106 "../../prop-src/lawgen.pcc"
nil_1_
#line 106 "../../prop-src/lawgen.pcc"
#line 106 "../../prop-src/lawgen.pcc"
));
#line 106 "../../prop-src/lawgen.pcc"
} else {
L3:;
#line 108 "../../prop-src/lawgen.pcc"
error( "%L%p with type %T is not unifiable\n", p, p->ty);
return NOexp;
#line 111 "../../prop-src/lawgen.pcc"
}
} break;
default: { goto L3; } break;
}
} else { goto L3; }
} break;
default: { goto L3; } break;
}
} else { goto L3; }
}
#line 112 "../../prop-src/lawgen.pcc"
#line 112 "../../prop-src/lawgen.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Function 'pat2exp' converts an invertible pattern into a
// constructor expression. Also extracts the bound variable bindings
// at the same time.
//
///////////////////////////////////////////////////////////////////////////////
static
#line 123 "../../prop-src/lawgen.pcc"
a_List<Tuple2<Id, Ty> > *
#line 123 "../../prop-src/lawgen.pcc"
boundvars =
#line 123 "../../prop-src/lawgen.pcc"
nil_1_
#line 123 "../../prop-src/lawgen.pcc"
#line 123 "../../prop-src/lawgen.pcc"
;
static Exps actual_args =
#line 124 "../../prop-src/lawgen.pcc"
#line 124 "../../prop-src/lawgen.pcc"
nil_1_
#line 124 "../../prop-src/lawgen.pcc"
#line 124 "../../prop-src/lawgen.pcc"
;
static Bool application_error = false;
Bool write_mode = false;
#line 128 "../../prop-src/lawgen.pcc"
#line 196 "../../prop-src/lawgen.pcc"
Exp pat2exp (Pat x_1);
Exps pat2exp (a_List<Pat> * x_1);
LabExps pat2exp (a_List<LabPat> * x_1);
Exp pat2constructor (Pat x_1);
Exp pat2unifier (Pat x_1);
Exp pat2exp (Pat x_1)
{
if (x_1) {
switch (x_1->tag__) {
case a_Pat::tag_WILDpat: {
if (write_mode) {
#line 164 "../../prop-src/lawgen.pcc"
return mkvariable(x_1);
#line 164 "../../prop-src/lawgen.pcc"
} else {
L4:;
#line 165 "../../prop-src/lawgen.pcc"
bug("pat2exp: %p", x_1); return NOexp;
#line 165 "../../prop-src/lawgen.pcc"
}
} break;
case a_Pat::tag_INDpat: {
if ((actual_args != nil_1_)) {
#line 133 "../../prop-src/lawgen.pcc"
int k = 0;
for_each(Exp, e, actual_args)
{ if (k == _INDpat(x_1)->_2) return e;
k++;
}
error("%LMissing argument %i in law variable %s\n",_INDpat(x_1)->_2,_INDpat(x_1)->_1);
application_error = true;
return NOexp;
#line 142 "../../prop-src/lawgen.pcc"
} else {
#line 144 "../../prop-src/lawgen.pcc"
boundvars =
#line 145 "../../prop-src/lawgen.pcc"
#line 145 "../../prop-src/lawgen.pcc"
list_1_(mkTuple2(_INDpat(x_1)->_1,_INDpat(x_1)->_3),boundvars)
#line 145 "../../prop-src/lawgen.pcc"
#line 145 "../../prop-src/lawgen.pcc"
;
return IDexp(_INDpat(x_1)->_1);
#line 147 "../../prop-src/lawgen.pcc"
}
} break;
case a_Pat::tag_IDpat: {
#line 131 "../../prop-src/lawgen.pcc"
return write_mode ? mkvariable(x_1) : IDexp(_IDpat(x_1)->_1);
#line 131 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_CONSpat: {
if (_CONSpat(x_1)->CONSpat) {
#line 157 "../../prop-src/lawgen.pcc"
return IDexp(_CONSpat(x_1)->CONSpat->name);
#line 157 "../../prop-src/lawgen.pcc"
} else { goto L4; }
} break;
case a_Pat::tag_APPpat: {
if (_APPpat(x_1)->_1) {
switch (_APPpat(x_1)->_1->tag__) {
case a_Pat::tag_CONSpat: {
#line 158 "../../prop-src/lawgen.pcc"
return CONSexp(_CONSpat(_APPpat(x_1)->_1)->CONSpat,
#line 158 "../../prop-src/lawgen.pcc"
#line 158 "../../prop-src/lawgen.pcc"
nil_1_
#line 158 "../../prop-src/lawgen.pcc"
#line 158 "../../prop-src/lawgen.pcc"
,pat2exp(_APPpat(x_1)->_2));
#line 158 "../../prop-src/lawgen.pcc"
} break;
default: { goto L4; } break;
}
} else { goto L4; }
} break;
case a_Pat::tag_TYPEDpat: {
#line 149 "../../prop-src/lawgen.pcc"
return pat2exp(_TYPEDpat(x_1)->_1);
#line 149 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_ASpat: {
#line 150 "../../prop-src/lawgen.pcc"
return pat2exp(_ASpat(x_1)->_2);
#line 150 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_LITERALpat: {
#line 148 "../../prop-src/lawgen.pcc"
return LITERALexp(_LITERALpat(x_1)->LITERALpat);
#line 148 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_CONTEXTpat: {
#line 151 "../../prop-src/lawgen.pcc"
return pat2exp(_CONTEXTpat(x_1)->_2);
#line 151 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_TUPLEpat: {
#line 152 "../../prop-src/lawgen.pcc"
return TUPLEexp(pat2exp(_TUPLEpat(x_1)->TUPLEpat));
#line 152 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_EXTUPLEpat: {
#line 153 "../../prop-src/lawgen.pcc"
return EXTUPLEexp(pat2exp(_EXTUPLEpat(x_1)->EXTUPLEpat));
#line 153 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_RECORDpat: {
#line 154 "../../prop-src/lawgen.pcc"
return RECORDexp(pat2exp(_RECORDpat(x_1)->_1));
#line 154 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_LISTpat: {
#line 160 "../../prop-src/lawgen.pcc"
return LISTexp(_LISTpat(x_1)->cons,_LISTpat(x_1)->nil,pat2exp(_LISTpat(x_1)->head),pat2exp(_LISTpat(x_1)->tail));
#line 160 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_VECTORpat: {
#line 162 "../../prop-src/lawgen.pcc"
return VECTORexp(_VECTORpat(x_1)->cons,pat2exp(_VECTORpat(x_1)->elements));
#line 162 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_GUARDpat: {
#line 155 "../../prop-src/lawgen.pcc"
return pat2exp(_GUARDpat(x_1)->_1);
#line 155 "../../prop-src/lawgen.pcc"
} break;
case a_Pat::tag_MARKEDpat: {
#line 156 "../../prop-src/lawgen.pcc"
return pat2exp(_MARKEDpat(x_1)->_2);
#line 156 "../../prop-src/lawgen.pcc"
} break;
default: { goto L4; } break;
}
} else {
#line 129 "../../prop-src/lawgen.pcc"
return NOexp;
#line 129 "../../prop-src/lawgen.pcc"
}
}
Exps pat2exp (a_List<Pat> * x_1)
{
if (x_1) {
#line 168 "../../prop-src/lawgen.pcc"
return
#line 168 "../../prop-src/lawgen.pcc"
#line 168 "../../prop-src/lawgen.pcc"
list_1_(pat2exp(x_1->_1),pat2exp(x_1->_2))
#line 168 "../../prop-src/lawgen.pcc"
#line 168 "../../prop-src/lawgen.pcc"
;
#line 168 "../../prop-src/lawgen.pcc"
} else {
#line 167 "../../prop-src/lawgen.pcc"
return
#line 167 "../../prop-src/lawgen.pcc"
#line 167 "../../prop-src/lawgen.pcc"
nil_1_
#line 167 "../../prop-src/lawgen.pcc"
#line 167 "../../prop-src/lawgen.pcc"
;
#line 167 "../../prop-src/lawgen.pcc"
}
}
LabExps pat2exp (a_List<LabPat> * x_1)
{
if (x_1) {
#line 172 "../../prop-src/lawgen.pcc"
LabExp labexp;
labexp.label = x_1->_1.label;
labexp.exp = pat2exp(x_1->_1.pat);
return
#line 176 "../../prop-src/lawgen.pcc"
#line 176 "../../prop-src/lawgen.pcc"
list_1_(labexp,pat2exp(x_1->_2))
#line 176 "../../prop-src/lawgen.pcc"
#line 176 "../../prop-src/lawgen.pcc"
;
#line 177 "../../prop-src/lawgen.pcc"
} else {
#line 170 "../../prop-src/lawgen.pcc"
return
#line 170 "../../prop-src/lawgen.pcc"
#line 170 "../../prop-src/lawgen.pcc"
nil_1_
#line 170 "../../prop-src/lawgen.pcc"
#line 170 "../../prop-src/lawgen.pcc"
;
#line 170 "../../prop-src/lawgen.pcc"
}
}
Exp pat2constructor (Pat x_1)
{
#line 180 "../../prop-src/lawgen.pcc"
Bool mode_save = write_mode;
write_mode = false;
Exp e = pat2exp(x_1);
write_mode = mode_save;
return e;
#line 186 "../../prop-src/lawgen.pcc"
}
Exp pat2unifier (Pat x_1)
{
#line 189 "../../prop-src/lawgen.pcc"
Bool mode_save = write_mode;
write_mode = true;
Exp e = pat2exp(x_1);
write_mode = mode_save;
return e;
#line 195 "../../prop-src/lawgen.pcc"
}
#line 196 "../../prop-src/lawgen.pcc"
#line 196 "../../prop-src/lawgen.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Method to lookup a pattern law.
//
///////////////////////////////////////////////////////////////////////////////
Exp DatatypeCompiler::lookup_law( Id id, Exps args)
{
Pat pat = lookup_pat(id);
#line 207 "../../prop-src/lawgen.pcc"
#line 234 "../../prop-src/lawgen.pcc"
{
if (pat) {
switch (pat->tag__) {
case a_Pat::tag_POLYpat: {
if (
#line 209 "../../prop-src/lawgen.pcc"
(_POLYpat(pat)->_6 == true)
#line 209 "../../prop-src/lawgen.pcc"
) {
#line 210 "../../prop-src/lawgen.pcc"
if (invertible(_POLYpat(pat)->_4) && _POLYpat(pat)->_5 == NOexp)
{
actual_args = args;
application_error = false;
if (_POLYpat(pat)->_2 != length(args))
{
error( "%Larity mismatch between law %p and arguments %f\n",
_POLYpat(pat)->_4, TUPLEexp(args));
return NOexp;
}
Exp exp = pat2exp(_POLYpat(pat)->_4);
actual_args =
#line 222 "../../prop-src/lawgen.pcc"
#line 222 "../../prop-src/lawgen.pcc"
nil_1_
#line 222 "../../prop-src/lawgen.pcc"
#line 222 "../../prop-src/lawgen.pcc"
;
if (application_error)
error( "%Lcannot apply law %p with arguments %f\n",
_POLYpat(pat)->_4, TUPLEexp(args));
return exp;
}
else
{
error( "%Llaw %s(...) = %p is not invertible\n",_POLYpat(pat)->_1,_POLYpat(pat)->_4);
}
#line 232 "../../prop-src/lawgen.pcc"
} else {
L5:; }
} break;
default: { goto L5; } break;
}
} else { goto L5; }
}
#line 234 "../../prop-src/lawgen.pcc"
#line 234 "../../prop-src/lawgen.pcc"
return NOexp;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to generate pattern law definitions
//
///////////////////////////////////////////////////////////////////////////////
void DatatypeCompiler::gen_law_defs (LawDefs law_defs)
{
for_each (LawDef, l, law_defs)
{
#line 248 "../../prop-src/lawgen.pcc"
#line 269 "../../prop-src/lawgen.pcc"
{
#line 251 "../../prop-src/lawgen.pcc"
l->set_loc();
// infer the type of the pattern.
l->ty = type_of(l->pat);
// If the law is invertible, generate
// code for the laws
if (l->invert)
{ if (invertible(l->pat) && l->guard == NOexp)
{
boundvars =
#line 262 "../../prop-src/lawgen.pcc"
#line 262 "../../prop-src/lawgen.pcc"
nil_1_
#line 262 "../../prop-src/lawgen.pcc"
#line 262 "../../prop-src/lawgen.pcc"
;
gen_law_inverse(l->loc(),l->id,l->args,pat2constructor(l->pat),l->ty);
boundvars =
#line 264 "../../prop-src/lawgen.pcc"
#line 264 "../../prop-src/lawgen.pcc"
nil_1_
#line 264 "../../prop-src/lawgen.pcc"
#line 264 "../../prop-src/lawgen.pcc"
;
}
else
error( "%Llaw %s(...) = %p is not invertible\n",l->id,l->pat);
}
#line 269 "../../prop-src/lawgen.pcc"
}
#line 270 "../../prop-src/lawgen.pcc"
#line 270 "../../prop-src/lawgen.pcc"
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Check if type can be a C++ parameter
//
///////////////////////////////////////////////////////////////////////////////
Bool is_parameter_type (Ty ty)
{
#line 282 "../../prop-src/lawgen.pcc"
#line 285 "../../prop-src/lawgen.pcc"
{
Ty _V2 = deref(ty);
if (_V2) {
switch (_V2->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(_TYCONty(_V2)->_1)) {
switch (_TYCONty(_V2)->_1->tag__) {
case a_TyCon::tag_RECORDtycon:
case a_TyCon::tag_ARRAYtycon: {
L6:;
#line 284 "../../prop-src/lawgen.pcc"
return false;
#line 284 "../../prop-src/lawgen.pcc"
} break;
default: {
L7:;
#line 285 "../../prop-src/lawgen.pcc"
return true;
#line 285 "../../prop-src/lawgen.pcc"
} break;
}
} else {
switch ((int)_TYCONty(_V2)->_1) {
case ((int)v_TUPLEtycon): { goto L6; } break;
default: { goto L7; } break;
}
}
} break;
default: { goto L7; } break;
}
} else { goto L7; }
}
#line 286 "../../prop-src/lawgen.pcc"
#line 286 "../../prop-src/lawgen.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to generate an inverse for a law definition
//
///////////////////////////////////////////////////////////////////////////////
void DatatypeCompiler::gen_law_inverse
(const Loc * location, Id id, Ids args, Exp exp, Ty ty)
{ // Generate the header name
pr(
"%^%/"
"%^// Definition of law %s"
"%^%/"
"%#"
"%^inline %t(",
id, location->begin_line, location->file_name, ty, id
);
// Generate the parameters
Bool comma = false;
#line 310 "../../prop-src/lawgen.pcc"
#line 342 "../../prop-src/lawgen.pcc"
{
for (;;) {
if (args) {
#line 313 "../../prop-src/lawgen.pcc"
if (comma) pr(", ");
#line 315 "../../prop-src/lawgen.pcc"
a_List<Tuple2<Id, Ty> > *
#line 315 "../../prop-src/lawgen.pcc"
bvs = boundvars;
Bool found = false;
Bool mode_save = write_mode;
write_mode = false;
#line 334 "../../prop-src/lawgen.pcc"
{
for (;;) {
if (bvs) {
#line 322 "../../prop-src/lawgen.pcc"
if (bvs->_1._1 == args->_1)
{
if (! is_parameter_type(bvs->_1._2))
{ error( "%Llaw '%s': type %T cannot be used in parameter %s\n",
id, bvs->_1._2,bvs->_1._1);
}
found = true; pr("%t",bvs->_1._2,bvs->_1._1);
bvs =
#line 330 "../../prop-src/lawgen.pcc"
#line 330 "../../prop-src/lawgen.pcc"
nil_1_
#line 330 "../../prop-src/lawgen.pcc"
#line 330 "../../prop-src/lawgen.pcc"
;
}
else
bvs = bvs->_2;
#line 334 "../../prop-src/lawgen.pcc"
} else { goto L9; }
}
L9:;
}
#line 335 "../../prop-src/lawgen.pcc"
#line 335 "../../prop-src/lawgen.pcc"
if (! found)
error( "%Llaw '%s': bound variable '%s' is absent in body %e\n",
id, args->_1, exp);
args = args->_2;
comma = true;
write_mode = mode_save;
#line 342 "../../prop-src/lawgen.pcc"
} else { goto L8; }
}
L8:;
}
#line 343 "../../prop-src/lawgen.pcc"
#line 343 "../../prop-src/lawgen.pcc"
// Generate the body
pr(")%^{ return %e; }\n\n", exp);
}
#line 348 "../../prop-src/lawgen.pcc"
/*
------------------------------- Statistics -------------------------------
Merge matching rules = yes
Number of DFA nodes merged = 141
Number of ifs generated = 20
Number of switches generated = 10
Number of labels = 7
Number of gotos = 17
Adaptive matching = disabled
Fast string matching = disabled
Inline downcasts = disabled
--------------------------------------------------------------------------
*/
| [
"[email protected]"
] | [
[
[
1,
797
]
]
] |
b9b4f96017e61c5890cfc906e8e57cbaf9d0b744 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/ipappprotocols/sip/common/inc/DataWrapperBase.h | f15279f1adbf74b2e2856fde35fcb200247ff8ca | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,688 | h | /*
* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
// This contains CDataWrapperBase
#if (!defined __DATA_WRAPPER_BASE__)
#define __DATA_WRAPPER_BASE__
// EPOC includes
#include <sipprofiletypeinfo.h>
#include <datawrapper.h>
class CDataWrapperBase : public CDataWrapper
{
public:
TBool GetBoolFromConfig(const TDesC& aSectName,const TDesC& aKeyName,TBool& aResult);
TBool GetIntFromConfig(const TDesC& aSectName, const TDesC& aKeyName, TInt& aResult);
TBool GetTUint32FromConfig(const TDesC& aSectName, const TDesC& aKeyName, TUint32& aResult);
TBool GetTUintFromConfig(const TDesC& aSectName, const TDesC& aKeyName, TUint& aResult);
TBool GetStringFromConfig(const TDesC& aSectName, const TDesC& aKeyName, TPtrC& aResult);
TBool GetHexFromConfig(const TDesC& aSectName, const TDesC& aKeyName, TInt& aResult);
virtual void InitialiseL();
inline RFs& FileServer() { return iFs; }
protected:
CDataWrapperBase();
virtual ~CDataWrapperBase();
private:
TBool GetCommandStringParameterL(const TDesC& aSectName, const TDesC& aKeyName, TPtrC& aResult);
private:
// Included ini files
RPointerArray<CIniData> iInclude;
RPointerArray<HBufC> iBuffer;
RFs iFs;
};
#endif /* __DATA_WRAPPER_BASE__ */
| [
"none@none"
] | [
[
[
1,
56
]
]
] |
b8a9e6223b82292469c6bc7af024833a15925edf | 06b233dece20cff0b92fbf3c6805d328f1176ef0 | /audit/audit/src/monitor_filter.cpp | 62509de3f1440de5add0dfed85067b021d4c96ca | [] | no_license | bsv/r245 | 589e4bb95310c7cfff90353afb148cdf08dccc4d | 754a33ab882c443f9103910b07fd45c2d4e2ce7b | refs/heads/master | 2021-01-18T11:02:02.340546 | 2011-06-27T09:30:14 | 2011-06-27T09:30:14 | 783,841 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 5,607 | cpp | #include "monitor_filter.h"
#include "monitor.h"
MonitorFilter::MonitorFilter(QObject *parent):QSortFilterProxyModel(parent)
{
trans_code_rexp = QRegExp("");
}
/**
* Является перегруженной функцией класса QSortFilterProxyModel.
* Отвечает за проверку каждой строки модели на соответствие условиям фильтрации.
*
* @return true, если строка удовлетворяет параметрам фильтрации, false, если не удовлетворяет.
*/
bool MonitorFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
qApp->processEvents(); // чтоб интерфейс не зависал
QModelIndex dev_name_indx = sourceModel()->index(sourceRow, Monitor::DevNameAttr, sourceParent);
QModelIndex dev_num_indx = sourceModel()->index(sourceRow, Monitor::DevNumAttr, sourceParent);
QModelIndex ch_indx = sourceModel()->index(sourceRow, Monitor::ChAttr, sourceParent);
QModelIndex tag_name_indx = sourceModel()->index(sourceRow, Monitor::TagNameAttr, sourceParent);
QModelIndex tag_id_indx = sourceModel()->index(sourceRow, Monitor::TagIdAttr, sourceParent);
QModelIndex date_indx = sourceModel()->index(sourceRow, Monitor::DateAttr, sourceParent);
QModelIndex time_indx = sourceModel()->index(sourceRow, Monitor::TimeAttr, sourceParent);
QModelIndex trans_code_indx = sourceModel()->index(sourceRow, Monitor::TransCodeAttr, sourceParent);
QModelIndex event_indx = sourceModel()->index(sourceRow, Monitor::TypeEventAttr, sourceParent);
return (sourceModel()->data(dev_name_indx).toString().contains(deviceRegExp) ||
sourceModel()->data(dev_num_indx).toString().contains(deviceRegExp))
&& (sourceModel()->data(trans_code_indx).toString().contains(trans_code_rexp))
&& sourceModel()->data(ch_indx).toString().contains(channelRegExp)
&& sourceModel()->data(event_indx).toString().contains(event_reg_exp)
&& (sourceModel()->data(tag_name_indx).toString().contains(tagRegExp) ||
sourceModel()->data(tag_id_indx).toString().contains(tagRegExp))
&& dateInRange(QDate().fromString(sourceModel()->data(date_indx).toString(), Qt::LocalDate))
&& timeInRange(sourceModel()->data(time_indx).toTime());
}
/**
* Устанавливает регулярное выражение на фильтрацию кода события.
*
* @param reg_exp - регулярное выражение для фильтра.
*/
void MonitorFilter::setTransCodeRE(QString reg_exp)
{
trans_code_rexp = QRegExp(reg_exp);
}
/**
* Устанавливает нижнюю границу для даты.
*
* @param date - нижняя граница даты.
*/
void MonitorFilter::setFilterMinimumDate(const QDate date)
{
minDate = date;
}
/**
* Устанавливает верхнюю границу для даты.
*
* @param date - нижняя граница даты.
*/
void MonitorFilter::setFilterMaximumDate(const QDate date)
{
maxDate = date;
}
/**
* Устанавливает нижнюю границу времени.
*
* @param time - нижняя граница времени.
*/
void MonitorFilter::setFilterMinimumTime(const QTime time)
{
minTime = time;
}
/**
* Устанавливает верхнюю границу времени.
*
* @param time - нижняя граница времени.
*/
void MonitorFilter::setFilterMaximumTime(const QTime time)
{
maxTime = time;
}
/**
* Устанавливает регулярные выражения для фильтра канала, устройства и метки.
*
* @param channel - регулярное выражение для канала.
* @param device - регулярное выражение для идентификатора устройства (числового или символьного).
* @param tag - регулярное выражение для идентификатора метки (числового или символьного).
*/
void MonitorFilter::setRegExp(QRegExp channel, QRegExp device, QRegExp tag, QRegExp event)
{
channelRegExp = channel;
deviceRegExp = device;
tagRegExp = tag;
event_reg_exp = event;
}
/**
* Проверяет дату на соответствие заданному диапазону от
* minDate до maxDate.
*
* @param date - значение проверяемого значения даты.
* @return true, если значение date удовлетворяет
* заданному диапазону.
*/
bool MonitorFilter::dateInRange(const QDate &date) const
{
return (!minDate.isValid() || date >= minDate)
&& (!maxDate.isValid() || date <= maxDate);
}
/**
* Проверяет время на соответствие заданному диапазону от
* minTime до maxTime.
*
* @param time - значение проверяемого значения времени.
* @return true, если значение time удовлетворяет
* заданному диапазону.
*/
bool MonitorFilter::timeInRange(const QTime &time) const
{
return (!minTime.isValid() || time >= minTime)
&& (!maxTime.isValid() || time <= maxTime);
}
| [
"bsv@bsv-M50Vc.(none)"
] | [
[
[
1,
133
]
]
] |
ce3de74af1503ea39c52deff65abec9089357850 | cfcd2a448c91b249ea61d0d0d747129900e9e97f | /thirdparty/OpenCOLLADA/COLLADAFramework/include/COLLADAFWSampler.h | 7be13d9b2cf85fb0624853e62c0d020273f341a9 | [] | no_license | fire-archive/OgreCollada | b1686b1b84b512ffee65baddb290503fb1ebac9c | 49114208f176eb695b525dca4f79fc0cfd40e9de | refs/heads/master | 2020-04-10T10:04:15.187350 | 2009-05-31T15:33:15 | 2009-05-31T15:33:15 | 268,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,468 | h | /*
Copyright (c) 2008 NetAllied Systems GmbH
This file is part of COLLADAFramework.
Licensed under the MIT Open Source License,
for details please see LICENSE file or the website
http://www.opensource.org/licenses/mit-license.php
*/
#ifndef __COLLADAFW_SAMPLER_H__
#define __COLLADAFW_SAMPLER_H__
#include "COLLADAFWPrerequisites.h"
#include "COLLADAFWUniqueId.h"
#include "COLLADAFWColor.h"
#include "COLLADAFWPointerArray.h"
namespace COLLADAFW
{
/**
* Declares the storage for the graphical representation of an object.
* The samplerId is the array index position in the samplers array.
*/
class Sampler
{
public:
/** The different sampler types. */
enum SamplerType
{
SAMPLER_TYPE_UNSPECIFIED,
SAMPLER_TYPE_1D,
SAMPLER_TYPE_2D,
SAMPLER_TYPE_3D,
SAMPLER_TYPE_CUBE,
SAMPLER_TYPE_RECT,
SAMPLER_TYPE_DEPTH,
SAMPLER_TYPE_STATE
};
/** Contains the texture filter functions.*/
enum SamplerFilter
{
SAMPLER_FILTER_UNSPECIFIED,
SAMPLER_FILTER_NONE,
SAMPLER_FILTER_NEAREST,
SAMPLER_FILTER_LINEAR,
SAMPLER_FILTER_NEAREST_MIPMAP_NEAREST,
SAMPLER_FILTER_LINEAR_MIPMAP_NEAREST,
SAMPLER_FILTER_NEAREST_MIPMAP_LINEAR,
SAMPLER_FILTER_LINEAR_MIPMAP_LINEAR
};
/**
Contains the texture wrap modes.
Wrap modes that affect the interpretation of s, t, and p texture
coordinates in <sampler_*> elements. The wrap mode enums map to the
following OpenGL symbols.*/
enum WrapMode
{
WRAP_MODE_UNSPECIFIED=0,
// NONE == GL_CLAMP_TO BORDER The defined behavior for NONE is
// consistent with decal texturing where the border is black.
// Mapping this calculation to GL_CLAMP_TO_BORDER is the best
// approximation of this.
WRAP_MODE_NONE,
// WRAP == GL_REPEAT Ignores the integer part of texture coordinates,
// using only the fractional part.
WRAP_MODE_WRAP,
// MIRROR == GL_MIRRORED_REPEAT First mirrors the texture coordinate.
// The mirrored coordinate is then clamped as described for CLAMP_TO_EDGE.
WRAP_MODE_MIRROR,
// CLAMP == GL_CLAMP_TO_EDGE Clamps texture coordinates at all
// mipmap levels such that the texture filter never samples a
// border texel. Note: GL_CLAMP takes any texels beyond the
// sampling border and substitutes those texels with the border
// color. So CLAMP_TO_EDGE is more appropriate. This also works
// much better with OpenGL ES where the GL_CLAMP symbol was removed
// from the OpenGL ES specification.
WRAP_MODE_CLAMP,
// BORDER GL_CLAMP_TO_BORDER Clamps texture coordinates at all
// MIPmaps such that the texture filter always samples border
// texels for fragments whose corresponding texture coordinate
// is sufficiently far outside the range [0, 1].
WRAP_MODE_BORDER
};
private:
/** The type of the current sampler. */
SamplerType mSamplerType;
/** The unique id of the image used as source for this sampler */
UniqueId mSourceImageUniqueId;
/** Texture minimization. Enumerated type fx_sampler_filter_common.
Applying a texture to a primitive implies a mapping from texture image
space to framebuffer image space. In general, this mapping involves
a reconstruction of the sampled texture image, followed by a
homogeneous warping implied by the mapping to framebuffer space, then a
filtering, followed finally by a resampling of the filtered, warped,
reconstructed image before applying it to a fragment. */
SamplerFilter mMinFilter;
/** Texture magnification. Enumerated type fx_sampler_filter_common.
When gamma indicates magnification, this value determines how the
texture value is obtained. */
SamplerFilter mMagFilter;
/** MIPmap filter. Enumerated type fx_sampler_filter_common. */
SamplerFilter mMipFilter;
/** Wrap modes */
WrapMode mWrapS;
WrapMode mWrapT;
WrapMode mWrapP;
/** When reading past the edge of the texture address space based on
the wrap modes involving clamps, this color takes over. Type
fx_color_common (four floating-point numbers in RGBA order). */
Color mBorderColor;
/** An xs:unsignedByte, which is the maximum number of progressive
levels that the sampler will evaluate. */
unsigned char mMipmapMaxlevel;
/** An xs:float, which biases the gamma (level of detail parameter)
that is used by the sampler to evaluate the MIPmap chain. */
float mMipmapBias;
public:
/** Constructor. */
Sampler();
/** Destructor. */
virtual ~Sampler();
/** Returns the sampler type. */
SamplerType getSamplerType ( ) { return mSamplerType; }
/** Set the sampler type. */
void setSamplerType ( SamplerType samplerType ) { mSamplerType = samplerType; }
/** Returns the unique id of the image used as source for this sampler */
const UniqueId& getSourceImage () const { return mSourceImageUniqueId; }
/** Returns the unique id of the image used as source for this sampler */
void setSource ( const UniqueId& sourceImageUniqueId ) { mSourceImageUniqueId = sourceImageUniqueId; }
/** Returns min filter*/
SamplerFilter getMinFilter() const { return mMinFilter; }
/** Sets the min filter. */
void setMinFilter ( SamplerFilter minFilter ) { mMinFilter = minFilter; }
/** Returns mag filter*/
SamplerFilter getMagFilter() const { return mMagFilter; }
/** Sets the mag filter. */
void setMagFilter ( SamplerFilter magFilter ) { mMagFilter = magFilter; }
/** Returns mip filter*/
SamplerFilter getMipFilter() const { return mMipFilter; }
/** Sets the mip filter. */
void setMipFilter ( SamplerFilter mipFilter ) { mMipFilter = mipFilter; }
/** Returns the wrap mode in dimension S.*/
WrapMode getWrapS() const { return mWrapS; }
/** Sets the wrap mode in dimension S.*/
void setWrapS ( WrapMode wrapS ) { mWrapS = wrapS; }
/** Returns the wrap mode in dimension T.*/
WrapMode getWrapT() const { return mWrapT; }
/** Sets the wrap mode in dimension T.*/
void setWrapT ( WrapMode wrapT ) { mWrapT = wrapT; }
/** Returns the wrap mode in dimension P*/
WrapMode getWrapP() const { return mWrapP; }
/** Sets the wrap mode in dimension P.*/
void setWrapP ( WrapMode wrapP ) { mWrapP = wrapP; }
/** Returns the border color. */
const Color& getBorderColor () const { return mBorderColor; }
/** Sets the border color. */
void setBorderColor ( const Color& borderColor ) { mBorderColor = borderColor; }
/** Returns the maximum number of progressive levels that the sampler will evaluate. */
unsigned char getMipmapMaxlevel () const { return mMipmapMaxlevel; }
/** Sets the maximum number of progressive levels that the sampler will evaluate. */
void setMipmapMaxlevel ( unsigned char mipmapMaxlevel ) { mMipmapMaxlevel = mipmapMaxlevel; }
/** Returns the mipmap Bias.*/
float getMipmapBias () const { return mMipmapBias; }
/** Returns the mipmap Bias.*/
void setMipmapBias ( float mipmapBias ) { mMipmapBias = mipmapBias; }
Sampler* clone() { return FW_NEW Sampler(*this); }
};
/**
* The samplerId is the array index position in the samplers array.
*/
typedef PointerArray<Sampler> SamplerPointerArray;
} // namespace COLLADAFW
#endif // __COLLADAFW_SAMPLER_H__
| [
"[email protected]"
] | [
[
[
1,
219
]
]
] |
1424490a963a076d2a1f45499d79909ca2df9869 | dcf9094fb3ad72896f9e8429be93a948c39fa8ea | /test/main.cpp | c74cb5298fdfaba02a6fa7f5b3be1abd1f8b10b7 | [] | no_license | mega-t72/vc | c1335fe18af07ad55d0549d6bbff2eeb48a72cf2 | 95528a52dddcbb065d01316ac91b61e077873c19 | refs/heads/master | 2021-01-01T19:25:44.963454 | 2011-09-26T04:08:29 | 2011-09-26T04:08:29 | 733,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 163 | cpp | //////////////
// main.cpp
//
#include <tchar.h>
//
int _tmain( int argc, _TCHAR*argv[], _TCHAR*envp[] ){
_tprintf( _T("Hello world!\r\n") );
return 0;
} | [
"[email protected]"
] | [
[
[
1,
9
]
]
] |
c3d9d88214e2d79201b55942307ec590169d3a8f | 6114db1d18909e8d38365a81ab5f0b1221c6d479 | /Sources/AsProfiled/stdafx.h | 0b2d4bf8e4b69faee7157f11256b044ddd58e0da | [] | no_license | bitmizone/asprofiled | c6bf81e89037b68d0a7c8a981be3cd9c8a4db7c7 | b54cb47b1d3ee1ce6ad7077960394ddd5578c0ff | refs/heads/master | 2021-01-10T14:14:42.048633 | 2011-06-21T11:38:26 | 2011-06-21T11:38:26 | 48,724,442 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 659 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently
#pragma once
#ifndef STRICT
#define STRICT
#endif
#include "targetver.h"
#define _ATL_APARTMENT_THREADED
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <afxwin.h>
#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdisp.h> // MFC Automation classes
#endif // _AFX_NO_OLE_SUPPORT
#include "resource.h"
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
using namespace ATL;
| [
"adamsonic@cf2cc628-70ab-11de-90d8-1fdda9445408"
] | [
[
[
1,
28
]
]
] |
95b6fd2cba89c97fbb583b853fe6f82487f61ee5 | 0b55a33f4df7593378f58b60faff6bac01ec27f3 | /Konstruct/Common/Graphics/kpgTexture.cpp | 1ce9cec983185a3f3b5912a52d1ae647bf68fff2 | [] | no_license | RonOHara-GG/dimgame | 8d149ffac1b1176432a3cae4643ba2d07011dd8e | bbde89435683244133dca9743d652dabb9edf1a4 | refs/heads/master | 2021-01-10T21:05:40.480392 | 2010-09-01T20:46:40 | 2010-09-01T20:46:40 | 32,113,739 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,235 | cpp | #include "StdAfx.h"
#include "Common\Graphics\kpgTexture.h"
#include "Common\Graphics\kpgRenderer.h"
#include "Common\Utility\kpuFileManager.h"
#include <d3dx9tex.h>
kpgTexture::kpgTexture(void)
{
m_pTexture = 0;
m_szFilename = 0;
}
kpgTexture::~kpgTexture(void)
{
if( m_szFilename )
free(m_szFilename);
if( m_pTexture )
m_pTexture->Release();
}
bool kpgTexture::Load(const char* szFilename)
{
m_szFilename = _strdup(szFilename);
// Grab the full filename
char szFullPath[512];
if( !kpuFileManager::GetFullFilePath(szFilename, szFullPath, sizeof(szFullPath)) )
return false;
// Create the texture
kpgRenderer* pRenderer = kpgRenderer::GetInstance();
if( D3DXCreateTextureFromFile(pRenderer->GetDevice(), szFullPath, &m_pTexture) != D3D_OK )
return false;
IDirect3DSurface9* pSurface;
if( m_pTexture->GetSurfaceLevel(0, &pSurface) != D3D_OK )
{
m_pTexture->Release();
m_pTexture = 0;
return false;
}
D3DSURFACE_DESC desc;
if( pSurface->GetDesc(&desc) != D3D_OK )
{
pSurface->Release();
m_pTexture->Release();
m_pTexture = 0;
return false;
}
pSurface->Release();
m_unWidth = desc.Width;
m_unHeight = desc.Height;
return true;
} | [
"acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e"
] | [
[
[
1,
57
]
]
] |
ce0e9499351322019b7c35b83db03244dcec8d7e | ab41c2c63e554350ca5b93e41d7321ca127d8d3a | /glm/GLM_GTX_color_space_YCoCg.h | f0cb8cafd6ebb6eaab633e351de8e06e6b873534 | [] | no_license | burner/e3rt | 2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e | 775470cc9b912a8c1199dd1069d7e7d4fc997a52 | refs/heads/master | 2021-01-11T08:08:00.665300 | 2010-04-26T11:42:42 | 2010-04-26T11:42:42 | 337,021 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 701 | h | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2008 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2008-11-28
// Updated : 2008-11-28
// Licence : This source is under MIT License
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef glm_gtx_color_space_YCoCg_api
#define glm_gtx_color_space_YCoCg_api
#include "gtx/color_space_YCoCg.hpp"
namespace glm
{
using GLM_GTX_color_space_YCoCg;
}
#endif//glm_gtx_color_space_YCoCg_api
| [
"[email protected]"
] | [
[
[
1,
19
]
]
] |
f6bd30769460460ec11572c44865e5ebbfd110e0 | f9351a01f0e2dec478e5b60c6ec6445dcd1421ec | /itl/libs/itl/test/test_interval_set/test_interval_set_shared.cpp | 6a5317faacc49c8bd3efd47a2ab77fec1c5fe47e | [
"BSL-1.0"
] | permissive | WolfgangSt/itl | e43ed68933f554c952ddfadefef0e466612f542c | 6609324171a96565cabcf755154ed81943f07d36 | refs/heads/master | 2016-09-05T20:35:36.628316 | 2008-11-04T11:44:44 | 2008-11-04T11:44:44 | 327,076 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,166 | cpp | /*----------------------------------------------------------------------------+
Copyright (c) 2008-2008: Joachim Faulhaber
+-----------------------------------------------------------------------------+
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENCE.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
+----------------------------------------------------------------------------*/
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_fundamentals_4_ordered_types, T, ordered_types)
{ interval_set_fundamentals_4_ordered_types<interval_set, T>();}
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_ctor_4_bicremental_types, T, bicremental_types)
{ interval_set_ctor_4_bicremental_types<interval_set, T>();}
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_add_sub_4_bicremental_types, T, bicremental_types)
{ interval_set_add_sub_4_bicremental_types<interval_set, T>();}
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_distinct_4_bicremental_types, T, bicremental_types)
{ interval_set_distinct_4_bicremental_types<interval_set, T>();}
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_distinct_4_bicremental_continuous_types, T, bicremental_continuous_types)
{ interval_set_distinct_4_bicremental_continuous_types<interval_set, T>();}
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_isolate_4_bicremental_continuous_types, T, bicremental_continuous_types)
{ interval_set_isolate_4_bicremental_continuous_types<interval_set, T>();}
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_contains_4_bicremental_types, T, bicremental_types)
{ interval_set_contains_4_bicremental_types<interval_set, T>();}
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_operators_4_bicremental_types, T, bicremental_types)
{ interval_set_operators_4_bicremental_types<interval_set, T>();}
BOOST_AUTO_TEST_CASE_TEMPLATE
(test_itl_interval_set_base_intersect_4_bicremental_types, T, bicremental_types)
{ interval_set_base_intersect_4_bicremental_types<interval_set, T>();}
| [
"jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a"
] | [
[
[
1,
44
]
]
] |
0fe5110f04032e597edd10b52ec7b3ae1a7825c7 | c70941413b8f7bf90173533115c148411c868bad | /core/src/vtxDynLib.cpp | 36660535713425cc6fe690004e8134346c8c76df | [] | no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,930 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
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 "vtxDynLib.h"
#include "vtxLogManager.h"
namespace vtx
{
//-----------------------------------------------------------------------
#if VTX_OS == VTX_WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#if VTX_OS == VTX_APPLE
#include "macPlugins.h"
#endif
//-----------------------------------------------------------------------
DynLib::DynLib(const String& name)
: mName(name),
mInstance(NULL)
{
}
//-----------------------------------------------------------------------
DynLib::~DynLib()
{
}
//-----------------------------------------------------------------------
void DynLib::load()
{
VTX_LOG("Loading dynamic library \"%s\"", mName.c_str());
String name = mName;
#if VTX_OS == VTX_LINUX
// on linux add .so
if (name.substr(name.length() - 3, 3) != ".so")
{
name += ".so";
}
#endif
mInstance = (DYNLIB_HANDLE)DYNLIB_LOAD(name.c_str());
if(!mInstance)
{
VTX_EXCEPT("Unable to load dynamic library \"%s\"\n(\"%s\")", mName.c_str(), getError().c_str());
}
}
//-----------------------------------------------------------------------
void DynLib::unload()
{
if(DYNLIB_UNLOAD(mInstance))
{
VTX_EXCEPT("Unable to unload dynamic library \"%s\"\n(\"%s\")", mName.c_str(), getError().c_str());
}
}
//-----------------------------------------------------------------------
const String& DynLib::getName() const
{
return mName;
}
//-----------------------------------------------------------------------
void* DynLib::getSymbol(const String& name) const throw()
{
return (void*)DYNLIB_GETSYM(mInstance, name.c_str());
}
//-----------------------------------------------------------------------
String DynLib::getError()
{
#if VTX_OS == VTX_WIN32
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL
);
String ret = (char*)lpMsgBuf;
// remove line break
ret = ret.substr(0, ret.length()-2);
LocalFree(lpMsgBuf);
return ret;
#elif VTX_OS == VTX_LINUX
return String(dlerror());
#elif VTX_OS == VTX_APPLE
return String(mac_errorBundle());
#else
return String("");
#endif
}
//-----------------------------------------------------------------------
}
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
] | [
[
[
1,
129
]
]
] |
f538ff20c205d8f2c03e3a161e5eb76557ecac2a | f13f46fbe8535a7573d0f399449c230a35cd2014 | /JelloMan/MainGame.h | adc6509179e725aff94d0bc8fe01046e162a986d | [] | no_license | fangsunjian/jello-man | 354f1c86edc2af55045d8d2bcb58d9cf9b26c68a | 148170a4834a77a9e1549ad3bb746cb03470df8f | refs/heads/master | 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,254 | h | #include "D3DUtil.h"
#include "PhysX.h"
#include "Controls.h"
#include "Blox2D.h"
#include "GameConfig.h"
#include "Level.h"
#include "RenderContext.h"
#include "FlyCamera.h"
#include "FollowCamera.h"
#include "Sound.h"
#include "LightController.h"
#include "Matrix.h"
#include <vector>
#include "Editor.h"
#include "PostProcessor.h"
#include "EdgeDetectionPostEffect.h"
#include "DeferredRenderer.h"
#include "ForwardRenderer.h"
#include "SSAOPostEffect.h"
#pragma warning(disable:4005)
#include "boost\thread\thread.hpp"
#pragma warning(default:4005)
class AudioEngine;
class MainGame
{
public:
// CONSTRUCTOR - DESTRUCTOR
MainGame();
virtual ~MainGame();
// GENERAL
void Initialize(GameConfig& refGameConfig);
void LoadResources(ID3D10Device* pDXDevice);
void UpdateScene(const float dTime);
void DrawScene();
void CheckControls();
void OnResize(ID3D10RenderTargetView* pRTView);
void Release();
void LoadScreen();
bool ResourcesLoaded()
{ return m_bResourcesLoaded; }
private:
void UpdatePhysics();
// DATAMEMBERS
float m_dTtime;
bool m_bResourcesLoaded;
bool m_bDebug;
int m_Orbs;
tstring m_LoadingText;
float m_AlphaHappyFace;
TextFormat* m_pDefaultFont;
TextFormat* m_pHappyFaceFont;
TextFormat* m_pLoadingResourcesFont;
TextFormat* m_pHappyEngineFont;
Editor* m_pEditorGUI;
Level* m_pLevel;
Graphics::Camera::FlyCamera* m_pEditorCamera;
Graphics::Camera::FollowCamera* m_pTrackingCamera;
LightController* m_pLightController;
AudioEngine* m_pAudioEngine;
Sound* m_pTestSound;
PhysX* m_pPhysXEngine;
RenderContext* m_pRenderContext;
DeferredRenderer* m_pDeferredRenderer;
ForwardRenderer* m_pForwardRenderer;
PostProcessor* m_pPostProcessor;
PostProcessor* m_pSSAOProcessor;
EdgeDetectionPostEffect* m_pEdgeDetectionEffect;
SSAOPostEffect* m_pSSAOEffect;
// PHYSX - THREADING
boost::thread m_PhysXThread;
boost::mutex m_DTimeLock;
bool m_bRunning;
GameTimer m_PhysXTimer;
float m_PhysXDTime;
float m_PhysXTimeBase;
// Disable default copy constructor and assignment operator
MainGame(const MainGame&);
MainGame& operator=(const MainGame&);
}; | [
"[email protected]",
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6"
] | [
[
[
1,
2
],
[
4,
8
],
[
11,
11
],
[
13,
25
],
[
27,
34
],
[
36,
38
],
[
40,
73
],
[
76,
76
],
[
78,
83
],
[
86,
102
],
[
107,
107
]
],
[
[
3,
3
],
[
9,
10
],
[
12,
12
],
[
26,
26
],
[
35,
35
],
[
39,
39
],
[
74,
75
],
[
77,
77
],
[
84,
85
],
[
103,
106
]
]
] |
1ec6b7f2fb839b229c7a8975abb8410a81d51a71 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/validators/schema/identity/XPathSymbols.cpp | 0e122b837f34c78e881f52105047321fed8b73f9 | [] | 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 | 4,854 | cpp | /*
* Copyright 2001,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: XPathSymbols.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/validators/schema/identity/XPathSymbols.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// SchemaSymbols: Static data
// ---------------------------------------------------------------------------
const XMLCh XPathSymbols::fgSYMBOL_AND[] =
{
chLatin_a, chLatin_n, chLatin_d, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_OR[] =
{
chLatin_o, chLatin_r, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_MOD[] =
{
chLatin_m, chLatin_o, chLatin_d, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_DIV[] =
{
chLatin_d, chLatin_i, chLatin_v, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_COMMENT[] =
{
chLatin_c, chLatin_o, chLatin_m, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_TEXT[] =
{
chLatin_t, chLatin_e, chLatin_x, chLatin_t, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_PI[] =
{
chLatin_p, chLatin_r, chLatin_o, chLatin_c, chLatin_e, chLatin_s, chLatin_s,
chLatin_i, chLatin_n, chLatin_g, chDash, chLatin_i, chLatin_n, chLatin_s, chLatin_t,
chLatin_r, chLatin_u, chLatin_c, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_NODE[] =
{
chLatin_n, chLatin_o, chLatin_d, chLatin_e, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_ANCESTOR[] =
{
chLatin_a, chLatin_n, chLatin_c, chLatin_e, chLatin_s, chLatin_t, chLatin_o,
chLatin_r, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_ANCESTOR_OR_SELF[] =
{
chLatin_a, chLatin_n, chLatin_c, chLatin_e, chLatin_s, chLatin_t, chLatin_o,
chLatin_r, chDash, chLatin_o, chLatin_r, chDash, chLatin_s, chLatin_e,
chLatin_l, chLatin_f, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_ATTRIBUTE[] =
{
chLatin_a, chLatin_t, chLatin_t, chLatin_r, chLatin_i, chLatin_b, chLatin_u,
chLatin_t, chLatin_e, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_CHILD[] =
{
chLatin_c, chLatin_h, chLatin_i, chLatin_l, chLatin_d, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_DESCENDANT[] =
{
chLatin_d, chLatin_e, chLatin_s, chLatin_c, chLatin_e, chLatin_n, chLatin_d,
chLatin_a, chLatin_n, chLatin_t, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_DESCENDANT_OR_SELF[] =
{
chLatin_d, chLatin_e, chLatin_s, chLatin_c, chLatin_e, chLatin_n, chLatin_d,
chLatin_a, chLatin_n, chLatin_t, chDash, chLatin_o, chLatin_r, chDash, chLatin_s,
chLatin_e, chLatin_l, chLatin_f, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_FOLLOWING[] =
{
chLatin_f, chLatin_o, chLatin_l, chLatin_l, chLatin_o, chLatin_w, chLatin_i,
chLatin_n, chLatin_g, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_FOLLOWING_SIBLING[] =
{
chLatin_f, chLatin_o, chLatin_l, chLatin_l, chLatin_o, chLatin_w, chLatin_i,
chLatin_n, chLatin_g, chDash, chLatin_s, chLatin_i, chLatin_b, chLatin_l, chLatin_i,
chLatin_n, chLatin_g, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_NAMESPACE[] =
{
chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chLatin_p, chLatin_a,
chLatin_c, chLatin_e, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_PARENT[] =
{
chLatin_p, chLatin_a, chLatin_r, chLatin_e, chLatin_n, chLatin_t, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_PRECEDING[] =
{
chLatin_p, chLatin_r, chLatin_e, chLatin_c, chLatin_e, chLatin_d, chLatin_i,
chLatin_n, chLatin_g, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_PRECEDING_SIBLING[] =
{
chLatin_p, chLatin_r, chLatin_e, chLatin_c, chLatin_e, chLatin_d, chLatin_i,
chLatin_n, chLatin_g, chDash, chLatin_s, chLatin_i, chLatin_b, chLatin_l, chLatin_i,
chLatin_n, chLatin_g, chNull
};
const XMLCh XPathSymbols::fgSYMBOL_SELF[] =
{
chLatin_s, chLatin_e, chLatin_l, chLatin_f, chNull
};
XERCES_CPP_NAMESPACE_END
/**
* End of file XPathSymbols.cpp
*/
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
160
]
]
] |
7d9dadf6d3f41b910379b17011e6d2f973482795 | 1e5a2230acf1c2edfe8b9d226100438f9374e98a | /src/tabimswitch/Win32Error.h | e5f13984341f0c8b9e72efba5db62e207a8c1d20 | [] | no_license | lifanxi/tabimswitch | 258860fea291c935d3630abeb61436e20f5dcd09 | f351fc4b04983e59d1ad2b91b85e396e1f4920ed | refs/heads/master | 2020-05-20T10:53:41.990172 | 2008-10-15T11:15:41 | 2008-10-15T11:15:41 | 32,111,854 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,616 | h | #ifndef _WIN32_ERROR_H_
#define _WIN32_ERROR_H_
#include <windows.h>
#include <wchar.h>
class Win32Error
{
public:
~Win32Error(void) { reset(); }
Win32Error(void) : m_errCode(::GetLastError()), m_pszErrorMsg(NULL), m_pwszErrorMsg(NULL) {}
Win32Error(DWORD error) : m_errCode(error), m_pszErrorMsg(NULL), m_pwszErrorMsg(NULL) { }
Win32Error(HRESULT hr) : m_errCode(HRESULT_TO_WIN32ERROR(hr)), m_pszErrorMsg(NULL), m_pwszErrorMsg(NULL) {}
Win32Error(int winsockError) : m_errCode(winsockError), m_pszErrorMsg(NULL), m_pwszErrorMsg(NULL) {}
void setErrorCode(DWORD win32Error) { m_errCode = win32Error; reset(); }
void setHResult(HRESULT hr) { m_errCode = HRESULT_TO_WIN32ERROR(hr); reset(); }
DWORD getErrorCode(void) const { return m_errCode; }
HRESULT getHResult(void) const { return HRESULT_FROM_WIN32(m_errCode); }
char const* getString()
{
if ( m_pszErrorMsg == NULL )
{
DWORD ret = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, m_errCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&m_pszErrorMsg, 0, NULL );
if ( ret == 0 )
m_pszErrorMsg = NULL;
else
{
char* pCRLF = strrchr(m_pszErrorMsg, '\r');
if ( ! pCRLF )
pCRLF = strrchr(m_pszErrorMsg, '\n');
if ( ! pCRLF )
*pCRLF = '\0';
}
}
return m_pszErrorMsg;
}
wchar_t const* getWString()
{
if ( m_pwszErrorMsg == NULL )
{
DWORD ret = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, m_errCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&m_pwszErrorMsg, 0, NULL );
if ( ret == 0 )
m_pwszErrorMsg = NULL;
else
{
char* pCRLF = strrchr(m_pszErrorMsg, L'\r');
if ( ! pCRLF )
pCRLF = strrchr(m_pszErrorMsg, L'\n');
if ( ! pCRLF )
*pCRLF = L'\0';
}
}
return m_pwszErrorMsg;
}
private:
DWORD m_errCode;
LPSTR m_pszErrorMsg;
LPWSTR m_pwszErrorMsg;
private:
//
// An "It just works" solution, refer to
// http://blogs.msdn.com/oldnewthing/archive/2006/11/03/942851.aspx
//
static DWORD HRESULT_TO_WIN32ERROR(HRESULT hRes)
{
DWORD win32error;
if ( WIN32_FROM_HRESULT(hRes, &win32error) )
return win32error;
else
return hRes;
}
static BOOL WIN32_FROM_HRESULT(HRESULT hr, OUT DWORD *pdwWin32)
{
if ((hr & 0xFFFF0000) == MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0)) {
// Could have come from many values, but we choose this one
*pdwWin32 = HRESULT_CODE(hr);
return TRUE;
}
if (hr == S_OK) {
*pdwWin32 = HRESULT_CODE(hr);
return TRUE;
}
// otherwise, we got an impossible value
return FALSE;
}
void reset(void)
{
if ( m_pszErrorMsg )
::LocalFree((HLOCAL)m_pszErrorMsg);
m_pszErrorMsg = NULL;
if ( m_pwszErrorMsg )
::LocalFree((HLOCAL)m_pwszErrorMsg);
m_pwszErrorMsg = NULL;
}
};
#endif // _WIN32_ERROR_H_
| [
"ftofficer.zhangc@237747d1-5336-0410-8d3f-2982d197fc3e"
] | [
[
[
1,
117
]
]
] |
661656f129a4b5253c8b85c87d683d349eb0a376 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlCapsule3.h | 649ff5fde1262b7fe4befd7c9940eaef7c336c4a | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,023 | h | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifndef WMLCAPSULE3_H
#define WMLCAPSULE3_H
#include "WmlSegment3.h"
namespace Wml
{
template <class Real>
class WML_ITEM Capsule3
{
public:
Capsule3 ();
Vector3<Real>& Origin ();
const Vector3<Real>& Origin () const;
Vector3<Real>& Direction ();
const Vector3<Real>& Direction () const;
Real& Radius ();
const Real& Radius () const;
Segment3<Real>& Segment ();
const Segment3<Real>& Segment () const;
protected:
Segment3<Real> m_kSegment;
Real m_fRadius;
};
typedef Capsule3<float> Capsule3f;
typedef Capsule3<double> Capsule3d;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
47
]
]
] |
32baf4c3a1ce8868c3fccef2ba087a27879e4285 | 2f72d621e6ec03b9ea243a96e8dd947a952da087 | /src/DynamicLines.cpp | 841e5e0c590b76cf316a37c73d51222b45f36b68 | [] | no_license | gspu/lol4fg | 752358c3c3431026ed025e8cb8777e4807eed7a0 | 12a08f3ef1126ce679ea05293fe35525065ab253 | refs/heads/master | 2023-04-30T05:32:03.826238 | 2011-07-23T23:35:14 | 2011-07-23T23:35:14 | 364,193,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,110 | cpp | #include "DynamicLines.h"
#include <Ogre.h>
#include <cassert>
#include <cmath>
using namespace Ogre;
enum {
POSITION_BINDING,
TEXCOORD_BINDING
};
DynamicLines::DynamicLines(OperationType opType)
{
initialize(opType,false);
setMaterial("BaseWhiteNoLighting");
mDirty = true;
}
DynamicLines::~DynamicLines()
{
}
void DynamicLines::setOperationType(OperationType opType)
{
mRenderOp.operationType = opType;
}
RenderOperation::OperationType DynamicLines::getOperationType() const
{
return mRenderOp.operationType;
}
void DynamicLines::addPoint(const Vector3 &p)
{
mPoints.push_back(p);
mDirty = true;
}
void DynamicLines::addPoint(Real x, Real y, Real z)
{
mPoints.push_back(Vector3(x,y,z));
mDirty = true;
}
const Vector3& DynamicLines::getPoint(unsigned short index) const
{
assert(index < mPoints.size() && "Point index is out of bounds!!");
return mPoints[index];
}
unsigned short DynamicLines::getNumPoints(void) const
{
return (unsigned short)mPoints.size();
}
void DynamicLines::setPoint(unsigned short index, const Vector3 &value)
{
assert(index < mPoints.size() && "Point index is out of bounds!!");
mPoints[index] = value;
mDirty = true;
}
void DynamicLines::clear()
{
mPoints.clear();
mDirty = true;
}
void DynamicLines::update()
{
if (mDirty) fillHardwareBuffers();
}
void DynamicLines::createVertexDeclaration()
{
VertexDeclaration *decl = mRenderOp.vertexData->vertexDeclaration;
decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION);
}
void DynamicLines::fillHardwareBuffers()
{
int size = mPoints.size();
prepareHardwareBuffers(size,0);
if (!size) {
mBox.setExtents(Vector3::ZERO,Vector3::ZERO);
mDirty=false;
return;
}
Vector3 vaabMin = mPoints[0];
Vector3 vaabMax = mPoints[0];
HardwareVertexBufferSharedPtr vbuf =
mRenderOp.vertexData->vertexBufferBinding->getBuffer(0);
Real *prPos = static_cast<Real*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
{
for(int i = 0; i < size; i++)
{
*prPos++ = mPoints[i].x;
*prPos++ = mPoints[i].y;
*prPos++ = mPoints[i].z;
if(mPoints[i].x < vaabMin.x)
vaabMin.x = mPoints[i].x;
if(mPoints[i].y < vaabMin.y)
vaabMin.y = mPoints[i].y;
if(mPoints[i].z < vaabMin.z)
vaabMin.z = mPoints[i].z;
if(mPoints[i].x > vaabMax.x)
vaabMax.x = mPoints[i].x;
if(mPoints[i].y > vaabMax.y)
vaabMax.y = mPoints[i].y;
if(mPoints[i].z > vaabMax.z)
vaabMax.z = mPoints[i].z;
}
}
vbuf->unlock();
mBox.setExtents(vaabMin, vaabMax);
mDirty = false;
}
/*
void DynamicLines::getWorldTransforms(Matrix4 *xform) const
{
// return identity matrix to prevent parent transforms
*xform = Matrix4::IDENTITY;
}
*/
/*
const Quaternion &DynamicLines::getWorldOrientation(void) const
{
return Quaternion::IDENTITY;
}
const Vector3 &DynamicLines::getWorldPosition(void) const
{
return Vector3::ZERO;
}
*/ | [
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
] | [
[
[
1,
142
]
]
] |
daf071e0f3a00691136d2b65165473212d34930c | 91bb2135a55f44aab607862c60d5c1def90b0736 | /main.cpp | 78eae7e03e8cc8bda3a68d45fead4dac8868df14 | [] | no_license | karronoli/AdaptiveBranchingFilter | 19a9db38fe8fa91958cb8ea338ba60cc3e046ac6 | 2af8640adc861cb983bca9e682a4a95c5b861e98 | refs/heads/master | 2016-09-05T18:15:13.088242 | 2010-02-17T11:29:42 | 2010-02-17T11:29:42 | 521,718 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 5,565 | cpp | /** \mainpage
* \Author アナログ・デバイセズ株式会社
* \date 2006.Sep.8
*
* このプログラムは、ADSP-BF537を搭載する評価基板、EZ-KIT BF537のデモ・プログラムである。
*
* ::main 関数を実行すると、各種の初期化を行い、割り込みハンドラ afw::rxISRを登録した後、
* 割り込みとDMAを許可してオーディオ信号の送受信を行う。オーディオ信号はSPORT0経由で入力
* し、DMAによってメモリ上に格納される。2次元DMAの各行が終わるたびにオーディオ信号受信割り込み
* が発生し、 afw::rxISRが呼び出される。
*
* afw::rxISRは割り込みをクリアし、トリプルバッファの制御を行う。そしてしかるべきデータを
* DMAの受信バッファから取り出すと、使いやすいよう並べなおしてユーザー定義のコールバック関数
* afw::processDataを呼び出す。
*
* afw::processDataは実際に信号処理を行う場所であるが、このアプリケーションはフレームワークで
* あり、処理の部分は空になっている。ユーザーはこの空の部分を自由に書き直して自身の
* アプリケーションに変える。 afw::processData は送信したいデータがあるならば出力バッファに格納して呼び出し関数に戻る。
*
* 呼び出した関数である afw::rxISRは出力データを並べ替えて然るべきDMAバッファに
* 格納する。
*
* EZ-KIT Lite BF-537のディップスイッチの設定は以下のとおり
- SW1 : すべてOFF
- SW7 : すべてON
- SW8 : 1-2をON、残りはすべてOFF
*/
/** \file main.cpp
* \brief メイン関数定義ファイル
* \author アナログ・デバイセズ株式会社
* \version 1.0
* \date 2006.Sep.8
*
* このファイルはVisualDSP++ 4.5のサンプル・アプリケーション、TalkTrhoughから
* 派生させたものである。EZ-KIT BF537のリソースを初期化し、48Ksample/Sのオーディオ
* フレームワークを起動する。受信データはコールバック関数 afw::processData によって
* 処理される。
*/
#include <ccblkfn.h>
#include "afw.h"
#include "utilbf537.h"
#include <cdefBF53x.h> // レジスタ・アドレスのインクルード
#include <signal.h> // 割込み関連のインクルード
#include <climits>
#include <stdio.h>
//const int led_offset = 6;
//const int led_all = 0x3F << led_offset;
const int sw10 = (1<<5);
const int sw11 = (1<<4);
extern void printParameter(int signal);
extern void changeParameter(int signal);
/** メイン関数
*
* 各ペリフェラルを初期化後、割り込み待ちに入る。
*/
//#include <btc.h>
void main(void)
{
utilbf537::initPLL(); // PLLを設定する
afw::init(); // オーディオ・フレームワーク初期化
afw::startAudio(); // オーディオ処理開始
// afw::init()でFER,DIR,INENは初期化済
//*pPORTF_FER &= ~sw10 & ~sw11 & led_all;
// EZ-KIT LiteのSW10を割込み入力,入力に設定. LED1&2をステータス表示に使う,出力に設定
//*pPORTFIO_DIR &= ~sw10 & ~sw11 & led_all;
//*pPORTFIO_INEN |= sw10 | sw11; // 入力バッファを有効にする
//*pPORTFIO_CLEAR = sw10 | sw11 | led_all; // 念のため割込み要求をクリアしておく&LEDを消灯
*pPORTFIO_EDGE |= sw10 | sw11; // エッジ割り込みに設定
*pPORTFIO_MASKA_SET = sw10; // 割込みAを選択
// 割り込みの許可。PORTF割り込みAの順位はデフォルトで12(IVG12)
*pSIC_IMASK |= IRQ_PFA_PORTFG; // SIC_IMASKのPORTF割込みAを許可する
interrupt(SIGIVG12, &printParameter); // 割込みハンドラ登録.順位12(IVG12)
*pPORTFIO_MASKB_SET = sw11; // 割込みBを選択
// 割り込みの許可。PORTF割り込みBの順位はデフォルト13(IVG13)
*pSIC_IMASK |= IRQ_PFB_PORTF ; // SIC_IMASKのPORTF割込みBを許可する
interrupt(SIGIVG13, &changeParameter); // 割込みハンドラ登録.順位13(IVG13)
while(1)
idle(); // 割り込み待ち
// BF537用にlibbtc532.dlbをリンク
//btc_init();
//while(1)
//btc_poll();
}
// 割込みハンドラ
#include "myparam.cpp"
fract param::Alpha = 0;
unsigned long param::Count = 0;
unsigned short param::Type = 0;
fract param::Psi = 0;
fract param::Myu = 0;
fract param::In = 0;
fract param::outLow = 0;
fract param::outHigh = 0;
fract param::apf = 0.0r;
void printParameter(int signal)
{
// LEDの状態を反転
//*pPORTFIO_TOGGLE = 4 << led_offset; // Flagピンのトグル
printf("Count:%d, Myu:%f\n", param::Count, (float)param::Myu);
// 割り込みをクリア
*pPORTFIO_CLEAR = sw10; // 割り込みのクリア
ssync(); // 確実にクリアされるまで待つ
}
void changeParameter(int signal)
{
const int led_offset = 6;
const int number_of_output_types = 6;
param::Type = (param::Type+1) % number_of_output_types;
//*pPORTFIO = param::Type << led_offset; // なぜか出力がなくなる
*pPORTFIO_CLEAR = sw11; // 割り込みのクリア
ssync(); // 確実にクリアされるまで待つ
}
| [
"[email protected]"
] | [
[
[
1,
130
]
]
] |
a5ac7f27a932ab8e7d81ffc36be92f37d31ae709 | 5fb8a3390a3bf748a1c902724d6fe20f6524c4b7 | /Dogfight2D/src/PropertyListener.h | 853bfafe8e16a767808a1d49d4497bbed2c442a5 | [] | no_license | DavidVondras/charlydogfightgame | 7e7d46cd4830afca8dade4e19751cdc5bf10b685 | 1631adf036da607318e833ab7322af0b57d52e35 | refs/heads/master | 2016-09-07T18:49:31.344404 | 2011-01-01T20:37:22 | 2011-01-01T20:37:22 | 41,377,758 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,479 | h | #pragma once
#include <stdlib.h>
#include <list>
#include <SFML\Graphics.hpp>
#include "ListHelper.h"
#include "Point.h"
namespace Types
{
enum PropertyWrapperType
{
Float,
Point
};
}
namespace df
{
class PropertyListener
{
private:
PropertyListener();
~PropertyListener();
struct PropertyWrapper
{
PropertyWrapper(void* propertyPtr, std::string stringFormat, Types::PropertyWrapperType type):
PropertyPtr(propertyPtr), StringFormat(stringFormat), PropertyType(type){}
Types::PropertyWrapperType PropertyType;
void* PropertyPtr;
std::string StringFormat;
};
sf::String _stringRenderBuffer;
std::list<PropertyWrapper*> _properties;
// Instance of the singleton
static PropertyListener* _instance;
public:
// Get the unique singleton instance
static PropertyListener& getInstance(void)
{
if(_instance == NULL) _instance = new PropertyListener();
return *_instance;
}
// Deletes the singleton instance
static void DeleteInstance(void)
{
if(_instance != NULL)
{
df::ListHelper::ClearListPointer<PropertyWrapper>(_instance->_properties);
delete _instance;
}
_instance = NULL;
}
void AddProperty(float* propertyPtr, const std::string stringFormat);
void AddProperty(df::Point* propertyPtr, const std::string stringFormat);
void RemoveProperty(void* propertyPtr);
void Draw(sf::RenderWindow& renderWindow);
};
} | [
"charles.hetier@2e9598b8-afb8-4876-edc4-84008ec66e72"
] | [
[
[
1,
66
]
]
] |
f7d3dc6306837b56aa88047c1383307e3bf3bd89 | 11af1673bab82ca2329ef8b596d1f3d2f8b82481 | /source/game/g_active.cpp | 84f26e6e4550dd4390798230e7d58362fa476ddb | [] | no_license | legacyrp/legacyojp | 8b33ecf24fd973bee5e7adbd369748cfdd891202 | d918151e917ea06e8698f423bbe2cf6ab9d7f180 | refs/heads/master | 2021-01-10T20:09:55.748893 | 2011-04-18T21:07:13 | 2011-04-18T21:07:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132,678 | cpp | // Copyright (C) 1999-2000 Id Software, Inc.
//
#include "g_local.h"
#include "bg_saga.h"
#include "g_admin.h"
#include "g_adminshared.h"
#include "g_emote.h"
#include "g_cvars.h"
extern void Jedi_Cloak( gentity_t *self );
extern void Jedi_Decloak( gentity_t *self );
#include "../namespace_begin.h"
qboolean PM_SaberInTransition( int move );
qboolean PM_SaberInStart( int move );
qboolean PM_SaberInReturn( int move );
//[StanceSelection]
//qboolean WP_SaberStyleValidForSaber( saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int saberAnimLevel );
//[/StanceSelection]
#include "../namespace_end.h"
qboolean saberCheckKnockdown_DuelLoss(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other);
extern vmCvar_t g_saberLockRandomNess;
void P_SetTwitchInfo(gclient_t *client)
{
client->ps.painTime = level.time;
client->ps.painDirection ^= 1;
}
/*
===============
G_DamageFeedback
Called just before a snapshot is sent to the given player.
Totals up all damage and generates both the player_state_t
damage values to that client for pain blends and kicks, and
global pain sound events for all clients.
===============
*/
void P_DamageFeedback( gentity_t *player ) {
gclient_t *client;
float count;
vec3_t angles;
client = player->client;
if ( client->ps.pm_type == PM_DEAD ) {
return;
}
// total points of damage shot at the player this frame
count = client->damage_blood + client->damage_armor;
if ( count == 0 ) {
return; // didn't take any damage
}
if ( count > 255 ) {
count = 255;
}
// send the information to the client
// world damage (falling, slime, etc) uses a special code
// to make the blend blob centered instead of positional
if ( client->damage_fromWorld ) {
client->ps.damagePitch = 255;
client->ps.damageYaw = 255;
client->damage_fromWorld = qfalse;
} else {
vectoangles( client->damage_from, angles );
client->ps.damagePitch = angles[PITCH]/360.0 * 256;
client->ps.damageYaw = angles[YAW]/360.0 * 256;
//cap them since we can't send negative values in here across the net
if (client->ps.damagePitch < 0)
{
client->ps.damagePitch = 0;
}
if (client->ps.damageYaw < 0)
{
client->ps.damageYaw = 0;
}
}
// play an apropriate pain sound
if ( (level.time > player->pain_debounce_time) && !(player->flags & FL_GODMODE) && !(player->s.eFlags & EF_DEAD) ) {
// don't do more than two pain sounds a second
// nmckenzie: also don't make him loud and whiny if he's only getting nicked.
if ( level.time - client->ps.painTime < 500 || count < 10) {
return;
}
P_SetTwitchInfo(client);
player->pain_debounce_time = level.time + 700;
G_AddEvent( player, EV_PAIN, player->health );
client->ps.damageEvent++;
if (client->damage_armor && !client->damage_blood)
{
client->ps.damageType = 1; //pure shields
}
else if (client->damage_armor)
{
client->ps.damageType = 2; //shields and health
}
else
{
client->ps.damageType = 0; //pure health
}
}
client->ps.damageCount = count;
//
// clear totals
//
client->damage_blood = 0;
client->damage_armor = 0;
client->damage_knockback = 0;
}
/*
=============
P_WorldEffects
Check for lava / slime contents and drowning
=============
*/
void P_WorldEffects( gentity_t *ent ) {
qboolean envirosuit;
int waterlevel;
if ( ent->client->noclip ) {
ent->client->airOutTime = level.time + 12000; // don't need air
return;
}
waterlevel = ent->waterlevel;
envirosuit = (qboolean)(ent->client->ps.powerups[PW_BATTLESUIT] > level.time);
//
// check for drowning
//
if ( waterlevel == 3 ) {
// envirosuit give air
if ( envirosuit ) {
ent->client->airOutTime = level.time + 10000;
}
// if out of air, start drowning
if ( ent->client->airOutTime < level.time) {
// drown!
ent->client->airOutTime += 1000;
if ( ent->health > 0 ) {
// take more damage the longer underwater
ent->damage += 2;
if (ent->damage > 15)
ent->damage = 15;
// play a gurp sound instead of a normal pain sound
if (ent->health <= ent->damage) {
G_Sound(ent, CHAN_VOICE, G_SoundIndex(/*"*drown.wav"*/"sound/player/gurp1.wav"));
} else if (rand()&1) {
G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp1.wav"));
} else {
G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp2.wav"));
}
// don't play a normal pain sound
ent->pain_debounce_time = level.time + 200;
G_Damage (ent, NULL, NULL, NULL, NULL,
ent->damage, DAMAGE_NO_ARMOR, MOD_WATER);
}
}
} else {
ent->client->airOutTime = level.time + 12000;
ent->damage = 2;
}
//
// check for sizzle damage (move to pmove?)
//
if (waterlevel &&
(ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) {
if (ent->health > 0
&& ent->pain_debounce_time <= level.time ) {
if ( envirosuit ) {
G_AddEvent( ent, EV_POWERUP_BATTLESUIT, 0 );
} else {
if (ent->watertype & CONTENTS_LAVA) {
G_Damage (ent, NULL, NULL, NULL, NULL,
30*waterlevel, 0, MOD_LAVA);
}
if (ent->watertype & CONTENTS_SLIME) {
G_Damage (ent, NULL, NULL, NULL, NULL,
10*waterlevel, 0, MOD_SLIME);
}
}
}
}
}
//==============================================================
extern void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback );
void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf )
{//RACC - this appears to be for impact damage for dynamic map entities, like elevators,
//glass, etc.
float magnitude, my_mass;
vec3_t velocity;
int cont;
qboolean easyBreakBrush = qtrue;
if( self->client )
{
VectorCopy( self->client->ps.velocity, velocity );
if( !self->mass )
{
//RACC - Player Characters normally don't have masses assigned so they default.
//to this.
my_mass = 10;
}
else
{
my_mass = self->mass;
}
}
else
{
VectorCopy( self->s.pos.trDelta, velocity );
if ( self->s.pos.trType == TR_GRAVITY )
{
velocity[2] -= 0.25f * g_gravity.value;
}
if( !self->mass )
{
my_mass = 1;
}
else if ( self->mass <= 10 )
{
my_mass = 10;
}
else
{
my_mass = self->mass;///10;
}
}
magnitude = VectorLength( velocity ) * my_mass / 10;
/*
if(pointcontents(self.absmax)==CONTENT_WATER)//FIXME: or other watertypes
magnitude/=3; //water absorbs 2/3 velocity
if(self.classname=="barrel"&&self.aflag)//rolling barrels are made for impacts!
magnitude*=3;
if(self.frozen>0&&magnitude<300&&self.flags&FL_ONGROUND&&loser==world&&self.velocity_z<-20&&self.last_onground+0.3<time)
magnitude=300;
*/
if ( other->material == MAT_GLASS
|| other->material == MAT_GLASS_METAL
|| other->material == MAT_GRATE1
|| ((other->flags&FL_BBRUSH)&&(other->spawnflags&8/*THIN*/))
|| (other->r.svFlags&SVF_GLASS_BRUSH) )
{
easyBreakBrush = qtrue;
}
if ( !self->client || self->client->ps.lastOnGround+300<level.time || ( self->client->ps.lastOnGround+100 < level.time && easyBreakBrush ) )
{
vec3_t dir1, dir2;
float force = 0, dot;
if ( easyBreakBrush )
magnitude *= 2;
//damage them
if ( magnitude >= 100 && other->s.number < ENTITYNUM_WORLD )
{
VectorCopy( velocity, dir1 );
VectorNormalize( dir1 );
if( VectorCompare( other->r.currentOrigin, vec3_origin ) )
{//a brush with no origin
VectorCopy ( dir1, dir2 );
}
else
{
VectorSubtract( other->r.currentOrigin, self->r.currentOrigin, dir2 );
VectorNormalize( dir2 );
}
dot = DotProduct( dir1, dir2 );
if ( dot >= 0.2 )
{
force = dot;
}
else
{
force = 0;
}
force *= (magnitude/50);
cont = trap_PointContents( other->r.absmax, other->s.number );
if( (cont&CONTENTS_WATER) )//|| (self.classname=="barrel"&&self.aflag))//FIXME: or other watertypes
{
force /= 3; //water absorbs 2/3 velocity
}
/*
if(self.frozen>0&&force>10)
force=10;
*/
if( ( force >= 1 && other->s.number != 0 ) || force >= 10)
{
/*
dprint("Damage other (");
dprint(loser.classname);
dprint("): ");
dprint(ftos(force));
dprint("\n");
*/
if ( other->r.svFlags & SVF_GLASS_BRUSH )
{
other->splashRadius = (float)(self->r.maxs[0] - self->r.mins[0])/4.0f;
}
if ( other->takedamage )
{
G_Damage( other, self, self, velocity, self->r.currentOrigin, force, DAMAGE_NO_ARMOR, MOD_CRUSH);//FIXME: MOD_IMPACT
}
else
{
G_ApplyKnockback( other, dir2, force );
}
}
}
//[CoOp]
//added FL_NO_IMPACT_DMG
if ( damageSelf && self->takedamage && !(self->flags&FL_NO_IMPACT_DMG))
//if ( damageSelf && self->takedamage )
//[/CoOp]
{
//Now damage me
//FIXME: more lenient falling damage, especially for when driving a vehicle
if ( self->client && self->client->ps.fd.forceJumpZStart )
{//we were force-jumping
if ( self->r.currentOrigin[2] >= self->client->ps.fd.forceJumpZStart )
{//we landed at same height or higher than we landed
magnitude = 0;
}
else
{//FIXME: take off some of it, at least?
magnitude = (self->client->ps.fd.forceJumpZStart-self->r.currentOrigin[2])/3;
}
}
//if(self.classname!="monster_mezzoman"&&self.netname!="spider")//Cats always land on their feet
//[BugFix3]
//I'm pretty sure that this is something left over from SP. ClientNum shouldn't have any relevence here.
if( ( magnitude >= 100 + self->health && self->s.weapon != WP_SABER ) || ( magnitude >= 700 ) )//&& self.safe_time < level.time ))//health here is used to simulate structural integrity
{
if ( (self->s.weapon == WP_SABER) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && magnitude < 1000 )
/*
if( ( magnitude >= 100 + self->health && self->s.number != 0 && self->s.weapon != WP_SABER ) || ( magnitude >= 700 ) )//&& self.safe_time < level.time ))//health here is used to simulate structural integrity
{
if ( (self->s.weapon == WP_SABER || self->s.number == 0) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && magnitude < 1000 )
*/
//[/BugFix3]
{//players and jedi take less impact damage
//allow for some lenience on high falls
magnitude /= 2;
/*
if ( self.absorb_time >= time )//crouching on impact absorbs 1/2 the damage
{
magnitude/=2;
}
*/
}
magnitude /= 40;
magnitude = magnitude - force/2;//If damage other, subtract half of that damage off of own injury
if ( magnitude >= 1 )
{
//FIXME: Put in a thingtype impact sound function
/*
dprint("Damage self (");
dprint(self.classname);
dprint("): ");
dprint(ftos(magnitude));
dprint("\n");
*/
/*
if ( self.classname=="player_sheep "&& self.flags&FL_ONGROUND && self.velocity_z > -50 )
return;
*/
//[CoOp]
//[SuperDindon]
if (!self->noFallDamage)
G_Damage( self, NULL, NULL, NULL, self->r.currentOrigin, magnitude/2, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT
//[/CoOp]
}
}
}
//FIXME: slow my velocity some?
// NOTENOTE We don't use lastimpact as of yet
// self->lastImpact = level.time;
/*
if(self.flags&FL_ONGROUND)
self.last_onground=time;
*/
}
}
void Client_CheckImpactBBrush( gentity_t *self, gentity_t *other )
{
if ( !other || !other->inuse )
{
return;
}
if (!self || !self->inuse || !self->client ||
self->client->tempSpectate >= level.time ||
self->client->sess.sessionTeam == TEAM_SPECTATOR)
{ //hmm.. let's not let spectators ram into breakables.
return;
}
/*
if (BG_InSpecialJump(self->client->ps.legsAnim))
{ //don't do this either, qa says it creates "balance issues"
return;
}
*/
if ( other->material == MAT_GLASS
|| other->material == MAT_GLASS_METAL
|| other->material == MAT_GRATE1
|| ((other->flags&FL_BBRUSH)&&(other->spawnflags&8/*THIN*/))
|| ((other->flags&FL_BBRUSH)&&(other->health<=10))
|| (other->r.svFlags&SVF_GLASS_BRUSH) )
{//clients only do impact damage against easy-break breakables
DoImpact( self, other, qfalse );
}
}
/*
===============
G_SetClientSound
===============
*/
void G_SetClientSound( gentity_t *ent ) {
if (ent->client && ent->client->isHacking)
{ //loop hacking sound
ent->client->ps.loopSound = level.snd_hack;
ent->s.loopIsSoundset = qfalse;
}
else if (ent->client && ent->client->isMedHealed > level.time)
{ //loop healing sound
ent->client->ps.loopSound = level.snd_medHealed;
ent->s.loopIsSoundset = qfalse;
}
else if (ent->client && ent->client->isMedSupplied > level.time)
{ //loop supplying sound
ent->client->ps.loopSound = level.snd_medSupplied;
ent->s.loopIsSoundset = qfalse;
}
else if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) {
ent->client->ps.loopSound = level.snd_fry;
ent->s.loopIsSoundset = qfalse;
} else {
ent->client->ps.loopSound = 0;
ent->s.loopIsSoundset = qfalse;
}
}
//==============================================================
/*
==============
ClientImpacts
==============
*/
void ClientImpacts( gentity_t *ent, pmove_t *pm ) {
int i, j;
trace_t trace;
gentity_t *other;
memset( &trace, 0, sizeof( trace ) );
for (i=0 ; i<pm->numtouch ; i++) {
for (j=0 ; j<i ; j++) {
if (pm->touchents[j] == pm->touchents[i] ) {
break;
}
}
if (j != i) {
continue; // duplicated
}
other = &g_entities[ pm->touchents[i] ];
if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) {
ent->touch( ent, other, &trace );
}
if ( !other->touch ) {
continue;
}
other->touch( other, ent, &trace );
}
}
/*
============
G_TouchTriggers
Find all trigger entities that ent's current position touches.
Spectators will only interact with teleporters.
============
*/
void G_TouchTriggers( gentity_t *ent ) {
int i, num;
int touch[MAX_GENTITIES];
gentity_t *hit;
trace_t trace;
vec3_t mins, maxs;
static vec3_t range = { 40, 40, 52 };
if ( !ent->client ) {
return;
}
// dead clients don't activate triggers!
if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) {
return;
}
VectorSubtract( ent->client->ps.origin, range, mins );
VectorAdd( ent->client->ps.origin, range, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
// can't use ent->r.absmin, because that has a one unit pad
VectorAdd( ent->client->ps.origin, ent->r.mins, mins );
VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs );
for ( i=0 ; i<num ; i++ ) {
hit = &g_entities[touch[i]];
if ( !hit->touch && !ent->touch ) {
continue;
}
if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) {
continue;
}
// ignore most entities if a spectator
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
if ( hit->s.eType != ET_TELEPORT_TRIGGER &&
// this is ugly but adding a new ET_? type will
// most likely cause network incompatibilities
hit->touch != Touch_DoorTrigger) {
continue;
}
}
// use seperate code for determining if an item is picked up
// so you don't have to actually contact its bounding box
if ( hit->s.eType == ET_ITEM ) {
if ( !BG_PlayerTouchesItem( &ent->client->ps, &hit->s, level.time ) ) {
continue;
}
} else {
if ( !trap_EntityContact( mins, maxs, hit ) ) {
continue;
}
}
memset( &trace, 0, sizeof(trace) );
if ( hit->touch ) {
hit->touch (hit, ent, &trace);
}
if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) {
ent->touch( ent, hit, &trace );
}
}
// if we didn't touch a jump pad this pmove frame
if ( ent->client->ps.jumppad_frame != ent->client->ps.pmove_framecount ) {
ent->client->ps.jumppad_frame = 0;
ent->client->ps.jumppad_ent = 0;
}
}
/*
============
G_MoverTouchTriggers
Find all trigger entities that ent's current position touches.
Spectators will only interact with teleporters.
============
*/
void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg )
{
int i, num;
float step, stepSize, dist;
int touch[MAX_GENTITIES];
gentity_t *hit;
trace_t trace;
vec3_t mins, maxs, dir, size, checkSpot;
const vec3_t range = { 40, 40, 52 };
// non-moving movers don't hit triggers!
if ( !VectorLengthSquared( ent->s.pos.trDelta ) )
{
return;
}
VectorSubtract( ent->r.mins, ent->r.maxs, size );
stepSize = VectorLength( size );
if ( stepSize < 1 )
{
stepSize = 1;
}
VectorSubtract( ent->r.currentOrigin, oldOrg, dir );
dist = VectorNormalize( dir );
for ( step = 0; step <= dist; step += stepSize )
{
VectorMA( ent->r.currentOrigin, step, dir, checkSpot );
VectorSubtract( checkSpot, range, mins );
VectorAdd( checkSpot, range, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
// can't use ent->r.absmin, because that has a one unit pad
VectorAdd( checkSpot, ent->r.mins, mins );
VectorAdd( checkSpot, ent->r.maxs, maxs );
for ( i=0 ; i<num ; i++ )
{
hit = &g_entities[touch[i]];
if ( hit->s.eType != ET_PUSH_TRIGGER )
{
continue;
}
if ( hit->touch == NULL )
{
continue;
}
if ( !( hit->r.contents & CONTENTS_TRIGGER ) )
{
continue;
}
if ( !trap_EntityContact( mins, maxs, hit ) )
{
continue;
}
memset( &trace, 0, sizeof(trace) );
if ( hit->touch != NULL )
{
hit->touch(hit, ent, &trace);
}
}
}
}
/*
=================
SpectatorThink
=================
*/
void SpectatorThink( gentity_t *ent, usercmd_t *ucmd ) {
pmove_t pm;
gclient_t *client;
client = ent->client;
if ( client->sess.spectatorState != SPECTATOR_FOLLOW ) {
client->ps.pm_type = PM_SPECTATOR;
client->ps.speed = 400; // faster than normal
client->ps.basespeed = 400;
//hmm, shouldn't have an anim if you're a spectator, make sure
//it gets cleared.
client->ps.legsAnim = 0;
client->ps.legsTimer = 0;
client->ps.torsoAnim = 0;
client->ps.torsoTimer = 0;
// set up for pmove
memset (&pm, 0, sizeof(pm));
pm.ps = &client->ps;
pm.cmd = *ucmd;
pm.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; // spectators can fly through bodies
pm.trace = trap_Trace;
pm.pointcontents = trap_PointContents;
pm.noSpecMove = g_noSpecMove.integer;
pm.animations = NULL;
pm.nonHumanoid = qfalse;
//Set up bg entity data
pm.baseEnt = (bgEntity_t *)g_entities;
pm.entSize = sizeof(gentity_t);
// perform a pmove
Pmove (&pm);
// save results of pmove
VectorCopy( client->ps.origin, ent->s.origin );
if (ent->client->tempSpectate < level.time)
{
G_TouchTriggers( ent );
}
trap_UnlinkEntity( ent );
}
client->oldbuttons = client->buttons;
client->buttons = ucmd->buttons;
if (client->tempSpectate < level.time)
{
// attack button cycles through spectators
if ( ( client->buttons & BUTTON_ATTACK ) && ! ( client->oldbuttons & BUTTON_ATTACK ) ) {
Cmd_FollowCycle_f( ent, 1 );
}
if (client->sess.spectatorState == SPECTATOR_FOLLOW && (ucmd->upmove > 0))
{ //jump now removes you from follow mode
StopFollowing(ent);
}
}
}
/*
=================
ClientInactivityTimer
Returns qfalse if the client is dropped
=================
*/
qboolean ClientInactivityTimer( gclient_t *client ) {
if ( ! g_inactivity.integer ) {
// give everyone some time, so if the operator sets g_inactivity during
// gameplay, everyone isn't kicked
client->inactivityTime = level.time + 60 * 1000;
client->inactivityWarning = qfalse;
} else if ( client->pers.cmd.forwardmove ||
client->pers.cmd.rightmove ||
client->pers.cmd.upmove ||
(client->pers.cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) {
client->inactivityTime = level.time + g_inactivity.integer * 1000;
client->inactivityWarning = qfalse;
} else if ( !client->pers.localClient ) {
if ( level.time > client->inactivityTime ) {
trap_DropClient( client - level.clients, "Dropped due to inactivity" );
return qfalse;
}
if ( level.time > client->inactivityTime - 10000 && !client->inactivityWarning ) {
client->inactivityWarning = qtrue;
trap_SendServerCommand( client - level.clients, "cp \"Ten seconds until inactivity drop!\n\"" );
}
}
return qtrue;
}
/*
==================
ClientTimerActions
Actions that happen once a second
==================
*/
void ClientTimerActions( gentity_t *ent, int msec ) {
gclient_t *client;
client = ent->client;
client->timeResidual += msec;
while ( client->timeResidual >= 1000 )
{
client->timeResidual -= 1000;
// count down health when over max
if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] ) {
ent->health--;
}
//[ExpSys]
/*
// count down armor when over max
if ( client->ps.stats[STAT_ARMOR] > client->ps.stats[STAT_MAX_HEALTH] ) {
client->ps.stats[STAT_ARMOR]--;
}
*/
//[/ExpSys]
}
}
/*
====================
ClientIntermissionThink
====================
*/
void ClientIntermissionThink( gclient_t *client ) {
client->ps.eFlags &= ~EF_TALK;
client->ps.eFlags &= ~EF_FIRING;
// the level will exit when everyone wants to or after timeouts
// swap and latch button actions
client->oldbuttons = client->buttons;
client->buttons = client->pers.cmd.buttons;
if ( client->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) & ( client->oldbuttons ^ client->buttons ) ) {
// this used to be an ^1 but once a player says ready, it should stick
client->readyToExit = qtrue;
}
}
extern void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags);
void G_VehicleAttachDroidUnit( gentity_t *vehEnt )
{
if ( vehEnt && vehEnt->m_pVehicle && vehEnt->m_pVehicle->m_pDroidUnit != NULL )
{
gentity_t *droidEnt = (gentity_t *)vehEnt->m_pVehicle->m_pDroidUnit;
mdxaBone_t boltMatrix;
vec3_t fwd;
trap_G2API_GetBoltMatrix(vehEnt->ghoul2, 0, vehEnt->m_pVehicle->m_iDroidUnitTag, &boltMatrix, vehEnt->r.currentAngles, vehEnt->r.currentOrigin, level.time,
NULL, vehEnt->modelScale);
BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, droidEnt->r.currentOrigin);
BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, fwd);
vectoangles( fwd, droidEnt->r.currentAngles );
if ( droidEnt->client )
{
VectorCopy( droidEnt->r.currentAngles, droidEnt->client->ps.viewangles );
VectorCopy( droidEnt->r.currentOrigin, droidEnt->client->ps.origin );
}
G_SetOrigin( droidEnt, droidEnt->r.currentOrigin );
trap_LinkEntity( droidEnt );
if ( droidEnt->NPC )
{
NPC_SetAnim( droidEnt, SETANIM_BOTH, BOTH_STAND2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );
}
}
}
//[BugFix42]
extern qboolean BG_SabersOff( playerState_t *ps );
//[/BugFix42]
//called gameside only from pmove code (convenience)
void G_CheapWeaponFire(int entNum, int ev)
{
gentity_t *ent = &g_entities[entNum];
if (!ent->inuse || !ent->client)
{
return;
}
switch (ev)
{
case EV_FIRE_WEAPON:
if (ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER &&
ent->client && ent->client->ps.m_iVehicleNum)
{ //a speeder with a pilot
gentity_t *rider = &g_entities[ent->client->ps.m_iVehicleNum-1];
if (rider->inuse && rider->client)
{ //pilot is valid...
if (rider->client->ps.weapon != WP_MELEE &&
//[BugFix42]
(rider->client->ps.weapon != WP_SABER || !BG_SabersOff(&rider->client->ps)))
//(rider->client->ps.weapon != WP_SABER || !rider->client->ps.saberHolstered))
//[/BugFix42]
{ //can only attack on speeder when using melee or when saber is holstered
break;
}
}
}
FireWeapon( ent, qfalse );
ent->client->dangerTime = level.time;
ent->client->ps.eFlags &= ~EF_INVULNERABLE;
ent->client->invulnerableTimer = 0;
break;
case EV_ALT_FIRE:
FireWeapon( ent, qtrue );
ent->client->dangerTime = level.time;
ent->client->ps.eFlags &= ~EF_INVULNERABLE;
ent->client->invulnerableTimer = 0;
break;
}
}
/*
================
ClientEvents
Events will be passed on to the clients for presentation,
but any server game effects are handled here
================
*/
#include "../namespace_begin.h"
qboolean BG_InKnockDownOnly( int anim );
#include "../namespace_end.h"
void ClientEvents( gentity_t *ent, int oldEventSequence ) {
int i;//, j;
int event;
gclient_t *client;
int damage;
vec3_t dir;
qboolean fired=qfalse,altFired=qfalse;
client = ent->client;
if ( oldEventSequence < client->ps.eventSequence - MAX_PS_EVENTS ) {
oldEventSequence = client->ps.eventSequence - MAX_PS_EVENTS;
}
for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) {
event = client->ps.events[ i & (MAX_PS_EVENTS-1) ];
switch ( event ) {
case EV_FALL:
case EV_ROLL:
{
int delta = client->ps.eventParms[ i & (MAX_PS_EVENTS-1) ];
qboolean knockDownage = qfalse;
if (ent->client && ent->client->ps.fallingToDeath)
{
break;
}
if ( ent->s.eType != ET_PLAYER )
{
break; // not in the player model
}
if ( g_dmflags.integer & DF_NO_FALLING )
{
break;
}
if (BG_InKnockDownOnly(ent->client->ps.legsAnim))
{
if (delta <= 14)
{
break;
}
knockDownage = qtrue;
}
else
{
if (delta <= 44)
{
break;
}
}
if (knockDownage)
{
damage = delta*1; //you suffer for falling unprepared. A lot. Makes throws and things useful, and more realistic I suppose.
}
else
{
if (g_gametype.integer == GT_SIEGE &&
delta > 60)
{ //longer falls hurt more
damage = delta*1; //good enough for now, I guess
}
else
{
damage = delta*0.16; //good enough for now, I guess
}
}
VectorSet (dir, 0, 0, 1);
ent->pain_debounce_time = level.time + 200; // no normal pain sound
//[CoOp]
//[SuperDindon]
if (!ent->noFallDamage)
G_Damage (ent, NULL, NULL, NULL, NULL, damage, DAMAGE_NO_ARMOR, MOD_FALLING);
//[/CoOp]
if (ent->health < 1)
{
G_Sound(ent, CHAN_AUTO, G_SoundIndex( "sound/player/fallsplat.wav" ));
}
}
break;
case EV_FIRE_WEAPON:
//[Reload]
if(ent->reloadTime > 0)
CancelReload(ent);//1.3
//[/Reload]
FireWeapon( ent, qfalse );
ent->client->dangerTime = level.time;
ent->client->ps.eFlags &= ~EF_INVULNERABLE;
ent->client->invulnerableTimer = 0;
fired=qtrue;
break;
case EV_ALT_FIRE:
if(ent->client->ps.weapon == WP_BOWCASTER)
return;
FireWeapon( ent, qtrue );
ent->client->dangerTime = level.time;
ent->client->ps.eFlags &= ~EF_INVULNERABLE;
ent->client->invulnerableTimer = 0;
altFired=qtrue;
break;
case EV_SABER_ATTACK:
ent->client->dangerTime = level.time;
ent->client->ps.eFlags &= ~EF_INVULNERABLE;
ent->client->invulnerableTimer = 0;
break;
//rww - Note that these must be in the same order (ITEM#-wise) as they are in holdable_t
case EV_USE_ITEM1: //seeker droid
ItemUse_Seeker(ent);
break;
case EV_USE_ITEM2: //shield
ItemUse_Shield(ent);
break;
case EV_USE_ITEM3: //medpack
ItemUse_MedPack(ent);
break;
case EV_USE_ITEM4: //big medpack
ItemUse_MedPack_Big(ent);
break;
case EV_USE_ITEM5: //binoculars
ItemUse_Binoculars(ent);
break;
case EV_USE_ITEM6: //sentry gun
ItemUse_Sentry(ent);
break;
case EV_USE_ITEM7: //jetpack
ItemUse_Jetpack(ent);
break;
case EV_USE_ITEM8: //health disp
//ItemUse_UseDisp(ent, HI_HEALTHDISP);
break;
case EV_USE_ITEM9: //ammo disp
//ItemUse_UseDisp(ent, HI_AMMODISP);
break;
case EV_USE_ITEM10: //eweb
ItemUse_UseEWeb(ent);
break;
case EV_USE_ITEM11: //cloak
ItemUse_UseCloak(ent);
break;
//[Flamethrower]
case EV_USE_ITEM12: //flamethrower
ItemUse_FlameThrower(ent);
break;
//[/Flamethrower]
default:
break;
}
}
}
//[KnockdownSys][SPPortComplete]
void G_ThrownDeathAnimForDeathAnim( gentity_t *hitEnt, vec3_t impactPoint )
{//racc - sets an alternate "being thrown" death animation based on current death animation.
int anim = -1;
if ( !hitEnt || !hitEnt->client )
{
return;
}
switch ( hitEnt->client->ps.legsAnim )
{
case BOTH_DEATH9://fall to knees, fall over
case BOTH_DEATH10://fall to knees, fall over
case BOTH_DEATH11://fall to knees, fall over
case BOTH_DEATH13://stumble back, fall over
case BOTH_DEATH17://jerky fall to knees, fall over
case BOTH_DEATH18://grab gut, fall to knees, fall over
case BOTH_DEATH19://grab gut, fall to knees, fall over
case BOTH_DEATH20://grab shoulder, fall forward
case BOTH_DEATH21://grab shoulder, fall forward
case BOTH_DEATH3://knee collapse, twist & fall forward
case BOTH_DEATH7://knee collapse, twist & fall forward
{
float dot;
vec3_t dir2Impact, fwdAngles, facing;
VectorSubtract( impactPoint, hitEnt->r.currentOrigin, dir2Impact );
dir2Impact[2] = 0;
VectorNormalize( dir2Impact );
VectorSet( fwdAngles, 0, hitEnt->client->ps.viewangles[YAW], 0 );
AngleVectors( fwdAngles, facing, NULL, NULL );
dot = DotProduct( facing, dir2Impact );//-1 = hit in front, 0 = hit on side, 1 = hit in back
if ( dot > 0.5f )
{//kicked in chest, fly backward
switch ( Q_irand( 0, 4 ) )
{//FIXME: don't start at beginning of anim?
case 0:
anim = BOTH_DEATH1;//thrown backwards
break;
case 1:
anim = BOTH_DEATH2;//fall backwards
break;
case 2:
anim = BOTH_DEATH15;//roll over backwards
break;
case 3:
anim = BOTH_DEATH22;//fast fall back
break;
case 4:
anim = BOTH_DEATH23;//fast fall back
break;
}
}
else if ( dot < -0.5f )
{//kicked in back, fly forward
switch ( Q_irand( 0, 5 ) )
{//FIXME: don't start at beginning of anim?
case 0:
anim = BOTH_DEATH14;
break;
case 1:
anim = BOTH_DEATH24;
break;
case 2:
anim = BOTH_DEATH25;
break;
case 3:
anim = BOTH_DEATH4;//thrown forwards
break;
case 4:
anim = BOTH_DEATH5;//thrown forwards
break;
case 5:
anim = BOTH_DEATH16;//thrown forwards
break;
}
}
else
{//hit on side, spin
switch ( Q_irand( 0, 2 ) )
{//FIXME: don't start at beginning of anim?
case 0:
anim = BOTH_DEATH12;
break;
case 1:
anim = BOTH_DEATH14;
break;
case 2:
anim = BOTH_DEATH15;
break;
case 3:
anim = BOTH_DEATH6;
break;
case 4:
anim = BOTH_DEATH8;
break;
}
}
}
break;
}
if ( anim != -1 )
{
NPC_SetAnim( hitEnt, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );
}
}
//[/SPPortComplete][/KnockdownSys]
/*
==============
SendPendingPredictableEvents
==============
*/
void SendPendingPredictableEvents( playerState_t *ps ) {
gentity_t *t;
int event, seq;
int extEvent, number;
// if there are still events pending
if ( ps->entityEventSequence < ps->eventSequence ) {
// create a temporary entity for this event which is sent to everyone
// except the client who generated the event
seq = ps->entityEventSequence & (MAX_PS_EVENTS-1);
event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 );
// set external event to zero before calling BG_PlayerStateToEntityState
extEvent = ps->externalEvent;
ps->externalEvent = 0;
// create temporary entity for event
t = G_TempEntity( ps->origin, event );
number = t->s.number;
BG_PlayerStateToEntityState( ps, &t->s, qtrue );
t->s.number = number;
t->s.eType = ET_EVENTS + event;
t->s.eFlags |= EF_PLAYER_EVENT;
t->s.otherEntityNum = ps->clientNum;
// send to everyone except the client who generated the event
t->r.svFlags |= SVF_NOTSINGLECLIENT;
t->r.singleClient = ps->clientNum;
// set back external event
ps->externalEvent = extEvent;
}
}
/*
==================
G_UpdateClientBroadcasts
Determines whether this client should be broadcast to any other clients.
A client is broadcast when another client is using force sight or is
==================
*/
#define MAX_JEDIMASTER_DISTANCE 2500
#define MAX_JEDIMASTER_FOV 100
#define MAX_SIGHT_DISTANCE 1500
#define MAX_SIGHT_FOV 100
static void G_UpdateForceSightBroadcasts ( gentity_t *self )
{
int i;
// Any clients with force sight on should see this client
for ( i = 0; i < level.numConnectedClients; i ++ )
{
gentity_t *ent = &g_entities[level.sortedClients[i]];
float dist;
vec3_t angles;
if ( ent == self )
{
continue;
}
// Not using force sight so we shouldnt broadcast to this one
if ( !(ent->client->ps.fd.forcePowersActive & (1<<FP_SEE) ) )
{
continue;
}
VectorSubtract( self->client->ps.origin, ent->client->ps.origin, angles );
dist = VectorLengthSquared ( angles );
vectoangles ( angles, angles );
// Too far away then just forget it
if ( dist > MAX_SIGHT_DISTANCE * MAX_SIGHT_DISTANCE )
{
continue;
}
// If not within the field of view then forget it
if ( !InFieldOfVision ( ent->client->ps.viewangles, MAX_SIGHT_FOV, angles ) )
{
break;
}
// Turn on the broadcast bit for the master and since there is only one
// master we are done
self->r.broadcastClients[ent->s.clientNum/32] |= (1 << (ent->s.clientNum%32));
break;
}
}
static void G_UpdateJediMasterBroadcasts ( gentity_t *self )
{
int i;
// Not jedi master mode then nothing to do
if ( g_gametype.integer != GT_JEDIMASTER )
{
return;
}
// This client isnt the jedi master so it shouldnt broadcast
if ( !self->client->ps.isJediMaster )
{
return;
}
// Broadcast ourself to all clients within range
for ( i = 0; i < level.numConnectedClients; i ++ )
{
gentity_t *ent = &g_entities[level.sortedClients[i]];
float dist;
vec3_t angles;
if ( ent == self )
{
continue;
}
VectorSubtract( self->client->ps.origin, ent->client->ps.origin, angles );
dist = VectorLengthSquared ( angles );
vectoangles ( angles, angles );
// Too far away then just forget it
if ( dist > MAX_JEDIMASTER_DISTANCE * MAX_JEDIMASTER_DISTANCE )
{
continue;
}
// If not within the field of view then forget it
if ( !InFieldOfVision ( ent->client->ps.viewangles, MAX_JEDIMASTER_FOV, angles ) )
{
continue;
}
// Turn on the broadcast bit for the master and since there is only one
// master we are done
self->r.broadcastClients[ent->s.clientNum/32] |= (1 << (ent->s.clientNum%32));
}
}
void G_UpdateClientBroadcasts ( gentity_t *self )
{
// Clear all the broadcast bits for this client
memset ( self->r.broadcastClients, 0, sizeof ( self->r.broadcastClients ) );
// The jedi master is broadcast to everyone in range
G_UpdateJediMasterBroadcasts ( self );
// Anyone with force sight on should see this client
G_UpdateForceSightBroadcasts ( self );
}
void G_AddPushVecToUcmd( gentity_t *self, usercmd_t *ucmd )
{
vec3_t forward, right, moveDir;
float pushSpeed, fMove, rMove;
if ( !self->client )
{
return;
}
pushSpeed = VectorLengthSquared(self->client->pushVec);
if(!pushSpeed)
{//not being pushed
return;
}
AngleVectors(self->client->ps.viewangles, forward, right, NULL);
VectorScale(forward, ucmd->forwardmove/127.0f * self->client->ps.speed, moveDir);
VectorMA(moveDir, ucmd->rightmove/127.0f * self->client->ps.speed, right, moveDir);
//moveDir is now our intended move velocity
VectorAdd(moveDir, self->client->pushVec, moveDir);
self->client->ps.speed = VectorNormalize(moveDir);
//moveDir is now our intended move velocity plus our push Vector
fMove = 127.0 * DotProduct(forward, moveDir);
rMove = 127.0 * DotProduct(right, moveDir);
ucmd->forwardmove = floor(fMove);//If in the same dir , will be positive
ucmd->rightmove = floor(rMove);//If in the same dir , will be positive
if ( self->client->pushVecTime < level.time )
{
VectorClear( self->client->pushVec );
}
}
qboolean G_StandingAnim( int anim )
{//NOTE: does not check idles or special (cinematic) stands
switch ( anim )
{
case BOTH_STAND1:
case BOTH_STAND2:
case BOTH_STAND3:
case BOTH_STAND4:
return qtrue;
break;
}
return qfalse;
}
qboolean G_ActionButtonPressed(int buttons)
{
if (buttons & BUTTON_ATTACK)
{
return qtrue;
}
else if (buttons & BUTTON_USE_HOLDABLE)
{
return qtrue;
}
else if (buttons & BUTTON_GESTURE)
{
return qtrue;
}
else if (buttons & BUTTON_USE)
{
return qtrue;
}
else if (buttons & BUTTON_FORCEGRIP)
{
return qtrue;
}
else if (buttons & BUTTON_ALT_ATTACK)
{
return qtrue;
}
else if (buttons & BUTTON_FORCEPOWER)
{
return qtrue;
}
else if (buttons & BUTTON_FORCE_LIGHTNING)
{
return qtrue;
}
else if (buttons & BUTTON_FORCE_DRAIN)
{
return qtrue;
}
return qfalse;
}
void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd )
{
vec3_t viewChange;
qboolean actionPressed;
int buttons;
if ( !ent || !ent->client || ent->health <= 0 || ent->client->ps.stats[STAT_HEALTH] <= 0 ||
ent->client->sess.sessionTeam == TEAM_SPECTATOR || (ent->client->ps.pm_flags & PMF_FOLLOW))
{
return;
}
buttons = ucmd->buttons;
if (ent->r.svFlags & SVF_BOT)
{ //they press use all the time..
buttons &= ~BUTTON_USE;
}
actionPressed = G_ActionButtonPressed(buttons);
VectorSubtract(ent->client->ps.viewangles, ent->client->idleViewAngles, viewChange);
if ( !VectorCompare( vec3_origin, ent->client->ps.velocity )
|| actionPressed || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove
|| !G_StandingAnim( ent->client->ps.legsAnim )
|| (ent->health+ent->client->ps.stats[STAT_ARMOR]) != ent->client->idleHealth
|| VectorLength(viewChange) > 10
|| ent->client->ps.legsTimer > 0
|| ent->client->ps.torsoTimer > 0
|| ent->client->ps.weaponTime > 0
|| ent->client->ps.weaponstate == WEAPON_CHARGING
|| ent->client->ps.weaponstate == WEAPON_CHARGING_ALT
|| ent->client->ps.zoomMode
|| (ent->client->ps.weaponstate != WEAPON_READY && ent->client->ps.weapon != WP_SABER)
|| ent->client->ps.forceHandExtend != HANDEXTEND_NONE
|| ent->client->ps.saberBlocked != BLOCKED_NONE
|| ent->client->ps.saberBlocking >= level.time
|| ent->client->ps.weapon == WP_MELEE
|| (ent->client->ps.weapon != ent->client->pers.cmd.weapon && ent->s.eType != ET_NPC))
{//FIXME: also check for turning?
qboolean brokeOut = qfalse;
if ( !VectorCompare( vec3_origin, ent->client->ps.velocity )
|| actionPressed || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove
|| (ent->health+ent->client->ps.stats[STAT_ARMOR]) != ent->client->idleHealth
|| ent->client->ps.zoomMode
|| (ent->client->ps.weaponstate != WEAPON_READY && ent->client->ps.weapon != WP_SABER)
|| (ent->client->ps.weaponTime > 0 && ent->client->ps.weapon == WP_SABER)
|| ent->client->ps.weaponstate == WEAPON_CHARGING
|| ent->client->ps.weaponstate == WEAPON_CHARGING_ALT
|| ent->client->ps.forceHandExtend != HANDEXTEND_NONE
|| ent->client->ps.saberBlocked != BLOCKED_NONE
|| ent->client->ps.saberBlocking >= level.time
|| ent->client->ps.weapon == WP_MELEE
|| (ent->client->ps.weapon != ent->client->pers.cmd.weapon && ent->s.eType != ET_NPC))
{
//if in an idle, break out
switch ( ent->client->ps.legsAnim )
{
case BOTH_STAND1IDLE1:
case BOTH_STAND2IDLE1:
case BOTH_STAND2IDLE2:
case BOTH_STAND3IDLE1:
case BOTH_STAND5IDLE1:
ent->client->ps.legsTimer = 0;
brokeOut = qtrue;
break;
}
switch ( ent->client->ps.torsoAnim )
{
case BOTH_STAND1IDLE1:
case BOTH_STAND2IDLE1:
case BOTH_STAND2IDLE2:
case BOTH_STAND3IDLE1:
case BOTH_STAND5IDLE1:
ent->client->ps.torsoTimer = 0;
ent->client->ps.weaponTime = 0;
ent->client->ps.saberMove = LS_READY;
brokeOut = qtrue;
break;
}
}
//
ent->client->idleHealth = (ent->health+ent->client->ps.stats[STAT_ARMOR]);
VectorCopy(ent->client->ps.viewangles, ent->client->idleViewAngles);
if ( ent->client->idleTime < level.time )
{
ent->client->idleTime = level.time;
}
if (brokeOut &&
(ent->client->ps.weaponstate == WEAPON_CHARGING || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT))
{
ent->client->ps.torsoAnim = TORSO_RAISEWEAP1;
}
}
else if ( level.time - ent->client->idleTime > 5000 )
{//been idle for 5 seconds
int idleAnim = -1;
switch ( ent->client->ps.legsAnim )
{
case BOTH_STAND1:
idleAnim = BOTH_STAND1IDLE1;
break;
case BOTH_STAND2:
idleAnim = BOTH_STAND2IDLE1;//Q_irand(BOTH_STAND2IDLE1,BOTH_STAND2IDLE2);
break;
case BOTH_STAND3:
idleAnim = BOTH_STAND3IDLE1;
break;
case BOTH_STAND5:
idleAnim = BOTH_STAND5IDLE1;
break;
}
if (idleAnim == BOTH_STAND2IDLE1 && Q_irand(1, 10) <= 5)
{
idleAnim = BOTH_STAND2IDLE2;
}
if ( idleAnim != -1 && /*PM_HasAnimation( ent, idleAnim )*/idleAnim > 0 && idleAnim < MAX_ANIMATIONS )
{
G_SetAnim(ent, ucmd, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0);
//don't idle again after this anim for a while
//ent->client->idleTime = level.time + PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim ) + Q_irand( 0, 2000 );
ent->client->idleTime = level.time + ent->client->ps.legsTimer + Q_irand( 0, 2000 );
}
}
}
void NPC_Accelerate( gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc )
{
if ( !ent->client || !ent->NPC )
{
return;
}
if ( !ent->NPC->stats.acceleration )
{//No acceleration means just start and stop
ent->NPC->currentSpeed = ent->NPC->desiredSpeed;
}
//FIXME: in cinematics always accel/decel?
else if ( ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed )
{//Only accelerate if at walkSpeeds
if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration )
{
//ent->client->ps.friction = 0;
ent->NPC->currentSpeed += ent->NPC->stats.acceleration;
}
else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed )
{
//ent->client->ps.friction = 0;
ent->NPC->currentSpeed = ent->NPC->desiredSpeed;
}
else if ( fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration )
{//decelerate even when walking
ent->NPC->currentSpeed -= ent->NPC->stats.acceleration;
}
else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed )
{//stop on a dime
ent->NPC->currentSpeed = ent->NPC->desiredSpeed;
}
}
else// if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed )
{//Only decelerate if at runSpeeds
if ( fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration )
{//Accelerate to runspeed
//ent->client->ps.friction = 0;
ent->NPC->currentSpeed += ent->NPC->stats.acceleration;
}
else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed )
{//accelerate instantly
//ent->client->ps.friction = 0;
ent->NPC->currentSpeed = ent->NPC->desiredSpeed;
}
else if ( fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration )
{
ent->NPC->currentSpeed -= ent->NPC->stats.acceleration;
}
else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed )
{
ent->NPC->currentSpeed = ent->NPC->desiredSpeed;
}
}
}
/*
-------------------------
NPC_GetWalkSpeed
-------------------------
*/
static int NPC_GetWalkSpeed( gentity_t *ent )
{
int walkSpeed = 0;
if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) )
return 0;
switch ( ent->client->playerTeam )
{
case NPCTEAM_PLAYER: //To shutup compiler, will add entries later (this is stub code)
default:
walkSpeed = ent->NPC->stats.walkSpeed;
break;
}
return walkSpeed;
}
/*
-------------------------
NPC_GetRunSpeed
-------------------------
*/
static int NPC_GetRunSpeed( gentity_t *ent )
{
int runSpeed = 0;
if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) )
return 0;
/*
switch ( ent->client->playerTeam )
{
case TEAM_BORG:
runSpeed = ent->NPC->stats.runSpeed;
runSpeed += BORG_RUN_INCR * (g_spskill->integer%3);
break;
case TEAM_8472:
runSpeed = ent->NPC->stats.runSpeed;
runSpeed += SPECIES_RUN_INCR * (g_spskill->integer%3);
break;
case TEAM_STASIS:
runSpeed = ent->NPC->stats.runSpeed;
runSpeed += STASIS_RUN_INCR * (g_spskill->integer%3);
break;
case TEAM_BOTS:
runSpeed = ent->NPC->stats.runSpeed;
break;
default:
runSpeed = ent->NPC->stats.runSpeed;
break;
}
*/
// team no longer indicates species/race. Use NPC_class to adjust speed for specific npc types
switch( ent->client->NPC_class)
{
case CLASS_PROBE: // droid cases here to shut-up compiler
case CLASS_GONK:
case CLASS_R2D2:
case CLASS_R5D2:
case CLASS_MARK1:
case CLASS_MARK2:
case CLASS_PROTOCOL:
case CLASS_ATST: // hmm, not really your average droid
case CLASS_MOUSE:
case CLASS_SEEKER:
case CLASS_REMOTE:
runSpeed = ent->NPC->stats.runSpeed;
break;
default:
runSpeed = ent->NPC->stats.runSpeed*1.3f; //rww - seems to slow in MP for some reason.
break;
}
return runSpeed;
}
//Seems like a slightly less than ideal method for this, could it be done on the client?
extern qboolean FlyingCreature( gentity_t *ent );
void G_CheckMovingLoopingSounds( gentity_t *ent, usercmd_t *ucmd )
{
if ( ent->client )
{
if ( (ent->NPC&&!VectorCompare( vec3_origin, ent->client->ps.moveDir ))//moving using moveDir
|| ucmd->forwardmove || ucmd->rightmove//moving using ucmds
|| (ucmd->upmove&&FlyingCreature( ent ))//flier using ucmds to move
|| (FlyingCreature( ent )&&!VectorCompare( vec3_origin, ent->client->ps.velocity )&&ent->health>0))//flier using velocity to move
{
switch( ent->client->NPC_class )
{
case CLASS_R2D2:
ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" );
break;
case CLASS_R5D2:
ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" );
break;
case CLASS_MARK2:
ent->s.loopSound = G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" );
break;
case CLASS_MOUSE:
ent->s.loopSound = G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" );
break;
case CLASS_PROBE:
ent->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" );
}
}
else
{//not moving under your own control, stop loopSound
if ( ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2
|| ent->client->NPC_class == CLASS_MARK2 || ent->client->NPC_class == CLASS_MOUSE
|| ent->client->NPC_class == CLASS_PROBE )
{
ent->s.loopSound = 0;
}
}
}
}
void G_HeldByMonster( gentity_t *ent, usercmd_t **ucmd )
{
if ( ent
&& ent->client
&& ent->client->ps.hasLookTarget )//NOTE: lookTarget is an entity number, so this presumes that client 0 is NOT a Rancor...
{
gentity_t *monster = &g_entities[ent->client->ps.lookTarget];
if ( monster && monster->client )
{
//take the monster's waypoint as your own
ent->waypoint = monster->waypoint;
if ( monster->s.NPC_class == CLASS_RANCOR )
{//only possibility right now, may add Wampa and Sand Creature later
BG_AttachToRancor( monster->ghoul2, //ghoul2 info
monster->r.currentAngles[YAW],
monster->r.currentOrigin,
level.time,
NULL,
monster->modelScale,
(qboolean)(monster->client->ps.eFlags2&EF2_GENERIC_NPC_FLAG),
ent->client->ps.origin,
ent->client->ps.viewangles,
NULL );
}
//[NPCSandCreature]
else if(monster->s.NPC_class == CLASS_SAND_CREATURE)
{
BG_AttachToSandCreature( monster->ghoul2, //ghoul2 info
monster->r.currentAngles[YAW],
monster->r.currentOrigin,
level.time,
NULL,
monster->modelScale,
ent->client->ps.origin,
ent->client->ps.viewangles,
NULL );
}
//[/NPCSandCreature]
VectorClear( ent->client->ps.velocity );
G_SetOrigin( ent, ent->client->ps.origin );
SetClientViewAngle( ent, ent->client->ps.viewangles );
G_SetAngles( ent, ent->client->ps.viewangles );
trap_LinkEntity( ent );//redundant?
}
}
// don't allow movement, weapon switching, and most kinds of button presses
(*ucmd)->forwardmove = 0;
(*ucmd)->rightmove = 0;
(*ucmd)->upmove = 0;
}
//[Linux]
#ifndef __linux__
typedef enum {
#else
enum {
#endif
//[/Linux]
TAUNT_TAUNT = 0,
TAUNT_BOW,
TAUNT_MEDITATE,
TAUNT_FLOURISH,
TAUNT_GLOAT
};
void G_SetTauntAnim( gentity_t *ent, int taunt )
{
int i= 0;
if (ent->client->pers.cmd.upmove ||
ent->client->pers.cmd.forwardmove ||
ent->client->pers.cmd.rightmove)
{ //hack, don't do while moving
return;
}
//[TAUNTFIX]
// dead clients dont get to spam taunt
if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) {
return;
}
if (ent->client->ps.emplacedIndex)
{ //on an emplaced gun
return;
}
if (ent->client->ps.m_iVehicleNum)
{ //in a vehicle like at-st
gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum];
if ( veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER )
return;
if ( veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER )
return;
if ( taunt == TAUNT_FLOURISH || taunt == TAUNT_GLOAT ) taunt = TAUNT_TAUNT;
if ( taunt == TAUNT_MEDITATE || taunt == TAUNT_BOW ) return;
}
//[/TAUNTFIX]
//[ALLTAUNTS]
/*
if ( taunt != TAUNT_TAUNT )
{//normal taunt always allowed
if ( g_gametype.integer != GT_DUEL
&& g_gametype.integer != GT_POWERDUEL )
{//no taunts unless in Duel
return;
}
}
*/
//[/ALLTAUNTS]
// MJN - Check to see if their in spectator
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ){
return;
}
// MJN - Check Sleeping
if( M_isSleeping(ent) ){
return;
}
// MJN - Check if we are already in an emote.
if( InEmote( ent->client->emote_num ) ){
M_Cmd_Emote(ent, ent->client->emote_num );
return;
}
// MJN - Check if we are already in a special emote.
if (ent->client->ps.forceHandExtendTime > level.time &&
ent->client->saberKnockedTime > level.time &&
InSpecialEmote( ent->client->ps.forceDodgeAnim ) )
{
ent->client->ps.forceHandExtendTime = level.time;
ent->client->ps.weaponTime = 0;
ent->client->saberKnockedTime = level.time;
ent->client->emote_num = 0;
return;
}
if ( ent->client->ps.torsoTimer < 1
&& ent->client->ps.forceHandExtend == HANDEXTEND_NONE
&& ent->client->ps.legsTimer < 1
&& ent->client->ps.weaponTime < 1
&& ent->client->ps.saberLockTime < level.time )
{
int anim = -1;
switch ( taunt )
{
case TAUNT_TAUNT:
if ( ent->client->ps.weapon != WP_SABER )
{
anim = BOTH_ENGAGETAUNT;
}
else if ( ent->client->saber[0].tauntAnim != -1 )
{
anim = ent->client->saber[0].tauntAnim;
}
else if ( ent->client->saber[1].model
&& ent->client->saber[1].model[0]
&& ent->client->saber[1].tauntAnim != -1 )
{
anim = ent->client->saber[1].tauntAnim;
}
else
{
switch ( ent->client->ps.fd.saberAnimLevel )
{
case SS_FAST:
case SS_TAVION:
if ( ent->client->ps.saberHolstered == 1
&& ent->client->saber[1].model
&& ent->client->saber[1].model[0] )
{//turn off second saber
G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff );
}
else if ( ent->client->ps.saberHolstered == 0 )
{//turn off first
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff );
}
ent->client->ps.saberHolstered = 2;
anim = BOTH_GESTURE1;
break;
case SS_MEDIUM:
case SS_STRONG:
case SS_DESANN:
anim = BOTH_ENGAGETAUNT;
break;
case SS_DUAL:
if ( ent->client->ps.saberHolstered == 1
&& ent->client->saber[1].model
&& ent->client->saber[1].model[0] )
{//turn on second saber
G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn );
}
else if ( ent->client->ps.saberHolstered == 2 )
{//turn on first
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn );
}
ent->client->ps.saberHolstered = 0;
anim = BOTH_DUAL_TAUNT;
break;
case SS_STAFF:
if ( ent->client->ps.saberHolstered > 0 )
{//turn on all blades
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn );
}
ent->client->ps.saberHolstered = 0;
anim = BOTH_STAFF_TAUNT;
break;
}
}
break;
case TAUNT_BOW:
if ( ent->client->saber[0].bowAnim != -1 )
{
anim = ent->client->saber[0].bowAnim;
}
else if ( ent->client->saber[1].model
&& ent->client->saber[1].model[0]
&& ent->client->saber[1].bowAnim != -1 )
{
anim = ent->client->saber[1].bowAnim;
}
else
{
anim = BOTH_BOW;
}
if ( ent->client->ps.saberHolstered == 1
&& ent->client->saber[1].model
&& ent->client->saber[1].model[0] )
{//turn off second saber
//[TAUNTFIX]
if (ent->client->ps.weapon == WP_SABER)
G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff );
//[/TAUNTFIX]
}
else if ( ent->client->ps.saberHolstered == 0 )
{//turn off first
//[TAUNTFIX]
if (ent->client->ps.weapon == WP_SABER)
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff );
//[/TAUNTFIX]
}
ent->client->ps.saberHolstered = 2;
break;
case TAUNT_MEDITATE:
if ( ent->client->saber[0].meditateAnim != -1 )
{
anim = ent->client->saber[0].meditateAnim;
}
else if ( ent->client->saber[1].model
&& ent->client->saber[1].model[0]
&& ent->client->saber[1].meditateAnim != -1 )
{
anim = ent->client->saber[1].meditateAnim;
}
else
{
anim = BOTH_MEDITATE;
}
if ( ent->client->ps.saberHolstered == 1
&& ent->client->saber[1].model
&& ent->client->saber[1].model[0] )
{//turn off second saber
//[TAUNTFIX]
if (ent->client->ps.weapon == WP_SABER)
G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff );
//[/TAUNTFIX]
}
else if ( ent->client->ps.saberHolstered == 0 )
{//turn off first
//[TAUNTFIX]
if (ent->client->ps.weapon == WP_SABER)
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff );
//[/TAUNTFIX]
}
ent->client->ps.saberHolstered = 2;
break;
case TAUNT_FLOURISH:
if ( ent->client->ps.weapon == WP_SABER )
{
if ( ent->client->ps.saberHolstered == 1
&& ent->client->saber[1].model
&& ent->client->saber[1].model[0] )
{//turn on second saber
G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn );
}
else if ( ent->client->ps.saberHolstered == 2 )
{//turn on first
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn );
}
ent->client->ps.saberHolstered = 0;
if ( ent->client->saber[0].flourishAnim != -1 )
{
anim = ent->client->saber[0].flourishAnim;
}
else if ( ent->client->saber[1].model
&& ent->client->saber[1].model[0]
&& ent->client->saber[1].flourishAnim != -1 )
{
anim = ent->client->saber[1].flourishAnim;
}
else
{
switch ( ent->client->ps.fd.saberAnimLevel )
{
case SS_FAST:
case SS_TAVION:
anim = BOTH_SHOWOFF_FAST;
break;
case SS_MEDIUM:
anim = BOTH_SHOWOFF_MEDIUM;
break;
case SS_STRONG:
case SS_DESANN:
anim = BOTH_SHOWOFF_STRONG;
break;
case SS_DUAL:
anim = BOTH_SHOWOFF_DUAL;
break;
case SS_STAFF:
anim = BOTH_SHOWOFF_STAFF;
break;
}
}
}
break;
case TAUNT_GLOAT:
if ( ent->client->saber[0].gloatAnim != -1 )
{
anim = ent->client->saber[0].gloatAnim;
}
else if ( ent->client->saber[1].model
&& ent->client->saber[1].model[0]
&& ent->client->saber[1].gloatAnim != -1 )
{
anim = ent->client->saber[1].gloatAnim;
}
else
{
switch ( ent->client->ps.fd.saberAnimLevel )
{
case SS_FAST:
case SS_TAVION:
anim = BOTH_VICTORY_FAST;
break;
case SS_MEDIUM:
anim = BOTH_VICTORY_MEDIUM;
break;
case SS_STRONG:
case SS_DESANN:
if ( ent->client->ps.saberHolstered )
{//turn on first
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn );
}
ent->client->ps.saberHolstered = 0;
anim = BOTH_VICTORY_STRONG;
break;
case SS_DUAL:
if ( ent->client->ps.saberHolstered == 1
&& ent->client->saber[1].model
&& ent->client->saber[1].model[0] )
{//turn on second saber
G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn );
}
else if ( ent->client->ps.saberHolstered == 2 )
{//turn on first
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn );
}
ent->client->ps.saberHolstered = 0;
anim = BOTH_VICTORY_DUAL;
break;
case SS_STAFF:
if ( ent->client->ps.saberHolstered )
{//turn on first
G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn );
}
ent->client->ps.saberHolstered = 0;
anim = BOTH_VICTORY_STAFF;
break;
}
}
break;
// MJN - Emotes
case 5://emsit
M_Cmd_Emote(ent, BOTH_SIT2);
break;
case 6://emsit2
M_Cmd_Emote(ent, BOTH_SIT6);
break;
case 7://emsit3
M_Cmd_Emote(ent, BOTH_SIT7);
break;
case 8://emwait
M_HolsterThoseSabers(ent);
anim = BOTH_STAND4;
break;
case 9://emsurrender
M_HolsterThoseSabers(ent);
anim = TORSO_SURRENDER_START;
break;
case 10://emsorrow
M_Cmd_Emote(ent, BOTH_FORCEHEAL_START);
break;
case 11://emhonor
M_Cmd_Emote(ent, BOTH_CROUCH3);
break;
case 12://emnod
anim = BOTH_HEADNOD;
break;
case 13://emshake
anim = BOTH_HEADSHAKE;
break;
case 14://empraise
anim = BOTH_TUSKENTAUNT1;
break;
case 15://emattenhut
M_HolsterThoseSabers(ent);
anim = BOTH_STAND8;
break;
case 16://emcrossarms
M_Cmd_Emote(ent, BOTH_STAND10);
break;
case 17://emalora
anim = BOTH_ALORA_TAUNT;
break;
case 18://emthrow
anim = M_Cmd_Two_RandAnim_f(ent, BOTH_SABERTHROW1START, BOTH_SABERTHROW2START);
break;
case 19://emtavion
anim = BOTH_TAVION_SWORDPOWER;
break;
case 20://empoint
anim = BOTH_SCEPTER_HOLD;
break;
case 21://emcomeon
anim = BOTH_COME_ON1;
break;
case 22://emsit4
M_Cmd_Emote(ent, BOTH_SIT1);
break;
case 23://emsit5
M_Cmd_Emote(ent, BOTH_SIT4);
break;
case 24://emsit6
M_Cmd_Emote(ent, BOTH_SIT5);
break;
case 25://emdance
anim = BOTH_A7_SOULCAL;
break;
case 26://empush
anim = BOTH_ATTACK11;
break;
case 27://emaim
anim = TORSO_WEAPONIDLE4;
break;
case 28://embutton
M_Cmd_Emote(ent, BOTH_BUTTON_HOLD);
break;
case 29://emchoked
anim = M_Cmd_Two_RandAnim_f(ent, BOTH_CHOKE1, BOTH_CHOKE3);
break;
case 30://emtyping
anim = BOTH_CONSOLE1;
break;
case 31://emdie1
M_Cmd_Emote(ent, BOTH_DEATH1);
break;
case 32://emdie2
M_Cmd_Emote(ent, BOTH_DEATH14);
break;
case 33://emdie3
M_Cmd_Emote(ent, BOTH_DEATH17);
break;
case 34://emtwitch
M_Cmd_Emote(ent, BOTH_DEATH14_UNGRIP);
break;
case 35://emtwitch2
M_Cmd_Emote(ent, TORSO_CHOKING1);
break;
case 36://emdie4
M_Cmd_Emote(ent, BOTH_DEATH4);
break;
default:// MJN - Implemented a failsafe.
G_Printf(S_COLOR_RED "Error: Animation %i not found.\n", anim); // This will tell you which anim it cannot find.
break;
}
if ( anim != -1 )
{
if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE )
{
ent->client->ps.forceHandExtend = HANDEXTEND_TAUNT;
ent->client->ps.forceDodgeAnim = anim;
// MJN - Entry for emotes
if (InSpecialEmote( anim ) )
{
// MJN - Stop running Forcepowers
while (i < NUM_FORCE_POWERS)
{
if ((ent->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION)
{
WP_ForcePowerStop(ent, i);
}
i++;
}
ent->client->ps.forceHandExtendTime = level.time + 9999999;
ent->client->saberKnockedTime = level.time + 9999999;
ent->client->ps.weaponTime = 99999999;
ent->client->emote_num = anim;
}
else{// basejk
ent->client->ps.forceHandExtendTime = level.time + BG_AnimLength(ent->localAnimIndex, (animNumber_t)anim);
}
}
if ( taunt != TAUNT_MEDITATE
&& taunt != TAUNT_BOW && ( taunt < 5 || taunt > MAX_EMOTES ) )
{//no sound for meditate or bow
G_AddEvent( ent, EV_TAUNT, taunt );
}
}
}
}
gentity_t *TouchingItem(gentity_t *ent)
{
int i, num;
int touch[MAX_GENTITIES];
vec3_t mins, maxs;
static vec3_t range = { 40, 40, 52 };
gentity_t *hit;
VectorSubtract( ent->client->ps.origin, range, mins );
VectorAdd( ent->client->ps.origin, range, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
for ( i=0 ; i<num ; i++ )
{
hit = &g_entities[touch[i]];
if ( !hit->touch && !ent->touch )
continue;
if ( !( hit->r.contents & CONTENTS_TRIGGER ) )
continue;
if(hit->s.eType == ET_ITEM && hit->item && hit->item->giType == IT_WEAPON)
return hit;
}
return NULL;
}
//[CoOp]
static qboolean ClientCinematicThink( gclient_t *client, usercmd_t *ucmd );
extern qboolean in_camera;
extern qboolean player_locked;
extern char cinematicSkipScript[1024];
extern qboolean skippingCutscene;
//[/CoOp]
//[ROQFILES]
extern qboolean inGameCinematic;
//[ROQFILES]
/*
==============
ClientThink
This will be called once for each client frame, which will
usually be a couple times for each server frame on fast clients.
If "g_synchronousClients 1" is set, this will be called exactly
once for each server frame, which makes for smooth demo recording.
==============
*/
//[DuelSys]
extern vmCvar_t g_duelTimer; // MJN - Next Duel Timer
extern vmCvar_t g_playerDuelShield; // MJN - Duel Shield
extern vmCvar_t g_duelStats; // MJN - Duel Stats
extern vmCvar_t g_logDuelStats;
//[/DuelSys]
//[SaberLockSys]
extern qboolean SabBeh_ButtonforSaberLock(gentity_t* self);
extern void G_RollBalance(gentity_t *self, gentity_t *inflictor, qboolean forceMishap);
//[/SaberLockSys]
//[StanceSelection]
extern qboolean G_ValidSaberStyle(gentity_t *ent, int saberStyle);
extern qboolean WP_SaberCanTurnOffSomeBlades( saberInfo_t *saber );
//[/StanceSelection]
extern void Reload(gentity_t *ent);
extern void ForceLift( gentity_t *self );
void G_SoundOnEnt( gentity_t *ent, int channel, const char *soundPath );
void ClientThink_real( gentity_t *ent ) {
gclient_t *client;
pmove_t pm;
int oldEventSequence;
int msec;
usercmd_t *ucmd;
qboolean isNPC = qfalse;
qboolean controlledByPlayer = qfalse;
qboolean killJetFlags = qtrue;
int i=0;
client = ent->client;
//[ROQFILES]
if(inGameCinematic)
{//don't update the game world if an ROQ files is running.
return;
}
//[/ROQFILES]
if (ent->s.eType == ET_NPC)
{
isNPC = qtrue;
}
// don't think if the client is not yet connected (and thus not yet spawned in)
if (client->pers.connected != CON_CONNECTED && !isNPC) {
return;
}
if(ent->client->blockTime <= level.time && ent->client->blockTime > 0)
{
ent->client->ps.userInt3 &= ~ (1 << FLAG_BLOCKING);
ent->client->blockTime = 0;
}
for(i=0;i<NUM_FORCE_POWERS;i++)
{
if(ent->client->forcePowerStart[i] <= level.time && ent->client->forcePowerStart[i] != -1)
{
ent->client->forcePowerStart[i]=-1;
ent->client->ps.fd.forcePowersActive |= ( 1 << i );
ent->client->ps.activeForcePass = ent->client->ps.fd.forcePowerLevel[i];
}
}
//[SentryHack]
if(ent->client->isHacking == -100 && ent->client->ps.hackingTime <= level.time)
{
ItemUse_Sentry2(ent);
ent->client->isHacking = qfalse;
}
//[/SentryHack]
//[SentryGun]
if (ent->sentryDeadThink <= level.time && ent->sentryDeadThink > 0 )
{
//G_Printf("Give!\n");
ent->client->ps.stats[STAT_HOLDABLE_ITEMS] |= (1 << HI_SENTRY_GUN);
ent->sentryDeadThink = 0;
}
//[/SentryGun]
//[Forcefield]
if (ent->forceFieldThink <= level.time && ent->forceFieldThink > 0)
{
ent->client->ps.stats[STAT_HOLDABLE_ITEMS] |= (1 << HI_SHIELD);
ent->forceFieldThink = 0;
}
//[/Forcefield]
if(ent->client->frozenTime <= level.time && (ent->client->ps.userInt3 & (1 << FLAG_FROZEN)))
ent->client->ps.userInt3 &= ~(1 << FLAG_FROZEN);
//ent->client->ps.pm_type = PM_NORMAL;
if((ent->client->pers.cmd.buttons & BUTTON_THERMALTHROW) && !ent->client->weaponbuttonNeedRelease)
{
gentity_t *item = TouchingItem(ent);
if(item != NULL && item->item != NULL)
{
trace_t *trace;
memset(&trace, 0, sizeof(trace));
Touch_Item(item,ent,trace);
}
else
{
vec3_t tossAngle;
AngleVectors( ent->client->ps.viewangles, tossAngle, NULL, NULL );
TossClientWeapon(ent,tossAngle,500);
//TossClientItems(ent);
}
ent->client->weaponbuttonNeedRelease = qtrue;
}
else if(!(ent->client->pers.cmd.buttons & BUTTON_THERMALTHROW) && ent->client->weaponbuttonNeedRelease)
ent->client->weaponbuttonNeedRelease = qfalse;
//[Reload]
if(ent->reloadTime <= level.time && ent->reloadTime > 0)
{
Reload(ent);
}
else if(ent->reloadTime > 0)
{
//keep him in the "use" anim
if (ent->client->ps.torsoAnim != BOTH_CONSOLE1)
{
G_SetAnim( ent, NULL, SETANIM_TORSO, BOTH_CONSOLE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 );
G_SoundOnEnt(ent, CHAN_WEAPON,"sound/effects/servo_hand.mp3");
}
else
{/*
if(ent->bulletsToReload > 0)
ent->client->ps.torsoTimer = ent->reloadTime;//ReloadTime(ent);
else
ent->client->ps.torsoTimer = 300;*/
}
ent->client->ps.weaponTime = ent->client->ps.torsoTimer - 100;
}
//[/Reload]
// This code was moved here from clientThink to fix a problem with g_synchronousClients
// being set to 1 when in vehicles.
if ( ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum )
{//driving a vehicle
if (g_entities[ent->client->ps.m_iVehicleNum].client)
{
gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum];
if (veh->m_pVehicle &&
veh->m_pVehicle->m_pPilot == (bgEntity_t *)ent)
{ //only take input from the pilot...
veh->client->ps.commandTime = ent->client->ps.commandTime;
memcpy(&veh->m_pVehicle->m_ucmd, &ent->client->pers.cmd, sizeof(usercmd_t));
if ( veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK )
{ //forced input if "chat bubble" is up
veh->m_pVehicle->m_ucmd.buttons = BUTTON_TALK;
veh->m_pVehicle->m_ucmd.forwardmove = 0;
veh->m_pVehicle->m_ucmd.rightmove = 0;
veh->m_pVehicle->m_ucmd.upmove = 0;
}
}
}
}
if (!(client->ps.pm_flags & PMF_FOLLOW))
{
if (g_gametype.integer == GT_SIEGE &&
client->siegeClass != -1 &&
bgSiegeClasses[client->siegeClass].saberStance)
{ //the class says we have to use this stance set.
if (!(bgSiegeClasses[client->siegeClass].saberStance & (1 << client->ps.fd.saberAnimLevel)))
{ //the current stance is not in the bitmask, so find the first one that is.
int i = SS_FAST;
while (i < SS_NUM_SABER_STYLES)
{
if (bgSiegeClasses[client->siegeClass].saberStance & (1 << i))
{
if (i == SS_DUAL
&& client->ps.saberHolstered == 1 )
{//one saber should be off, adjust saberAnimLevel accordinly
client->ps.fd.saberAnimLevelBase = i;
client->ps.fd.saberAnimLevel = SS_FAST;
client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel;
}
else if ( i == SS_STAFF
&& client->ps.saberHolstered == 1
&& client->saber[0].singleBladeStyle != SS_NONE)
{//one saber or blade should be off, adjust saberAnimLevel accordinly
client->ps.fd.saberAnimLevelBase = i;
client->ps.fd.saberAnimLevel = client->saber[0].singleBladeStyle;
client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel;
}
else
{
client->ps.fd.saberAnimLevelBase = client->ps.fd.saberAnimLevel = i;
client->ps.fd.saberDrawAnimLevel = i;
}
break;
}
i++;
}
}
}
//[StanceSelection]
else
{//check to see if we got a valid saber style and holster setting.
if ( !G_ValidSaberStyle(ent, ent->client->ps.fd.saberAnimLevel) )
{//had an illegal style, revert to a valid one
for(int i = 1; i < SS_NUM_SABER_STYLES; i++)
{
if(G_ValidSaberStyle(ent, i))
{
ent->client->ps.fd.saberAnimLevel = i;
ent->client->saberCycleQueue = ent->client->ps.fd.saberAnimLevel;
}
}
}
if(!ent->client->ps.saberInFlight)
{//can't switch saber holster settings if saber is out.
if (ent->client->saber[0].model[0] && ent->client->saber[1].model[0]
&& WP_SaberCanTurnOffSomeBlades( &ent->client->saber[1] )
&& ent->client->ps.fd.saberAnimLevel != SS_DUAL
&& ent->client->ps.saberHolstered == 0)
{//using dual sabers, but not the dual style, turn off blade
ent->client->ps.saberHolstered = 1;
}
else if (ent->client->saber[0].numBlades > 1
&& WP_SaberCanTurnOffSomeBlades( &ent->client->saber[0] )
&& ent->client->ps.fd.saberAnimLevel != SS_STAFF
&& ent->client->ps.saberHolstered == 0)
{//using staff saber, but not the staff style, turn off blade
ent->client->ps.saberHolstered = 1;
}
}
}
//[/StanceSelection]
}
// mark the time, so the connection sprite can be removed
ucmd = &ent->client->pers.cmd;
if ( client && (client->ps.eFlags2&EF2_HELD_BY_MONSTER) )
{
G_HeldByMonster( ent, &ucmd );
}
//[CoOp]
if (client->ps.clientNum < MAX_CLIENTS)
{//player stuff
if ( in_camera )
{
// watch the code here, you MUST "return" within this IF(), *unless* you're stopping the cinematic skip.
//skip cutscene code
if ( !skippingCutscene && (ojp_skipcutscenes.integer == 1
|| ojp_skipcutscenes.integer == 2 || ClientCinematicThink(ent->client, &ent->client->pers.cmd)))
{//order the system to accelerate the cutscene
if (cinematicSkipScript[0])
{//there's a skip script for this cutscene
trap_ICARUS_RunScript(&g_entities[client->ps.clientNum], cinematicSkipScript );
cinematicSkipScript[0] = 0;
}
skippingCutscene = qtrue;
if(ojp_skipcutscenes.integer == 2 || ojp_skipcutscenes.integer == 4)
{//use time accell
trap_Cvar_Set("timescale", "100");
}
return;
}
else if(skippingCutscene && (ojp_skipcutscenes.integer == 0
|| ((ojp_skipcutscenes.integer == 3 || ojp_skipcutscenes.integer == 4)
&& ClientCinematicThink(ent->client, &ent->client->pers.cmd))) )
{//stopping a skip already in progress
skippingCutscene = qfalse;
trap_Cvar_Set("timescale", "1");
}
}
if (player_locked)
{//players' controls are locked, a scripting thingy
ucmd->forwardmove = 0;
ucmd->rightmove = 0;
ucmd->buttons = 0;
ucmd->upmove = 0;
}
}
//[/CoOp]
// sanity check the command time to prevent speedup cheating
if ( ucmd->serverTime > level.time + 200 ) {
ucmd->serverTime = level.time + 200;
// G_Printf("serverTime <<<<<\n" );
}
if ( ucmd->serverTime < level.time - 1000 ) {
ucmd->serverTime = level.time - 1000;
// G_Printf("serverTime >>>>>\n" );
}
if (isNPC && (ucmd->serverTime - client->ps.commandTime) < 1)
{
ucmd->serverTime = client->ps.commandTime + 100;
}
msec = ucmd->serverTime - client->ps.commandTime;
// following others may result in bad times, but we still want
// to check for follow toggles
if ( msec < 1 && client->sess.spectatorState != SPECTATOR_FOLLOW ) {
return;
}
if ( msec > 200 ) {
msec = 200;
}
if ( pmove_msec.integer < 8 ) {
trap_Cvar_Set("pmove_msec", "8");
}
else if (pmove_msec.integer > 33) {
trap_Cvar_Set("pmove_msec", "33");
}
if ( pmove_fixed.integer || client->pers.pmoveFixed ) {
ucmd->serverTime = ((ucmd->serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer;
//if (ucmd->serverTime - client->ps.commandTime <= 0)
// return;
}
//
// check for exiting intermission
//
if ( level.intermissiontime )
{
if ( ent->s.number < MAX_CLIENTS
|| client->NPC_class == CLASS_VEHICLE )
{//players and vehicles do nothing in intermissions
ClientIntermissionThink( client );
return;
}
}
// spectators don't do much
//[CoOp]
//NPCs on the NPCTEAM_NEUTRAL (vehicles and bots) use the same team number as the TEAM_SPECTATOR.
//As such, this was causing those NPCs to act like they were spectating while in CoOp!
if ( client->ps.clientNum < MAX_CLIENTS && (client->sess.sessionTeam == TEAM_SPECTATOR || client->tempSpectate > level.time) ) {
//if ( client->sess.sessionTeam == TEAM_SPECTATOR || client->tempSpectate > level.time ) {
//[/CoOp]
if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
return;
}
SpectatorThink( ent, ucmd );
return;
}
if (ent && ent->client && (ent->client->ps.eFlags & EF_INVULNERABLE))
{
if (ent->client->invulnerableTimer <= level.time)
{
//ent->client->ps.eFlags &= ~EF_INVULNERABLE;
}
}
if (ent->s.eType != ET_NPC)
{
// check for inactivity timer, but never drop the local client of a non-dedicated server
if ( !ClientInactivityTimer( client ) ) {
return;
}
}
//[ExpSys]
//update a player's skill if they haven't had it update in a while.
//1.3 (DarthDie) -- update as soon as we have had skill changed, so we can do AddText
if(!ent->NPC && !(ent->r.svFlags & SVF_BOT) && client->skillUpdated /*&& client->skillDebounce < level.time*/)
{
trap_SendServerCommand(ent->s.number, va("nfr %i %i %i", (int) ent->client->sess.skillPoints, 0, ent->client->sess.sessionTeam));
client->skillDebounce = level.time + 5000;
client->skillUpdated = qfalse;
}
//[/ExpSys]
//Check if we should have a fullbody push effect around the player
if (client->pushEffectTime > level.time)
{
client->ps.eFlags |= EF_BODYPUSH;
}
else if (client->pushEffectTime)
{
client->pushEffectTime = 0;
client->ps.eFlags &= ~EF_BODYPUSH;
}
if (client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK))
{
client->ps.eFlags |= EF_JETPACK;
}
else
{
client->ps.eFlags &= ~EF_JETPACK;
}
if ( client->noclip ) {
client->ps.pm_type = PM_NOCLIP;
} else if ( client->ps.eFlags & EF_DISINTEGRATION ) {
client->ps.pm_type = PM_NOCLIP;
} else if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
client->ps.pm_type = PM_DEAD;
} else {
if (client->ps.forceGripChangeMovetype)
{
client->ps.pm_type = client->ps.forceGripChangeMovetype;
}
else
{
if (client->jetPackOn)
{
client->ps.pm_type = PM_JETPACK;
client->ps.eFlags |= EF_JETPACK_ACTIVE;
killJetFlags = qfalse;
}
//else if(client->frozenTime > level.time)
//client->ps.pm_type = PM_FREEZE;
else
{
// MJN - Freeze Emote
if ( client->emote_freeze ) {
client->ps.pm_type = PM_FREEZE;
}
else {
client->ps.pm_type = PM_NORMAL;
}
}
}
}
if (killJetFlags)
{
client->ps.eFlags &= ~EF_JETPACK_ACTIVE;
client->ps.eFlags &= ~EF_JETPACK_FLAMING;
}
#define SLOWDOWN_DIST 128.0f
#define MIN_NPC_SPEED 16.0f
if (client->bodyGrabIndex != ENTITYNUM_NONE)
{
gentity_t *grabbed = &g_entities[client->bodyGrabIndex];
if (!grabbed->inuse || grabbed->s.eType != ET_BODY ||
(grabbed->s.eFlags & EF_DISINTEGRATION) ||
(grabbed->s.eFlags & EF_NODRAW))
{
if (grabbed->inuse && grabbed->s.eType == ET_BODY)
{
grabbed->s.ragAttach = 0;
}
client->bodyGrabIndex = ENTITYNUM_NONE;
}
else
{
mdxaBone_t rhMat;
vec3_t rhOrg, tAng;
vec3_t bodyDir;
float bodyDist;
ent->client->ps.forceHandExtend = HANDEXTEND_DRAGGING;
if (ent->client->ps.forceHandExtendTime < level.time + 500)
{
ent->client->ps.forceHandExtendTime = level.time + 1000;
}
VectorSet(tAng, 0, ent->client->ps.viewangles[YAW], 0);
trap_G2API_GetBoltMatrix(ent->ghoul2, 0, 0, &rhMat, tAng, ent->client->ps.origin, level.time,
NULL, ent->modelScale); //0 is always going to be right hand bolt
BG_GiveMeVectorFromMatrix(&rhMat, ORIGIN, rhOrg);
VectorSubtract(rhOrg, grabbed->r.currentOrigin, bodyDir);
bodyDist = VectorLength(bodyDir);
if (bodyDist > 40.0f)
{ //can no longer reach
grabbed->s.ragAttach = 0;
client->bodyGrabIndex = ENTITYNUM_NONE;
}
else if (bodyDist > 24.0f)
{
bodyDir[2] = 0; //don't want it floating
//VectorScale(bodyDir, 0.1f, bodyDir);
VectorAdd(grabbed->epVelocity, bodyDir, grabbed->epVelocity);
G_Sound(grabbed, CHAN_AUTO, G_SoundIndex("sound/player/roll1.wav"));
}
}
}
else if (ent->client->ps.forceHandExtend == HANDEXTEND_DRAGGING)
{
ent->client->ps.forceHandExtend = HANDEXTEND_WEAPONREADY;
}
if (ent->NPC && ent->s.NPC_class != CLASS_VEHICLE) //vehicles manage their own speed
{
//FIXME: swoop should keep turning (and moving forward?) for a little bit?
if ( ent->NPC->combatMove == qfalse )
{
//if ( !(ucmd->buttons & BUTTON_USE) )
if (1)
{//Not leaning
qboolean Flying = (qboolean)(ucmd->upmove && (ent->client->ps.eFlags2&EF2_FLYING));//ent->client->moveType == MT_FLYSWIM);
qboolean Climbing = (qboolean)(ucmd->upmove && ent->watertype&CONTENTS_LADDER );
//client->ps.friction = 6;
if ( ucmd->forwardmove || ucmd->rightmove || Flying )
{
//if ( ent->NPC->behaviorState != BS_FORMATION )
{//In - Formation NPCs set thier desiredSpeed themselves
if ( ucmd->buttons & BUTTON_WALKING )
{
ent->NPC->desiredSpeed = NPC_GetWalkSpeed( ent );//ent->NPC->stats.walkSpeed;
}
else//running
{
ent->NPC->desiredSpeed = NPC_GetRunSpeed( ent );//ent->NPC->stats.runSpeed;
}
if ( ent->NPC->currentSpeed >= 80 && !controlledByPlayer )
{//At higher speeds, need to slow down close to stuff
//Slow down as you approach your goal
// if ( ent->NPC->distToGoal < SLOWDOWN_DIST && client->race != RACE_BORG && !(ent->NPC->aiFlags&NPCAI_NO_SLOWDOWN) )//128
if ( ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags&NPCAI_NO_SLOWDOWN) )//128
{
if ( ent->NPC->desiredSpeed > MIN_NPC_SPEED )
{
float slowdownSpeed = ((float)ent->NPC->desiredSpeed) * ent->NPC->distToGoal / SLOWDOWN_DIST;
ent->NPC->desiredSpeed = ceil(slowdownSpeed);
if ( ent->NPC->desiredSpeed < MIN_NPC_SPEED )
{//don't slow down too much
ent->NPC->desiredSpeed = MIN_NPC_SPEED;
}
}
}
}
}
}
else if ( Climbing )
{
ent->NPC->desiredSpeed = ent->NPC->stats.walkSpeed;
}
else
{//We want to stop
ent->NPC->desiredSpeed = 0;
}
NPC_Accelerate( ent, qfalse, qfalse );
if ( ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed )
{//No-one walks this slow
client->ps.speed = ent->NPC->currentSpeed = 0;//Full stop
ucmd->forwardmove = 0;
ucmd->rightmove = 0;
}
else
{
if ( ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed )
{//Play the walkanim
ucmd->buttons |= BUTTON_WALKING;
}
else
{
ucmd->buttons &= ~BUTTON_WALKING;
}
if ( ent->NPC->currentSpeed > 0 )
{//We should be moving
if ( Climbing || Flying )
{
if ( !ucmd->upmove )
{//We need to force them to take a couple more steps until stopped
ucmd->upmove = ent->NPC->last_ucmd.upmove;//was last_upmove;
}
}
else if ( !ucmd->forwardmove && !ucmd->rightmove )
{//We need to force them to take a couple more steps until stopped
ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove;//was last_forwardmove;
ucmd->rightmove = ent->NPC->last_ucmd.rightmove;//was last_rightmove;
}
}
client->ps.speed = ent->NPC->currentSpeed;
//rwwFIXMEFIXME: do this and also check for all real client
if (1)
{
//Slow down on turns - don't orbit!!!
float turndelta = 0;
// if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always thinks it trying to turn according to desiredYaw
//if( client->renderInfo.renderFlags & RF_LOCKEDANGLE ) // yeah I know the RF_ flag is a pretty ugly hack...
if (0) //rwwFIXMEFIXME: ...
{
turndelta = (180 - fabs( AngleDelta( ent->r.currentAngles[YAW], ent->NPC->lockedDesiredYaw ) ))/180;
}
else
{
turndelta = (180 - fabs( AngleDelta( ent->r.currentAngles[YAW], ent->NPC->desiredYaw ) ))/180;
}
if ( turndelta < 0.75f )
{
client->ps.speed = 0;
}
else if ( ent->NPC->distToGoal < 100 && turndelta < 1.0 )
{//Turn is greater than 45 degrees or closer than 100 to goal
client->ps.speed = floor(((float)(client->ps.speed))*turndelta);
}
}
}
}
}
else
{
ent->NPC->desiredSpeed = ( ucmd->buttons & BUTTON_WALKING ) ? NPC_GetWalkSpeed( ent ) : NPC_GetRunSpeed( ent );
client->ps.speed = ent->NPC->desiredSpeed;
}
//[CoOp]
//add case to prevent NPCs from getting their ucmds halved
if (ucmd->buttons & BUTTON_WALKING && ent->s.eType != ET_NPC)
//if (ucmd->buttons & BUTTON_WALKING)
//[/CoOp]
{ //sort of a hack I guess since MP handles walking differently from SP (has some proxy cheat prevention methods)
if (ucmd->forwardmove > 64)
{
ucmd->forwardmove = 64;
}
else if (ucmd->forwardmove < -64)
{
ucmd->forwardmove = -64;
}
if (ucmd->rightmove > 64)
{
ucmd->rightmove = 64;
}
else if ( ucmd->rightmove < -64)
{
ucmd->rightmove = -64;
}
//ent->client->ps.speed = ent->client->ps.basespeed = NPC_GetRunSpeed( ent );
}
client->ps.basespeed = client->ps.speed;
}
else if (!client->ps.m_iVehicleNum &&
(!ent->NPC || ent->s.NPC_class != CLASS_VEHICLE)) //if riding a vehicle it will manage our speed and such
{
// set speed
if(ent->client->ps.userInt3 & (1<<FLAG_FROZEN))
client->ps.speed = 0;
else if((ent->client->ps.fd.forcePowersActive & (1 << FP_LEVITATION)))
client->ps.speed = g_speed.value /(3);
else if(ent->client->ps.eFlags & EF_WALK )
client->ps.speed = g_speed.value /(2);
else
client->ps.speed = g_speed.value;
//Check for a siege class speed multiplier
if (g_gametype.integer == GT_SIEGE &&
client->siegeClass != -1)
{
client->ps.speed *= bgSiegeClasses[client->siegeClass].speed;
}
if (client->bodyGrabIndex != ENTITYNUM_NONE)
{ //can't go nearly as fast when dragging a body around
client->ps.speed *= 0.2f;
}
client->ps.basespeed = client->ps.speed;
}
if ( !ent->NPC || !(ent->NPC->aiFlags&NPCAI_CUSTOM_GRAVITY) )
{//use global gravity
if (ent->NPC && ent->s.NPC_class == CLASS_VEHICLE &&
ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->gravity)
{ //use custom veh gravity
client->ps.gravity = ent->m_pVehicle->m_pVehicleInfo->gravity;
}
else
{
if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE)
{ //in space, so no gravity...
client->ps.gravity = 1.0f;
if (ent->s.number < MAX_CLIENTS)
{
VectorScale(client->ps.velocity, 0.8f, client->ps.velocity);
}
}
else
{
if (client->ps.eFlags2 & EF2_SHIP_DEATH)
{ //float there
VectorClear(client->ps.velocity);
client->ps.gravity = 1.0f;
}
else
{
client->ps.gravity = g_gravity.value;
}
}
}
}
if (ent->client->ps.duelInProgress)
{//racc - we're in a private duel.
gentity_t *duelAgainst = &g_entities[ent->client->ps.duelIndex];
//Keep the time updated, so once this duel ends this player can't engage in a duel for another
//10 seconds. This will give other people a chance to engage in duels in case this player wants
//to engage again right after he's done fighting and someone else is waiting.
//[DuelSys]
ent->client->ps.fd.privateDuelTime = level.time + ( g_duelTimer.integer * 1000 );//10000;
//ent->client->ps.fd.privateDuelTime = level.time + 10000;
//[/DuelSys]
if (ent->client->ps.duelTime < level.time)
{//racc - just started the private duel.
//[DuelSys]
int playerDuelShield; // MJN - for Shields.
//auto holster sabers on private duel start instead of requiring them to be holstered pre-start.
// MJN - Holster those sabers
if (ent->client->ps.weapon == WP_SABER
&& ent->client->ps.duelTime )
{
if(!ent->client->ps.saberHolstered){
if (ent->client->saber[0].soundOff){
G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOff);
}
if (ent->client->saber[1].soundOff){
G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOff);
}
ent->client->ps.saberHolstered = 2;
}
//[/DuelSys]
G_AddEvent(ent, EV_PRIVATE_DUEL, 2);
ent->client->ps.duelTime = 0;
//[DuelSys]
// MJN - Code to save HP/Shield status and give duel declared HP/Shields:
ent->client->savedHP = ent->client->ps.stats[STAT_HEALTH];
ent->client->savedArmor = ent->client->ps.stats[STAT_ARMOR];
// MJN - Update Shields to new values if g_mPlayerDuelShield is anything else but 0.
playerDuelShield = g_playerDuelShield.integer;
// Make sure we have a valid value:
if( playerDuelShield > 100 )
playerDuelShield = 100;
if( playerDuelShield >= 0){
ent->client->ps.stats[STAT_HEALTH] = ent->health = 100; // defaults to 100.
ent->client->ps.stats[STAT_ARMOR] = playerDuelShield;
}
//[/DuelSys]
}
if (duelAgainst
&& duelAgainst->client
&& duelAgainst->inuse
&& duelAgainst->client->ps.weapon == WP_SABER
//[DuelSys]
//removed the holstered requirement
//&& duelAgainst->client->ps.saberHolstered
//[/DuelSys]
&& duelAgainst->client->ps.duelTime)
{
//[DuelSys]
int playerDuelShield; // MJN - for Shields.
//auto holster sabers at start of duel.
if( !duelAgainst->client->ps.saberHolstered ){
if (duelAgainst->client->saber[0].soundOff){
G_Sound(duelAgainst, CHAN_AUTO, duelAgainst->client->saber[0].soundOff);
}
if (duelAgainst->client->saber[1].soundOff){
G_Sound(duelAgainst, CHAN_AUTO, duelAgainst->client->saber[1].soundOff);
}
duelAgainst->client->ps.saberHolstered = 2;
}
//[/DuelSys]
G_AddEvent(duelAgainst, EV_PRIVATE_DUEL, 2);
duelAgainst->client->ps.duelTime = 0;
//[DuelSys]
// MJN - Code to save hitpoint status and give duel hitpoints:
duelAgainst->client->savedHP = duelAgainst->client->ps.stats[STAT_HEALTH];
duelAgainst->client->savedArmor = duelAgainst->client->ps.stats[STAT_ARMOR];
// MJN - Update Shields to new values if g_mPlayerDuelShield is anything else but 0.
playerDuelShield = g_playerDuelShield.integer;
// Make sure we have a valid value:
if( playerDuelShield > 100 )
playerDuelShield = 100;
if( playerDuelShield >= 0 ){
duelAgainst->client->ps.stats[STAT_HEALTH] = duelAgainst->health = 100; // defaults to 100.
duelAgainst->client->ps.stats[STAT_ARMOR] = playerDuelShield;
}
//[/DuelSys]
}
}
else
{
client->ps.speed = 0;
client->ps.basespeed = 0;
ucmd->forwardmove = 0;
ucmd->rightmove = 0;
ucmd->upmove = 0;
}
if (!duelAgainst || !duelAgainst->client || !duelAgainst->inuse ||
duelAgainst->client->ps.duelIndex != ent->s.number)
{//racc - bad dueling opponent state.
ent->client->ps.duelInProgress = qfalse;
G_AddEvent(ent, EV_PRIVATE_DUEL, 0);
}
else if (duelAgainst->health < 1 || duelAgainst->client->ps.stats[STAT_HEALTH] < 1)
{//racc - our opponent died.
ent->client->ps.duelInProgress = qfalse;
duelAgainst->client->ps.duelInProgress = qfalse;
G_AddEvent(ent, EV_PRIVATE_DUEL, 0);
G_AddEvent(duelAgainst, EV_PRIVATE_DUEL, 0);
//Winner gets full health.. providing he's still alive
if (ent->health > 0 && ent->client->ps.stats[STAT_HEALTH] > 0)
{
//[DuelSys]
int playerDuelShield; // MJN - for Shields.
// MJN - Lets show those stats!!
switch ( g_duelStats.integer ){
case 1: // Private only
trap_SendServerCommand( ent-g_entities, va("print \"%s ^7defeated %s ^7with ^1%i ^7HP ^7and ^2%i ^7Shields Remaining.\n\"",
ent->client->pers.netname, duelAgainst->client->pers.netname, ent->client->ps.stats[STAT_HEALTH], ent->client->ps.stats[STAT_ARMOR] ) );
trap_SendServerCommand( duelAgainst-g_entities, va("print \"%s ^7defeated %s ^7with ^1%i ^7HP ^7and ^2%i ^7Shields Remaining.\n\"",
ent->client->pers.netname, duelAgainst->client->pers.netname, ent->client->ps.stats[STAT_HEALTH], ent->client->ps.stats[STAT_ARMOR] ) );
break;
case 2: // Everyone on server
trap_SendServerCommand( -1, va("print \"%s ^7defeated %s ^7with ^1%i ^7HP ^7and ^2%i ^7Shields Remaining.\n\"",
ent->client->pers.netname, duelAgainst->client->pers.netname, ent->client->ps.stats[STAT_HEALTH], ent->client->ps.stats[STAT_ARMOR] ) );
break;
default:
break;
}// MJN - End of Duel Stats
// MJN - Log duel stats to the games.log for possible parsing.
if (g_logDuelStats.integer){
G_LogPrintf( "mlog_privateduelstats: %s defeated %s with %i HP and %i Shields Remaining.\n",
ent->client->pers.netname, duelAgainst->client->pers.netname, ent->client->ps.stats[STAT_HEALTH], ent->client->ps.stats[STAT_ARMOR] );
}
// Give em some shields.
playerDuelShield = g_playerDuelShield.integer;
// Make sure we have a valid value:
if( playerDuelShield > 100 )
playerDuelShield = 100;
if( playerDuelShield >= 0 ){ // MJN - New style HP/Shields:
ent->client->ps.stats[STAT_HEALTH] = ent->health = ent->client->savedHP;
ent->client->ps.stats[STAT_ARMOR] = ent->client->savedArmor;
}
else if ( playerDuelShield < 0 ) { // MJN - base-jk style
if (ent->health < ent->client->ps.stats[STAT_MAX_HEALTH]){
ent->client->ps.stats[STAT_HEALTH] = ent->health = ent->client->ps.stats[STAT_MAX_HEALTH];
}
}
if (g_spawnInvulnerability.integer)
{
ent->client->ps.eFlags |= EF_INVULNERABLE;
ent->client->invulnerableTimer = level.time + g_spawnInvulnerability.integer;
}
}
else
{ //it was a draw, because we both managed to die in the same frame
trap_SendServerCommand( -1, va("cp \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELTIE")) );
}
}
else
{
vec3_t vSub;
float subLen = 0;
VectorSubtract(ent->client->ps.origin, duelAgainst->client->ps.origin, vSub);
subLen = VectorLength(vSub);
if (subLen >= 1024)
{//racc - duelers too far apart. Terminate duel.
ent->client->ps.duelInProgress = qfalse;
duelAgainst->client->ps.duelInProgress = qfalse;
G_AddEvent(ent, EV_PRIVATE_DUEL, 0);
G_AddEvent(duelAgainst, EV_PRIVATE_DUEL, 0);
//[DuelSys]
// MJN - Get Saved HP and Armor Back, but only if g_playerDuelShield is set up for that.
if(g_playerDuelShield.integer >= 0)
{
if (ent->health > 0 && ent->client->ps.stats[STAT_HEALTH] > 0 )
{
ent->client->ps.stats[STAT_HEALTH] = ent->health = ent->client->savedHP;
ent->client->ps.stats[STAT_ARMOR] = ent->client->savedArmor;
}
if (duelAgainst->health > 0 && duelAgainst->client->ps.stats[STAT_HEALTH] > 0 )
{
duelAgainst->client->ps.stats[STAT_HEALTH] = duelAgainst->health = duelAgainst->client->savedHP;
duelAgainst->client->ps.stats[STAT_ARMOR] = duelAgainst->client->savedArmor;
}
}
//[/DuelSys]
trap_SendServerCommand( -1, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELSTOP")) );
}
}
}
if (ent->client->doingThrow > level.time)
{
gentity_t *throwee = &g_entities[ent->client->throwingIndex];
if (!throwee->inuse || !throwee->client || throwee->health < 1 ||
throwee->client->sess.sessionTeam == TEAM_SPECTATOR ||
(throwee->client->ps.pm_flags & PMF_FOLLOW) ||
throwee->client->throwingIndex != ent->s.number)
{
ent->client->doingThrow = 0;
ent->client->ps.forceHandExtend = HANDEXTEND_NONE;
if (throwee->inuse && throwee->client)
{
throwee->client->ps.heldByClient = 0;
throwee->client->beingThrown = 0;
if (throwee->client->ps.forceHandExtend != HANDEXTEND_POSTTHROWN)
{
throwee->client->ps.forceHandExtend = HANDEXTEND_NONE;
}
}
}
}
if (ent->client->beingThrown > level.time)
{
gentity_t *thrower = &g_entities[ent->client->throwingIndex];
if (!thrower->inuse || !thrower->client || thrower->health < 1 ||
thrower->client->sess.sessionTeam == TEAM_SPECTATOR ||
(thrower->client->ps.pm_flags & PMF_FOLLOW) ||
thrower->client->throwingIndex != ent->s.number)
{
ent->client->ps.heldByClient = 0;
ent->client->beingThrown = 0;
if (ent->client->ps.forceHandExtend != HANDEXTEND_POSTTHROWN)
{
ent->client->ps.forceHandExtend = HANDEXTEND_NONE;
}
if (thrower->inuse && thrower->client)
{
thrower->client->doingThrow = 0;
thrower->client->ps.forceHandExtend = HANDEXTEND_NONE;
}
}
else if (thrower->inuse && thrower->client && thrower->ghoul2 &&
trap_G2_HaveWeGhoul2Models(thrower->ghoul2))
{
{
float pDif = 40.0f;
vec3_t boltOrg, pBoltOrg;
vec3_t tAngles;
vec3_t vDif;
vec3_t entDir, otherAngles;
vec3_t fwd, right;
//Always look at the thrower.
VectorSubtract( thrower->client->ps.origin, ent->client->ps.origin, entDir );
VectorCopy( ent->client->ps.viewangles, otherAngles );
otherAngles[YAW] = vectoyaw( entDir );
SetClientViewAngle( ent, otherAngles );
VectorCopy(thrower->client->ps.viewangles, tAngles);
tAngles[PITCH] = tAngles[ROLL] = 0;
//Get the direction between the pelvis and position of the hand
VectorCopy(thrower->client->ps.origin, pBoltOrg);
AngleVectors(tAngles, fwd, right, 0);
boltOrg[0] = pBoltOrg[0] + fwd[0]*8 + right[0]*pDif;
boltOrg[1] = pBoltOrg[1] + fwd[1]*8 + right[1]*pDif;
boltOrg[2] = pBoltOrg[2];
//G_TestLine(boltOrg, pBoltOrg, 0x0000ff, 50);
VectorSubtract(ent->client->ps.origin, boltOrg, vDif);
if (VectorLength(vDif) > 32.0f && (thrower->client->doingThrow - level.time) < 4500)
{ //the hand is too far away, and can no longer hold onto us, so escape.
ent->client->ps.heldByClient = 0;
ent->client->beingThrown = 0;
thrower->client->doingThrow = 0;
thrower->client->ps.forceHandExtend = HANDEXTEND_NONE;
G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*pain25.wav") );
ent->client->ps.forceDodgeAnim = 2;
ent->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN;
ent->client->ps.forceHandExtendTime = level.time + 500;
ent->client->ps.velocity[2] = 400;
G_PreDefSound(ent->client->ps.origin, PDSOUND_FORCEJUMP);
}
else if ((client->beingThrown - level.time) < 4000)
{ //step into the next part of the throw, and go flying back
float vScale = 400.0f;
ent->client->ps.forceHandExtend = HANDEXTEND_POSTTHROWN;
ent->client->ps.forceHandExtendTime = level.time + 1200;
ent->client->ps.forceDodgeAnim = 0;
thrower->client->ps.forceHandExtend = HANDEXTEND_POSTTHROW;
thrower->client->ps.forceHandExtendTime = level.time + 200;
ent->client->ps.heldByClient = 0;
ent->client->ps.heldByClient = 0;
ent->client->beingThrown = 0;
thrower->client->doingThrow = 0;
AngleVectors(thrower->client->ps.viewangles, vDif, 0, 0);
ent->client->ps.velocity[0] = vDif[0]*vScale;
ent->client->ps.velocity[1] = vDif[1]*vScale;
ent->client->ps.velocity[2] = 400;
G_EntitySound( ent, CHAN_VOICE, G_SoundIndex("*pain100.wav") );
G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*jump1.wav") );
//Set the thrower as the "other killer", so if we die from fall/impact damage he is credited.
ent->client->ps.otherKiller = thrower->s.number;
ent->client->ps.otherKillerTime = level.time + 8000;
ent->client->ps.otherKillerDebounceTime = level.time + 100;
//[Asteroids]
ent->client->otherKillerMOD = MOD_FALLING;
ent->client->otherKillerVehWeapon = 0;
ent->client->otherKillerWeaponType = WP_NONE;
//[/Asteroids]
}
else
{ //see if we can move to be next to the hand.. if it's not clear, break the throw.
vec3_t intendedOrigin;
trace_t tr;
trace_t tr2;
VectorSubtract(boltOrg, pBoltOrg, vDif);
VectorNormalize(vDif);
VectorClear(ent->client->ps.velocity);
intendedOrigin[0] = pBoltOrg[0] + vDif[0]*pDif;
intendedOrigin[1] = pBoltOrg[1] + vDif[1]*pDif;
intendedOrigin[2] = thrower->client->ps.origin[2];
trap_Trace(&tr, intendedOrigin, ent->r.mins, ent->r.maxs, intendedOrigin, ent->s.number, ent->clipmask);
trap_Trace(&tr2, ent->client->ps.origin, ent->r.mins, ent->r.maxs, intendedOrigin, ent->s.number, CONTENTS_SOLID);
if (tr.fraction == 1.0 && !tr.startsolid && tr2.fraction == 1.0 && !tr2.startsolid)
{
VectorCopy(intendedOrigin, ent->client->ps.origin);
if ((client->beingThrown - level.time) < 4800)
{
ent->client->ps.heldByClient = thrower->s.number+1;
}
}
else
{ //if the guy can't be put here then it's time to break the throw off.
ent->client->ps.heldByClient = 0;
ent->client->beingThrown = 0;
thrower->client->doingThrow = 0;
thrower->client->ps.forceHandExtend = HANDEXTEND_NONE;
G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*pain25.wav") );
ent->client->ps.forceDodgeAnim = 2;
ent->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN;
ent->client->ps.forceHandExtendTime = level.time + 500;
ent->client->ps.velocity[2] = 400;
G_PreDefSound(ent->client->ps.origin, PDSOUND_FORCEJUMP);
}
}
}
}
}
else if (ent->client->ps.heldByClient)
{
ent->client->ps.heldByClient = 0;
}
//rww - moved this stuff into the pmove code so that it's predicted properly
//BG_AdjustClientSpeed(&client->ps, &client->pers.cmd, level.time);
// set up for pmove
oldEventSequence = client->ps.eventSequence;
memset (&pm, 0, sizeof(pm));
if ( ent->flags & FL_FORCE_GESTURE ) {
ent->flags &= ~FL_FORCE_GESTURE;
ent->client->pers.cmd.buttons |= BUTTON_GESTURE;
}
if (ent->client && ent->client->ps.fallingToDeath &&
//[CoOp]
//[SuperDindon]
(level.time - FALL_FADE_TIME) > ent->client->ps.fallingToDeath &&
!ent->noFallDamage)
//(level.time - FALL_FADE_TIME) > ent->client->ps.fallingToDeath)
//[/CoOp]
{ //die!
if (ent->health > 0)
{
gentity_t *otherKiller = ent;
if (ent->client->ps.otherKillerTime > level.time &&
ent->client->ps.otherKiller != ENTITYNUM_NONE)
{
otherKiller = &g_entities[ent->client->ps.otherKiller];
if (!otherKiller->inuse)
{
otherKiller = ent;
}
}
G_Damage(ent, otherKiller, otherKiller, NULL, ent->client->ps.origin, 9999, DAMAGE_NO_PROTECTION, MOD_FALLING);
G_MuteSound(ent->s.number, CHAN_VOICE); //stop screaming, because you are dead!
}
}
if (ent->client->ps.otherKillerTime > level.time &&
ent->client->ps.groundEntityNum != ENTITYNUM_NONE &&
ent->client->ps.otherKillerDebounceTime < level.time)
{
ent->client->ps.otherKillerTime = 0;
ent->client->ps.otherKiller = ENTITYNUM_NONE;
}
else if (ent->client->ps.otherKillerTime > level.time &&
ent->client->ps.groundEntityNum == ENTITYNUM_NONE)
{
if (ent->client->ps.otherKillerDebounceTime < (level.time + 100))
{
ent->client->ps.otherKillerDebounceTime = level.time + 100;
}
}
//NOTE: can't put USE here *before* PMove!!
if ( ent->client->ps.useDelay > level.time
&& ent->client->ps.m_iVehicleNum )
{//when in a vehicle, debounce the use...
ucmd->buttons &= ~BUTTON_USE;
}
//FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?)
G_AddPushVecToUcmd( ent, ucmd );
//play/stop any looping sounds tied to controlled movement
G_CheckMovingLoopingSounds( ent, ucmd );
pm.ps = &client->ps;
pm.cmd = *ucmd;
if ( pm.ps->pm_type == PM_DEAD ) {
pm.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY;
}
//[BotTweaks]
//We want to allow players to be able to move thru monsterclips.
/*
else if ( ent->r.svFlags & SVF_BOT ) {
pm.tracemask = MASK_PLAYERSOLID | CONTENTS_MONSTERCLIP;
}
*/
//[/BotTweaks]
else {
pm.tracemask = MASK_PLAYERSOLID;
}
pm.trace = trap_Trace;
pm.pointcontents = trap_PointContents;
pm.debugLevel = g_debugMove.integer;
pm.noFootsteps = (qboolean)(( g_dmflags.integer & DF_NO_FOOTSTEPS ) > 0);
pm.pmove_fixed = pmove_fixed.integer | client->pers.pmoveFixed;
pm.pmove_msec = pmove_msec.integer;
pm.animations = bgAllAnims[ent->localAnimIndex].anims;//NULL;
//rww - bgghoul2
pm.ghoul2 = NULL;
#ifdef _DEBUG
if (g_disableServerG2.integer)
{
}
else
#endif
if (ent->ghoul2)
{
if (ent->localAnimIndex > 1)
{ //if it isn't humanoid then we will be having none of this.
pm.ghoul2 = NULL;
}
else
{
pm.ghoul2 = ent->ghoul2;
pm.g2Bolts_LFoot = trap_G2API_AddBolt(ent->ghoul2, 0, "*l_leg_foot");
pm.g2Bolts_RFoot = trap_G2API_AddBolt(ent->ghoul2, 0, "*r_leg_foot");
}
}
//I'll just do this every frame in case the scale changes in realtime (don't need to update the g2 inst for that)
VectorCopy(ent->modelScale, pm.modelScale);
//rww end bgghoul2
pm.gametype = g_gametype.integer;
pm.debugMelee = g_debugMelee.integer;
pm.stepSlideFix = g_stepSlideFix.integer;
pm.noSpecMove = g_noSpecMove.integer;
pm.nonHumanoid = (qboolean)(ent->localAnimIndex > 0);
VectorCopy( client->ps.origin, client->oldOrigin );
//Set up bg entity data
pm.baseEnt = (bgEntity_t *)g_entities;
pm.entSize = sizeof(gentity_t);
if (ent->client->ps.saberLockTime > level.time)
{//racc - handle saberlocks
gentity_t *blockOpp = &g_entities[ent->client->ps.saberLockEnemy];
if (blockOpp && blockOpp->inuse && blockOpp->client)
{
vec3_t lockDir, lockAng;
//VectorClear( ent->client->ps.velocity );
VectorSubtract( blockOpp->r.currentOrigin, ent->r.currentOrigin, lockDir );
//lockAng[YAW] = vectoyaw( defDir );
vectoangles(lockDir, lockAng);
SetClientViewAngle( ent, lockAng );
}
//[SaberLockSys]
if(ent->client->pers.cmd.buttons & BUTTON_ALT_ATTACK && ent->client->pers.cmd.forwardmove < 0
&& !( ent->client->ps.stats[STAT_DODGE] < DODGE_CRITICALLEVEL
|| ent->client->ps.saberAttackChainCount >= MISHAPLEVEL_HEAVY))
{//breaking out of the saberlock!
ent->client->ps.saberLockFrame = 0;
}
else if ( ent->client->ps.saberLockHitCheckTime < level.time )
//if ( ent->client->ps.saberLockHitCheckTime < level.time )
//[/SaberLockSys]
{//have moved to next frame since last lock push
//[SaberLockSys]
//racc - tweaked this to slow down the speed at which the saber locks advance. I'm not sure I like this or not yet.
ent->client->ps.saberLockHitCheckTime = level.time + 25;
//ent->client->ps.saberLockHitCheckTime = level.time;//so we don't push more than once per server frame
//saber locks now use direction and button presses instead of just tapping the attack button.
if( ent->client->ps.userInt3 & (1 << FLAG_LOCKWINNER) )
//if(SabBeh_ButtonforSaberLock(ent))
//if ( ( ent->client->buttons & BUTTON_ATTACK ) && ! ( ent->client->oldbuttons & BUTTON_ATTACK ) )
//[/SaberLockSys]
{
if ( ent->client->ps.saberLockHitIncrementTime < level.time )
{//have moved to next frame since last saberlock attack button press
ent->client->ps.saberLockHitIncrementTime = level.time;//so we don't register an attack key press more than once per server frame
ent->client->ps.saberLockHits++;
//[/SaberLockSys]
}
}
if ( ent->client->ps.saberLockHits > 0 )
{
if ( !ent->client->ps.saberLockAdvance )
{
ent->client->ps.saberLockHits--;
}
ent->client->ps.saberLockAdvance = qtrue;
}
}
}
else
{
ent->client->ps.saberLockFrame = 0;
//check for taunt
if ( (pm.cmd.generic_cmd == GENCMD_ENGAGE_DUEL) && (g_gametype.integer == GT_DUEL || g_gametype.integer == GT_POWERDUEL) )
{//already in a duel, make it a taunt command
pm.cmd.buttons |= BUTTON_GESTURE;
}
}
if (ent->s.number >= MAX_CLIENTS)
{
VectorCopy(ent->r.mins, pm.mins);
VectorCopy(ent->r.maxs, pm.maxs);
#if 1
if (ent->s.NPC_class == CLASS_VEHICLE &&
ent->m_pVehicle )
{
if ( ent->m_pVehicle->m_pPilot)
{ //vehicles want to use their last pilot ucmd I guess
if ((level.time - ent->m_pVehicle->m_ucmd.serverTime) > 2000)
{ //Previous owner disconnected, maybe
ent->m_pVehicle->m_ucmd.serverTime = level.time;
ent->client->ps.commandTime = level.time-100;
msec = 100;
}
memcpy(&pm.cmd, &ent->m_pVehicle->m_ucmd, sizeof(usercmd_t));
//no veh can strafe
pm.cmd.rightmove = 0;
//no crouching or jumping!
pm.cmd.upmove = 0;
//NOTE: button presses were getting lost!
assert(g_entities[ent->m_pVehicle->m_pPilot->s.number].client);
pm.cmd.buttons = (g_entities[ent->m_pVehicle->m_pPilot->s.number].client->pers.cmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK));
}
if ( ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER )
{
if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE )
{//ATST crushes anything underneath it
//ROP VEHICLE_IMP START
//Now 'fixed' ram damage for walkers so that it uses a vehicle parameter
gentity_t *under = &g_entities[ent->client->ps.groundEntityNum];
if ( under && under->health && under->takedamage && under->nDamageFromVehicleTimer < level.time)
{
vec3_t down = {0,0,-1};
int nVehicleCrushingDamage = ent->client->ps.speed * ent->m_pVehicle->m_pVehicleInfo->SpeedMultiplierForRamDamage;
//FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin
G_Damage( under, ent, ent, down, under->r.currentOrigin,
nVehicleCrushingDamage, 0, MOD_CRUSH );
//Don't allow more damage from this vehicle for a bit
under->nDamageFromVehicleTimer = level.time + 500;
}
//ROP VEHICLE_IMP END
}
}
}
#endif
}
Pmove (&pm);
if (ent->client->solidHack)
{
if (ent->client->solidHack > level.time)
{ //whee!
ent->r.contents = 0;
}
else
{
ent->r.contents = CONTENTS_BODY;
ent->client->solidHack = 0;
}
}
if ( ent->NPC )
{
VectorCopy( ent->client->ps.viewangles, ent->r.currentAngles );
}
if (pm.checkDuelLoss)
{//racc - we owned someone in a saber duel, but didn't super break from the saberlock. Check for death blow conditions.
//[SaberLockSys]
//racc - losing a saberlock with checkDuelLoss set results in the loser mishaping.
if (pm.checkDuelLoss > 0 && (pm.checkDuelLoss <= MAX_CLIENTS || (pm.checkDuelLoss < (MAX_GENTITIES-1) && g_entities[pm.checkDuelLoss-1].s.eType == ET_NPC) ) )
{
gentity_t *clientLost = &g_entities[pm.checkDuelLoss-1];
if (clientLost && clientLost->inuse && clientLost->client)
{
G_RollBalance(clientLost, ent, qtrue);
}
}
pm.checkDuelLoss = 0;
}
//[Asteroids]
if ( ent->client->ps.groundEntityNum < ENTITYNUM_WORLD )
{//standing on an ent
gentity_t *groundEnt = &g_entities[ent->client->ps.groundEntityNum];
if ( groundEnt
&& groundEnt->s.eType == ET_NPC
&& groundEnt->s.NPC_class == CLASS_VEHICLE
&& groundEnt->inuse
&& groundEnt->health > 0
&& groundEnt->m_pVehicle )
{//standing on a valid, living vehicle
if ( !groundEnt->client->ps.speed
&& groundEnt->m_pVehicle->m_ucmd.upmove > 0 )
{//a vehicle that's trying to take off!
//just kill me
vec3_t up = {0,0,1};
G_Damage( ent, NULL, NULL, up, ent->r.currentOrigin, 9999999, DAMAGE_NO_PROTECTION, MOD_CRUSH );
return;
}
}
}
//[/Asteroids]
if (pm.cmd.generic_cmd &&
(pm.cmd.generic_cmd != ent->client->lastGenCmd || ent->client->lastGenCmdTime < level.time))
{
ent->client->lastGenCmd = pm.cmd.generic_cmd;
//[SaberSys]
if (pm.cmd.generic_cmd == GENCMD_SABERATTACKCYCLE)
{//saber style toggling debounces debounces faster than normal debouncable commands.
ent->client->lastGenCmdTime = level.time + 100;
}
else if (pm.cmd.generic_cmd != GENCMD_FORCE_THROW &&
//if (pm.cmd.generic_cmd != GENCMD_FORCE_THROW &&
//[/SaberSys]
//[ForceSys]
pm.cmd.generic_cmd != GENCMD_FORCE_PULL &&
pm.cmd.generic_cmd != GENCMD_FORCE_SPEED)
//pm.cmd.generic_cmd != GENCMD_FORCE_PULL)
//[/ForceSys]
{ //these are the only two where you wouldn't care about a delay between
ent->client->lastGenCmdTime = level.time + 300; //default 100ms debounce between issuing the same command.
}
switch(pm.cmd.generic_cmd)
{
case 0:
break;
case GENCMD_SABERSWITCH:
Cmd_ToggleSaber_f(ent);
break;
case GENCMD_ENGAGE_DUEL:
if ( g_gametype.integer == GT_DUEL || g_gametype.integer == GT_POWERDUEL )
{//already in a duel, made it a taunt command
}
else
{
Cmd_EngageDuel_f(ent);
}
break;
case GENCMD_FORCE_HEAL:
ForceHeal(ent);
break;
case GENCMD_FORCE_SPEED:
ForceSpeed(ent, 0);
break;
case GENCMD_FORCE_THROW:
ForceThrow(ent, qfalse);
break;
case GENCMD_FORCE_PULL:
ForceThrow(ent, qtrue);
break;
case GENCMD_FORCE_DISTRACT:
ForceTelepathy(ent);
break;
case GENCMD_FORCE_RAGE:
ForceRage(ent);
break;
case GENCMD_FORCE_MANIPULATE:
ForceProtect(ent);
break;
//[ForceSys][Reload]
case GENCMD_FORCE_ABSORB:
break;
//[/ForceSys][/Reload]
case GENCMD_FORCE_HEALOTHER:
ForceTeamHeal(ent);
break;
case GENCMD_FORCE_LIFT:
ForceLift(ent);
break;
case GENCMD_FORCE_SEEING:
ForceSeeing(ent);
break;
case GENCMD_USE_SEEKER:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SEEKER)) &&
G_ItemUsable(&ent->client->ps, HI_SEEKER) )
{
ItemUse_Seeker(ent);
G_AddEvent(ent, EV_USE_ITEM0+HI_SEEKER, 0);
//[SeekerItemNpc] the seeker is an npc and is commandable by using the item again. This flag will be removed when the
//seeker dies
//ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SEEKER);
//[/SeekerItemNpc]
}
break;
case GENCMD_USE_FIELD:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SHIELD)) &&
G_ItemUsable(&ent->client->ps, HI_SHIELD) )
{
ItemUse_Shield(ent);
G_AddEvent(ent, EV_USE_ITEM0+HI_SHIELD, 0);
ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SHIELD);
}
break;
case GENCMD_USE_BACTA:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC)) &&
G_ItemUsable(&ent->client->ps, HI_MEDPAC) )
{
ItemUse_MedPack(ent);
G_AddEvent(ent, EV_USE_ITEM0+HI_MEDPAC, 0);
ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_MEDPAC);
}
break;
case GENCMD_USE_BACTABIG:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC_BIG)) &&
G_ItemUsable(&ent->client->ps, HI_MEDPAC_BIG) )
{
ItemUse_MedPack_Big(ent);
G_AddEvent(ent, EV_USE_ITEM0+HI_MEDPAC_BIG, 0);
ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_MEDPAC_BIG);
}
break;
case GENCMD_USE_ELECTROBINOCULARS:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_BINOCULARS)) &&
G_ItemUsable(&ent->client->ps, HI_BINOCULARS) )
{
ItemUse_Binoculars(ent);
if (ent->client->ps.zoomMode == 0)
{
G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 1);
}
else
{
G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 2);
}
}
break;
case GENCMD_ZOOM:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_BINOCULARS)) &&
G_ItemUsable(&ent->client->ps, HI_BINOCULARS) )
{
ItemUse_Binoculars(ent);
if (ent->client->ps.zoomMode == 0)
{
G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 1);
}
else
{
G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 2);
}
}
break;
case GENCMD_USE_SENTRY:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SENTRY_GUN)) &&
G_ItemUsable(&ent->client->ps, HI_SENTRY_GUN) )
{
ItemUse_Sentry(ent);
//G_AddEvent(ent, EV_USE_ITEM0+HI_SENTRY_GUN, 0);
//ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SENTRY_GUN);
}
break;
case GENCMD_USE_JETPACK:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) &&
G_ItemUsable(&ent->client->ps, HI_JETPACK) )
{
ItemUse_Jetpack(ent);
G_AddEvent(ent, EV_USE_ITEM0+HI_JETPACK, 0);
/*
if (ent->client->ps.zoomMode == 0)
{
G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 1);
}
else
{
G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 2);
}
*/
}
break;
case GENCMD_USE_HEALTHDISP:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_HEALTHDISP)) &&
G_ItemUsable(&ent->client->ps, HI_HEALTHDISP) )
{
//ItemUse_UseDisp(ent, HI_HEALTHDISP);
G_AddEvent(ent, EV_USE_ITEM0+HI_HEALTHDISP, 0);
}
break;
case GENCMD_USE_AMMODISP:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_AMMODISP)) &&
G_ItemUsable(&ent->client->ps, HI_AMMODISP) )
{
//ItemUse_UseDisp(ent, HI_AMMODISP);
G_AddEvent(ent, EV_USE_ITEM0+HI_AMMODISP, 0);
}
break;
case GENCMD_USE_EWEB:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_EWEB)) &&
G_ItemUsable(&ent->client->ps, HI_EWEB) )
{
ItemUse_UseEWeb(ent);
G_AddEvent(ent, EV_USE_ITEM0+HI_EWEB, 0);
}
break;
case GENCMD_USE_CLOAK:
if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_CLOAK)) &&
G_ItemUsable(&ent->client->ps, HI_CLOAK) )
{
if ( ent->client->ps.powerups[PW_CLOAKED] )
{//decloak
Jedi_Decloak( ent );
}
else
{//cloak
Jedi_Cloak( ent );
}
}
break;
case GENCMD_SABERATTACKCYCLE:
Cmd_SaberAttackCycle_f(ent);
break;
case GENCMD_TAUNT:
G_SetTauntAnim( ent, TAUNT_TAUNT );
break;
case GENCMD_BOW:
G_SetTauntAnim( ent, TAUNT_BOW );
break;
case GENCMD_MEDITATE:
G_SetTauntAnim( ent, TAUNT_MEDITATE );
break;
case GENCMD_FLOURISH:
G_SetTauntAnim( ent, TAUNT_FLOURISH );
break;
case GENCMD_GLOAT:
G_SetTauntAnim( ent, TAUNT_GLOAT );
break;
default:
break;
}
}
// save results of pmove
if ( ent->client->ps.eventSequence != oldEventSequence ) {
ent->eventTime = level.time;
}
if (g_smoothClients.integer)
{
BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qfalse );
//rww - 12-03-02 - Don't snap the origin of players! It screws prediction all up.
}
else {
BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qfalse );
}
if (isNPC)
{
ent->s.eType = ET_NPC;
}
SendPendingPredictableEvents( &ent->client->ps );
//[Grapple]
if ( !( ent->client->ps.eFlags & EF_SPOTLIGHT ) ) {
client->fireHeld = qfalse; // for grapple
}
if (mod_grapple.integer)
{
if (mod_grapple.integer==2 || (g_trueJedi.integer && client->ps.trueNonJedi == qtrue))
{
if ( (pm.cmd.buttons & BUTTON_FORCE_DRAIN) &&
ent->client->ps.pm_type != PM_DEAD &&
!ent->client->hookhasbeenfired) {
Weapon_GrapplingHook_Fire( ent );
ent->client->hookhasbeenfired = qtrue;
}
else if ( client->hook && (client->fireHeld == qfalse || !(pm.cmd.buttons & BUTTON_FORCE_DRAIN)) )
{
Weapon_HookFree(client->hook);
}
if ( !(pm.cmd.buttons & BUTTON_FORCE_DRAIN) &&
ent->client->ps.pm_type != PM_DEAD &&
ent->client->hookhasbeenfired &&
ent->client->fireHeld) {
ent->client->fireHeld = qfalse;
ent->client->hookhasbeenfired = qfalse;
}
}
}
else
{
if ( client->hook && (client->fireHeld == qfalse || !(pm.cmd.buttons & BUTTON_FORCE_DRAIN) ))
{
Weapon_HookFree(client->hook);
}
if ( !( ent->client->ps.eFlags & EF_SPOTLIGHT ) ) {
client->fireHeld = qfalse; // for grapple
}
}
// use the snapped origin for linking so it matches client predicted versions
VectorCopy( ent->s.pos.trBase, ent->r.currentOrigin );
if (ent->s.eType != ET_NPC ||
ent->s.NPC_class != CLASS_VEHICLE ||
!ent->m_pVehicle ||
!ent->m_pVehicle->m_iRemovedSurfaces)
{ //let vehicles that are getting broken apart do their own crazy sizing stuff
VectorCopy (pm.mins, ent->r.mins);
VectorCopy (pm.maxs, ent->r.maxs);
}
ent->waterlevel = pm.waterlevel;
ent->watertype = pm.watertype;
// execute client events
ClientEvents( ent, oldEventSequence );
if ( pm.useEvent )
{
//TODO: Use
// TryUse( ent );
}
if ((ent->client->pers.cmd.buttons & BUTTON_USE) && ent->client->ps.useDelay < level.time)
{
TryUse(ent);
ent->client->ps.useDelay = level.time + 100;
}
// link entity now, after any personal teleporters have been used
trap_LinkEntity (ent);
if ( !ent->client->noclip ) {
G_TouchTriggers( ent );
}
// NOTE: now copy the exact origin over otherwise clients can be snapped into solid
VectorCopy( ent->client->ps.origin, ent->r.currentOrigin );
//test for solid areas in the AAS file
// BotTestAAS(ent->r.currentOrigin);
// touch other objects
ClientImpacts( ent, &pm );
// save results of triggers and client events
if (ent->client->ps.eventSequence != oldEventSequence) {
ent->eventTime = level.time;
}
// swap and latch button actions
client->oldbuttons = client->buttons;
client->buttons = ucmd->buttons;
client->latched_buttons |= client->buttons & ~client->oldbuttons;
// G_VehicleAttachDroidUnit( ent );
// Did we kick someone in our pmove sequence?
if (client->ps.forceKickFlip)
{
gentity_t *faceKicked = &g_entities[client->ps.forceKickFlip-1];
if (faceKicked && faceKicked->client && (!OnSameTeam(ent, faceKicked) || g_friendlyFire.integer) &&
(!faceKicked->client->ps.duelInProgress || faceKicked->client->ps.duelIndex == ent->s.number) &&
(!ent->client->ps.duelInProgress || ent->client->ps.duelIndex == faceKicked->s.number))
{
if ( faceKicked && faceKicked->client && faceKicked->health && faceKicked->takedamage )
{//push them away and do pain
vec3_t oppDir;
int strength = (int)VectorNormalize2( client->ps.velocity, oppDir );
strength *= 0.05;
VectorScale( oppDir, -1, oppDir );
G_Damage( faceKicked, ent, ent, oppDir, client->ps.origin, strength, DAMAGE_NO_ARMOR, MOD_MELEE );
if ( faceKicked->client->ps.weapon != WP_SABER ||
faceKicked->client->ps.fd.saberAnimLevel != FORCE_LEVEL_3 ||
(!BG_SaberInAttack(faceKicked->client->ps.saberMove) && !PM_SaberInStart(faceKicked->client->ps.saberMove) && !PM_SaberInReturn(faceKicked->client->ps.saberMove) && !PM_SaberInTransition(faceKicked->client->ps.saberMove)) )
{
if (faceKicked->health > 0 &&
faceKicked->client->ps.stats[STAT_HEALTH] > 0 &&
faceKicked->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN)
{
if (BG_KnockDownable(&faceKicked->client->ps) && Q_irand(1, 10) <= 3)
{ //only actually knock over sometimes, but always do velocity hit
faceKicked->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN;
faceKicked->client->ps.forceHandExtendTime = level.time + 1100;
faceKicked->client->ps.forceDodgeAnim = 0; //this toggles between 1 and 0, when it's 1 we should play the get up anim
}
faceKicked->client->ps.otherKiller = ent->s.number;
faceKicked->client->ps.otherKillerTime = level.time + 5000;
faceKicked->client->ps.otherKillerDebounceTime = level.time + 100;
//[Asteroids]
faceKicked->client->otherKillerMOD = MOD_MELEE;
faceKicked->client->otherKillerVehWeapon = 0;
faceKicked->client->otherKillerWeaponType = WP_NONE;
//[/Asteroids]
faceKicked->client->ps.velocity[0] = oppDir[0]*(strength*40);
faceKicked->client->ps.velocity[1] = oppDir[1]*(strength*40);
faceKicked->client->ps.velocity[2] = 200;
}
}
G_Sound( faceKicked, CHAN_AUTO, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) );
}
}
client->ps.forceKickFlip = 0;
}
// check for respawning
if ( client->ps.stats[STAT_HEALTH] <= 0
&& !(client->ps.eFlags2&EF2_HELD_BY_MONSTER)//can't respawn while being eaten
&& ent->s.eType != ET_NPC ) {
// wait for the attack button to be pressed
if ( level.time > client->respawnTime && !gDoSlowMoDuel ) {
// forcerespawn is to prevent users from waiting out powerups
int forceRes = g_forcerespawn.integer;
if (g_gametype.integer == GT_POWERDUEL)
{
forceRes = 1;
}
else if (g_gametype.integer == GT_SIEGE &&
g_siegeRespawn.integer)
{ //wave respawning on
forceRes = 1;
}
else if((g_gametype.integer == GT_FFA || g_gametype.integer == GT_TEAM ||
g_gametype.integer == GT_CTF) &&
ojp_ffaRespawnTimer.integer)
forceRes = 1;
if ( forceRes > 0 &&
( level.time - client->respawnTime ) > forceRes * 1000 ) {
respawn( ent );
return;
}
// pressing attack or use is the normal respawn method
if ( ucmd->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) ) {
respawn( ent );
}
}
else if (gDoSlowMoDuel)
{
client->respawnTime = level.time + 1000;
}
return;
}
// perform once-a-second actions
ClientTimerActions( ent, msec );
G_UpdateClientBroadcasts ( ent );
//try some idle anims on ent if getting no input and not moving for some time
G_CheckClientIdle( ent, ucmd );
// This code was moved here from clientThink to fix a problem with g_synchronousClients
// being set to 1 when in vehicles.
if ( ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum )
{//driving a vehicle
//run it
if (g_entities[ent->client->ps.m_iVehicleNum].inuse && g_entities[ent->client->ps.m_iVehicleNum].client)
{
ClientThink(ent->client->ps.m_iVehicleNum, &g_entities[ent->client->ps.m_iVehicleNum].m_pVehicle->m_ucmd);
}
else
{ //vehicle no longer valid?
ent->client->ps.m_iVehicleNum = 0;
}
}
}
/*
==================
G_CheckClientTimeouts
Checks whether a client has exceded any timeouts and act accordingly
==================
*/
void G_CheckClientTimeouts ( gentity_t *ent )
{
// Only timeout supported right now is the timeout to spectator mode
if ( !g_timeouttospec.integer )
{
return;
}
// Already a spectator, no need to boot them to spectator
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR )
{
return;
}
// See how long its been since a command was received by the client and if its
// longer than the timeout to spectator then force this client into spectator mode
if ( level.time - ent->client->pers.cmd.serverTime > g_timeouttospec.integer * 1000 )
{
SetTeam ( ent, "spectator" );
}
}
/*
==================
ClientThink
A new command has arrived from the client
==================
*/
void ClientThink( int clientNum,usercmd_t *ucmd ) {
gentity_t *ent;
ent = g_entities + clientNum;
if (clientNum < MAX_CLIENTS)
{
trap_GetUsercmd( clientNum, &ent->client->pers.cmd );
}
// mark the time we got info, so we can display the
// phone jack if they don't get any for a while
ent->client->lastCmdTime = level.time;
if (ucmd)
{
ent->client->pers.cmd = *ucmd;
}
/* This was moved to clientthink_real, but since its sort of a risky change i left it here for
now as a more concrete reference - BSD
if ( clientNum < MAX_CLIENTS
&& ent->client->ps.m_iVehicleNum )
{//driving a vehicle
if (g_entities[ent->client->ps.m_iVehicleNum].client)
{
gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum];
if (veh->m_pVehicle &&
veh->m_pVehicle->m_pPilot == (bgEntity_t *)ent)
{ //only take input from the pilot...
veh->client->ps.commandTime = ent->client->ps.commandTime;
memcpy(&veh->m_pVehicle->m_ucmd, &ent->client->pers.cmd, sizeof(usercmd_t));
if ( veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK )
{ //forced input if "chat bubble" is up
veh->m_pVehicle->m_ucmd.buttons = BUTTON_TALK;
veh->m_pVehicle->m_ucmd.forwardmove = 0;
veh->m_pVehicle->m_ucmd.rightmove = 0;
veh->m_pVehicle->m_ucmd.upmove = 0;
}
}
}
}
*/
if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) {
ClientThink_real( ent );
}
// vehicles are clients and when running synchronous they still need to think here
// so special case them.
else if ( clientNum >= MAX_CLIENTS ) {
ClientThink_real( ent );
}
/* This was moved to clientthink_real, but since its sort of a risky change i left it here for
now as a more concrete reference - BSD
if ( clientNum < MAX_CLIENTS
&& ent->client->ps.m_iVehicleNum )
{//driving a vehicle
//run it
if (g_entities[ent->client->ps.m_iVehicleNum].inuse &&
g_entities[ent->client->ps.m_iVehicleNum].client)
{
ClientThink(ent->client->ps.m_iVehicleNum, &g_entities[ent->client->ps.m_iVehicleNum].m_pVehicle->m_ucmd);
}
else
{ //vehicle no longer valid?
ent->client->ps.m_iVehicleNum = 0;
}
}
*/
}
void G_RunClient( gentity_t *ent ) {
if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) {
return;
}
ent->client->pers.cmd.serverTime = level.time;
ClientThink_real( ent );
}
/*
==================
SpectatorClientEndFrame
==================
*/
void SpectatorClientEndFrame( gentity_t *ent ) {
gclient_t *cl;
if (ent->s.eType == ET_NPC)
{
assert(0);
return;
}
// if we are doing a chase cam or a remote view, grab the latest info
if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) {
int clientNum;//, flags;
clientNum = ent->client->sess.spectatorClient;
// team follow1 and team follow2 go to whatever clients are playing
if ( clientNum == -1 ) {
clientNum = level.follow1;
} else if ( clientNum == -2 ) {
clientNum = level.follow2;
}
if ( clientNum >= 0 ) {
cl = &level.clients[ clientNum ];
if ( cl->pers.connected == CON_CONNECTED && cl->sess.sessionTeam != TEAM_SPECTATOR ) {
//flags = (cl->mGameFlags & ~(PSG_VOTED | PSG_TEAMVOTED)) | (ent->client->mGameFlags & (PSG_VOTED | PSG_TEAMVOTED));
//ent->client->mGameFlags = flags;
ent->client->ps.eFlags = cl->ps.eFlags;
ent->client->ps = cl->ps;
ent->client->ps.pm_flags |= PMF_FOLLOW;
return;
} else {
// drop them to free spectators unless they are dedicated camera followers
if ( ent->client->sess.spectatorClient >= 0 ) {
ent->client->sess.spectatorState = SPECTATOR_FREE;
ClientBegin( ent->client - level.clients, qtrue );
}
}
}
}
if ( ent->client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
ent->client->ps.pm_flags |= PMF_SCOREBOARD;
} else {
ent->client->ps.pm_flags &= ~PMF_SCOREBOARD;
}
}
/*
==============
ClientEndFrame
Called at the end of each server frame for each connected client
A fast client will have multiple ClientThink for each ClientEdFrame,
while a slow client may have multiple ClientEndFrame between ClientThink.
==============
*/
void ClientEndFrame( gentity_t *ent ) {
int i;
clientPersistant_t *pers;
qboolean isNPC = qfalse;
if (ent->s.eType == ET_NPC)
{
isNPC = qtrue;
}
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
SpectatorClientEndFrame( ent );
return;
}
pers = &ent->client->pers;
// turn off any expired powerups
for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
if ( ent->client->ps.powerups[ i ] < level.time ) {
ent->client->ps.powerups[ i ] = 0;
}
}
//
// If the end of unit layout is displayed, don't give
// the player any normal movement attributes
//
if ( level.intermissiontime ) {
if ( ent->s.number < MAX_CLIENTS
|| ent->client->NPC_class == CLASS_VEHICLE )
{//players and vehicles do nothing in intermissions
return;
}
}
// burn from lava, etc
P_WorldEffects (ent);
// apply all the damage taken this frame
P_DamageFeedback (ent);
// add the EF_CONNECTION flag if we haven't gotten commands recently
if ( level.time - ent->client->lastCmdTime > 1000 ) {
ent->s.eFlags |= EF_CONNECTION;
} else {
ent->s.eFlags &= ~EF_CONNECTION;
}
ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health...
G_SetClientSound (ent);
// set the latest infor
if (g_smoothClients.integer) {
BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qfalse );
//rww - 12-03-02 - Don't snap the origin of players! It screws prediction all up.
}
else {
BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qfalse );
}
if (isNPC)
{
ent->s.eType = ET_NPC;
}
SendPendingPredictableEvents( &ent->client->ps );
// set the bit for the reachability area the client is currently in
// i = trap_AAS_PointReachabilityAreaIndex( ent->client->ps.origin );
// ent->client->areabits[i >> 3] |= 1 << (i & 7);
}
//[CoOp]
/*
====================
ClientIntermissionThink
====================
*/
static qboolean ClientCinematicThink( gclient_t *client, usercmd_t *ucmd ) {
client->ps.eFlags &= ~EF_FIRING;
// swap button actions
client->oldbuttons = client->buttons;
client->buttons = ucmd->buttons;
if ( client->buttons & ( BUTTON_USE ) & ( client->oldbuttons ^ client->buttons ) ) {
return( qtrue );
}
return( qfalse );
}
//[/CoOp]
| [
"[email protected]@5776d9f2-9662-11de-ad41-3fcdc5e0e42d"
] | [
[
[
1,
4517
]
]
] |
d8fdf436d30e04a23387c9592b95984ef4141f63 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/win/WebPreferences.cpp | 23d12a70ec330abccee9a63348df907b75e438fb | [
"BSD-2-Clause"
] | permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,636 | cpp | /*
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple 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. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebKit.h"
#include "WebKitDLL.h"
#include "WebPreferences.h"
#include "COMPtr.h"
#include "WebNotificationCenter.h"
#include "WebPreferenceKeysPrivate.h"
#include <wtf/text/StringHash.h>
#include <WebCore/FileSystem.h>
#include <WebCore/Font.h>
#include <WebCore/PlatformString.h>
#include <WebCore/WKCACFLayerRenderer.h>
#include "WebLocalizableStrings.h"
#include <CoreFoundation/CoreFoundation.h>
#include <limits>
#include <shlobj.h>
#include <tchar.h>
#include <wtf/HashMap.h>
#include <wtf/OwnArrayPtr.h>
#include <wtf/text/CString.h>
#if PLATFORM(CG)
#include <CoreGraphics/CoreGraphics.h>
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif
using namespace WebCore;
using std::numeric_limits;
static const String& oldPreferencesPath()
{
static String path = pathByAppendingComponent(roamingUserSpecificStorageDirectory(), "WebKitPreferences.plist");
return path;
}
template<typename NumberType> struct CFNumberTraits { static const unsigned Type; };
template<> struct CFNumberTraits<int> { static const unsigned Type = kCFNumberSInt32Type; };
template<> struct CFNumberTraits<LONGLONG> { static const unsigned Type = kCFNumberLongLongType; };
template<> struct CFNumberTraits<float> { static const unsigned Type = kCFNumberFloat32Type; };
template<typename NumberType>
static NumberType numberValueForPreferencesValue(CFPropertyListRef value)
{
if (!value)
return 0;
CFTypeID cfType = CFGetTypeID(value);
if (cfType == CFStringGetTypeID())
return static_cast<NumberType>(CFStringGetIntValue(static_cast<CFStringRef>(value)));
else if (cfType == CFBooleanGetTypeID()) {
Boolean boolVal = CFBooleanGetValue(static_cast<CFBooleanRef>(value));
return boolVal ? 1 : 0;
} else if (cfType == CFNumberGetTypeID()) {
NumberType val = 0;
CFNumberGetValue(static_cast<CFNumberRef>(value), CFNumberTraits<NumberType>::Type, &val);
return val;
}
return 0;
}
template<typename NumberType>
static RetainPtr<CFNumberRef> cfNumber(NumberType value)
{
return RetainPtr<CFNumberRef>(AdoptCF, CFNumberCreate(0, CFNumberTraits<NumberType>::Type, &value));
}
static bool booleanValueForPreferencesValue(CFPropertyListRef value)
{
return numberValueForPreferencesValue<int>(value);
}
// WebPreferences ----------------------------------------------------------------
static CFDictionaryRef defaultSettings;
static HashMap<WTF::String, COMPtr<WebPreferences> > webPreferencesInstances;
WebPreferences* WebPreferences::sharedStandardPreferences()
{
static WebPreferences* standardPreferences;
if (!standardPreferences) {
standardPreferences = WebPreferences::createInstance();
standardPreferences->setAutosaves(TRUE);
standardPreferences->load();
}
return standardPreferences;
}
WebPreferences::WebPreferences()
: m_refCount(0)
, m_autoSaves(0)
, m_automaticallyDetectsCacheModel(true)
, m_numWebViews(0)
{
gClassCount++;
gClassNameCount.add("WebPreferences");
}
WebPreferences::~WebPreferences()
{
gClassCount--;
gClassNameCount.remove("WebPreferences");
}
WebPreferences* WebPreferences::createInstance()
{
WebPreferences* instance = new WebPreferences();
instance->AddRef();
return instance;
}
HRESULT WebPreferences::postPreferencesChangesNotification()
{
IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
HRESULT hr = nc->postNotificationName(webPreferencesChangedNotification(), static_cast<IWebPreferences*>(this), 0);
if (FAILED(hr))
return hr;
return S_OK;
}
WebPreferences* WebPreferences::getInstanceForIdentifier(BSTR identifier)
{
if (!identifier)
return sharedStandardPreferences();
WTF::String identifierString(identifier, SysStringLen(identifier));
return webPreferencesInstances.get(identifierString).get();
}
void WebPreferences::setInstance(WebPreferences* instance, BSTR identifier)
{
if (!identifier || !instance)
return;
WTF::String identifierString(identifier, SysStringLen(identifier));
webPreferencesInstances.add(identifierString, instance);
}
void WebPreferences::removeReferenceForIdentifier(BSTR identifier)
{
if (!identifier || webPreferencesInstances.isEmpty())
return;
WTF::String identifierString(identifier, SysStringLen(identifier));
WebPreferences* webPreference = webPreferencesInstances.get(identifierString).get();
if (webPreference && webPreference->m_refCount == 1)
webPreferencesInstances.remove(identifierString);
}
void WebPreferences::initializeDefaultSettings()
{
if (defaultSettings)
return;
CFMutableDictionaryRef defaults = CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(defaults, CFSTR(WebKitStandardFontPreferenceKey), CFSTR("Times New Roman"));
CFDictionaryAddValue(defaults, CFSTR(WebKitFixedFontPreferenceKey), CFSTR("Courier New"));
CFDictionaryAddValue(defaults, CFSTR(WebKitSerifFontPreferenceKey), CFSTR("Times New Roman"));
CFDictionaryAddValue(defaults, CFSTR(WebKitSansSerifFontPreferenceKey), CFSTR("Arial"));
CFDictionaryAddValue(defaults, CFSTR(WebKitCursiveFontPreferenceKey), CFSTR("Comic Sans MS"));
CFDictionaryAddValue(defaults, CFSTR(WebKitFantasyFontPreferenceKey), CFSTR("Comic Sans MS"));
CFDictionaryAddValue(defaults, CFSTR(WebKitMinimumFontSizePreferenceKey), CFSTR("1"));
CFDictionaryAddValue(defaults, CFSTR(WebKitMinimumLogicalFontSizePreferenceKey), CFSTR("9"));
CFDictionaryAddValue(defaults, CFSTR(WebKitDefaultFontSizePreferenceKey), CFSTR("16"));
CFDictionaryAddValue(defaults, CFSTR(WebKitDefaultFixedFontSizePreferenceKey), CFSTR("13"));
WTF::String defaultDefaultEncoding(LPCTSTR_UI_STRING("ISO-8859-1", "The default, default character encoding"));
CFDictionaryAddValue(defaults, CFSTR(WebKitDefaultTextEncodingNamePreferenceKey), defaultDefaultEncoding.createCFString());
CFDictionaryAddValue(defaults, CFSTR(WebKitUserStyleSheetEnabledPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitUserStyleSheetLocationPreferenceKey), CFSTR(""));
CFDictionaryAddValue(defaults, CFSTR(WebKitShouldPrintBackgroundsPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitTextAreasAreResizablePreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitJavaEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitJavaScriptEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitWebSecurityEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitAllowUniversalAccessFromFileURLsPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitAllowFileAccessFromFileURLsPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitJavaScriptCanAccessClipboardPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitXSSAuditorEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitFrameFlatteningEnabledPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitJavaScriptCanOpenWindowsAutomaticallyPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitPluginsEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitDatabasesEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitLocalStorageEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitExperimentalNotificationsEnabledPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitZoomsTextOnlyPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitAllowAnimatedImagesPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitAllowAnimatedImageLoopingPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitDisplayImagesKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitBackForwardCacheExpirationIntervalKey), CFSTR("1800"));
CFDictionaryAddValue(defaults, CFSTR(WebKitTabToLinksPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitPrivateBrowsingEnabledPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitRespectStandardStyleKeyEquivalentsPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitShowsURLsInToolTipsPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitPDFDisplayModePreferenceKey), CFSTR("1"));
CFDictionaryAddValue(defaults, CFSTR(WebKitPDFScaleFactorPreferenceKey), CFSTR("0"));
RetainPtr<CFStringRef> linkBehaviorStringRef(AdoptCF, CFStringCreateWithFormat(0, 0, CFSTR("%d"), WebKitEditableLinkDefaultBehavior));
CFDictionaryAddValue(defaults, CFSTR(WebKitEditableLinkBehaviorPreferenceKey), linkBehaviorStringRef.get());
CFDictionaryAddValue(defaults, CFSTR(WebKitHistoryItemLimitKey), CFSTR("1000"));
CFDictionaryAddValue(defaults, CFSTR(WebKitHistoryAgeInDaysLimitKey), CFSTR("7"));
CFDictionaryAddValue(defaults, CFSTR(WebKitIconDatabaseLocationKey), CFSTR(""));
CFDictionaryAddValue(defaults, CFSTR(WebKitIconDatabaseEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitFontSmoothingTypePreferenceKey), CFSTR("2"));
CFDictionaryAddValue(defaults, CFSTR(WebKitFontSmoothingContrastPreferenceKey), CFSTR("2"));
CFDictionaryAddValue(defaults, CFSTR(WebKitCookieStorageAcceptPolicyPreferenceKey), CFSTR("2"));
CFDictionaryAddValue(defaults, CFSTR(WebContinuousSpellCheckingEnabledPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebGrammarCheckingEnabledPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(AllowContinuousSpellCheckingPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitUsesPageCachePreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitLocalStorageDatabasePathPreferenceKey), CFSTR(""));
RetainPtr<CFStringRef> cacheModelRef(AdoptCF, CFStringCreateWithFormat(0, 0, CFSTR("%d"), WebCacheModelDocumentViewer));
CFDictionaryAddValue(defaults, CFSTR(WebKitCacheModelPreferenceKey), cacheModelRef.get());
CFDictionaryAddValue(defaults, CFSTR(WebKitAuthorAndUserStylesEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitApplicationChromeModePreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitOfflineWebApplicationCacheEnabledPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitPaintNativeControlsPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitUseHighResolutionTimersPreferenceKey), kCFBooleanTrue);
RetainPtr<CFStringRef> pluginAllowedRunTime(AdoptCF, CFStringCreateWithFormat(0, 0, CFSTR("%u"), numeric_limits<unsigned>::max()));
CFDictionaryAddValue(defaults, CFSTR(WebKitPluginAllowedRunTimePreferenceKey), pluginAllowedRunTime.get());
CFDictionaryAddValue(defaults, CFSTR(WebKitAcceleratedCompositingEnabledPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitShowDebugBordersPreferenceKey), kCFBooleanFalse);
CFDictionaryAddValue(defaults, CFSTR(WebKitDNSPrefetchingEnabledPreferenceKey), kCFBooleanTrue);
CFDictionaryAddValue(defaults, CFSTR(WebKitMemoryInfoEnabledPreferenceKey), kCFBooleanFalse);
defaultSettings = defaults;
}
RetainPtr<CFPropertyListRef> WebPreferences::valueForKey(CFStringRef key)
{
RetainPtr<CFPropertyListRef> value = CFDictionaryGetValue(m_privatePrefs.get(), key);
if (value)
return value;
value.adoptCF(CFPreferencesCopyAppValue(key, kCFPreferencesCurrentApplication));
if (value)
return value;
return CFDictionaryGetValue(defaultSettings, key);
}
void WebPreferences::setValueForKey(CFStringRef key, CFPropertyListRef value)
{
CFDictionarySetValue(m_privatePrefs.get(), key, value);
if (m_autoSaves) {
CFPreferencesSetAppValue(key, value, kCFPreferencesCurrentApplication);
save();
}
}
BSTR WebPreferences::stringValueForKey(CFStringRef key)
{
RetainPtr<CFPropertyListRef> value = valueForKey(key);
if (!value || (CFGetTypeID(value.get()) != CFStringGetTypeID()))
return 0;
CFStringRef str = static_cast<CFStringRef>(value.get());
CFIndex length = CFStringGetLength(str);
const UniChar* uniChars = CFStringGetCharactersPtr(str);
if (uniChars)
return SysAllocStringLen((LPCTSTR)uniChars, length);
BSTR bstr = SysAllocStringLen(0, length);
if (!bstr)
return 0;
if (!CFStringGetCString(str, (char*)bstr, (length+1)*sizeof(WCHAR), kCFStringEncodingUTF16)) {
SysFreeString(bstr);
return 0;
}
bstr[length] = 0;
return bstr;
}
int WebPreferences::integerValueForKey(CFStringRef key)
{
return numberValueForPreferencesValue<int>(valueForKey(key).get());
}
BOOL WebPreferences::boolValueForKey(CFStringRef key)
{
return booleanValueForPreferencesValue(valueForKey(key).get());
}
float WebPreferences::floatValueForKey(CFStringRef key)
{
return numberValueForPreferencesValue<float>(valueForKey(key).get());
}
LONGLONG WebPreferences::longlongValueForKey(CFStringRef key)
{
return numberValueForPreferencesValue<LONGLONG>(valueForKey(key).get());
}
void WebPreferences::setStringValue(CFStringRef key, LPCTSTR value)
{
BSTR val = stringValueForKey(key);
if (val && !_tcscmp(val, value))
return;
SysFreeString(val);
RetainPtr<CFStringRef> valueRef(AdoptCF,
CFStringCreateWithCharactersNoCopy(0, (UniChar*)_wcsdup(value), (CFIndex)_tcslen(value), kCFAllocatorMalloc));
setValueForKey(key, valueRef.get());
postPreferencesChangesNotification();
}
void WebPreferences::setIntegerValue(CFStringRef key, int value)
{
if (integerValueForKey(key) == value)
return;
setValueForKey(key, cfNumber(value).get());
postPreferencesChangesNotification();
}
void WebPreferences::setFloatValue(CFStringRef key, float value)
{
if (floatValueForKey(key) == value)
return;
setValueForKey(key, cfNumber(value).get());
postPreferencesChangesNotification();
}
void WebPreferences::setBoolValue(CFStringRef key, BOOL value)
{
if (boolValueForKey(key) == value)
return;
setValueForKey(key, value ? kCFBooleanTrue : kCFBooleanFalse);
postPreferencesChangesNotification();
}
void WebPreferences::setLongLongValue(CFStringRef key, LONGLONG value)
{
if (longlongValueForKey(key) == value)
return;
setValueForKey(key, cfNumber(value).get());
postPreferencesChangesNotification();
}
BSTR WebPreferences::webPreferencesChangedNotification()
{
static BSTR webPreferencesChangedNotification = SysAllocString(WebPreferencesChangedNotification);
return webPreferencesChangedNotification;
}
BSTR WebPreferences::webPreferencesRemovedNotification()
{
static BSTR webPreferencesRemovedNotification = SysAllocString(WebPreferencesRemovedNotification);
return webPreferencesRemovedNotification;
}
void WebPreferences::save()
{
CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}
void WebPreferences::load()
{
initializeDefaultSettings();
m_privatePrefs.adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
migrateWebKitPreferencesToCFPreferences();
}
void WebPreferences::migrateWebKitPreferencesToCFPreferences()
{
CFStringRef didMigrateKey = CFSTR(WebKitDidMigrateWebKitPreferencesToCFPreferencesPreferenceKey);
if (boolValueForKey(didMigrateKey))
return;
bool oldValue = m_autoSaves;
m_autoSaves = true;
setBoolValue(didMigrateKey, TRUE);
m_autoSaves = oldValue;
WTF::CString path = oldPreferencesPath().utf8();
RetainPtr<CFURLRef> urlRef(AdoptCF, CFURLCreateFromFileSystemRepresentation(0, reinterpret_cast<const UInt8*>(path.data()), path.length(), false));
if (!urlRef)
return;
RetainPtr<CFReadStreamRef> stream(AdoptCF, CFReadStreamCreateWithFile(0, urlRef.get()));
if (!stream)
return;
if (!CFReadStreamOpen(stream.get()))
return;
CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0 | kCFPropertyListXMLFormat_v1_0;
RetainPtr<CFPropertyListRef> plist(AdoptCF, CFPropertyListCreateFromStream(0, stream.get(), 0, kCFPropertyListMutableContainersAndLeaves, &format, 0));
CFReadStreamClose(stream.get());
if (!plist || CFGetTypeID(plist.get()) != CFDictionaryGetTypeID())
return;
copyWebKitPreferencesToCFPreferences(static_cast<CFDictionaryRef>(plist.get()));
deleteFile(oldPreferencesPath());
}
void WebPreferences::copyWebKitPreferencesToCFPreferences(CFDictionaryRef dict)
{
ASSERT_ARG(dict, dict);
int count = CFDictionaryGetCount(dict);
if (count <= 0)
return;
CFStringRef didRemoveDefaultsKey = CFSTR(WebKitDidMigrateDefaultSettingsFromSafari3BetaPreferenceKey);
bool omitDefaults = !booleanValueForPreferencesValue(CFDictionaryGetValue(dict, didRemoveDefaultsKey));
OwnArrayPtr<CFTypeRef> keys(new CFTypeRef[count]);
OwnArrayPtr<CFTypeRef> values(new CFTypeRef[count]);
CFDictionaryGetKeysAndValues(dict, keys.get(), values.get());
for (int i = 0; i < count; ++i) {
if (!keys[i] || !values[i] || CFGetTypeID(keys[i]) != CFStringGetTypeID())
continue;
if (omitDefaults) {
CFTypeRef defaultValue = CFDictionaryGetValue(defaultSettings, keys[i]);
if (defaultValue && CFEqual(defaultValue, values[i]))
continue;
}
setValueForKey(static_cast<CFStringRef>(keys[i]), values[i]);
}
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebPreferences::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IWebPreferences*>(this);
else if (IsEqualGUID(riid, IID_IWebPreferences))
*ppvObject = static_cast<IWebPreferences*>(this);
else if (IsEqualGUID(riid, IID_IWebPreferencesPrivate))
*ppvObject = static_cast<IWebPreferencesPrivate*>(this);
else if (IsEqualGUID(riid, CLSID_WebPreferences))
*ppvObject = this;
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE WebPreferences::AddRef(void)
{
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE WebPreferences::Release(void)
{
ULONG newRef = --m_refCount;
if (!newRef)
delete(this);
return newRef;
}
// IWebPreferences ------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebPreferences::standardPreferences(
/* [retval][out] */ IWebPreferences** standardPreferences)
{
if (!standardPreferences)
return E_POINTER;
*standardPreferences = sharedStandardPreferences();
(*standardPreferences)->AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::initWithIdentifier(
/* [in] */ BSTR anIdentifier,
/* [retval][out] */ IWebPreferences** preferences)
{
WebPreferences *instance = getInstanceForIdentifier(anIdentifier);
if (instance) {
*preferences = instance;
instance->AddRef();
return S_OK;
}
load();
*preferences = this;
AddRef();
if (anIdentifier) {
m_identifier = anIdentifier;
setInstance(this, m_identifier);
}
this->postPreferencesChangesNotification();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::identifier(
/* [retval][out] */ BSTR* ident)
{
if (!ident)
return E_POINTER;
*ident = m_identifier ? SysAllocString(m_identifier) : 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::standardFontFamily(
/* [retval][out] */ BSTR* family)
{
*family = stringValueForKey(CFSTR(WebKitStandardFontPreferenceKey));
return (*family) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setStandardFontFamily(
/* [in] */ BSTR family)
{
setStringValue(CFSTR(WebKitStandardFontPreferenceKey), family);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::fixedFontFamily(
/* [retval][out] */ BSTR* family)
{
*family = stringValueForKey(CFSTR(WebKitFixedFontPreferenceKey));
return (*family) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setFixedFontFamily(
/* [in] */ BSTR family)
{
setStringValue(CFSTR(WebKitFixedFontPreferenceKey), family);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::serifFontFamily(
/* [retval][out] */ BSTR* fontFamily)
{
*fontFamily = stringValueForKey(CFSTR(WebKitSerifFontPreferenceKey));
return (*fontFamily) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setSerifFontFamily(
/* [in] */ BSTR family)
{
setStringValue(CFSTR(WebKitSerifFontPreferenceKey), family);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::sansSerifFontFamily(
/* [retval][out] */ BSTR* family)
{
*family = stringValueForKey(CFSTR(WebKitSansSerifFontPreferenceKey));
return (*family) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setSansSerifFontFamily(
/* [in] */ BSTR family)
{
setStringValue(CFSTR(WebKitSansSerifFontPreferenceKey), family);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::cursiveFontFamily(
/* [retval][out] */ BSTR* family)
{
*family = stringValueForKey(CFSTR(WebKitCursiveFontPreferenceKey));
return (*family) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setCursiveFontFamily(
/* [in] */ BSTR family)
{
setStringValue(CFSTR(WebKitCursiveFontPreferenceKey), family);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::fantasyFontFamily(
/* [retval][out] */ BSTR* family)
{
*family = stringValueForKey(CFSTR(WebKitFantasyFontPreferenceKey));
return (*family) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setFantasyFontFamily(
/* [in] */ BSTR family)
{
setStringValue(CFSTR(WebKitFantasyFontPreferenceKey), family);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::defaultFontSize(
/* [retval][out] */ int* fontSize)
{
*fontSize = integerValueForKey(CFSTR(WebKitDefaultFontSizePreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setDefaultFontSize(
/* [in] */ int fontSize)
{
setIntegerValue(CFSTR(WebKitDefaultFontSizePreferenceKey), fontSize);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::defaultFixedFontSize(
/* [retval][out] */ int* fontSize)
{
*fontSize = integerValueForKey(CFSTR(WebKitDefaultFixedFontSizePreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setDefaultFixedFontSize(
/* [in] */ int fontSize)
{
setIntegerValue(CFSTR(WebKitDefaultFixedFontSizePreferenceKey), fontSize);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::minimumFontSize(
/* [retval][out] */ int* fontSize)
{
*fontSize = integerValueForKey(CFSTR(WebKitMinimumFontSizePreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setMinimumFontSize(
/* [in] */ int fontSize)
{
setIntegerValue(CFSTR(WebKitMinimumFontSizePreferenceKey), fontSize);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::minimumLogicalFontSize(
/* [retval][out] */ int* fontSize)
{
*fontSize = integerValueForKey(CFSTR(WebKitMinimumLogicalFontSizePreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setMinimumLogicalFontSize(
/* [in] */ int fontSize)
{
setIntegerValue(CFSTR(WebKitMinimumLogicalFontSizePreferenceKey), fontSize);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::defaultTextEncodingName(
/* [retval][out] */ BSTR* name)
{
*name = stringValueForKey(CFSTR(WebKitDefaultTextEncodingNamePreferenceKey));
return (*name) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setDefaultTextEncodingName(
/* [in] */ BSTR name)
{
setStringValue(CFSTR(WebKitDefaultTextEncodingNamePreferenceKey), name);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::userStyleSheetEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitUserStyleSheetEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setUserStyleSheetEnabled(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitUserStyleSheetEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::userStyleSheetLocation(
/* [retval][out] */ BSTR* location)
{
*location = stringValueForKey(CFSTR(WebKitUserStyleSheetLocationPreferenceKey));
return (*location) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setUserStyleSheetLocation(
/* [in] */ BSTR location)
{
setStringValue(CFSTR(WebKitUserStyleSheetLocationPreferenceKey), location);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::isJavaEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitJavaEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setJavaEnabled(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitJavaEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::isJavaScriptEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitJavaScriptEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setJavaScriptEnabled(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitJavaScriptEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::isWebSecurityEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitWebSecurityEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setWebSecurityEnabled(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitWebSecurityEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::allowUniversalAccessFromFileURLs(
/* [retval][out] */ BOOL* allowAccess)
{
*allowAccess = boolValueForKey(CFSTR(WebKitAllowUniversalAccessFromFileURLsPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setAllowUniversalAccessFromFileURLs(
/* [in] */ BOOL allowAccess)
{
setBoolValue(CFSTR(WebKitAllowUniversalAccessFromFileURLsPreferenceKey), allowAccess);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::allowFileAccessFromFileURLs(
/* [retval][out] */ BOOL* allowAccess)
{
*allowAccess = boolValueForKey(CFSTR(WebKitAllowFileAccessFromFileURLsPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setAllowFileAccessFromFileURLs(
/* [in] */ BOOL allowAccess)
{
setBoolValue(CFSTR(WebKitAllowFileAccessFromFileURLsPreferenceKey), allowAccess);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::javaScriptCanAccessClipboard(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitJavaScriptCanAccessClipboardPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setJavaScriptCanAccessClipboard(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitJavaScriptCanAccessClipboardPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::isXSSAuditorEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitXSSAuditorEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setXSSAuditorEnabled(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitXSSAuditorEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::isFrameFlatteningEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitFrameFlatteningEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setFrameFlatteningEnabled(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitFrameFlatteningEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::javaScriptCanOpenWindowsAutomatically(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitJavaScriptCanOpenWindowsAutomaticallyPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setJavaScriptCanOpenWindowsAutomatically(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitJavaScriptCanOpenWindowsAutomaticallyPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::arePlugInsEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitPluginsEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setPlugInsEnabled(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitPluginsEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::allowsAnimatedImages(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitAllowAnimatedImagesPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setAllowsAnimatedImages(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitAllowAnimatedImagesPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::allowAnimatedImageLooping(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitAllowAnimatedImageLoopingPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setAllowAnimatedImageLooping(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitAllowAnimatedImageLoopingPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setLoadsImagesAutomatically(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitDisplayImagesKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::loadsImagesAutomatically(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitDisplayImagesKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setAutosaves(
/* [in] */ BOOL enabled)
{
m_autoSaves = !!enabled;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::autosaves(
/* [retval][out] */ BOOL* enabled)
{
*enabled = m_autoSaves ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setShouldPrintBackgrounds(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitShouldPrintBackgroundsPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::shouldPrintBackgrounds(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitShouldPrintBackgroundsPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setPrivateBrowsingEnabled(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitPrivateBrowsingEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::privateBrowsingEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitPrivateBrowsingEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setTabsToLinks(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitTabToLinksPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::tabsToLinks(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitTabToLinksPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setUsesPageCache(
/* [in] */ BOOL usesPageCache)
{
setBoolValue(CFSTR(WebKitUsesPageCachePreferenceKey), usesPageCache);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::usesPageCache(
/* [retval][out] */ BOOL* usesPageCache)
{
*usesPageCache = boolValueForKey(CFSTR(WebKitUsesPageCachePreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::textAreasAreResizable(
/* [retval][out] */ BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitTextAreasAreResizablePreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setTextAreasAreResizable(
/* [in] */ BOOL enabled)
{
setBoolValue(CFSTR(WebKitTextAreasAreResizablePreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::historyItemLimit(int* limit)
{
*limit = integerValueForKey(CFSTR(WebKitHistoryItemLimitKey));
return S_OK;
}
HRESULT WebPreferences::setHistoryItemLimit(int limit)
{
setIntegerValue(CFSTR(WebKitHistoryItemLimitKey), limit);
return S_OK;
}
HRESULT WebPreferences::historyAgeInDaysLimit(int* limit)
{
*limit = integerValueForKey(CFSTR(WebKitHistoryAgeInDaysLimitKey));
return S_OK;
}
HRESULT WebPreferences::setHistoryAgeInDaysLimit(int limit)
{
setIntegerValue(CFSTR(WebKitHistoryAgeInDaysLimitKey), limit);
return S_OK;
}
HRESULT WebPreferences::unused1()
{
ASSERT_NOT_REACHED();
return E_FAIL;
}
HRESULT WebPreferences::unused2()
{
ASSERT_NOT_REACHED();
return E_FAIL;
}
HRESULT WebPreferences::iconDatabaseLocation(
/* [out] */ BSTR* location)
{
*location = stringValueForKey(CFSTR(WebKitIconDatabaseLocationKey));
return (*location) ? S_OK : E_FAIL;
}
HRESULT WebPreferences::setIconDatabaseLocation(
/* [in] */ BSTR location)
{
setStringValue(CFSTR(WebKitIconDatabaseLocationKey), location);
return S_OK;
}
HRESULT WebPreferences::iconDatabaseEnabled(BOOL* enabled)//location)
{
*enabled = boolValueForKey(CFSTR(WebKitIconDatabaseEnabledPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setIconDatabaseEnabled(BOOL enabled )//location)
{
setBoolValue(CFSTR(WebKitIconDatabaseEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::fontSmoothing(
/* [retval][out] */ FontSmoothingType* smoothingType)
{
*smoothingType = (FontSmoothingType) integerValueForKey(CFSTR(WebKitFontSmoothingTypePreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setFontSmoothing(
/* [in] */ FontSmoothingType smoothingType)
{
setIntegerValue(CFSTR(WebKitFontSmoothingTypePreferenceKey), smoothingType);
if (smoothingType == FontSmoothingTypeWindows)
smoothingType = FontSmoothingTypeMedium;
#if PLATFORM(CG)
wkSetFontSmoothingLevel((int)smoothingType);
#endif
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::fontSmoothingContrast(
/* [retval][out] */ float* contrast)
{
*contrast = floatValueForKey(CFSTR(WebKitFontSmoothingContrastPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setFontSmoothingContrast(
/* [in] */ float contrast)
{
setFloatValue(CFSTR(WebKitFontSmoothingContrastPreferenceKey), contrast);
#if PLATFORM(CG)
wkSetFontSmoothingContrast(contrast);
#endif
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::editableLinkBehavior(
/* [out, retval] */ WebKitEditableLinkBehavior* editableLinkBehavior)
{
WebKitEditableLinkBehavior value = (WebKitEditableLinkBehavior) integerValueForKey(CFSTR(WebKitEditableLinkBehaviorPreferenceKey));
switch (value) {
case WebKitEditableLinkDefaultBehavior:
case WebKitEditableLinkAlwaysLive:
case WebKitEditableLinkOnlyLiveWithShiftKey:
case WebKitEditableLinkLiveWhenNotFocused:
case WebKitEditableLinkNeverLive:
*editableLinkBehavior = value;
break;
default: // ensure that a valid result is returned
*editableLinkBehavior = WebKitEditableLinkDefaultBehavior;
break;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setEditableLinkBehavior(
/* [in] */ WebKitEditableLinkBehavior behavior)
{
setIntegerValue(CFSTR(WebKitEditableLinkBehaviorPreferenceKey), behavior);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::editingBehavior(
/* [out, retval] */ WebKitEditingBehavior* editingBehavior)
{
*editingBehavior = (WebKitEditingBehavior) integerValueForKey(CFSTR(WebKitEditingBehaviorPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setEditingBehavior(
/* [in] */ WebKitEditingBehavior behavior)
{
setIntegerValue(CFSTR(WebKitEditingBehaviorPreferenceKey), behavior);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::cookieStorageAcceptPolicy(
/* [retval][out] */ WebKitCookieStorageAcceptPolicy *acceptPolicy )
{
if (!acceptPolicy)
return E_POINTER;
*acceptPolicy = (WebKitCookieStorageAcceptPolicy)integerValueForKey(CFSTR(WebKitCookieStorageAcceptPolicyPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setCookieStorageAcceptPolicy(
/* [in] */ WebKitCookieStorageAcceptPolicy acceptPolicy)
{
setIntegerValue(CFSTR(WebKitCookieStorageAcceptPolicyPreferenceKey), acceptPolicy);
return S_OK;
}
HRESULT WebPreferences::continuousSpellCheckingEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebContinuousSpellCheckingEnabledPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setContinuousSpellCheckingEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebContinuousSpellCheckingEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::grammarCheckingEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebGrammarCheckingEnabledPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setGrammarCheckingEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebGrammarCheckingEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::allowContinuousSpellChecking(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(AllowContinuousSpellCheckingPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setAllowContinuousSpellChecking(BOOL enabled)
{
setBoolValue(CFSTR(AllowContinuousSpellCheckingPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::isDOMPasteAllowed(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitDOMPasteAllowedPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setDOMPasteAllowed(BOOL enabled)
{
setBoolValue(CFSTR(WebKitDOMPasteAllowedPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::cacheModel(WebCacheModel* cacheModel)
{
if (!cacheModel)
return E_POINTER;
*cacheModel = (WebCacheModel)integerValueForKey(CFSTR(WebKitCacheModelPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setCacheModel(WebCacheModel cacheModel)
{
setIntegerValue(CFSTR(WebKitCacheModelPreferenceKey), cacheModel);
return S_OK;
}
HRESULT WebPreferences::setShouldPaintCustomScrollbars(BOOL shouldPaint)
{
setBoolValue(CFSTR(WebKitPaintCustomScrollbarsPreferenceKey), shouldPaint);
return S_OK;
}
HRESULT WebPreferences::shouldPaintCustomScrollbars(BOOL* shouldPaint)
{
*shouldPaint = boolValueForKey(CFSTR(WebKitPaintCustomScrollbarsPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::shouldPaintNativeControls(BOOL* shouldPaint)
{
*shouldPaint = boolValueForKey(CFSTR(WebKitPaintNativeControlsPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setShouldPaintNativeControls(BOOL shouldPaint)
{
setBoolValue(CFSTR(WebKitPaintNativeControlsPreferenceKey), shouldPaint);
return S_OK;
}
HRESULT WebPreferences::setDeveloperExtrasEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitDeveloperExtrasEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::developerExtrasEnabled(BOOL* enabled)
{
if (!enabled)
return E_POINTER;
*enabled = boolValueForKey(CFSTR(WebKitDeveloperExtrasEnabledPreferenceKey));
return S_OK;
}
bool WebPreferences::developerExtrasDisabledByOverride()
{
return !!boolValueForKey(CFSTR(DisableWebKitDeveloperExtrasPreferenceKey));
}
HRESULT WebPreferences::setAutomaticallyDetectsCacheModel(BOOL automaticallyDetectsCacheModel)
{
m_automaticallyDetectsCacheModel = !!automaticallyDetectsCacheModel;
return S_OK;
}
HRESULT WebPreferences::automaticallyDetectsCacheModel(BOOL* automaticallyDetectsCacheModel)
{
if (!automaticallyDetectsCacheModel)
return E_POINTER;
*automaticallyDetectsCacheModel = m_automaticallyDetectsCacheModel;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setAuthorAndUserStylesEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitAuthorAndUserStylesEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::authorAndUserStylesEnabled(BOOL* enabled)
{
if (!enabled)
return E_POINTER;
*enabled = boolValueForKey(CFSTR(WebKitAuthorAndUserStylesEnabledPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::inApplicationChromeMode(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitApplicationChromeModePreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setApplicationChromeMode(BOOL enabled)
{
setBoolValue(CFSTR(WebKitApplicationChromeModePreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setOfflineWebApplicationCacheEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitOfflineWebApplicationCacheEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::offlineWebApplicationCacheEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitOfflineWebApplicationCacheEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setDatabasesEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitDatabasesEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::databasesEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitDatabasesEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setLocalStorageEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitLocalStorageEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::localStorageEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitLocalStorageEnabledPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::localStorageDatabasePath(BSTR* location)
{
*location = stringValueForKey(CFSTR(WebKitLocalStorageDatabasePathPreferenceKey));
return (*location) ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setLocalStorageDatabasePath(BSTR location)
{
setStringValue(CFSTR(WebKitLocalStorageDatabasePathPreferenceKey), location);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setExperimentalNotificationsEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitExperimentalNotificationsEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::experimentalNotificationsEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitExperimentalNotificationsEnabledPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setZoomsTextOnly(BOOL zoomsTextOnly)
{
setBoolValue(CFSTR(WebKitZoomsTextOnlyPreferenceKey), zoomsTextOnly);
return S_OK;
}
HRESULT WebPreferences::zoomsTextOnly(BOOL* zoomsTextOnly)
{
*zoomsTextOnly = boolValueForKey(CFSTR(WebKitZoomsTextOnlyPreferenceKey));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::setShouldUseHighResolutionTimers(BOOL useHighResolutionTimers)
{
setBoolValue(CFSTR(WebKitUseHighResolutionTimersPreferenceKey), useHighResolutionTimers);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebPreferences::shouldUseHighResolutionTimers(BOOL* useHighResolutionTimers)
{
*useHighResolutionTimers = boolValueForKey(CFSTR(WebKitUseHighResolutionTimersPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setPluginAllowedRunTime(UINT allowedRunTime)
{
setIntegerValue(CFSTR(WebKitPluginAllowedRunTimePreferenceKey), allowedRunTime);
return S_OK;
}
HRESULT WebPreferences::pluginAllowedRunTime(UINT* allowedRunTime)
{
*allowedRunTime = integerValueForKey(CFSTR(WebKitPluginAllowedRunTimePreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setPreferenceForTest(BSTR key, BSTR value)
{
if (!SysStringLen(key) || !SysStringLen(value))
return E_FAIL;
RetainPtr<CFStringRef> keyString(AdoptCF, CFStringCreateWithCharacters(0, reinterpret_cast<UniChar*>(key), SysStringLen(key)));
RetainPtr<CFStringRef> valueString(AdoptCF, CFStringCreateWithCharacters(0, reinterpret_cast<UniChar*>(value), SysStringLen(value)));
setValueForKey(keyString.get(), valueString.get());
postPreferencesChangesNotification();
return S_OK;
}
HRESULT WebPreferences::setAcceleratedCompositingEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitAcceleratedCompositingEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::acceleratedCompositingEnabled(BOOL* enabled)
{
#if USE(ACCELERATED_COMPOSITING)
*enabled = WKCACFLayerRenderer::acceleratedCompositingAvailable() && boolValueForKey(CFSTR(WebKitAcceleratedCompositingEnabledPreferenceKey));
#else
*enabled = FALSE;
#endif
return S_OK;
}
HRESULT WebPreferences::showDebugBorders(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitShowDebugBordersPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setShowDebugBorders(BOOL enabled)
{
setBoolValue(CFSTR(WebKitShowDebugBordersPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::showRepaintCounter(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitShowRepaintCounterPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setShowRepaintCounter(BOOL enabled)
{
setBoolValue(CFSTR(WebKitShowRepaintCounterPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::setCustomDragCursorsEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitCustomDragCursorsEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::customDragCursorsEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitCustomDragCursorsEnabledPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setDNSPrefetchingEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitDNSPrefetchingEnabledPreferenceKey), enabled);
return S_OK;
}
HRESULT WebPreferences::isDNSPrefetchingEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitDNSPrefetchingEnabledPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::memoryInfoEnabled(BOOL* enabled)
{
*enabled = boolValueForKey(CFSTR(WebKitMemoryInfoEnabledPreferenceKey));
return S_OK;
}
HRESULT WebPreferences::setMemoryInfoEnabled(BOOL enabled)
{
setBoolValue(CFSTR(WebKitMemoryInfoEnabledPreferenceKey), enabled);
return S_OK;
}
void WebPreferences::willAddToWebView()
{
++m_numWebViews;
}
void WebPreferences::didRemoveFromWebView()
{
ASSERT(m_numWebViews);
if (--m_numWebViews == 0) {
IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
nc->postNotificationName(webPreferencesRemovedNotification(), static_cast<IWebPreferences*>(this), 0);
}
}
| [
"[email protected]"
] | [
[
[
1,
1514
]
]
] |
69e0b6e353a3b15c005e28797fd71978a7ce6ebb | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/conjurer/conjurer/src/conjurer/objectplacingundocmd_main.cc | 23cf3eeaa42effe229bbc54b07055dd0849e8726 | [] | 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 | 10,562 | cc | #include "precompiled/pchconjurerapp.h"
//------------------------------------------------------------------------------
// objectplacingundocmd_main.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "conjurer/objectplacingundocmd.h"
#include "entity/nentityobjectserver.h"
#include "nlevel/nlevel.h"
#include "nlevel/nlevelmanager.h"
#include "nphysics/ncphysicsobj.h"
#include "conjurer/nobjecteditorstate.h"
#include "ndebug/ndebugcomponentserver.h"
#include "animcomp/ncharacterserver.h"
#include "ndebug/nceditor.h"
#include "zombieentity/ncsuperentity.h"
#include "nspatial/ncspatial.h"
#include "zombieentity/nctransform.h"
#include "nspatial/ncspatial.h"
#include "nspatial/ncspatialindoor.h"
//------------------------------------------------------------------------------
/**
Constructor
@param object Affected entity
@param label Label of the command
@param isDelete Flag: is a delete command?
*/
ObjectPlacingUndoCmd::ObjectPlacingUndoCmd( nEntityObject* object, const char * label, bool isDelete)
{
if ( !object )
{
this->valid = false;
return;
}
this->valid = true;
this->firstExecution = true;
this->isDeleteCmd = isDelete;
this->AddEntity( object );
this->label = label;
}
//------------------------------------------------------------------------------
/**
Constructor
@param objects Affected entities array
@param label Label of the command
@param isDelete Flag: is a delete command?
*/
ObjectPlacingUndoCmd::ObjectPlacingUndoCmd( nArray<nEntityObject*>* objects, const char * label, bool isDelete)
{
if ( objects->Size() <= 0 )
{
this->valid = false;
return;
}
this->valid = true;
this->firstExecution = true;
this->isDeleteCmd = isDelete;
for ( int i = 0; i < objects->Size(); i++ )
{
nEntityObject* obj = (*objects)[i];
this->AddEntity( obj );
}
this->label = label;
}
//------------------------------------------------------------------------------
/**
Constructor
@param objects Affected entities array
@param label Label of the command
@param isDelete Flag: is a delete command?
*/
ObjectPlacingUndoCmd::ObjectPlacingUndoCmd( nArray<nRefEntityObject>* objects, const char * label, bool isDelete)
{
if ( objects->Size() <= 0 )
{
this->valid = false;
return;
}
this->valid = true;
this->firstExecution = true;
this->isDeleteCmd = isDelete;
for ( int i = 0; i < objects->Size(); i++ )
{
nEntityObject* obj = (*objects)[i];
this->AddEntity( obj );
}
this->label = label;
}
//------------------------------------------------------------------------------
/**
Constructor
@param objects Affected entities
@param label Label of the command
@param isDelete Flag: is a delete command?
This command is created with a pointer to an id array of the created entities
*/
ObjectPlacingUndoCmd::ObjectPlacingUndoCmd( nArray<nEntityObjectId>* objects, const char * label, bool isDelete )
{
if ( objects->Size() <= 0 )
{
this->valid = false;
return;
}
this->valid = true;
this->firstExecution = true;
this->isDeleteCmd = isDelete;
nEntityObjectServer* entServer = nEntityObjectServer::Instance();
for (int i= 0; i < objects->Size(); i++)
{
nEntityObjectId id = (*objects)[i];
nEntityObject* ent = entServer->GetEntityObject( id );
this->AddEntity( ent );
}
this->label = label;
}
//------------------------------------------------------------------------------
/**
Destructor
*/
ObjectPlacingUndoCmd::~ObjectPlacingUndoCmd()
{
for (int i=0;i < undoInfo.Size(); i++)
{
// Decrement reference count. If it is equal to one (2 before calling Release), then the entity
// is referenced only in the entity server, so it must be deleted if the command is in the redo side
// (it was executed but later was undone)
ObjPlaceUndoInfo& info = this->undoInfo.At( i );
if ( info.refEntity.isvalid() )
{
int n = info.refEntity->GetRefCount();
if ( n == 1 && ( ( this->undone && ! this->isDeleteCmd ) || ( ! this->undone && this->isDeleteCmd ) ) )
{
nEntityObjectServer::Instance()->RemoveEntityObject( info.refEntity.get() );
}
}
}
}
//------------------------------------------------------------------------------
/**
*/
void
ObjectPlacingUndoCmd::AddEntity(nEntityObject* object)
{
n_assert( object );
ObjPlaceUndoInfo& info = this->undoInfo.At( this->undoInfo.Size() );
info.className = object->GetEntityClass()->GetProperName();
info.entityId = object->GetId();
info.refEntity = object;
object->AddRef();
ncTransform *ct = object->GetComponent<ncTransform>();
n_assert( ct );
info.placedInstanceTransform.settranslation( ct->GetPosition() );
info.placedInstanceTransform.setquatrotation( ct->GetQuat() );
info.placedInstanceTransform.setscale( ct->GetScale() );
// add also the facade if the entity is a indoor
ncSpatialIndoor* spatialIndoorComp = object->GetComponent<ncSpatialIndoor>();
if (spatialIndoorComp )
{
nEntityObject* facade = spatialIndoorComp->GetFacade();
if ( facade )
{
this->AddEntity( facade );
}
}
}
//------------------------------------------------------------------------------
/**
Execute
@return Success
*/
bool ObjectPlacingUndoCmd::Execute( void )
{
if ( !this->valid )
{
return false;
}
// Don't execute the command when it's created, because it is executed before creation
if ( firstExecution )
{
this->firstExecution = false;
return true;
}
if ( this->isDeleteCmd )
{
this->RemoveObjects();
}
else
{
this->InsertObjects();
}
return true;
}
//------------------------------------------------------------------------------
/**
Unexecute
@return Success
*/
bool ObjectPlacingUndoCmd::Unexecute( void )
{
if ( !this->valid )
{
return false;
}
if ( this->isDeleteCmd )
{
this->InsertObjects();
}
else
{
this->RemoveObjects();
}
this->firstExecution = false;
return true;
}
//------------------------------------------------------------------------------
/**
*/
void
ObjectPlacingUndoCmd::InsertObjects( void )
{
// Change selection
nObjectEditorState* objst = static_cast<nObjectEditorState*>( nKernelServer::Instance()->Lookup("/app/conjurer/appstates/object") );
objst->ResetSelection();
// Loop through objects to insert
for (int i=0;i< this->undoInfo.Size(); i++)
{
n_assert( this->undoInfo[i].refEntity.isvalid() );
nEntityObject* object = this->undoInfo[i].refEntity;
// Set initial transform (also inserts into space automatically)
ncTransform *ct = object->GetComponent<ncTransform>();
n_assert( ct );
ct->SetPosition( this->undoInfo[i].placedInstanceTransform.gettranslation() );
ct->SetQuat( this->undoInfo[i].placedInstanceTransform.getquatrotation() );
ct->SetScale( this->undoInfo[i].placedInstanceTransform.getscale() );
// Make object enter in the level again
object->ReturnFromLimbo( object );
// Add editor component to debug server. This could be done with binding to the limbo signals, but this way we save at least some bindings
ncEditor* edComp = object->GetComponent<ncEditor>();
if ( edComp )
{
nDebugComponentServer::Instance()->Add( edComp );
// Set deletion flag
edComp->SetDeleted( false );
}
// Add to selection
objst->AddEntityToSelection( object->GetId() );
}
// Refresh selection object transforms
objst->AssignToolObjectTransform();
// Signal GUI that some entity could have been created or deleted
nUndoServer::Instance()->SignalEntityModified( nUndoServer::Instance() );
}
//------------------------------------------------------------------------------
/**
*/
void
ObjectPlacingUndoCmd::RemoveObjects( void )
{
// Clear selection
nObjectEditorState* objst = static_cast<nObjectEditorState*>( nKernelServer::Instance()->Lookup("/app/conjurer/appstates/object") );
objst->ResetSelection();
// Loop through objects to delete. This is done in the reverse order of InsertObjects so it acts like a stack
for (int i = this->undoInfo.Size() - 1; i >= 0; i--)
{
n_assert( this->undoInfo[i].refEntity.isvalid() );
nEntityObject* object = this->undoInfo[i].refEntity;
// Update editor component. This could be done with binding to the limbo signals, but this way we save at least some bindings
ncEditor* edComp = object->GetComponent<ncEditor>();
if ( edComp )
{
// Remove editor component from debug server
nDebugComponentServer::Instance()->Remove( edComp );
// Set deletion flag
edComp->SetDeleted( true );
}
// Make object to don't belong to the level
object->SendToLimbo( object );
}
// Refresh selection object transforms
objst->AssignToolObjectTransform();
// Signal GUI that some entity could have been created or deleted
nUndoServer::Instance()->SignalEntityModified( nUndoServer::Instance() );
}
//------------------------------------------------------------------------------
/**
Get byte size
*/
int ObjectPlacingUndoCmd::GetSize( void )
{
return sizeof( this );
}
//------------------------------------------------------------------------------
/**
Remove references to external objects
*/
void
ObjectPlacingUndoCmd::RemoveReferences()
{
for (int i=0;i < undoInfo.Size(); i++)
{
ObjPlaceUndoInfo& info = this->undoInfo.At( i );
info.refEntity->Release();
}
}
//------------------------------------------------------------------------------ | [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
348
]
]
] |
11688d6cf0a38b8367502b938f9e78d26c5dcbd0 | b3283c88e4ddb5f228f16448be6e9dee3d8cb272 | /ngy313/detail/gtkglextmm_graphic_system.hpp | 6b6467d74fa8fd352f7502469ed0b4aeda83f0f3 | [
"BSD-3-Clause",
"BSL-1.0"
] | permissive | nagoya313/ngy313 | ae386c84a4d3b5b68d5e172b32de9cd0fe90cf5c | 7c93a3edf69080559049d5e759a4db1be5e1e2fd | refs/heads/master | 2021-01-10T19:09:18.562953 | 2011-07-27T17:12:19 | 2011-07-27T17:12:19 | 1,025,796 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,007 | hpp | #ifndef NGY313_DETAIL_GTKGLEXTMM_GRAPHIC_SYSTEM_HPP_
#define NGY313_DETAIL_GTKGLEXTMM_GRAPHIC_SYSTEM_HPP_
#include <cassert>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <thread>
#include <type_traits>
#include <boost/mpl/at.hpp>
#include <boost/noncopyable.hpp>
#include <boost/signals2.hpp>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <gtkglmm.h>
#include <ngy313/fwd.hpp>
#include <ngy313/fvf_traits.hpp>
#include <ngy313/vertex_member.hpp>
#include <ngy313/detail/fwd.hpp>
#include <ngy313/detail/drawable_traits_key.hpp>
namespace ngy313 { namespace detail {
class gtkglextmm_graphic_system : boost::noncopyable {
class system_impl;
public:
typedef const std::unique_ptr<system_impl> &handle_type;
class scoped_render : boost::noncopyable {
public:
template <typename Graphic>
explicit scoped_render(const basic_graphic_system<Graphic> &system)
: gl_window_(system.handle()->realized() ?
system.handle()->get_gl_window() :
Glib::RefPtr<Gdk::GL::Window>()),
succeeded_(begin_scene(*system.handle())) {}
~scoped_render() {
if (succeeded()) {
end_scene();
}
}
bool succeeded() const {
return succeeded_;
}
private:
bool begin_scene(Gtk::GL::DrawingArea &area) {
return gl_window_ ? gl_window_->gl_begin(area.get_gl_context()) : false;
}
void end_scene() {
assert(gl_window_);
gl_window_->gl_end();
}
Glib::RefPtr<Gdk::GL::Window> gl_window_;
bool succeeded_;
};
class enable_texture : boost::noncopyable {
public:
template <typename Drawable>
explicit enable_texture(gtkglextmm_graphic_system &device,
const Drawable &drawable) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, *drawable.texture1().handle().get());
}
~enable_texture() {
glDisable(GL_TEXTURE_2D);
}
};
class scoped_blend : boost::noncopyable {
public:
template <typename BlendPair>
explicit scoped_blend(gtkglextmm_graphic_system &device, BlendPair &&)
: enable_alpha_(glIsEnabled(GL_BLEND)),
src_blend_(get_src_blend_mode()),
dest_blend_(get_dest_blend_mode()) {
glEnable(GL_BLEND);
set_blend_pair<BlendPair>();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
}
~scoped_blend() {
set_blend_mode(src_blend_, dest_blend_);
glDisable(GL_BLEND);
}
private:
static void set_blend_mode(GLenum src, GLenum dest) {
glBlendFunc(src, dest);
}
template <typename BlendPair>
static void set_blend_pair() {
set_blend_mode(BlendPair::src_type::value, BlendPair::dest_type::value);
}
static GLenum get_src_blend_mode() {
GLint temp;
glGetIntegerv(GL_BLEND_SRC, &temp);
return static_cast<GLenum>(temp);
}
static GLenum get_dest_blend_mode() {
GLint temp;
glGetIntegerv(GL_BLEND_DST, &temp);
return static_cast<GLenum>(temp);
}
bool enable_alpha_;
GLenum src_blend_;
GLenum dest_blend_;
};
template <typename Window>
explicit gtkglextmm_graphic_system(const basic_window<Window> &window)
: graphic_(new system_impl(window)) {}
void resize(int width, int height) {
graphic_->resize(width, height);
assert(width == this->width() && height == this->height());
}
int width() const {
return graphic_->width();
}
int height() const {
return graphic_->height();
}
void present() {
graphic_->present();
}
template <typename Wrap>
void clear_screen(const basic_color_wrap<Wrap> &color) {
graphic_->clear(color);
}
std::uint32_t pixel_color(int x, int y) const {
return graphic_->pixel_color(x, y);
}
template <typename Drawable,
typename List = typename std::decay<Drawable>::type::list_type>
void draw_primitive(Drawable &&drawable) {
const auto vertex = drawable.vertex();
const scoped_list<
fvf_traits<
typename boost::mpl::at<
List,
fvf_key>::type>::fvf_type::value> list(vertex);
glDrawArrays(boost::mpl::at<List, primitive_key>::type::type::value,
0,
boost::mpl::at<List, size_key>::type::type::value);
}
const handle_type &handle() const {
return graphic_;
}
boost::signals2::signal<void ()> &before_reset() {
return graphic_->before_reset();
}
boost::signals2::signal<void ()> &after_reset() {
return graphic_->after_reset();
}
private:
class system_impl : public Gtk::GL::DrawingArea,
boost::noncopyable {
public:
template <typename Window>
explicit system_impl(const basic_window<Window> &window)
: width_(window.width()),
height_(window.height()),
realized_(false) {
static std::once_flag flag_;
std::call_once(flag_, [] {Gtk::GL::init(0, 0);});
const Glib::RefPtr<Gdk::GL::Config> gl_config
= Gdk::GL::Config::create(
Gdk::GL::MODE_RGB
| Gdk::GL::MODE_DEPTH
| Gdk::GL::MODE_DOUBLE);
if (!gl_config) {
throw std::runtime_error("OpenGLの初期化に失敗しました");
}
set_gl_capability(gl_config);
window.handle()->add(*this);
window.handle()->show_all_children();
}
template <typename Wrap>
void clear(const basic_color_wrap<Wrap> &color) {
glClearColor(color.get_blue_float(),
color.get_green_float(),
color.get_red_float(),
color.get_alpha_float());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
std::uint32_t pixel_color(int x, int y) const {
return 0;
}
void present() {
scoped_gl gl(*this);
gl.swap_buffers();
}
void resize(int width, int height) {
width_ = width;
height_ = height;
glViewport(0, 0, width_, height_);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.f,
static_cast<float>(width_),
static_cast<float>(height_),
0.f,
0.f,
1.f);
assert(width == this->width() && height == this->height());
}
int width() const {
return width_;
}
int height() const {
return height_;
}
bool realized() const {
return realized_;
}
boost::signals2::signal<void ()> &before_reset() {
return before_reset_;
}
boost::signals2::signal<void ()> &after_reset() {
return after_reset_;
}
protected:
virtual bool on_configure_event(GdkEventConfigure *event) {
const scoped_gl gl(*this);
glViewport(0, 0, width_, height_);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.f,
static_cast<float>(width_),
static_cast<float>(height_),
0.f,
0.f,
1.f);
return true;
}
virtual void on_realize() {
Gtk::DrawingArea::on_realize();
after_reset_();
realized_ = true;
}
virtual bool on_expose_event(GdkEventExpose *event) {
scoped_gl gl(*this);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
gl.swap_buffers();
return true;
}
private:
int width_;
int height_;
bool realized_;
boost::signals2::signal<void ()> before_reset_;
boost::signals2::signal<void ()> after_reset_;
};
class scoped_gl : boost::noncopyable {
public:
explicit scoped_gl(Gtk::GL::DrawingArea &area)
: gl_window_(area.get_gl_window()) {
assert(gl_window_);
gl_window_->gl_begin(area.get_gl_context());
}
~scoped_gl() {
assert(gl_window_);
gl_window_->gl_end();
}
void swap_buffers() {
assert(gl_window_);
gl_window_->swap_buffers();
}
private:
Glib::RefPtr<Gdk::GL::Window> gl_window_;
};
struct scoped_vertex_enable {
template <typename Vertex>
explicit scoped_vertex_enable(const Vertex &vertex) {
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3,
GL_FLOAT,
sizeof(vertex.front()),
&vertex_member_at<position_member>(vertex[0]).x_);
}
~scoped_vertex_enable() {
glDisableClientState(GL_VERTEX_ARRAY);
}
};
template <std::uint32_t FVF, typename T = void>
struct scoped_color_enable : private scoped_vertex_enable {
template <typename Vertex>
explicit scoped_color_enable(const Vertex &vertex)
: scoped_vertex_enable(vertex) {}
};
template <std::uint32_t FVF>
struct scoped_color_enable<FVF, typename std::enable_if<FVF & 0x02>::type>
: private scoped_vertex_enable {
template <typename Vertex>
explicit scoped_color_enable(const Vertex &vertex)
: scoped_vertex_enable(vertex) {
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4,
GL_FLOAT,
sizeof(vertex.front()),
&vertex_member_at<diffuse_member>(vertex[0]).r_);
}
~scoped_color_enable() {
glDisableClientState(GL_COLOR_ARRAY);
}
};
template <std::uint32_t FVF, typename T = void>
struct scoped_texture_1_enable : private scoped_color_enable<FVF> {
template <typename Vertex>
explicit scoped_texture_1_enable(const Vertex &vertex)
: scoped_texture_1_enable::scoped_color_enable(vertex) {}
};
template <std::uint32_t FVF>
struct scoped_texture_1_enable<FVF,
typename std::enable_if<FVF & 0x08>::type>
: private scoped_color_enable<FVF - 0x08> {
template <typename Vertex>
explicit scoped_texture_1_enable(const Vertex &vertex)
: scoped_texture_1_enable::scoped_color_enable(vertex) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2,
GL_FLOAT,
sizeof(vertex.front()),
&vertex_member_at<texture_member>(
vertex[0]).texture_array[0].u);
}
~scoped_texture_1_enable() {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
};
template <std::uint32_t FVF>
struct scoped_list : private scoped_texture_1_enable<FVF> {
template <typename Vertex>
explicit scoped_list(const Vertex &vertex)
: scoped_list::scoped_texture_1_enable(vertex) {}
};
std::unique_ptr<system_impl> graphic_;
};
}}
#endif
| [
"[email protected]"
] | [
[
[
1,
392
]
]
] |
c8133328f7dbb21feb348a20ff96cdece417bf6e | 09f09cd06656848ed80f132c7073568c4ce87bd5 | /CBIR/Retrieval/Dib.cpp | 1e9b3a525b24b77d51a02812069ca59c5c117618 | [] | no_license | cyb3727/annrecognition | 90ecf3af572f8b629b276a06af51785f656ca2be | 6e4f200e1119196eba5e7fe56efa93e3ed978bc1 | refs/heads/master | 2021-01-17T11:31:39.865232 | 2011-07-10T13:50:44 | 2011-07-10T13:50:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,476 | cpp | // Dib.cpp : implementation file
//
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <windowsx.h> // especially for GlobalAllocPtr
#include "Dib.h"
#include "iostream"
#include "fstream"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_SERIAL(CDib, CObject, 0)
using namespace std;
////////////////////////////////////////////////////////////////////////////
CDib::CDib()
{
m_hDib = NULL;
m_hBitmap = NULL;
m_pPalette = NULL;
m_pBitmap = NULL;
}
CDib::~CDib()
{
Destroy();
if (m_pBitmap != NULL)
{
delete m_pBitmap;
m_pBitmap = NULL;
}
if (m_pPalette != NULL)
{
delete m_pPalette;
m_pPalette = NULL;
}
}
void CDib::Destroy()
{
if (m_hDib != NULL)
{
DestroyDIB(m_hDib);
m_hDib = NULL;
}
}
HDIB CDib::Detach()
{
if (m_hDib == NULL)
return NULL;
HDIB hDib = m_hDib;
m_hDib = NULL;
if (m_pBitmap != NULL)
{
delete m_pBitmap;
m_pBitmap = NULL;
}
if (m_pPalette != NULL)
{
delete m_pPalette;
m_pPalette = NULL;
}
return hDib;
}
BOOL CDib::Create(DWORD dwWidth, DWORD dwHeight)
{
HDIB hDib = CreateDefaultDIB(dwWidth, dwHeight);
if (! hDib)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Create(DWORD dwWidth, DWORD dwHeight, WORD wBitCount)
{
HDIB hDib = CreateDIB(dwWidth, dwHeight, wBitCount);
if (! hDib)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Create(LPBYTE lpDIB)
{
if (lpDIB == NULL)
return FALSE;
DWORD dwSize = DIBlockSize(lpDIB);
HDIB hDib = GlobalAlloc(GHND, dwSize);
// Check that DIB handle is valid
if (! hDib)
return FALSE;
LPBYTE lpbi = (LPBYTE)GlobalLock(hDib);
if (! lpbi)
return FALSE;
CopyMemory(lpbi, lpDIB, dwSize);
GlobalUnlock(hDib);
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Create(LPBYTE lpDIB,
WORD wBitCount) // bits/pixel
{
if (lpDIB == NULL)
return FALSE;
if (! Create(lpDIB))
return FALSE;
WORD wBits = ((LPBITMAPINFOHEADER)lpDIB)->biBitCount;
if (wBitCount == wBits)
return TRUE;
HDIB hNewDib = ConvertDIBFormat(m_hDib, wBitCount, NULL);
if (! hNewDib)
return FALSE;
Destroy();
m_hDib = hNewDib;
return UpdateInternal();
}
BOOL CDib::Create(HBITMAP hBitmap) // DIB Section
{
if (! hBitmap)
return FALSE;
HDIB hDib = DIBSectionToDIB(hBitmap);
if (! hDib)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Create(HBITMAP hBitmap, // DIB Section
WORD wBitCount) // bits/pixel
{
HDIB hNewDib;
if (! hBitmap)
return FALSE;
HDIB hDib = DIBSectionToDIB(hBitmap);
if (! hDib)
return FALSE;
DIBSECTION ds;
GetObject(hBitmap, sizeof(DIBSECTION), &ds);
if (wBitCount == ds.dsBmih.biBitCount)
hNewDib = hDib;
else
{
hNewDib = ConvertDIBFormat(hDib, wBitCount, NULL);
// cleanup hDib
GlobalFree(hDib);
}
if (! hNewDib)
return FALSE;
Destroy();
m_hDib = hNewDib;
return UpdateInternal();
}
BOOL CDib::Create(HBITMAP hBitmap, // DDB bitmap
HPALETTE hPalette) // DDB palette
{
if (! hBitmap)
return FALSE;
HDIB hDib = BitmapToDIB(hBitmap, hPalette);
if (! hDib)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Create(HBITMAP hBitmap, // DDB bitmap
HPALETTE hPalette, // DDB palette
WORD wBitCount) // bits/pixel
{
if (! hBitmap)
return FALSE;
HDIB hDib = BitmapToDIB(hBitmap, hPalette, wBitCount);
if (! hDib)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Create(CRect rcScreen)
{
HDIB hDib = CopyScreenToDIB(rcScreen);
if (! hDib)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Create(HWND hWnd, WORD fPrintArea)
{
HDIB hDib = CopyWindowToDIB(hWnd, fPrintArea);
if (! hDib)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Create(HWND hWnd, CRect rcClientArea)
{
HDIB hDib = CopyClientRectToDIB(hWnd, rcClientArea);
if (! hDib)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
BOOL CDib::Attach(HDIB hDib)
{
if (hDib == NULL)
return FALSE;
Destroy();
m_hDib = hDib;
return UpdateInternal();
}
void CDib::Serialize(CArchive& ar)
{
CObject::Serialize(ar);
ar.Flush();
if (ar.IsStoring())
{
Write(ar.GetFile());
}
else
{
Read(ar.GetFile());
}
}
BOOL CDib::Load(UINT uIDS, LPCTSTR lpszDibType)
{
LPCTSTR lpszDibRes = MAKEINTRESOURCE(uIDS);
return Load(lpszDibRes, lpszDibType);
}
BOOL CDib::Load(LPCTSTR lpszDibRes, LPCTSTR lpszDibType)
{
HINSTANCE hInst = AfxGetInstanceHandle();
HRSRC hRes = ::FindResource(hInst, lpszDibRes, lpszDibType);
HGLOBAL hData = ::LoadResource(hInst, hRes);
// if resource ok?
if (hRes == NULL || hData == NULL)
return FALSE;
// get resource buffer
LPBYTE lpBuf = (LPBYTE)::LockResource(hData);
// is DIB ?
if (((LPBITMAPFILEHEADER)lpBuf)->bfType != DIB_HEADER_MARKER/*"BM"*/)
return FALSE;
// use this buffer to create CDib
LPBYTE lpDIB = lpBuf + sizeof(BITMAPFILEHEADER);
return Create(lpDIB);
}
BOOL CDib::Load(LPCTSTR lpszDibFile)
{
TRY
{
CFile file(lpszDibFile, CFile::modeRead|CFile::shareDenyNone);
if (! Read(&file))
return FALSE;
}
CATCH (CException, e)
{
return FALSE;
}
END_CATCH
return TRUE;
}
BOOL CDib::Save(LPCTSTR lpszDibFile)
{
TRY
{
CFile file(lpszDibFile, CFile::modeCreate|CFile::modeWrite);
if (! Write(&file))
return FALSE;
}
CATCH (CException, e)
{
return FALSE;
}
END_CATCH
return TRUE;
}
BOOL CDib::Read(CFile *pFile)
{
WaitCursorBegin();
LPBITMAPINFOHEADER lpbi;
DWORD dwSize;
TRY
{
// read DIB file header
BITMAPFILEHEADER bmfHdr;
pFile->Read(&bmfHdr, sizeof(BITMAPFILEHEADER));
// is DIB file?
if (bmfHdr.bfType != DIB_HEADER_MARKER) // "BM"
{
WaitCursorEnd();
return FALSE;
}
DWORD dwLength = pFile->GetLength();
if (bmfHdr.bfSize != dwLength)
bmfHdr.bfSize = dwLength;
// read DIB buffer
dwSize = bmfHdr.bfSize - sizeof(BITMAPFILEHEADER);
lpbi = (LPBITMAPINFOHEADER)GlobalAllocPtr(GHND, dwSize);
DWORD dwCount = pFile->Read(lpbi, dwSize);
// read ok?
if (dwCount != dwSize)
{
GlobalFreePtr(lpbi);
WaitCursorEnd();
return FALSE;
}
// Check to see that it's a Windows DIB -- an OS/2 DIB would cause
// strange problems with the rest of the DIB API since the fields
// in the header are different and the color table entries are
// smaller.
//
// If it's not a Windows DIB (e.g. if biSize is wrong), return NULL.
if (lpbi->biSize != sizeof(BITMAPINFOHEADER))
{
GlobalFreePtr(lpbi);
WaitCursorEnd();
return FALSE;
}
// fill color num item
int nNumColors = (UINT)lpbi->biClrUsed;
if (nNumColors == 0)
{
// no color table for 24-bit, default size otherwise
if (lpbi->biBitCount > 8)//(lpbi->biBitCount != 24)
nNumColors = 1 << lpbi->biBitCount; // standard size table
}
// fill in some default values if they are zero
if (lpbi->biClrUsed == 0)
lpbi->biClrUsed = nNumColors;
if (lpbi->biSizeImage == 0)
lpbi->biSizeImage = ((((lpbi->biWidth * (DWORD)lpbi->biBitCount) + 31) & ~31) >> 3) * lpbi->biHeight;
}
CATCH (CException, e)
{
GlobalFreePtr(lpbi);
WaitCursorEnd();
return FALSE;
}
END_CATCH
// create CDib with DIB buffer
BOOL bSuccess = Create((LPBYTE)lpbi);
GlobalFreePtr(lpbi);
WaitCursorEnd();
return bSuccess;
/*HDIB hDib = ReadDIBFile((HANDLE)pFile->m_hFile);
if (hDib == NULL)
return FALSE;
return Attach(hDib);*/
}
BOOL CDib::Write(CFile *pFile)
{
WaitCursorBegin();
BITMAPFILEHEADER bmfHdr; // Header for Bitmap file
LPBITMAPINFOHEADER lpBI; // Pointer to DIB info structure
DWORD dwDIBSize;
// Get a pointer to the DIB memory, the first of which contains
// a BITMAPINFO structure
lpBI = (LPBITMAPINFOHEADER)GlobalLock(m_hDib);
if (!lpBI)
{
GlobalUnlock(m_hDib);
WaitCursorEnd();
return FALSE;
}
// Check to see if we're dealing with an OS/2 DIB. If so, don't
// save it because our functions aren't written to deal with these
// DIBs.
if (lpBI->biSize != sizeof(BITMAPINFOHEADER))
{
GlobalUnlock(m_hDib);
WaitCursorEnd();
return FALSE;
}
// Fill in the fields of the file header
// Fill in file type (first 2 bytes must be "BM" for a bitmap)
bmfHdr.bfType = DIB_HEADER_MARKER; // "BM"
// Calculating the size of the DIB is a bit tricky (if we want to
// do it right). The easiest way to do this is to call GlobalSize()
// on our global handle, but since the size of our global memory may have
// been padded a few bytes, we may end up writing out a few too
// many bytes to the file (which may cause problems with some apps,
// like HC 3.0).
//
// So, instead let's calculate the size manually.
//
// To do this, find size of header plus size of color table. Since the
// first DWORD in both BITMAPINFOHEADER and BITMAPCOREHEADER conains
// the size of the structure, let's use this.
// Partial Calculation
dwDIBSize = *(LPDWORD)lpBI + PaletteSize((LPBYTE)lpBI);
// Now calculate the size of the image
// It's an RLE bitmap, we can't calculate size, so trust the biSizeImage
// field
if ((lpBI->biCompression == BI_RLE8) || (lpBI->biCompression == BI_RLE4))
dwDIBSize += lpBI->biSizeImage;
else
{
DWORD dwBmBitsSize; // Size of Bitmap Bits only
// It's not RLE, so size is Width (DWORD aligned) * Height
dwBmBitsSize = WIDTHBYTES((lpBI->biWidth)*((DWORD)lpBI->biBitCount)) *
lpBI->biHeight;
dwDIBSize += dwBmBitsSize;
// Now, since we have calculated the correct size, why don't we
// fill in the biSizeImage field (this will fix any .BMP files which
// have this field incorrect).
lpBI->biSizeImage = dwBmBitsSize;
}
// Calculate the file size by adding the DIB size to sizeof(BITMAPFILEHEADER)
bmfHdr.bfSize = dwDIBSize + sizeof(BITMAPFILEHEADER);
bmfHdr.bfReserved1 = 0;
bmfHdr.bfReserved2 = 0;
// Now, calculate the offset the actual bitmap bits will be in
// the file -- It's the Bitmap file header plus the DIB header,
// plus the size of the color table.
bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + lpBI->biSize +
PaletteSize((LPBYTE)lpBI);
TRY
{
// Write the file header
pFile->Write(&bmfHdr, sizeof(BITMAPFILEHEADER));
// write DIB buffer
pFile->Write(lpBI, dwDIBSize);
}
CATCH (CException, e)
{
GlobalUnlock(m_hDib);
WaitCursorEnd();
return FALSE;
}
END_CATCH
GlobalUnlock(m_hDib);
WaitCursorEnd();
return TRUE;
// return WriteDIBFile(m_hDib, (HANDLE)pFile->m_hFile);
}
CDib * CDib::Clone()
{
if (m_hDib == NULL)
return NULL;
HDIB hDIB = CopyHandle(m_hDib);
if (hDIB == NULL)
return NULL;
CDib *pDib = new CDib;
pDib->m_hDib = hDIB;
pDib->BuildPalette();
pDib->BuildBitmap();
return pDib;
}
BOOL CDib::Display(CDC* pDC, int xDest, int yDest, int nWidthDest, int nHeightDest,
int xSrc, int ySrc, DWORD dwRop)
{
if (IsRequireDither(pDC))
{
CRect rcDest(xDest, yDest, xDest+nWidthDest, yDest+nHeightDest);
CRect rcSrc(xSrc, ySrc, xSrc+nWidthDest, ySrc+nHeightDest);
return DitherDisplay(pDC, rcDest, rcSrc, dwRop);
}
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
CBitmap* pOldBmp = MemDC.SelectObject(m_pBitmap);
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
BOOL bSuccess = pDC->BitBlt( xDest, yDest,
nWidthDest, nHeightDest,
&MemDC,
xSrc, ySrc,
dwRop);
MemDC.SelectObject(pOldBmp);
pDC->SelectPalette(pOldPal, TRUE);
return bSuccess;
}
BOOL CDib::Display(CDC * pDC, int xDest, int yDest, int nWidthDest, int nHeightDest,
int xSrc, int ySrc, int nWidthSrc, int nHeightSrc, DWORD dwRop)
{
if (IsRequireDither(pDC))
{
CRect rcDest(xDest, yDest, xDest+nWidthDest, yDest+nHeightDest);
CRect rcSrc(xSrc, ySrc, xSrc+nWidthSrc, ySrc+nHeightSrc);
return DitherDisplay(pDC, rcDest, rcSrc, dwRop);
}
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
CBitmap* pOldBmp = MemDC.SelectObject(m_pBitmap);
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
BOOL bSuccess = pDC->StretchBlt( xDest, yDest,
nWidthDest, nHeightDest,
&MemDC,
xSrc, ySrc,
nWidthSrc, nHeightSrc,
dwRop);
MemDC.SelectObject(pOldBmp);
pDC->SelectPalette(pOldPal, TRUE);
return bSuccess;
}
BOOL CDib::Display(CDC * pDC, int x, int y, DWORD dwRop)
{
if (IsRequireDither(pDC))
{
int nWidth = (int)GetWidth();
int nHeight = (int)GetHeight();
CRect rcDest(x, y, x+nWidth, y+nHeight);
CRect rcSrc(0, 0, nWidth, nHeight);
return DitherDisplay(pDC, rcDest, rcSrc, dwRop);
}
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
CBitmap* pOldBmp = MemDC.SelectObject(m_pBitmap);
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
BOOL bSuccess = pDC->BitBlt(x, y,
GetWidth(), GetHeight(),
&MemDC,
0, 0,
dwRop);
MemDC.SelectObject(pOldBmp);
pDC->SelectPalette(pOldPal, TRUE);
return bSuccess;
}
BOOL CDib::Display(CDC* pDC, CRect rcDest, CRect rcSrc, DWORD dwRop)
{
if (IsRequireDither(pDC))
return DitherDisplay(pDC, rcDest, rcSrc, dwRop);
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
CBitmap* pOldBmp = MemDC.SelectObject(m_pBitmap);
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
BOOL bSuccess = pDC->StretchBlt( rcDest.left, rcDest.top,
rcDest.Width(), rcDest.Height(),
&MemDC,
rcSrc.left, rcSrc.top,
rcSrc.Width(), rcSrc.Height(),
dwRop);
MemDC.SelectObject(pOldBmp);
pDC->SelectPalette(pOldPal, TRUE);
return bSuccess;
}
BOOL CDib::BuildBitmap()
{
if (m_pBitmap != NULL)
{
delete m_pBitmap;
m_pBitmap = NULL;
m_hBitmap = NULL;
}
m_hBitmap = DIBToDIBSection(m_hDib);
if (m_hBitmap == NULL)
return FALSE;
m_pBitmap = new CBitmap;
m_pBitmap->Attach(m_hBitmap);
return TRUE;
}
BOOL CDib::BuildPalette()
{
if (m_pPalette != NULL)
{
delete m_pPalette;
m_pPalette = NULL;
}
HPALETTE hPalette = CreateDIBPalette(m_hDib);
if (hPalette == NULL)
return FALSE;
m_pPalette = new CPalette;
m_pPalette->Attach(hPalette);
return TRUE;
}
BOOL CDib::UpdateInternal()
{
BuildPalette();
return BuildBitmap();
}
CPalette* CDib::GetPalette()
{
return m_pPalette;
}
CBitmap* CDib::GetBitmap()
{
return m_pBitmap;
}
BOOL CDib::IsEmpty()
{
if (m_hDib == NULL)
return TRUE;
if (! GlobalLock(m_hDib))
return TRUE;
GlobalUnlock(m_hDib);
return FALSE;
}
DWORD CDib::GetCompression()
{
LPBITMAPINFOHEADER lpBI = (LPBITMAPINFOHEADER)GlobalLock(m_hDib);
if (!lpBI)
{
GlobalUnlock(m_hDib);
return 0;
}
DWORD dwCompression = lpBI->biCompression;
GlobalUnlock(m_hDib);
return dwCompression;
}
WORD CDib::GetBitCount()
{
LPBITMAPINFOHEADER lpBI = (LPBITMAPINFOHEADER)GlobalLock(m_hDib);
if (!lpBI)
{
GlobalUnlock(m_hDib);
return 0;
}
WORD wBitCount = lpBI->biBitCount;
GlobalUnlock(m_hDib);
return wBitCount;
}
LONG CDib::GetWidth()
{
// get DIB buffer pointer
LPBYTE lpDIB = (LPBYTE)GlobalLock(m_hDib);
if (! lpDIB)
{
GlobalUnlock(m_hDib);
return 0;
}
LONG lWidth = (LONG)DIBWidth(lpDIB);
GlobalUnlock(m_hDib);
return lWidth;
}
LONG CDib::GetHeight()
{
// get DIB buffer pointer
LPBYTE lpDIB = (LPBYTE)GlobalLock(m_hDib);
if (! lpDIB)
{
GlobalUnlock(m_hDib);
return 0;
}
LONG lHeight = (LONG)DIBHeight(lpDIB);
GlobalUnlock(m_hDib);
return lHeight;
}
LONG CDib::GetWidthBytes()
{
return WIDTHBYTES((GetWidth())*((DWORD)GetBitCount()));
}
COLORREF CDib::GetPixel(LONG x, LONG y)
{
COLORREF cColor;
switch (GetBitCount())
{
case 1 : if (1<<(7-x%8) &
*(BYTE*)(GetBitsPtr()+GetPixelOffset(x, y)))
cColor = RGB(255,255,255);
else
cColor = RGB(0,0,0);
break;
case 4 :
{
PALETTEENTRY PaletteColors[16];
m_pPalette->GetPaletteEntries(0, 16, PaletteColors);
int nIndex = (*(BYTE*)(GetBitsPtr()+GetPixelOffset(x, y)) &
(x%2 ? 0x0f : 0xf0)) >> (x%2 ? 0 : 4);
cColor = RGB(PaletteColors[nIndex].peRed,
PaletteColors[nIndex].peGreen,
PaletteColors[nIndex].peBlue);
}
break;
case 8 :
{
PALETTEENTRY PaletteColors[256];
m_pPalette->GetPaletteEntries(0, 256, PaletteColors);
int nIndex = *(BYTE*)(GetBitsPtr()+GetPixelOffset(x, y));
cColor = RGB(PaletteColors[nIndex].peRed,
PaletteColors[nIndex].peGreen,
PaletteColors[nIndex].peBlue);
}
break;
default: cColor = RGB(*(BYTE*)(GetBitsPtr()+GetPixelOffset(x, y)),
*(BYTE*)(GetBitsPtr()+GetPixelOffset(x, y)+1),
*(BYTE*)(GetBitsPtr()+GetPixelOffset(x, y)+2));
break;
}
return cColor;
}
LONG CDib::GetPixelOffset(LONG x, LONG y)
{
switch (GetBitCount())
{
case 1:
case 4:
case 8:
return (GetHeight()-y-1)*GetWidthBytes()+x/(8/GetBitCount());
default:
return (GetHeight()-y-1)*GetWidthBytes()+x*(GetBitCount()/8);
}
}
LPBYTE CDib::GetBitsPtr()
{
LPBYTE lpDIB = (LPBYTE)GlobalLock(m_hDib);
if (! lpDIB)
{
GlobalUnlock(m_hDib);
return NULL;
}
LPBYTE lpData = FindDIBBits(lpDIB);
GlobalUnlock(m_hDib);
return lpData;
}
HANDLE CDib::GetHandle()
{
return m_hDib;
}
WORD CDib::GetColorNumber()
{
LPBYTE lpBI = (LPBYTE)GlobalLock(m_hDib);
if (! lpBI)
{
GlobalUnlock(m_hDib);
return 0;
}
WORD wColors = DIBNumColors(lpBI);
GlobalUnlock(m_hDib);
return wColors;
}
WORD CDib::GetPaletteSize()
{
LPBYTE lpBI = (LPBYTE)GlobalLock(m_hDib);
if (! lpBI)
{
GlobalUnlock(m_hDib);
return 0;
}
WORD wPalSize = PaletteSize(lpBI);
GlobalUnlock(m_hDib);
return wPalSize;
}
CDC* CDib::BeginPaint(CDC *pDC)
{
m_pMemDC = new CDC;
m_pMemDC->CreateCompatibleDC(pDC);
m_pPaletteTmp = m_pMemDC->SelectPalette(m_pPalette, TRUE);
m_pMemDC->RealizePalette();
m_pBitmapTmp = (CBitmap *)m_pMemDC->SelectObject(m_pBitmap);
return m_pMemDC;
}
void CDib::EndPaint()
{
m_pMemDC->SelectObject(m_pBitmapTmp);
m_pMemDC->SelectPalette(m_pPaletteTmp, TRUE);
delete m_pMemDC;
Create(m_hBitmap);
}
BOOL CDib::DisplayPalette(CDC* pDC, CRect rc)
{
return ::DisplayPalette(pDC->GetSafeHdc(), &rc, (HPALETTE)m_pPalette->GetSafeHandle());
}
BOOL CDib::DisplayTransparent(CDC * pDC, int x, int y, COLORREF cTransparentColor)
{
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
DrawTransparentBitmap(pDC->GetSafeHdc(),
m_hBitmap,
x,
y,
cTransparentColor);
pDC->SelectPalette(pOldPal, TRUE);
return TRUE;
}
#define UPVALUE(x, n) ((x)/((n) ? (n) : 1) + ((x)%((n) ? (n) : 1) ? 1 : 0))
BOOL CDib::DisplayFadeIn(CDC* pDC, int x, int y, int nDeta, DWORD dwDelayTime)
{
// backup DIB
HDIB hDib = CopyHandle(m_hDib);
// get color number
WORD wNumColors = GetColorNumber();
BITMAPINFO *bmi = (BITMAPINFO *)GlobalLock(m_hDib);
BITMAPINFO *bmi0 = (BITMAPINFO *)GlobalLock(hDib);
if (! bmi)
return FALSE;
BOOL bDone = FALSE;
int nDetaR, nDetaG, nDetaB;
// fade out
if (wNumColors) // There is palette
{
// build black image
for (WORD i=0; i<wNumColors; ++i)
{
bmi->bmiColors[i].rgbRed = 0 ;
bmi->bmiColors[i].rgbGreen = 0 ;
bmi->bmiColors[i].rgbBlue = 0 ;
}
UpdateInternal();
// display black first
Display(pDC, x, y, SRCCOPY);
while (! bDone)
{
bDone = TRUE;
for (WORD i=0; i<wNumColors; i++)
{
nDetaR = UPVALUE(bmi0->bmiColors[i].rgbRed-bmi->bmiColors[i].rgbRed, nDeta);
nDetaG = UPVALUE(bmi0->bmiColors[i].rgbGreen-bmi->bmiColors[i].rgbGreen, nDeta);
nDetaB = UPVALUE(bmi0->bmiColors[i].rgbBlue-bmi->bmiColors[i].rgbBlue, nDeta);
if (! Fade(nDetaR, nDetaG, nDetaB,
bmi0->bmiColors[i].rgbRed,
bmi0->bmiColors[i].rgbGreen,
bmi0->bmiColors[i].rgbBlue,
&(bmi->bmiColors[i].rgbRed),
&(bmi->bmiColors[i].rgbGreen),
&(bmi->bmiColors[i].rgbBlue)))
bDone = FALSE;
}
UpdateInternal();
Display(pDC, x, y, SRCCOPY);
Delay(dwDelayTime);
nDeta--;
}
}
else // No palette
{
// should increase the speed!
dwDelayTime /= 10;
// bits position
LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER)bmi;
LPBYTE lpBits = (LPBYTE)lpbi + lpbi->biSize;
LPBYTE lpBits0 = (LPBYTE)bmi0 + lpbi->biSize;
int nDelta = WIDTHBYTES(lpbi->biBitCount*lpbi->biWidth) - lpbi->biWidth*lpbi->biBitCount/8;
int nx, ny;
// build black image
for (ny=0; ny<lpbi->biHeight; ny++)
{
for (nx=0; nx<lpbi->biWidth; nx++)
{
*lpBits++ = 0;
*lpBits++ = 0;
*lpBits++ = 0;
}
lpBits += nDelta;
}
lpBits = (LPBYTE)lpbi + lpbi->biSize;
UpdateInternal();
// display black first
Display(pDC, x, y, SRCCOPY);
BYTE r, g, b, r0, g0, b0;
while (! bDone)
{
bDone = TRUE;
for (ny=0; ny<lpbi->biHeight; ny++)
{
for (nx=0; nx<lpbi->biWidth; nx++)
{
b0 = (BYTE)*lpBits0++;
g0 = (BYTE)*lpBits0++;
r0 = (BYTE)*lpBits0++;
b = (BYTE)*(lpBits);
g = (BYTE)*(lpBits+1);
r = (BYTE)*(lpBits+2);
nDetaR = UPVALUE(r0-r, nDeta);
nDetaG = UPVALUE(g0-g, nDeta);
nDetaB = UPVALUE(b0-b, nDeta);
if (! Fade(nDetaR, nDetaG, nDetaB, r0, g0, b0, &r, &g, &b))
bDone = FALSE;
*lpBits++ = b;
*lpBits++ = g;
*lpBits++ = r;
}
lpBits += nDelta;
lpBits0 += nDelta;
}
lpBits = (LPBYTE)lpbi + lpbi->biSize;
lpBits0 = (LPBYTE)bmi0 + lpbi->biSize;
UpdateInternal();
Display(pDC, x, y, SRCCOPY);
Delay(dwDelayTime);
nDeta--;
}
}
// cleanup
GlobalUnlock(m_hDib);
GlobalUnlock(hDib);
// restore DIB
m_hDib = CopyHandle(hDib);
GlobalFree(hDib);
return TRUE;
}
BOOL CDib::DisplayFadeOut(CDC* pDC, int x, int y, int nDeta, DWORD dwDelayTime)
{
// display first
Display(pDC, x, y, SRCCOPY);
// backup DIB
HDIB hDib = CopyHandle(m_hDib);
// get color number
WORD wNumColors = GetColorNumber();
BITMAPINFO *bmi = (BITMAPINFO *)GlobalLock(m_hDib);
if (! bmi)
return FALSE;
BOOL bDone = FALSE;
int nDetaR, nDetaG, nDetaB;
// fade out
if (wNumColors) // There is palette
{
while (! bDone)
{
bDone = TRUE;
for (WORD i=0; i<wNumColors; i++)
{
nDetaR = -1*UPVALUE(bmi->bmiColors[i].rgbRed, nDeta);
nDetaG = -1*UPVALUE(bmi->bmiColors[i].rgbGreen, nDeta);
nDetaB = -1*UPVALUE(bmi->bmiColors[i].rgbBlue, nDeta);
if (! Fade(nDetaR, nDetaG, nDetaB,
0, 0, 0,
&(bmi->bmiColors[i].rgbRed),
&(bmi->bmiColors[i].rgbGreen),
&(bmi->bmiColors[i].rgbBlue)))
bDone = FALSE;
}
UpdateInternal();
Display(pDC, x, y, SRCCOPY);
Delay(dwDelayTime);
nDeta--;
}
}
else // No palette
{
// should increase the speed!
dwDelayTime /= 10;
// bits position
LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER)bmi;
LPBYTE lpBits = (LPBYTE)lpbi + lpbi->biSize;
int nDelta = WIDTHBYTES(lpbi->biBitCount*lpbi->biWidth) - lpbi->biWidth*lpbi->biBitCount/8;
BYTE r, g, b;
int nx, ny;
while (! bDone)
{
bDone = TRUE;
for (ny=0; ny<lpbi->biHeight; ny++)
{
for (nx=0; nx<lpbi->biWidth; nx++)
{
b = (BYTE)*(lpBits);
g = (BYTE)*(lpBits+1);
r = (BYTE)*(lpBits+2);
nDetaR = -1*UPVALUE(r, nDeta);
nDetaG = -1*UPVALUE(g, nDeta);
nDetaB = -1*UPVALUE(b, nDeta);
if (! Fade(nDetaR, nDetaG, nDetaB, 0, 0, 0, &r, &g, &b))
bDone = FALSE;
*lpBits++ = b;
*lpBits++ = g;
*lpBits++ = r;
}
lpBits += nDelta;
}
lpBits = (LPBYTE)lpbi + lpbi->biSize;
UpdateInternal();
Display(pDC, x, y, SRCCOPY);
Delay(dwDelayTime);
nDeta--;
}
}
// cleanup
GlobalUnlock(m_hDib);
// restore DIB
m_hDib = CopyHandle(hDib);
GlobalFree(hDib);
return TRUE;
}
BOOL CDib::DisplayMosaicIn(CDC *pDC, int xx, int yy, int nTileSize, DWORD dwDelayTime, DWORD dwRop)
{
// count the number of dwTileNum
DWORD dwTileNum=(GetWidth()/nTileSize + ((GetWidth() % nTileSize) ? 1:0))*
(GetHeight()/nTileSize + ((GetHeight() % nTileSize) ? 1:0));
// allocate tile array
POINT *point = new POINT[dwTileNum];
if (point == NULL)
return FALSE;
// initialize the tile array
LONG x=0, y=0;
for (DWORD i=0;i<dwTileNum;++i)
{
point[i].x=x;
point[i].y=y;
x+=nTileSize;
if (x >= GetWidth())
{
x=0;
y+=nTileSize;
}
}
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
CBitmap* pOldBmp = MemDC.SelectObject(m_pBitmap);
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
double fMax = RAND_MAX;
BOOL bDone = FALSE;
while (! bDone)
{
DWORD n = (DWORD)((double)dwTileNum*(double)((double)rand()/fMax));
x = point[n].x;
y = point[n].y;
pDC->BitBlt(xx+x,
yy+y,
nTileSize,
nTileSize,
&MemDC,
x,
y,
dwRop);
dwTileNum--;
bDone = !dwTileNum;
point[n].x = point[dwTileNum].x;
point[n].y = point[dwTileNum].y;
Delay(dwDelayTime);
}
MemDC.SelectObject(pOldBmp);
pDC->SelectPalette(pOldPal, TRUE);
delete[] point;
return TRUE;
}
BOOL CDib::DisplayMosaicOut(CDC *pDC, int xx, int yy, int nTileSize, DWORD dwDelayTime)
{
// display dib first
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
CBitmap* pOldBmp = MemDC.SelectObject(m_pBitmap);
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
pDC->BitBlt(xx, yy,
GetWidth(), GetHeight(),
&MemDC,
0, 0,
SRCCOPY);
// count the number of dwTileNum
DWORD dwTileNum=(GetWidth()/nTileSize + ((GetWidth() % nTileSize) ? 1:0))*
(GetHeight()/nTileSize + ((GetHeight() % nTileSize) ? 1:0));
// allocate tile array
POINT *point = new POINT[dwTileNum];
if (point == NULL)
return FALSE;
// initialize the tile array
LONG x=0, y=0;
for (DWORD i=0;i<dwTileNum;++i)
{
point[i].x=x;
point[i].y=y;
x+=nTileSize;
if (x >= GetWidth())
{
x=0;
y+=nTileSize;
}
}
CBrush brush(GetSysColor(COLOR_WINDOW));
CBrush* oldbrush = pDC->SelectObject(&brush);
CPen pen(PS_SOLID,1,GetSysColor(COLOR_WINDOW));
CPen* oldpen = pDC->SelectObject(&pen);
double fMax = RAND_MAX;
BOOL bDone = FALSE;
while (! bDone)
{
DWORD n = (DWORD)((double)dwTileNum*(double)((double)rand()/fMax));
x = point[n].x;
y = point[n].y;
pDC->Rectangle( xx+x,
yy+y,
xx+x+nTileSize+1,
yy+y+nTileSize+1);
dwTileNum--;
bDone = !dwTileNum;
point[n].x = point[dwTileNum].x;
point[n].y = point[dwTileNum].y;
Delay(dwDelayTime);
}
MemDC.SelectObject(pOldBmp);
pDC->SelectPalette(pOldPal, TRUE);
pDC->SelectObject(oldbrush);
pDC->SelectObject(oldpen);
delete[] point;
return TRUE;
}
BOOL CDib::Display(int nEffect, CDC* pDC, int x, int y, int nDeta, DWORD dwDelayTime, DWORD dwRop)
{
if (nEffect == EFFECT_FADE)
return DisplayFadeIn(pDC, x, y, nDeta, dwDelayTime);
else if (nEffect == EFFECT_MOSAIC)
return DisplayMosaicIn(pDC, x, y, nDeta, dwDelayTime, dwRop);
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
CBitmap* pOldBmp = MemDC.SelectObject(m_pBitmap);
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
LONG i = 0;
BOOL bDone = FALSE;
while (! bDone)
{
switch (nEffect)
{
case EFFECT_SCANDOWN:
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->BitBlt(x,
y+i,
GetWidth(),
nDeta,
&MemDC,
0,
i,
dwRop);
i += nDeta;
break;
case EFFECT_SCANUP:
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->BitBlt(x,
y+GetHeight()-i,
GetWidth(),
nDeta,
&MemDC,
0,
GetHeight()-i,
dwRop);
i += nDeta;
break;
case EFFECT_SCANRIGHT:
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->BitBlt(x+i,
y,
nDeta,
GetHeight(),
&MemDC,
i,
0,
dwRop);
i += nDeta;
break;
case EFFECT_SCANLEFT:
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->BitBlt(x+GetWidth()-i,
y,
nDeta,
GetHeight(),
&MemDC,
GetWidth()-i,
0,
dwRop);
i += nDeta;
break;
case EFFECT_VSPLITSCAN:
if (i > GetHeight()/2)
{
i = GetHeight()/2;
bDone = TRUE;
}
pDC->BitBlt(x,
y+i,
GetWidth(),
nDeta,
&MemDC,
0,
i,
dwRop);
pDC->BitBlt(x,
y+GetHeight()-i,
GetWidth(),
i,
&MemDC,
0,
GetHeight()-i,
dwRop);
i += nDeta;
break;
case EFFECT_HSPLITSCAN:
if (i > GetWidth()/2)
{
i = GetWidth()/2;
bDone = TRUE;
}
pDC->BitBlt(x+i,
y,
nDeta,
GetHeight(),
&MemDC,
i,
0,
dwRop);
pDC->BitBlt(x+GetWidth()-i,
y,
nDeta,
GetHeight(),
&MemDC,
GetWidth()-i,
0,
dwRop);
i += nDeta;
break;
case EFFECT_MOVEDOWN:
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->BitBlt(x,
y,
GetWidth(),
i+nDeta,
&MemDC,
0,
GetHeight()-i,
dwRop);
i += nDeta;
break;
case EFFECT_MOVEUP:
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->BitBlt(x,
y+GetHeight()-i,
GetWidth(),
i,
&MemDC,
0,
0,
dwRop);
i += nDeta;
break;
case EFFECT_MOVERIGHT:
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->BitBlt(x,
y,
i+nDeta,
GetHeight(),
&MemDC,
GetWidth()-i,
0,
dwRop);
i += nDeta;
break;
case EFFECT_MOVELEFT:
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->BitBlt(x+GetWidth()-i,
y,
i,
GetHeight(),
&MemDC,
0,
0,
dwRop);
i += nDeta;
break;
case EFFECT_VSPLITMOVE:
if (i > GetHeight()/2)
{
i = GetHeight()/2;
bDone = TRUE;
}
pDC->BitBlt(x,
y,
GetWidth(),
i+nDeta,
&MemDC,
0,
GetHeight()/2-i,
dwRop);
pDC->BitBlt(x,
y+GetHeight()-i,
GetWidth(),
i,
&MemDC,
0,
GetHeight()/2,
dwRop);
i += nDeta;
break;
case EFFECT_HSPLITMOVE:
if (i > GetWidth()/2)
{
i = GetWidth()/2;
bDone = TRUE;
}
pDC->BitBlt(x,
y,
i+nDeta,
GetHeight(),
&MemDC,
GetWidth()/2-i,
0,
dwRop);
pDC->BitBlt(x+GetWidth()-i,
y,
i,
GetHeight(),
&MemDC,
GetWidth()/2,
0,
dwRop);
i += nDeta;
break;
case EFFECT_VCROSSMOVE:
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->BitBlt(x,
y,
GetWidth()/2,
i+nDeta,
&MemDC,
0,
GetHeight()-i,
dwRop);
pDC->BitBlt(x+GetWidth()/2,
y+GetHeight()-i,
GetWidth(),
i,
&MemDC,
GetWidth()/2,
0,
dwRop);
i += nDeta;
break;
case EFFECT_HCROSSMOVE:
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->BitBlt(x,
y,
i+nDeta,
GetHeight()/2,
&MemDC,
GetWidth()-i,
0,
dwRop);
pDC->BitBlt(x+GetWidth()-i,
y+GetHeight()/2,
i,
GetHeight()/2,
&MemDC,
0,
GetHeight()/2,
dwRop);
i += nDeta;
break;
case EFFECT_VRASTER:
{
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
LONG j = 0;
BOOL bQuitLoop = FALSE;
while (! bQuitLoop)
{
if (j > GetWidth())
{
j = GetWidth();
bQuitLoop = TRUE;
}
pDC->BitBlt(x+j,
y,
nDeta,
i+1,
&MemDC,
j,
GetHeight()-i,
dwRop);
j += nDeta;
if (j > GetWidth())
{
j = GetWidth();
bQuitLoop = TRUE;
}
pDC->BitBlt(x+j,
y+GetHeight()-i,
nDeta,
i,
&MemDC,
j,
0,
dwRop);
j += nDeta;
}
i++;
break;
}
case EFFECT_HRASTER:
{
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
LONG j = 0;
BOOL bQuitLoop = FALSE;
while (! bQuitLoop)
{
if (j > GetHeight())
{
j = GetHeight();
bQuitLoop = TRUE;
}
pDC->BitBlt(x,
y+j,
i+1,
nDeta,
&MemDC,
GetWidth()-i,
j,
dwRop);
j += nDeta;
if (j > GetHeight())
{
j = GetHeight();
bQuitLoop = TRUE;
}
pDC->BitBlt(x+GetWidth()-i,
y+j,
i,
nDeta,
&MemDC,
0,
j,
dwRop);
j += nDeta;
}
i++;
break;
}
case EFFECT_HBLIND:
{
if (i > nDeta)
{
i = nDeta;
bDone = TRUE;
}
for (LONG j=i; j<GetHeight(); j+=nDeta)
pDC->BitBlt(x,
y+j,
GetWidth(),
1,
&MemDC,
0,
j,
dwRop);
i++;
break;
}
case EFFECT_VBLIND:
if (i > nDeta)
{
i = nDeta;
bDone = TRUE;
}
for (LONG j=i; j<GetWidth(); j+=nDeta)
pDC->BitBlt(x+j,
y,
1,
GetHeight(),
&MemDC,
j,
0,
dwRop);
i++;
break;
} // end of switch
Delay(dwDelayTime);
} // end of while
MemDC.SelectObject(pOldBmp);
pDC->SelectPalette(pOldPal, TRUE);
return TRUE;
}
BOOL CDib::Clear(int nEffect, CDC* pDC, int x, int y, int nDeta, DWORD dwDelayTime)
{
if (nEffect == EFFECT_FADE)
return DisplayFadeOut(pDC, x, y, nDeta, dwDelayTime);
else if (nEffect == EFFECT_MOSAIC)
return DisplayMosaicOut(pDC, x, y, nDeta, dwDelayTime);
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
CBitmap* pOldBmp = MemDC.SelectObject(m_pBitmap);
CPalette* pOldPal = pDC->SelectPalette(m_pPalette, TRUE);
pDC->RealizePalette();
pDC->BitBlt(x,
y,
GetWidth(),
GetHeight(),
&MemDC,
0,
0,
SRCCOPY);
CBrush brush(GetSysColor(COLOR_WINDOW));
CBrush* oldbrush = pDC->SelectObject(&brush);
CPen pen(PS_SOLID,1,GetSysColor(COLOR_WINDOW));
CPen* oldpen = pDC->SelectObject(&pen);
LONG i = 0;
BOOL bDone = FALSE;
while (! bDone)
{
switch (nEffect)
{
case EFFECT_SCANDOWN:
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->Rectangle(x,
y+i,
x+GetWidth(),
y+nDeta);
i += nDeta;
break;
case EFFECT_SCANUP:
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->Rectangle(x,
y+GetHeight()-i,
x+GetWidth(),
y+GetHeight()-i+nDeta);
i += nDeta;
break;
case EFFECT_SCANRIGHT:
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->Rectangle(x+i,
y,
x+nDeta,
y+GetHeight());
i += nDeta;
break;
case EFFECT_SCANLEFT:
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->Rectangle(x+GetWidth()-i,
y,
x+GetWidth()-i+nDeta,
y+GetHeight());
i += nDeta;
break;
case EFFECT_VSPLITSCAN:
if (i > GetHeight()/2)
{
i = GetHeight()/2;
bDone = TRUE;
}
pDC->Rectangle(x,
y+i,
x+GetWidth(),
y+i+nDeta);
pDC->Rectangle(x,
y+GetHeight()-i,
x+GetWidth(),
y+GetHeight());
i += nDeta;
break;
case EFFECT_HSPLITSCAN:
if (i > GetWidth()/2)
{
i = GetWidth()/2;
bDone = TRUE;
}
pDC->Rectangle(x+i,
y,
x+i+nDeta,
y+GetHeight());
pDC->Rectangle(x+GetWidth()-i,
y,
x+GetWidth(),
y+GetHeight());
i += nDeta;
break;
case EFFECT_MOVEDOWN:
{
i += nDeta;
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->BitBlt(x, //x dest
y+i, //y dest
GetWidth(), //width
GetHeight()-i, //depth
&MemDC,
0, //x source
0, //y source
SRCCOPY);
pDC->Rectangle(x, y+i-nDeta,
x+GetWidth(), y+i);
break;
}
case EFFECT_MOVEUP:
{
i += nDeta;
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->BitBlt(x, //x dest
y, //y dest
GetWidth(), //width
GetHeight()-i, //depth
&MemDC,
0, //x source
i, //y source
SRCCOPY);
pDC->Rectangle( x,
y+GetHeight()-i,
x+GetWidth(),
y+GetHeight());
break;
}
case EFFECT_MOVERIGHT:
{
i += nDeta;
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->BitBlt(x+i, //x dest
y, //y dest
GetWidth()-i, //width
GetHeight(), //depth
&MemDC,
0, //x source
0, //y source
SRCCOPY);
pDC->Rectangle(x+i-nDeta, y,
x+i, y+GetHeight());
break;
}
case EFFECT_MOVELEFT:
{
i += nDeta;
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->BitBlt(x, //x dest
y, //y dest
GetWidth()-i, //width
GetHeight(), //depth
&MemDC,
i, //y source
0, //x source
SRCCOPY);
pDC->Rectangle( x+GetWidth()-i,
y,
x+GetWidth(),
y+GetHeight());
break;
}
case EFFECT_VCROSSMOVE:
{
i += nDeta;
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
pDC->BitBlt(x, //x dest
y+i, //y dest
GetWidth()/2, //width
GetHeight()-i, //depth
&MemDC,
0, //x source
0, //y source
SRCCOPY);
pDC->Rectangle(x, y+i-nDeta,
x+GetWidth()/2, y+i);
pDC->BitBlt(x+GetWidth()/2, //x dest
y, //y dest
GetWidth(), //width
GetHeight()-i, //depth
&MemDC,
GetWidth()/2, //x source
i, //y source
SRCCOPY);
pDC->Rectangle( x+GetWidth()/2,
y+GetHeight()-i,
x+GetWidth(),
y+GetHeight());
break;
}
case EFFECT_HCROSSMOVE:
{
i += nDeta;
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
pDC->BitBlt(x+i, //x dest
y, //y dest
GetWidth()-i, //width
GetHeight()/2, //depth
&MemDC,
0, //x source
0, //y source
SRCCOPY);
pDC->Rectangle(x+i-nDeta, y,
x+i, y+GetHeight()/2);
pDC->BitBlt(x, //x dest
y+GetHeight()/2, //depth
GetWidth()-i, //width
GetHeight(), //depth
&MemDC,
i, //y source
GetHeight()/2, //depth
SRCCOPY);
pDC->Rectangle( x+GetWidth()-i,
y+GetHeight()/2,
x+GetWidth(),
y+GetHeight());
break;
}
case EFFECT_VSPLITMOVE:
{
i += nDeta;
if (i > GetHeight()/2)
{
i = GetHeight()/2;
bDone = TRUE;
}
pDC->BitBlt(x, //x dest
y, //y dest
GetWidth(), //width
GetHeight()/2-i, //depth
&MemDC,
0, //x source
i, //y source
SRCCOPY);
pDC->BitBlt(x, //x dest
y+GetHeight()/2+i, //y dest
GetWidth(), //width
GetHeight()/2-i, //depth
&MemDC,
0, //x source
GetHeight()/2, //y source
SRCCOPY);
pDC->Rectangle( x,
y+GetHeight()/2-i,
x+GetWidth(),
y+GetHeight()/2+i+1);
break;
}
case EFFECT_HSPLITMOVE:
{
i += nDeta;
if (i > GetWidth()/2)
{
i = GetWidth()/2;
bDone = TRUE;
}
pDC->BitBlt(x, //x dest
y, //y dest
GetWidth()/2-i, //width
GetHeight(), //depth
&MemDC,
i, //y source
0, //x source
SRCCOPY);
pDC->BitBlt(x+GetWidth()/2+i, //x dest
y, //y dest
GetWidth()/2-i, //width
GetHeight(), //depth
&MemDC,
GetWidth()/2, //x source
0, //y source
SRCCOPY);
pDC->Rectangle( x+GetWidth()/2-i,
y,
x+GetWidth()/2+i+1,
y+GetHeight());
break;
}
case EFFECT_VRASTER:
{
if (i > GetHeight())
{
i = GetHeight();
bDone = TRUE;
}
LONG j = 0;
BOOL bQuitLoop = FALSE;
while (! bQuitLoop)
{
if (j > GetWidth())
{
j = GetWidth();
bQuitLoop = TRUE;
}
pDC->BitBlt(x+j, //x dest
y+i, //y dest
nDeta, //width
GetHeight()-i, //depth
&MemDC,
j, //x source
0, //y source
SRCCOPY);
pDC->Rectangle(x+j, y+i-1,
x+j+nDeta, y+i);
j += nDeta;
if (j > GetWidth())
{
j = GetWidth();
bQuitLoop = TRUE;
}
pDC->BitBlt(x+j, //x dest
y, //y dest
nDeta, //width
GetHeight()-i, //depth
&MemDC,
j, //y source
i, //x source
SRCCOPY);
pDC->Rectangle( x+j,
y+GetHeight()-i,
x+j+nDeta,
y+GetHeight());
j += nDeta;
}
i++;
break;
}
case EFFECT_HRASTER:
{
if (i > GetWidth())
{
i = GetWidth();
bDone = TRUE;
}
LONG j = 0;
BOOL bQuitLoop = FALSE;
while (! bQuitLoop)
{
if (j > GetHeight())
{
j = GetHeight();
bQuitLoop = TRUE;
}
pDC->BitBlt(x+i, //x dest
y+j, //y dest
GetWidth()-i, //width
nDeta, //depth
&MemDC,
0, //x source
j, //y source
SRCCOPY);
pDC->Rectangle(x+i-1, y+j,
x+i, y+j+nDeta);
j += nDeta;
if (j > GetHeight())
{
j = GetHeight();
bQuitLoop = TRUE;
}
pDC->BitBlt(x, //x dest
y+j, //y dest
GetWidth()-i, //width
nDeta, //depth
&MemDC,
i, //y source
j, //x source
SRCCOPY);
pDC->Rectangle( x+GetWidth()-i,
y+j,
x+GetWidth(),
y+j+nDeta);
j += nDeta;
}
i++;
break;
}
case EFFECT_HBLIND:
{
if (i > nDeta)
{
i = nDeta;
bDone = TRUE;
}
for (LONG j=i; j<GetHeight(); j+=nDeta)
pDC->Rectangle( x,
y+j,
x+GetWidth(),
y+j+1);
i++;
break;
}
case EFFECT_VBLIND:
if (i > nDeta)
{
i = nDeta;
bDone = TRUE;
}
for (LONG j=i; j<GetWidth(); j+=nDeta)
pDC->Rectangle( x+j,
y,
x+j+1,
y+GetHeight());
i++;
break;
} // end of switch
Delay(dwDelayTime);
} // end of while
MemDC.SelectObject(pOldBmp);
pDC->SelectPalette(pOldPal, TRUE);
return TRUE;
}
HDIB CDib::CopyRect(CRect rc)
{
return CropDIB(m_hDib, rc);
}
BOOL CDib::CutRect(CRect rc)
{
HDIB hNewDib = CutDIB(m_hDib, rc);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::MergeDib(HDIB hDib, CPoint ptTopLeft)
{
POINT pt;
pt.x = ptTopLeft.x;
pt.y = ptTopLeft.y;
HDIB hNewDib = MergeDIB(m_hDib, hDib, pt);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::TransparentMergeDib(HDIB hDib, CPoint ptTopLeft, COLORREF crTransparent)
{
POINT pt;
pt.x = ptTopLeft.x;
pt.y = ptTopLeft.y;
HDIB hNewDib = TransparentMergeDIB(m_hDib, hDib, pt, crTransparent);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib:: Crop(CRect rc)
{
HDIB hNewDib = CropDIB(m_hDib, rc);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::Rotate(double fDegrees, COLORREF clrBack)
{
HDIB hNewDib = RotateDIB(m_hDib, fDegrees, clrBack);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::Rotate90()
{
HDIB hNewDib = RotateDIB(m_hDib);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::Rotate180()
{
HDIB h = RotateDIB(m_hDib);
if (! h)
return FALSE;
HDIB hNewDib = RotateDIB(h);
DestroyDIB(h);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::Rotate270()
{
HDIB h1 = RotateDIB(m_hDib);
if (! h1)
return FALSE;
HDIB h2 = RotateDIB(h1);
DestroyDIB(h1);
if (! h2)
return FALSE;
HDIB hNewDib = RotateDIB(h2);
DestroyDIB(h2);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::FlipHorz()
{
HDIB hNewDib = FlipHorzDIB(m_hDib);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::FlipVert()
{
HDIB hNewDib = FlipVertDIB(m_hDib);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib:: ChangeImageSize(int nWidth, int nHeight)
{
HDIB hNewDib = ChangeDIBSize(m_hDib, nWidth, nHeight);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::Zoom(double fRatioX, double fRatioY)
{
int nWidth = (int)(fRatioX * (double)GetWidth());
int nHeight = (int)(fRatioY * (double)GetHeight());
HDIB hNewDib = ChangeDIBSize(m_hDib, nWidth, nHeight);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib:: ChangeCanvasSize(int nWidth, int nHeight, int nPosition)
{
HDIB hNewDib = ChangeDIBCanvasSize(m_hDib, nWidth, nHeight, nPosition);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::IsRequireDither(CDC* pDC)
{
// if device can not display DIB color, dithering DIB
if (GetBitCount() > 8 &&
pDC->GetDeviceCaps(BITSPIXEL) <= 8)
return TRUE;
return FALSE;
}
BOOL CDib::DitherDisplay(CDC* pDC, CRect rcDest, CRect rcSrc, DWORD dwRop)
{
return DitherDisplayDIB(pDC->GetSafeHdc(),
rcDest,
m_hDib,
rcSrc,
dwRop);
}
BOOL CDib::AdjustColor(int nColorModel, int v1, int v2, int v3)
{
if (! AdjustDIBColor(m_hDib, nColorModel, v1, v2, v3))
return FALSE;
return UpdateInternal();
}
BOOL CDib::AdjustBrightness(int v)
{
if (! AdjustDIBBrightness(m_hDib, v))
return FALSE;
return UpdateInternal();
}
BOOL CDib::AdjustContrast(int v)
{
if (! AdjustDIBContrast(m_hDib, v))
return FALSE;
return UpdateInternal();
}
BOOL CDib::SeparateRGB(int nIndex)
{
HDIB hNewDib = SeparateRGBfromDIB(m_hDib, nIndex);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::FilteRGB(int nIndex)
{
HDIB hNewDib = FilteRGBfromDIB(m_hDib, nIndex);
if (! hNewDib)
return FALSE;
// set to m_hDib
Destroy();
m_hDib = hNewDib;
// return
return UpdateInternal();
}
BOOL CDib::ColorQuantize(int nColorBits)
{
HDIB hNewDib;
if (nColorBits > 8)
hNewDib = ConvertDIBFormat(m_hDib, nColorBits, NULL);
else
{
int nColors = 1<<nColorBits;
hNewDib = ColorQuantizeDIB(m_hDib, nColorBits, nColors);
}
if (! hNewDib)
return FALSE;
Destroy();
m_hDib = hNewDib;
return UpdateInternal();
}
BOOL CDib::ChangeToGrayscale(int nMethod, double fRedWeight, double fGreenWeight, double fBlueWeight)
{
HPALETTE hPal = ConvertToGrayscale(m_hDib, nMethod, fRedWeight, fGreenWeight, fBlueWeight);
if (hPal == NULL)
return FALSE;
// set new palette
if (m_pPalette != NULL)
delete m_pPalette;
m_pPalette = new CPalette;
m_pPalette->Attach(hPal);
// rebuild bitmap
return UpdateInternal();
}
BOOL CDib::HighPass(int Strength, int nAlgorithm)
{
if (IsEmpty())
return FALSE;
if (! HighPassDIB(m_hDib, Strength, nAlgorithm))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::LowPass(int Strength, int nAlgorithm)
{
if (IsEmpty())
return FALSE;
if (! LowPassDIB(m_hDib, Strength, nAlgorithm))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::EdgeEnhance(int Strength, int nAlgorithm)
{
if (IsEmpty())
return FALSE;
if (! EdgeEnhanceDIB(m_hDib, Strength, nAlgorithm))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::MedianFilter()
{
if (IsEmpty())
return FALSE;
if (! MedianFilterDIB(m_hDib))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::ConvertFormat(WORD wBitCount)
{
if (IsEmpty())
return FALSE;
if (GetBitCount() == wBitCount)
return TRUE;
HDIB hNewDib = ConvertDIBFormat(m_hDib, wBitCount, NULL);
if (! hNewDib)
return FALSE;
Destroy();
m_hDib = hNewDib;
return UpdateInternal();
}
BOOL CDib::Erosion(BOOL bHoriz)
{
if (IsEmpty())
return FALSE;
if (! ErosionDIB(m_hDib, bHoriz))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::Dilation(BOOL bHoriz)
{
if (IsEmpty())
return FALSE;
if (! DilationDIB(m_hDib, bHoriz))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::MorphOpen(BOOL bHoriz)
{
if (IsEmpty())
return FALSE;
if (! MorphOpenDIB(m_hDib, bHoriz))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::MorphClose(BOOL bHoriz)
{
if (IsEmpty())
return FALSE;
if (! MorphCloseDIB(m_hDib, bHoriz))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::Contour(BOOL bHoriz)
{
if (IsEmpty())
return FALSE;
if (! ContourDIB(m_hDib, bHoriz))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::Thinning()
{
if (IsEmpty())
return FALSE;
if (! ThinningDIB(m_hDib))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::Reverse()
{
if (IsEmpty())
return FALSE;
if (! ReverseDIB(m_hDib))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::FFT()
{
if (IsEmpty())
return FALSE;
if (! FFTDIB(m_hDib))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::DCT()
{
if (IsEmpty())
return FALSE;
if (! DCTDIB(m_hDib))
return FALSE;
// return
return UpdateInternal();
}
BOOL CDib::WALh()
{
if (IsEmpty())
return FALSE;
if (! WALhDIB(m_hDib))
return FALSE;
// return
return UpdateInternal();
}
| [
"damoguyan8844@2e4fddd8-cc6a-11de-b393-33af5e5426e5"
] | [
[
[
1,
2705
]
]
] |
10a81594834de3ae3a9befd474fa1980888c4100 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/MyGUI/include/MyGUI_Delegate.h | dbe3e70a9fc28f01ac7fcd962671db06fd6aa777 | [] | no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,837 | h | /*!
@file
@author Albert Semenov
@date 11/2007
@module
*//*
This file is part of MyGUI.
MyGUI 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 3 of the License, or
(at your option) any later version.
MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_DELEGATE_H__
#define __MYGUI_DELEGATE_H__
#include "MyGUI_Common.h"
#include <typeinfo>
#include <list>
// source
// http://rsdn.ru/article/cpp/delegates.xml
// генерация делегатов для различного колличества параметров
namespace MyGUI
{
namespace delegates
{
// базовый класс для тех классов, что хотят себя отвязывать от мульти делегатов
class MYGUI_EXPORT IDelegateUnlink
{
public:
virtual ~IDelegateUnlink() { }
IDelegateUnlink() { m_baseDelegateUnlink = this; }
bool compare(IDelegateUnlink * _unlink) { return m_baseDelegateUnlink == _unlink->m_baseDelegateUnlink; }
private:
IDelegateUnlink * m_baseDelegateUnlink;
};
inline IDelegateUnlink * GetDelegateUnlink(void * _base) { return 0; }
inline IDelegateUnlink * GetDelegateUnlink(IDelegateUnlink * _base) { return _base; }
}
// без параметров
#define MYGUI_SUFFIX 0
#define MYGUI_TEMPLATE
#define MYGUI_TEMPLATE_PARAMS
#define MYGUI_TEMPLATE_ARGS
#define MYGUI_T_TEMPLATE_PARAMS <typename T>
#define MYGUI_T_TEMPLATE_ARGS <T>
#define MYGUI_PARAMS
#define MYGUI_ARGS
#define MYGUI_TYPENAME
#include "MyGUI_DelegateImplement.h"
// один параметр
#define MYGUI_SUFFIX 1
#define MYGUI_TEMPLATE template
#define MYGUI_TEMPLATE_PARAMS <typename TP1>
#define MYGUI_TEMPLATE_ARGS <TP1>
#define MYGUI_T_TEMPLATE_PARAMS <typename T, typename TP1>
#define MYGUI_T_TEMPLATE_ARGS <T, TP1>
#define MYGUI_PARAMS TP1 p1
#define MYGUI_ARGS p1
#define MYGUI_TYPENAME typename
#include "MyGUI_DelegateImplement.h"
// два параметра
#define MYGUI_SUFFIX 2
#define MYGUI_TEMPLATE template
#define MYGUI_TEMPLATE_PARAMS <typename TP1, typename TP2>
#define MYGUI_TEMPLATE_ARGS <TP1, TP2>
#define MYGUI_T_TEMPLATE_PARAMS <typename T, typename TP1, typename TP2>
#define MYGUI_T_TEMPLATE_ARGS <T, TP1, TP2>
#define MYGUI_PARAMS TP1 p1, TP2 p2
#define MYGUI_ARGS p1, p2
#define MYGUI_TYPENAME typename
#include "MyGUI_DelegateImplement.h"
// три параметра
#define MYGUI_SUFFIX 3
#define MYGUI_TEMPLATE template
#define MYGUI_TEMPLATE_PARAMS <typename TP1, typename TP2, typename TP3>
#define MYGUI_TEMPLATE_ARGS <TP1, TP2, TP3>
#define MYGUI_T_TEMPLATE_PARAMS <typename T, typename TP1, typename TP2, typename TP3>
#define MYGUI_T_TEMPLATE_ARGS <T, TP1, TP2, TP3>
#define MYGUI_PARAMS TP1 p1, TP2 p2, TP3 p3
#define MYGUI_ARGS p1, p2, p3
#define MYGUI_TYPENAME typename
#include "MyGUI_DelegateImplement.h"
// четыре параметра
#define MYGUI_SUFFIX 4
#define MYGUI_TEMPLATE template
#define MYGUI_TEMPLATE_PARAMS <typename TP1, typename TP2, typename TP3, typename TP4>
#define MYGUI_TEMPLATE_ARGS <TP1, TP2, TP3, TP4>
#define MYGUI_T_TEMPLATE_PARAMS <typename T, typename TP1, typename TP2, typename TP3, typename TP4>
#define MYGUI_T_TEMPLATE_ARGS <T, TP1, TP2, TP3, TP4>
#define MYGUI_PARAMS TP1 p1, TP2 p2, TP3 p3, TP4 p4
#define MYGUI_ARGS p1, p2, p3, p4
#define MYGUI_TYPENAME typename
#include "MyGUI_DelegateImplement.h"
// пять параметров
#define MYGUI_SUFFIX 5
#define MYGUI_TEMPLATE template
#define MYGUI_TEMPLATE_PARAMS <typename TP1, typename TP2, typename TP3, typename TP4, typename TP5>
#define MYGUI_TEMPLATE_ARGS <TP1, TP2, TP3, TP4, TP5>
#define MYGUI_T_TEMPLATE_PARAMS <typename T, typename TP1, typename TP2, typename TP3, typename TP4, typename TP5>
#define MYGUI_T_TEMPLATE_ARGS <T, TP1, TP2, TP3, TP4, TP5>
#define MYGUI_PARAMS TP1 p1, TP2 p2, TP3 p3, TP4 p4, TP5 p5
#define MYGUI_ARGS p1, p2, p3, p4, p5
#define MYGUI_TYPENAME typename
#include "MyGUI_DelegateImplement.h"
} // namespace MyGUI
#endif // __MYGUI_DELEGATE_H__
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
] | [
[
[
1,
136
]
]
] |
3d55694ed13a800e0fdc74680de904174a736781 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/ISerializable.h | 4e54f0b263787fb7df93f2e31b795be6972883c8 | [] | no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | #pragma once
#ifndef __HALAK_SERIALIZABLE_INTERFACE__
#define __HALAK_SERIALIZABLE_INTERFACE__
# include <Halak/FWD.h>
namespace Halak
{
class ISerializable
{
HKInterfaceFOURCC('I', 'S', 'R', 'Z');
public:
virtual ~ISerializable() { }
virtual void Serialize(StreamWriter& writer) = 0;
virtual void Deserialize(StreamReader& reader) = 0;
};
}
#endif | [
"[email protected]"
] | [
[
[
1,
20
]
]
] |
51731e27bb64ef46e32904b89f4a79ca7f20188c | 8342f87cc7e048aa812910975c68babc6fb6c5d8 | /client/Game2/Control/ActionPerformers.cpp | c2edb1ea865df0ffd3bc7a2af12c53622b487dc1 | [] | no_license | espes/hoverrace | 1955c00961af4bb4f5c846f20e65ec9312719c08 | 7d5fd39ba688e2c537f35f7c723dedced983a98c | refs/heads/master | 2021-01-23T13:23:03.710443 | 2010-12-19T22:26:12 | 2010-12-19T22:26:12 | 2,005,364 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,453 | cpp | // ActionPerformers.cpp
// A collection of classes implementing the ActionPerformer template class
// (just has to implement Perform() and a constructor). These are all
// actions to be performed when the user presses a control key.
//
// Copyright (c) 2010, Ryan Curtin
//
// Licensed under GrokkSoft HoverRace SourceCode License v1.0(the "License");
// you may not use this file except in compliance with the License.
//
// A copy of the license should have been attached to the package from which
// you have taken this file. If you can not find the license you can not use
// this file.
//
//
// The author makes no representations about the suitability of
// this software for any purpose. It is provided "as is" "AS IS",
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
//
// See the License for the specific language governing permissions
// and limitations under the License.
//
#include "StdAfx.h"
#include "ActionPerformers.h"
using namespace HoverRace::Client::Control;
using namespace HoverRace::MainCharacter;
// constructor does not need to do anything but save our pointer
PlayerEffectAction::PlayerEffectAction(std::string name, int listOrder, HoverRace::MainCharacter::MainCharacter* pmc) : ControlAction(name, listOrder), mc(pmc) { }
void PlayerEffectAction::SetMainCharacter(HoverRace::MainCharacter::MainCharacter* mc) { this->mc = mc; }
void EngineAction::operator()(int eventValue)
{
if(eventValue > 0)
mc->SetEngineState(true);
else
mc->SetEngineState(false);
}
void TurnLeftAction::operator()(int eventValue)
{
if(eventValue > 0)
mc->SetTurnLeftState(true);
else
mc->SetTurnLeftState(false);
}
void TurnRightAction::operator()(int eventValue)
{
if(eventValue > 0)
mc->SetTurnRightState(true);
else
mc->SetTurnRightState(false);
}
void JumpAction::operator()(int eventValue)
{
if(eventValue > 0)
mc->SetJump();
}
void PowerupAction::operator()(int eventValue)
{
if(eventValue > 0)
mc->SetPowerup();
}
void ChangeItemAction::operator()(int eventValue)
{
if(eventValue > 0)
mc->SetChangeItem();
}
void BrakeAction::operator()(int eventValue)
{
if(eventValue > 0)
mc->SetBrakeState(true);
else
mc->SetBrakeState(false);
}
void LookBackAction::operator()(int eventValue)
{
if(eventValue > 0)
mc->SetLookBackState(true);
else
mc->SetLookBackState(false);
}
| [
"ryan@7d5085ce-8879-48fc-b0cc-67565f2357fd",
"zoogie@7d5085ce-8879-48fc-b0cc-67565f2357fd"
] | [
[
[
1,
32
],
[
34,
34
],
[
36,
92
]
],
[
[
33,
33
],
[
35,
35
],
[
93,
93
]
]
] |
efff81f978cbf6442306dacc63266275d2052efc | ce0622a0f49dd0ca172db04efdd9484064f20973 | /tools/GameList/CFtpClient.cpp | e23d8a11a7b24266049ba89c1a880800034ad7f1 | [] | no_license | maninha22crazy/xboxplayer | a78b0699d4002058e12c8f2b8c83b1cbc3316500 | e9ff96899ad8e8c93deb3b2fe9168239f6a61fe1 | refs/heads/master | 2020-12-24T18:42:28.174670 | 2010-03-14T13:57:37 | 2010-03-14T13:57:37 | 56,190,024 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,368 | cpp | #include "CFtpClient.h"
#include <string>
#include "Externs.h"
#include "Utility.h"
using namespace std;
#define BUFFER_SIZE 1024
CFtpClient::CFtpClient(void)
{
m_nSIZE = 20480;
}
CFtpClient::~CFtpClient(void)
{
}
bool CFtpClient::Startup()
{
WORD wvis;
WSADATA wsaData;
int err;
// 判断socket的版本
wvis = MAKEWORD(1,1);
err = WSAStartup(wvis,&wsaData);
if(err != 0)
{
return false;
}
if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion ) != 1 ) // 如果socket的版本不是1.1退出
{
WSACleanup();
return false;
}
return true;
}
/**********************************************************
函名名称: GetConnect
描 述: 与服务器建立连接
输入参数: string host 服务器IP
int port 服务端口
输出参数:
返 回 值: SOCKET (SOCKET 连接成功,NULL 连接失败)
**********************************************************/
SOCKET CFtpClient::GetConnect(string host, int port)
{
SOCKET Client=socket(AF_INET,SOCK_STREAM,0); // 创建socket,TCP/IP协议
// 判断地址族
SOCKADDR_IN addrClient;
addrClient.sin_addr.S_un.S_addr = inet_addr("192.168.73.1");
addrClient.sin_family = AF_INET;
addrClient.sin_port = htons(port);
//========================== 破解 begin =================================
BOOL bBroadcast = TRUE;
if( setsockopt(Client, SOL_SOCKET, 0x5802, (PCSTR)&bBroadcast, sizeof(BOOL) ) != 0 )
{
printf( "Failed to set socket to 5802, error\n");
}
if( setsockopt(Client, SOL_SOCKET, 0x5801, (PCSTR)&bBroadcast, sizeof(BOOL) ) != 0 )
{
printf( "Failed to set socket to 5801, error\n");
}
//========================== 破解 end =================================
if(connect(Client,(SOCKADDR*)&addrClient,sizeof(SOCKADDR))==SOCKET_ERROR)
{
return NULL;
}
return Client;
}
/**********************************************************
函名名称: ConnectFtp
描 述: 与服务器建立连接
输入参数:
输出参数:
返 回 值: SOCKET (SOCKET 连接成功,NULL 连接失败)
**********************************************************/
SOCKET CFtpClient::ConnectFtp(string strServerIp, int nPort, string strUserName, string strPassWord)
{
SOCKET client = GetConnect(strServerIp, nPort);
int len;
char recvBuf[100];
//ZeroMemory(recvBuf,sizeof(recvBuf));
len = recv(client,recvBuf,100,0);
if(!client)
{
return NULL;
}
if(SendCommand(client, "USER", strUserName, 331 ) )
{
if(SendCommand(client, "PASS", strPassWord, 230 ) ) // 服务器需要密码,发送密码
{
return client; // 用户名及密码通过验证
}
}
return NULL;
}
/**********************************************************
函名名称: SetFilePos
描 述: 向服务器上文件发送偏移请求
输入参数: SOCKET Client 连接服务器的SOCKET
LONG pos 偏移量
输出参数:
返 回 值: BOOL
**********************************************************/
BOOL CFtpClient::SetFilePos(SOCKET Client,LONG pos)
{
string strPos;
char buffer[20];
ltoa(pos,buffer,10);
strPos = buffer;
if(!SendCommand(Client,"REST",strPos,350))
{
return false; // 定位出错
}
return true;
}
/**********************************************************
函名名称: SendCommand
描 述: 向服务器发送命令
输入参数: SOCKET Client 连接服务器的SOCKET
string strCmd 要发送的命令
string code 返回的代码
输出参数:
返 回 值: BOOL
**********************************************************/
BOOL CFtpClient::SendCommand(SOCKET Client,string strCmd, string strInfo,LONG expCode,LONG* lpResult,string* lpOther)
{
LONG len = 0,lResponse = 0;
char sendBuf[BUFFER_SIZE+1],recvBuf[BUFFER_SIZE+1];
ZeroMemory(sendBuf,sizeof(sendBuf));
ZeroMemory(recvBuf,sizeof(recvBuf));
// 构建命令
//USES_CONVERSION;
_snprintf_s(sendBuf, BUFFER_SIZE, "%s %s\r\n", strCmd.c_str(), strInfo.c_str());
send(Client,sendBuf,strlen(sendBuf),0);
len = recv(Client,recvBuf,BUFFER_SIZE,0);
if (len < 0)
{
Sleep(200);
len = recv(Client,recvBuf,BUFFER_SIZE,0);
if (len < 0)
{
return false;
}
}
char* szStop;
lResponse = strtol(recvBuf,&szStop,10);
if (lpResult)
{
*lpResult = lResponse;
}
if (lpOther)
{
*lpOther = string(szStop);
}
m_strRecvLastInfo = recvBuf;
return expCode == lResponse;
}
/**********************************************************
函名名称: SendCommand
描 述: 向服务器发送命令
输入参数: SOCKET Client 连接服务器的SOCKET
string strCmd 要发送的命令
string code 返回的代码
输出参数:
返 回 值: LONG
**********************************************************/
LONG CFtpClient::SendCommand(SOCKET Client,string strCmd, string strInfo)
{
LONG len = 0,lResponse = 0;
char sendBuf[BUFFER_SIZE+1],recvBuf[BUFFER_SIZE+1];
ZeroMemory(sendBuf,sizeof(sendBuf));
ZeroMemory(recvBuf,sizeof(recvBuf));
// 构建命令
//USES_CONVERSION;
_snprintf_s(sendBuf,BUFFER_SIZE,"%s %s\r\n",strCmd.c_str(), strInfo.c_str());
send(Client,sendBuf,strlen(sendBuf),0);
len = recv(Client,recvBuf,BUFFER_SIZE,0);
if (len < 0)
{
Sleep(200);
len = recv(Client,recvBuf,BUFFER_SIZE,0);
if (len < 0)
{
return 0;
}
}
char* szStop;
lResponse = strtol(recvBuf,&szStop,10);
m_strRecvLastInfo = recvBuf;
return lResponse;
}
/**********************************************************
函名名称: GetCode
描 述: 获取服务器返回码
输入参数: char *buf 给定的字符串
输出参数:
返 回 值: string
**********************************************************/
string CFtpClient::GetCode(char *buf)
{
string str;
str = buf;
try
{
str=str.substr(0,3);
return str;
}
catch (...)
{
return "";
}
}
/**********************************************************
函名名称: GetValue
描 述: 获取服务器返回值
输入参数: char *buf 给定的字符串
输出参数:
返 回 值: string
**********************************************************/
string CFtpClient::GetValue(char *buf)
{
string str;
str = buf;
try
{
if(str.length() > 4)
{
str = str.substr(4, str.length() - 4);
}
return str;
}
catch (...)
{
return "";
}
}
/**********************************************************
函名名称: GetHost
描 述: 从给定字符中分离出IP地址
输入参数: string pasvStr 给定的字符串
输出参数:
返 回 值: string
**********************************************************/
string CFtpClient::GetHost(string pasvStr)
{
int index = pasvStr.rfind('(');
//取出"()"中的部份
string sIP;
string temp;
temp = pasvStr.substr(index+2, pasvStr.length()-index-2);
//取出最后一个","后面的数字
int i=temp.rfind(',');
string sPort2=temp.substr(i + 1, temp.length()-i-1);
temp=temp.substr(0, i);
//取出倒数第二个","后面的数字
i = temp.rfind(',');
string sPort1=temp.substr(i + 1,temp.length()-i-1);
temp=temp.substr(0, i);
//将","改为"."组成服器的IP地址
temp = replace_all(temp,",", ".");
//返回分离出来的IP地址
return temp;
}
/**********************************************************
函名名称: GetPort
描 述: 从给定字符中分离出端口号
输入参数: string pasvStr 给定的字符串
输出参数:
返 回 值: int
**********************************************************/
int CFtpClient::GetPort(string pasvStr)
{
int index = pasvStr.rfind('(');
string temp; // 取出"()"中的部份
temp = pasvStr.substr(index+1, pasvStr.length()-index-2);
int i = temp.rfind(',');
string sPort2 = temp.substr(i + 1,temp.length()-i-1); // 取出最后一个","后面的数字
temp = temp.substr(0, i);
i = temp.rfind(',');
string sPort1=temp.substr(i + 1, temp.length()-i-1); // 取出倒数第二个","后面的数字
int port1 = atoi(sPort1.c_str()); // 将分别分离出来的字符转换成数字
int port2 = atoi(sPort2.c_str());
//计算得出临时端口号并返回
return port1*256 + port2;
} | [
"eme915@343f5ee6-a13e-11de-ba2c-3b65426ee844"
] | [
[
[
1,
323
]
]
] |
b1496872bf6c6e3929d11bcab59db67c0d0b7e2a | 8a074a6cd0613f86f215642def7c3b578b2afb71 | /B+ Tree/include/BTreeFile.h | 492f952b6395a228ac5e6ebf3506b7f5248bb4cc | [] | no_license | tdw44/CS-4321-B--Tree | 0a79b8387791bd8cf7681d496e7389667ea2bd1f | d8f766bf666274e7ce518fb124399ecc644cb419 | refs/heads/master | 2020-04-14T19:27:27.763005 | 2011-10-25T17:05:58 | 2011-10-25T17:05:58 | 2,644,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | h | #ifndef _B_TREE_FILE_H_
#define _B_TREE_FILE_H_
#include "BTreeheaderPage.h"
#include "BTreeFileScan.h"
#include "BTreeTest.h"
#include "BTreeInclude.h"
class BTreeFile {
public:
friend class BTreeDriver;
BTreeFile(Status& status, const char *filename);
Status DestroyFile();
~BTreeFile();
Status Insert(const char *key, const RecordID rid);
BTreeFileScan* OpenScan(const char* lowKey, const char* highKey);
Status PrintTree (PageID pageID, bool printContents);
Status PrintWhole (bool printContents = false);
private:
BTreeHeaderPage* header;
//Please don't delete this method. It's used for testing,
// and may be useful for you.
PageID GetLeftLeaf();
};
#endif | [
"[email protected]"
] | [
[
[
1,
43
]
]
] |
e1a043a984fe553fccce53bec506b9e24650f577 | 2fdbf2ba994ba3ed64f0e2dc75cd2dfce4936583 | /spectre/dom/domnode.h | 4afcbfb1579871fa9df8eeae770ee624def3e619 | [] | no_license | TERRANZ/terragraph | 36219a4e512e15a925769512a6b60637d39830bf | ea8c36070f532ad0a4af08e46b19f4ee1b85f279 | refs/heads/master | 2020-05-25T10:31:26.994233 | 2011-01-29T21:23:04 | 2011-01-29T21:23:04 | 1,047,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | h | #ifndef DOMNODE_H
#define DOMNODE_H
#include <QDomNode>
class DomDocument;
class DomElement;
class DomNode
{
public:
DomNode();
private:
explicit DomNode(const QDomNode &qDomNode);
public:
bool isNull() const;
DomNode parentNode() const;
DomDocument ownerDocument() const;
void clear();
DomNode clone() const;
DomNode appendChild(const DomNode &newChild);
DomNode insertAfter(const DomNode &newChild, const DomNode &refChild);
DomNode insertBefore(const DomNode &newChild, const DomNode &refChild);
DomNode replaceChild(const DomNode &newChild, const DomNode &oldChild);
DomNode removeChild(const DomNode &oldChild);
DomDocument toDocument() const;
DomElement toElement() const;
protected:
QDomNode m_QDomNode;
friend class DomElement;
friend class DomDocument;
};
#endif // DOMNODE_H
| [
"[email protected]"
] | [
[
[
1,
41
]
]
] |
ae4d9a17b7e9159b4fe253954a8bdd4134ea99a8 | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXSizeDlgBar.h | ec2903e21b857ce3cd408d1dd2cc15b7a90184b8 | [] | 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 | WINDOWS-1252 | C++ | false | false | 4,909 | h | // ===================================================================================
// Class Specification : COXSizeDialogBar
// ===================================================================================
// Header file : OXSizeDialogBar.h
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
// Some portions Copyright (C)1994-5 Micro Focus Inc, 2465 East Bayshore Rd, Palo Alto, CA 94303.
// //////////////////////////////////////////////////////////////////////////
// Properties:
// NO Abstract class (does not have any objects)
// YES Derived from COXSizeControlBar
// YES Is a Cwnd.
// YES Two stage creation (constructor & Create())
// YES Has a message map
// YES Needs a resource (template)
// NO Persistent objects (saveable on disk)
// NO Uses exceptions
// //////////////////////////////////////////////////////////////////////////
// Desciption :
//
// This class implements a sizeable dialog bar, that should be entirely compatible with
// CDialogBar. If you specify the SZBARF_DLGAUTOSIZE on construction, the controls on the
// dialog bar will be moved and sized to fit within the current size of the dialog bar.
// This provides a very simple, yet effective form of geometry management. If you don not
// specify this style, then there is no geometry management facilities, so the controls
// within the dialog bar remain fixed, and will simply be clipped if the bar is resized
// too small. You may or course, override OnSizedOrDocked to move the controls around.
//
// This control should be 100% compatible with CDialogBar. Please see the MFC documentation
// on CDialogBar for details.
// Remark:
//
// Prerequisites (necessary conditions):
// ***
/////////////////////////////////////////////////////////////////////////////
#ifndef __SIZEDLGBAR_H__
#define __SIZEDLGBAR_H__
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "OXDllExt.h"
#include "OXSizeCtrlBar.h"
typedef void* GADGETRESIZEHANDLE;
GADGETRESIZEHANDLE CreateGadgetResizeHandle(CWnd* pWnd);
void DestroyGadgetResizeHandle(GADGETRESIZEHANDLE Handle);
void ResizeGadgetsOnWindow(GADGETRESIZEHANDLE Handle, int cx, int cy);
class OX_CLASS_DECL COXSizeDialogBar : public COXSizeControlBar
{
DECLARE_DYNCREATE(COXSizeDialogBar)
// Data members -------------------------------------------------------------
public:
protected:
CSize m_sizeDefault;
GADGETRESIZEHANDLE m_GadgetResizeHandle;
_AFX_OCC_DIALOG_INFO* m_pOccDialogInfo;
LPCTSTR m_lpszTemplateName;
private :
// Member functions ---------------------------------------------------------
public:
COXSizeDialogBar(int nStyle = SZBARF_STDMOUSECLICKS);
// --- In : nStyle : See COXSizeControlBar::COXSizeDialogBar for details
// --- Out :
// --- Returns :
// --- Effect : Constructor of object
// It will initialize the internal state
BOOL Create(CWnd* pParentWnd, LPCTSTR lpszTemplateName, UINT nStyle, UINT nID);
// --- In :
// --- Out :
// --- Returns :
// --- Effect : See CDialogBar::Create for details
BOOL Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID)
{ return Create(pParentWnd, MAKEINTRESOURCE(nIDTemplate), nStyle, nID); };
// --- In :
// --- Out :
// --- Returns :
// --- Effect : See CDialogBar::Create for details
virtual void OnSizedOrDocked(int cx, int cy, BOOL bFloating, int flags);
// --- In :
// --- Out :
// --- Returns :
// --- Effect : See COXSizeControlBar::OnSizedOrDocked for details
virtual ~COXSizeDialogBar();
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Destructor of object
virtual BOOL OnInitDialog()
{
ASSERT((GetStyle() & WS_THICKFRAME)==NULL);
return TRUE;
}
protected:
// support for OCX's inside dialog bars
#ifndef _AFX_NO_OCC_SUPPORT
// functions necessary for OLE control containment
virtual BOOL SetOccDialogInfo(_AFX_OCC_DIALOG_INFO* pOccDialogInfo);
afx_msg LRESULT HandleInitDialog(WPARAM, LPARAM);
#endif
//{{AFX_MSG(COXSizeDialogBar)
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
//}}AFX_MSG
virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler);
DECLARE_MESSAGE_MAP()
private:
};
#endif // __SIZEDLGBAR_H__
| [
"[email protected]"
] | [
[
[
1,
146
]
]
] |
5a9d71ca3a4cfabc3c7056a038d7db76e1faecef | 11da90929ba1488c59d25c57a5fb0899396b3bb2 | /Src/FileWriter.hpp | 795c7d9b9b5b15b8783909e3ced013010fc92475 | [] | 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 | 1,360 | hpp | #ifndef __ARSLEXIS_FILE_WRITER_HPP__
#define __ARSLEXIS_FILE_WRITER_HPP__
#include <Writer.hpp>
#include <File.hpp>
class FileWriter: public Writer
{
File file_;
public:
FileWriter();
#if defined(_PALM_OS)
status_t open(const char_t* name, ulong_t openMode=fileModeReadWrite, ulong_t type=0, ulong_t creator=0, uint_t cardNo=0);
#elif defined(_WIN32)
//! @todo Transform parameter names into human-readable form.
//! @note If all the parameters except fileName will have sensible default values then it'll be possible to use the same call to open() on both platforms.
status_t open(const char_t* lpFileName, // file name
DWORD dwDesiredAccess, // access mode
DWORD dwShareMode, // share mode
LPSECURITY_ATTRIBUTES lpSecurityAttributes, // SD
DWORD dwCreationDisposition, // how to create
DWORD dwFlagsAndAttributes, // file attributes
HANDLE hTemplateFile);
#else
# error "Declare FileWriter::open() for your system."
#endif
status_t writeRaw(const void* begin, uint_t length);
status_t flush();
bool isOpen() const
{return file_.isOpen();}
~FileWriter();
};
#endif | [
"andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9",
"kjk@10a9aba9-86da-0310-ac04-a2df2cc00fd9"
] | [
[
[
1,
6
],
[
9,
9
],
[
13,
13
],
[
15,
17
],
[
20,
21
],
[
32,
34
],
[
36,
36
],
[
43,
43
],
[
45,
45
],
[
47,
48
]
],
[
[
7,
8
],
[
10,
12
],
[
14,
14
],
[
18,
19
],
[
22,
31
],
[
35,
35
],
[
37,
42
],
[
44,
44
],
[
46,
46
]
]
] |
f30c5efe15775cd73036a2b4fae11db1f9dfc798 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/ibevnts.hpp | 084bfe528868df80958ec793fd08d1c79e9ae946 | [] | no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,591 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'IBEvnts.pas' rev: 6.00
#ifndef IBEvntsHPP
#define IBEvntsHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <IBCtrls.hpp> // Pascal unit
#include <Grids.hpp> // Pascal unit
#include <StdCtrls.hpp> // Pascal unit
#include <ExtCtrls.hpp> // Pascal unit
#include <Dialogs.hpp> // Pascal unit
#include <Forms.hpp> // Pascal unit
#include <Controls.hpp> // Pascal unit
#include <Graphics.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Ibevnts
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TIBEAEventsEditor;
class PASCALIMPLEMENTATION TIBEAEventsEditor : public Forms::TForm
{
typedef Forms::TForm inherited;
__published:
Extctrls::TPanel* Panel1;
Extctrls::TPanel* Panel2;
Grids::TStringGrid* cEvents;
Stdctrls::TLabel* RequestedEvents;
Stdctrls::TButton* bOK;
Stdctrls::TButton* bCancel;
void __fastcall FormCreate(System::TObject* Sender);
public:
#pragma option push -w-inl
/* TCustomForm.Create */ inline __fastcall virtual TIBEAEventsEditor(Classes::TComponent* AOwner) : Forms::TForm(AOwner) { }
#pragma option pop
#pragma option push -w-inl
/* TCustomForm.CreateNew */ inline __fastcall virtual TIBEAEventsEditor(Classes::TComponent* AOwner, int Dummy) : Forms::TForm(AOwner, Dummy) { }
#pragma option pop
#pragma option push -w-inl
/* TCustomForm.Destroy */ inline __fastcall virtual ~TIBEAEventsEditor(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TWinControl.CreateParented */ inline __fastcall TIBEAEventsEditor(HWND ParentWindow) : Forms::TForm(ParentWindow) { }
#pragma option pop
};
//-- var, const, procedure ---------------------------------------------------
extern PACKAGE TIBEAEventsEditor* IBEAEventsEditor;
extern PACKAGE bool __fastcall EditAlerterEvents(Classes::TStrings* Events);
} /* namespace Ibevnts */
using namespace Ibevnts;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // IBEvnts
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
] | [
[
[
1,
76
]
]
] |
e292cc27f8d89f45e7d02a754cc32912d2d35584 | 41c264ec05b297caa2a6e05e4476ce0576a8d7a9 | /OpenHoldem/MainFrm.h | 85c8d042a51241f8087527f8d8ae13d7cdcf6d3a | [] | no_license | seawei/openholdem | cf19a90911903d7f4d07f956756bd7e521609af3 | ba408c835b71dc1a9d674eee32958b69090fb86c | refs/heads/master | 2020-12-25T05:40:09.628277 | 2009-01-25T01:17:10 | 2009-01-25T01:17:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,491 | h | #ifndef INC_MAINFRM_H
#define INC_MAINFRM_H
#include "MyCToolBar.h"
#include "..\CTablemap\CTablemap.h"
#include "..\CCritSec\CCritSec.h"
#define HWND_CHECK_TIMER 1
#define ENABLE_BUTTONS_TIMER 2
#define UPDATE_STATUS_BAR_TIMER 3
#define ATTACH_WINDOW_TIMER 4
class CMainFrame : public CFrameWnd
{
protected: // create from serialization only
DECLARE_DYNCREATE(CMainFrame)
DECLARE_MESSAGE_MAP()
CMainFrame();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnFileOpen();
afx_msg void OnEditFormula();
afx_msg void OnScraperOutput();
afx_msg void OnViewShootreplayframe();
afx_msg void OnEditPreferences();
afx_msg void OnFileLoadTableMap();
afx_msg void OnDllLoad();
afx_msg void OnBnClickedRedCircle();
afx_msg void OnBnClickedGreenCircle();
afx_msg void OnClickedFlags();
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnUpdateStatus(CCmdUI *pCmdUI);
afx_msg void OnAutoplayer();
afx_msg void OnMinMax();
afx_msg void OnAttachTop();
afx_msg void OnAttachBottom();
afx_msg void OnLockBlinds();
afx_msg void OnPokerproConnect();
afx_msg void OnUpdateMenuFileNew(CCmdUI* pCmdUI);
afx_msg void OnUpdateMenuFileOpen(CCmdUI* pCmdUI);
afx_msg void OnUpdateMenuFileLoadProfile(CCmdUI* pCmdUI);
afx_msg void OnUpdateFileConnect(CCmdUI *pCmdUI);
afx_msg void OnUpdateMenuDllLoad(CCmdUI* pCmdUI);
afx_msg void OnUpdateDllLoadspecificfile(CCmdUI *pCmdUI);
afx_msg void OnUpdateViewMainToolbar(CCmdUI *pCmdUI);
afx_msg void OnUpdateViewFlagsToolbar(CCmdUI *pCmdUI);
afx_msg void OnUpdateViewStatusbar(CCmdUI *pCmdUI);
afx_msg void OnUpdatePokerproConnect(CCmdUI *pCmdUI);
afx_msg void OnUpdateViewShootreplayframe(CCmdUI *pCmdUI);
afx_msg void OnFormulaViewMainToolbar();
afx_msg void OnFormulaViewFlagsToolbar();
afx_msg void OnFormulaViewStatusbar();
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg void OnDllLoadspecificfile();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg LRESULT OnSetWindowText(WPARAM, LPARAM title);
afx_msg void OnPerlLoadFormula();
afx_msg void OnUpdateMenuPerlLoadSpecificFormula(CCmdUI* pCmdUI);
afx_msg void OnPerlLoadSpecificFormula();
afx_msg void OnPerlEditMainFormula();
afx_msg void OnUpdateMenuPerlLoad(CCmdUI* pCmdUI);
afx_msg void OnPerlCheckSyntax();
afx_msg void OnPerlReloadFormula();
afx_msg void OnUpdateMenuPerlReloadFormula(CCmdUI* pCmdUI);
afx_msg void OnUpdateMenuPerlCheckSyntax(CCmdUI* pCmdUI);
afx_msg void OnUpdateMenuPerlEditMainFormula(CCmdUI* pCmdUI);
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual ~CMainFrame();
virtual BOOL DestroyWindow();
CMyToolBar m_MainToolBar;
public:
// public accessors
const HWND attached_hwnd() { return _attached_hwnd; }
const bool flags(const int i) { if (i>=0 && i<=9) return _flags[i]; else return false; }
const bool wait_cursor() { return _wait_cursor; }
public:
#define ENT CSLock lock(m_critsec);
// public mutators
void set_attached_hwnd(const HWND h) { ENT _attached_hwnd = h; }
void set_flags(const int i, const bool b) { ENT if (i>=0 && i<=9) _flags[i] = b; }
void set_wait_cursor(const bool b) { ENT _wait_cursor = b; }
#undef ENT
private:
// private variables - use public accessors and public mutators to address these
HWND _attached_hwnd; // Table that we are attached to
bool _flags[10]; // Flags button status
bool _wait_cursor; // Used if we need to display a wait cursor anywhere
private:
// private functions and variables - not available via accessors or mutators
void ReadRegString(CString RegistryKey, char* RegistryValue);
void WriteRegString(CString RegistryKey, CString RegistryValue);
int CreateMainToolbar(void);
int CreateFlagsToolbar(void);
void AlignToolbars(void);
int CreateStatusBar(void);
CStatusBar _status_bar;
CMyToolBar _tool_bar;
CString _status_plcards, _status_comcards, _status_pokerhand, _status_prwin, _status_nopp;
CString _status_nit, _status_action, _status_handrank;
RECT _table_view_size;
bool _autoplay_pressed;
RECT _prev_att_rect, _prev_wrect;
CCritSec m_critsec;
};
// used by EnumProcTopLevelWindowList function
extern CArray <STableList, STableList> g_tlist;
BOOL CALLBACK EnumProcTopLevelWindowList(HWND hwnd, LPARAM lparam);
bool check_window_match(SWholeMap *map, HWND h, RECT r, CString title);
#endif /* INC_MAINFRM_H */ | [
"[email protected]"
] | [
[
[
1,
121
]
]
] |
58b8e5c6a1352122d6ab2da6b70627fcf22f8aef | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/06112002/Include/arch/Win32/DirectX/DI8InputDeviceDB.h | e00108a53572e2ffc3e14ec2f89012fa1e50f9e0 | [] | 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 | 843 | h | #ifndef _DI8INPUTDEVICEDB_H_
#define _DI8INPUTDEVICEDB_H_
#include <Input/InputDeviceDB.h>
#include <PlatformData.h>
#include <dinput.h>
#include <Win32/DirectX/DI8Joystick.h>
#include <Win32/DirectX/DI8Mouse.h>
#include <Win32/DirectX/DI8Keyboard.h>
/** @ingroup DI8_Input_Group
* @brief Derived InputDeviceDB class for the DirectInput8 Platform
*/
class DI8InputDeviceDB: public InputDeviceDB{
protected:
/** @var Win32PlatformData *m_platform
* @brief A pointer to Fusions platform information
*/
Win32PlatformData *m_platform;
public:
DI8InputDeviceDB ();
virtual ~DI8InputDeviceDB ();
virtual bool CreateDirectInput (void);
virtual IInputDevice * AddDevice (IInputDevice::DeviceType type);
};
extern IDirectInput8 *di8;
#endif // #ifndef _DI8INPUTDEVICEDB_H_
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] | [
[
[
1,
30
]
]
] |
d3d2e9737b2427a754a1cdf3b3d1aee76c9d3b78 | 4aedb4f2fba771b4a2f1b6ba85001fff23f16d09 | /brain3_3/brain3_3.h | caa691dd2d856de3d8614e5d6c393c286b03eedd | [] | no_license | orfest/codingmonkeys-icfpc | 9eacf6b51f03ed271505235e65e53a44ae4addd0 | 8ee42d89261c62ecaddf853edd4e5bb9b097b10b | refs/heads/master | 2020-12-24T16:50:44.419429 | 2009-06-29T17:52:44 | 2009-06-29T17:52:44 | 32,205,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 531 | h | #ifndef BRAIN3_3_H
#define BRAIN3_3_H
#include "brain.h"
#include "common.h"
#include "vector.h"
class VM;
class B3_3 : public Brain{
public:
B3_3(int scenarioNumber, VM* vm);
virtual PortMapping _step(const PortMapping& output);
virtual std::vector<pointF> getShipsPositions(const PortMapping& output) const;
virtual int getShipsNumber() const;
private:
PortMapping prevResult;
PortMapping prevInput;
int step;
void getOrbits(const PortMapping & sensors);
};
#endif //BRAIN3_H
| [
"gorodilovm@6cd8edf8-6250-11de-81d0-cf1ed2c911a4",
"vizovitin@6cd8edf8-6250-11de-81d0-cf1ed2c911a4"
] | [
[
[
1,
21
],
[
24,
26
]
],
[
[
22,
23
]
]
] |
e23cda41112939a7adadac28bf38e32609ddc9c9 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/engine/rb_logic/jsetvar.cpp | 97d9b19858f11242fb8be45dddb580bfbb8de337 | [] | no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 1,866 | cpp | //****************************************************************************/
// File: JSetVar.cpp
// Desc:
//****************************************************************************/
#include "stdafx.h"
#include "JAnimation.h"
#include "JVar.h"
#include "JSetVar.h"
//****************************************************************************/
/* JSetVar implementation
//****************************************************************************/
decl_class(JSetVar);
JSetVar::JSetVar()
{
m_pVar = NULL;
m_Operation = SetOp_Set;
} // JSetVar::JSetVar
void JSetVar::OnPlay()
{
if (!m_pVar)
{
Init();
}
if (m_pVar)
{
float fValS = 0.0f;
float fValD = 0.0f;
if (!m_pVar->GetFloatValue( fValD ) || !cast( fValS, m_Value ))
{
m_pVar->SetValue( m_Value.c_str() );
}
else
{
switch (m_Operation)
{
case SetOp_Set:
fValD = fValS;
break;
case SetOp_Add:
fValD += fValS;
break;
case SetOp_Subtract:
fValD -= fValS;
break;
case SetOp_Multiply:
fValD *= fValS;
break;
case SetOp_SetIfGreater:
if (fValD > fValS) fValD = fValS;
break;
case SetOp_SetIfLess:
if (fValD < fValS) fValD = fValS;
break;
}
static JString sVal;
cast( sVal, fValD );
m_pVar->SetValue( sVal.c_str() );
}
}
} // JSetVar::OnPlay
void JSetVar::Init()
{
m_pVar = g_pObjectServer->FindObject<JVar>( m_Var.c_str(), this );
} // JSetVar::Init
| [
"[email protected]"
] | [
[
[
1,
72
]
]
] |
2004c7b27da6274bb9eef244cc4d96a251da3d56 | 50f94444677eb6363f2965bc2a29c09f8da7e20d | /Src/EmptyProject/ScreenFlash.h | 3594a512f22f3d5c7a96223977b654baec6f4abf | [] | no_license | gasbank/poolg | efd426db847150536eaa176d17dcddcf35e74e5d | e73221494c4a9fd29c3d75fb823c6fb1983d30e5 | refs/heads/master | 2020-04-10T11:56:52.033568 | 2010-11-04T19:31:00 | 2010-11-04T19:31:00 | 1,051,621 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 912 | h | #pragma once
class AlphaShader;
class ScreenFlash
{
public:
ScreenFlash(void);
~ScreenFlash(void);
HRESULT onCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc );
HRESULT onResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc );
void onLostDevice();
void onDestroyDevice();
HRESULT frameRender( IDirect3DDevice9* pd3dDevice );
HRESULT frameMove( double fTime, float fElapsedTime );
HRESULT handleMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
void release();
void screenFlashing( float durationSec, float r, float g, float b );
private:
AlphaShader* m_alphaShader;
LPD3DXMESH m_testPolygon;
LPD3DXMESH m_testPolygonCloned;
float m_screenFlashAlphaAngle;
float m_screenFlashDurationSec;
D3DXCOLOR m_screenFlashCV;
bool m_bStop;
};
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
9
],
[
16,
17
],
[
19,
30
]
],
[
[
10,
15
],
[
18,
18
]
]
] |
6676d59565bdabf787d7d731b36dbf708d964507 | 14bc620a0365e83444dad45611381c7f6bcd052b | /ITUEngine/Managers/SettingsManager.hpp | 5c8d0c2d1e58557c8ce8e6c7f7d19dce88c753bd | [] | no_license | jumoel/itu-gameengine | a5750bfdf391ae64407217bfc1df8b2a3db551c7 | 062dd47bc1be0f39a0add8615e81361bcaa2bd4c | refs/heads/master | 2020-05-03T20:39:31.307460 | 2011-12-19T10:54:10 | 2011-12-19T10:54:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | hpp | #ifndef ITUENGINE_SETTINGS_MANAGER_H
#define ITUENGINE_SETTINGS_MANAGER_H
#include <Templates/TSingleton.hpp>
#include <ThirdParty/pugixml/pugixml.hpp>
#include <string>
class SettingsManager
{
public:
SettingsManager() {}
~SettingsManager() {}
void StartUp();
void ShutDown();
void SaveXML();
void SetOption(std::string identifier, std::string value);
void SetOptionToDefault(std::string identifier);
void SetAllOptionsToDefaults();
std::string GetOption(std::string identifier);
std::string GetOptionDefault(std::string identifier);
private:
pugi::xml_document doc;
};
#endif | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
28
]
],
[
[
29,
29
]
]
] |
b4458f6fdad25e07bf6f7e9f91e746fd76d52e6c | 7c93f9e101f6bba916bc1a967eb8e787afe9be92 | /7z920/CPP/7zip/UI/Common/LoadCodecs.cpp | 2b98b844580c301a04b6a932620fa292a837b431 | [] | no_license | ditupao/vx7zip | 95759f909368c14f5b8f9a3cbee18a54dc3eae78 | 13fa94305e8d3491f9d920351e5d1534957a1c06 | refs/heads/master | 2016-08-11T10:55:47.619762 | 2011-06-05T09:50:51 | 2011-06-05T09:50:51 | 47,533,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,616 | cpp | // LoadCodecs.cpp
#include "StdAfx.h"
#include "LoadCodecs.h"
#include "../../../Common/MyCom.h"
#ifdef NEW_FOLDER_INTERFACE
#include "../../../Common/StringToInt.h"
#endif
#include "../../../Windows/PropVariant.h"
#include "../../ICoder.h"
#include "../../Common/RegisterArc.h"
#ifdef EXTERNAL_CODECS
#include "../../../Windows/FileFind.h"
#include "../../../Windows/DLL.h"
#ifdef NEW_FOLDER_INTERFACE
#include "../../../Windows/ResourceString.h"
static const UInt kIconTypesResId = 100;
#endif
#ifdef _MY_WIN32
#include "Windows/Registry.h"
#endif
using namespace NWindows;
using namespace NFile;
#ifdef _MY_WIN32
extern HINSTANCE g_hInstance;
#endif
static CSysString GetLibraryFolderPrefix()
{
#ifdef _MY_WIN32
TCHAR fullPath[MAX_PATH + 1];
::GetModuleFileName(g_hInstance, fullPath, MAX_PATH);
CSysString path = fullPath;
int pos = path.ReverseFind(TEXT(CHAR_PATH_SEPARATOR));
return path.Left(pos + 1);
#else
return CSysString(); // FIX IT
#endif
}
#define kCodecsFolderName TEXT("Codecs")
#define kFormatsFolderName TEXT("Formats")
static const TCHAR *kMainDll = TEXT("7z.dll");
#ifdef _MY_WIN32
static LPCTSTR kRegistryPath = TEXT("Software") TEXT(STRING_PATH_SEPARATOR) TEXT("7-zip");
static LPCTSTR kProgramPathValue = TEXT("Path");
static bool ReadPathFromRegistry(HKEY baseKey, CSysString &path)
{
NRegistry::CKey key;
if(key.Open(baseKey, kRegistryPath, KEY_READ) == ERROR_SUCCESS)
if (key.QueryValue(kProgramPathValue, path) == ERROR_SUCCESS)
{
NName::NormalizeDirPathPrefix(path);
return true;
}
return false;
}
#endif
CSysString GetBaseFolderPrefixFromRegistry()
{
CSysString moduleFolderPrefix = GetLibraryFolderPrefix();
#ifdef _MY_WIN32
if (!NFind::DoesFileExist(moduleFolderPrefix + kMainDll) &&
!NFind::DoesDirExist(moduleFolderPrefix + kCodecsFolderName) &&
!NFind::DoesDirExist(moduleFolderPrefix + kFormatsFolderName))
{
CSysString path;
if (ReadPathFromRegistry(HKEY_CURRENT_USER, path))
return path;
if (ReadPathFromRegistry(HKEY_LOCAL_MACHINE, path))
return path;
}
#endif
return moduleFolderPrefix;
}
typedef UInt32 (WINAPI *GetNumberOfMethodsFunc)(UInt32 *numMethods);
typedef UInt32 (WINAPI *GetNumberOfFormatsFunc)(UInt32 *numFormats);
typedef UInt32 (WINAPI *GetHandlerPropertyFunc)(PROPID propID, PROPVARIANT *value);
typedef UInt32 (WINAPI *GetHandlerPropertyFunc2)(UInt32 index, PROPID propID, PROPVARIANT *value);
typedef UInt32 (WINAPI *CreateObjectFunc)(const GUID *clsID, const GUID *iid, void **outObject);
typedef UInt32 (WINAPI *SetLargePageModeFunc)();
static HRESULT GetCoderClass(GetMethodPropertyFunc getMethodProperty, UInt32 index,
PROPID propId, CLSID &clsId, bool &isAssigned)
{
NWindows::NCOM::CPropVariant prop;
isAssigned = false;
RINOK(getMethodProperty(index, propId, &prop));
if (prop.vt == VT_BSTR)
{
isAssigned = true;
clsId = *(const GUID *)prop.bstrVal;
}
else if (prop.vt != VT_EMPTY)
return E_FAIL;
return S_OK;
}
HRESULT CCodecs::LoadCodecs()
{
CCodecLib &lib = Libs.Back();
lib.GetMethodProperty = (GetMethodPropertyFunc)lib.Lib.GetProc("GetMethodProperty");
if (lib.GetMethodProperty == NULL)
return S_OK;
UInt32 numMethods = 1;
GetNumberOfMethodsFunc getNumberOfMethodsFunc = (GetNumberOfMethodsFunc)lib.Lib.GetProc("GetNumberOfMethods");
if (getNumberOfMethodsFunc != NULL)
{
RINOK(getNumberOfMethodsFunc(&numMethods));
}
for(UInt32 i = 0; i < numMethods; i++)
{
CDllCodecInfo info;
info.LibIndex = Libs.Size() - 1;
info.CodecIndex = i;
RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kEncoder, info.Encoder, info.EncoderIsAssigned));
RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kDecoder, info.Decoder, info.DecoderIsAssigned));
Codecs.Add(info);
}
return S_OK;
}
static HRESULT ReadProp(
GetHandlerPropertyFunc getProp,
GetHandlerPropertyFunc2 getProp2,
UInt32 index, PROPID propID, NCOM::CPropVariant &prop)
{
if (getProp2)
return getProp2(index, propID, &prop);;
return getProp(propID, &prop);
}
static HRESULT ReadBoolProp(
GetHandlerPropertyFunc getProp,
GetHandlerPropertyFunc2 getProp2,
UInt32 index, PROPID propID, bool &res)
{
NCOM::CPropVariant prop;
RINOK(ReadProp(getProp, getProp2, index, propID, prop));
if (prop.vt == VT_BOOL)
res = VARIANT_BOOLToBool(prop.boolVal);
else if (prop.vt != VT_EMPTY)
return E_FAIL;
return S_OK;
}
static HRESULT ReadStringProp(
GetHandlerPropertyFunc getProp,
GetHandlerPropertyFunc2 getProp2,
UInt32 index, PROPID propID, UString &res)
{
NCOM::CPropVariant prop;
RINOK(ReadProp(getProp, getProp2, index, propID, prop));
if (prop.vt == VT_BSTR)
res = prop.bstrVal;
else if (prop.vt != VT_EMPTY)
return E_FAIL;
return S_OK;
}
#endif
#if 0
static const unsigned int kNumArcsMax = 48;
static unsigned int g_NumArcs = 0;
static const CArcInfo *g_Arcs[kNumArcsMax];
void RegisterArc(const CArcInfo *arcInfo)
{
if (g_NumArcs < kNumArcsMax)
g_Arcs[g_NumArcs++] = arcInfo;
}
#endif
//extern const unsigned int kNumArcsMax;
extern unsigned int g_NumArcs;
extern unsigned int g_DefaultArcIndex;
extern const CArcInfo *g_Arcs[48];
static void SplitString(const UString &srcString, UStringVector &destStrings)
{
destStrings.Clear();
UString s;
int len = srcString.Length();
if (len == 0)
return;
for (int i = 0; i < len; i++)
{
wchar_t c = srcString[i];
if (c == L' ')
{
if (!s.IsEmpty())
{
destStrings.Add(s);
s.Empty();
}
}
else
s += c;
}
if (!s.IsEmpty())
destStrings.Add(s);
}
void CArcInfoEx::AddExts(const wchar_t *ext, const wchar_t *addExt)
{
UStringVector exts, addExts;
if (ext != 0)
SplitString(ext, exts);
if (addExt != 0)
SplitString(addExt, addExts);
for (int i = 0; i < exts.Size(); i++)
{
CArcExtInfo extInfo;
extInfo.Ext = exts[i];
if (i < addExts.Size())
{
extInfo.AddExt = addExts[i];
if (extInfo.AddExt == L"*")
extInfo.AddExt.Empty();
}
Exts.Add(extInfo);
}
}
#ifdef EXTERNAL_CODECS
HRESULT CCodecs::LoadFormats()
{
const NDLL::CLibrary &lib = Libs.Back().Lib;
GetHandlerPropertyFunc getProp = 0;
GetHandlerPropertyFunc2 getProp2 = (GetHandlerPropertyFunc2)lib.GetProc("GetHandlerProperty2");
if (getProp2 == NULL)
{
getProp = (GetHandlerPropertyFunc)lib.GetProc("GetHandlerProperty");
if (getProp == NULL)
return S_OK;
}
UInt32 numFormats = 1;
GetNumberOfFormatsFunc getNumberOfFormats = (GetNumberOfFormatsFunc)lib.GetProc("GetNumberOfFormats");
if (getNumberOfFormats != NULL)
{
RINOK(getNumberOfFormats(&numFormats));
}
if (getProp2 == NULL)
numFormats = 1;
for(UInt32 i = 0; i < numFormats; i++)
{
CArcInfoEx item;
item.LibIndex = Libs.Size() - 1;
item.FormatIndex = i;
RINOK(ReadStringProp(getProp, getProp2, i, NArchive::kName, item.Name));
NCOM::CPropVariant prop;
if (ReadProp(getProp, getProp2, i, NArchive::kClassID, prop) != S_OK)
continue;
if (prop.vt != VT_BSTR)
continue;
item.ClassID = *(const GUID *)prop.bstrVal;
prop.Clear();
UString ext, addExt;
RINOK(ReadStringProp(getProp, getProp2, i, NArchive::kExtension, ext));
RINOK(ReadStringProp(getProp, getProp2, i, NArchive::kAddExtension, addExt));
item.AddExts(ext, addExt);
ReadBoolProp(getProp, getProp2, i, NArchive::kUpdate, item.UpdateEnabled);
if (item.UpdateEnabled)
ReadBoolProp(getProp, getProp2, i, NArchive::kKeepName, item.KeepName);
if (ReadProp(getProp, getProp2, i, NArchive::kStartSignature, prop) == S_OK)
if (prop.vt == VT_BSTR)
{
UInt len = ::SysStringByteLen(prop.bstrVal);
item.StartSignature.SetCapacity(len);
memmove(item.StartSignature, prop.bstrVal, len);
}
Formats.Add(item);
}
return S_OK;
}
#ifdef NEW_FOLDER_INTERFACE
void CCodecIcons::LoadIcons(HMODULE m)
{
UString iconTypes = MyLoadStringW(m, kIconTypesResId);
UStringVector pairs;
SplitString(iconTypes, pairs);
for (int i = 0; i < pairs.Size(); i++)
{
const UString &s = pairs[i];
int pos = s.Find(L':');
CIconPair iconPair;
iconPair.IconIndex = -1;
if (pos < 0)
pos = s.Length();
else
{
UString num = s.Mid(pos + 1);
if (!num.IsEmpty())
{
const wchar_t *end;
iconPair.IconIndex = (UInt32)ConvertStringToUInt64(num, &end);
if (*end != L'\0')
continue;
}
}
iconPair.Ext = s.Left(pos);
IconPairs.Add(iconPair);
}
}
bool CCodecIcons::FindIconIndex(const UString &ext, int &iconIndex) const
{
iconIndex = -1;
for (int i = 0; i < IconPairs.Size(); i++)
{
const CIconPair &pair = IconPairs[i];
if (ext.CompareNoCase(pair.Ext) == 0)
{
iconIndex = pair.IconIndex;
return true;
}
}
return false;
}
#endif
#ifdef _7ZIP_LARGE_PAGES
extern "C"
{
extern SIZE_T g_LargePageSize;
}
#endif
HRESULT CCodecs::LoadDll(const CSysString &dllPath, bool needCheckDll)
{
if (needCheckDll)
{
NDLL::CLibrary library;
if (!library.LoadEx(dllPath, LOAD_LIBRARY_AS_DATAFILE))
return S_OK;
}
Libs.Add(CCodecLib());
CCodecLib &lib = Libs.Back();
#ifdef NEW_FOLDER_INTERFACE
lib.Path = dllPath;
#endif
bool used = false;
HRESULT res = S_OK;
if (lib.Lib.Load(dllPath))
{
#ifdef NEW_FOLDER_INTERFACE
lib.LoadIcons();
#endif
#ifdef _7ZIP_LARGE_PAGES
if (g_LargePageSize != 0)
{
SetLargePageModeFunc setLargePageMode = (SetLargePageModeFunc)lib.Lib.GetProc("SetLargePageMode");
if (setLargePageMode != 0)
setLargePageMode();
}
#endif
lib.CreateObject = (CreateObjectFunc)lib.Lib.GetProc("CreateObject");
if (lib.CreateObject != 0)
{
int startSize = Codecs.Size();
res = LoadCodecs();
used = (Codecs.Size() != startSize);
if (res == S_OK)
{
startSize = Formats.Size();
res = LoadFormats();
used = used || (Formats.Size() != startSize);
}
}
}
if (!used)
Libs.DeleteBack();
return res;
}
HRESULT CCodecs::LoadDllsFromFolder(const CSysString &folderPrefix)
{
NFile::NFind::CEnumerator enumerator(folderPrefix + CSysString(TEXT("*")));
NFile::NFind::CFileInfo fi;
while (enumerator.Next(fi))
{
if (fi.IsDir())
continue;
RINOK(LoadDll(folderPrefix + fi.Name, true));
}
return S_OK;
}
#endif
#ifndef _SFX
static inline void SetBuffer(CByteBuffer &bb, const Byte *data, int size)
{
bb.SetCapacity(size);
memmove((Byte *)bb, data, size);
}
#endif
HRESULT CCodecs::Load()
{
#ifdef NEW_FOLDER_INTERFACE
InternalIcons.LoadIcons(g_hInstance);
#endif
Formats.Clear();
#ifdef EXTERNAL_CODECS
Codecs.Clear();
#endif
for (UInt32 i = 0; i < g_NumArcs; i++)
{
const CArcInfo &arc = *g_Arcs[i];
CArcInfoEx item;
item.Name = arc.Name;
item.CreateInArchive = arc.CreateInArchive;
item.CreateOutArchive = arc.CreateOutArchive;
item.AddExts(arc.Ext, arc.AddExt);
item.UpdateEnabled = (arc.CreateOutArchive != 0);
item.KeepName = arc.KeepName;
#ifndef _SFX
SetBuffer(item.StartSignature, arc.Signature, arc.SignatureSize);
#endif
Formats.Add(item);
}
#ifdef EXTERNAL_CODECS
const CSysString baseFolder = GetBaseFolderPrefixFromRegistry();
RINOK(LoadDll(baseFolder + kMainDll, false));
RINOK(LoadDllsFromFolder(baseFolder + kCodecsFolderName TEXT(STRING_PATH_SEPARATOR)));
RINOK(LoadDllsFromFolder(baseFolder + kFormatsFolderName TEXT(STRING_PATH_SEPARATOR)));
#endif
return S_OK;
}
#ifndef _SFX
int CCodecs::FindFormatForArchiveName(const UString &arcPath) const
{
int slashPos1 = arcPath.ReverseFind(WCHAR_PATH_SEPARATOR);
int slashPos2 = arcPath.ReverseFind(L'.');
int dotPos = arcPath.ReverseFind(L'.');
if (dotPos < 0 || dotPos < slashPos1 || dotPos < slashPos2)
return -1;
UString ext = arcPath.Mid(dotPos + 1);
for (int i = 0; i < Formats.Size(); i++)
{
const CArcInfoEx &arc = Formats[i];
if (!arc.UpdateEnabled)
continue;
if (arc.FindExtension(ext) >= 0)
return i;
}
return -1;
}
int CCodecs::FindFormatForArchiveName2(const UString &arcPath) const
{
int slashPos1 = arcPath.ReverseFind(WCHAR_PATH_SEPARATOR);
int slashPos2 = arcPath.ReverseFind(L'.');
int dotPos = arcPath.ReverseFind(L'.');
if (dotPos < 0 || dotPos < slashPos1 || dotPos < slashPos2)
return -1;
UString ext = arcPath.Mid(dotPos + 1);
for (int i = 0; i < Formats.Size(); i++)
{
const CArcInfoEx &arc = Formats[i];
if (arc.FindExtension(ext) >= 0)
return i;
}
return -1;
}
int CCodecs::FindFormatForExtension(const UString &ext) const
{
if (ext.IsEmpty())
return -1;
for (int i = 0; i < Formats.Size(); i++)
if (Formats[i].FindExtension(ext) >= 0)
return i;
return -1;
}
int CCodecs::FindFormatForArchiveType(const UString &arcType) const
{
for (int i = 0; i < Formats.Size(); i++)
if (Formats[i].Name.CompareNoCase(arcType) == 0)
return i;
return -1;
}
bool CCodecs::FindFormatForArchiveType(const UString &arcType, CIntVector &formatIndices) const
{
formatIndices.Clear();
for (int pos = 0; pos < arcType.Length();)
{
int pos2 = arcType.Find('.', pos);
if (pos2 < 0)
pos2 = arcType.Length();
const UString name = arcType.Mid(pos, pos2 - pos);
int index = FindFormatForArchiveType(name);
if (index < 0 && name != L"*")
{
formatIndices.Clear();
return false;
}
formatIndices.Add(index);
pos = pos2 + 1;
}
return true;
}
#endif
#ifdef EXTERNAL_CODECS
#ifdef EXPORT_CODECS
extern unsigned int g_NumCodecs;
STDAPI CreateCoder2(bool encode, UInt32 index, const GUID *iid, void **outObject);
STDAPI GetMethodProperty(UInt32 codecIndex, PROPID propID, PROPVARIANT *value);
// STDAPI GetNumberOfMethods(UInt32 *numCodecs);
#endif
STDMETHODIMP CCodecs::GetNumberOfMethods(UInt32 *numMethods)
{
*numMethods =
#ifdef EXPORT_CODECS
g_NumCodecs +
#endif
Codecs.Size();
return S_OK;
}
STDMETHODIMP CCodecs::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
#ifdef EXPORT_CODECS
if (index < g_NumCodecs)
return GetMethodProperty(index, propID, value);
#endif
const CDllCodecInfo &ci = Codecs[index
#ifdef EXPORT_CODECS
- g_NumCodecs
#endif
];
if (propID == NMethodPropID::kDecoderIsAssigned)
{
NWindows::NCOM::CPropVariant propVariant;
propVariant = ci.DecoderIsAssigned;
propVariant.Detach(value);
return S_OK;
}
if (propID == NMethodPropID::kEncoderIsAssigned)
{
NWindows::NCOM::CPropVariant propVariant;
propVariant = ci.EncoderIsAssigned;
propVariant.Detach(value);
return S_OK;
}
return Libs[ci.LibIndex].GetMethodProperty(ci.CodecIndex, propID, value);
}
STDMETHODIMP CCodecs::CreateDecoder(UInt32 index, const GUID *iid, void **coder)
{
#ifdef EXPORT_CODECS
if (index < g_NumCodecs)
return CreateCoder2(false, index, iid, coder);
#endif
const CDllCodecInfo &ci = Codecs[index
#ifdef EXPORT_CODECS
- g_NumCodecs
#endif
];
if (ci.DecoderIsAssigned)
return Libs[ci.LibIndex].CreateObject(&ci.Decoder, iid, (void **)coder);
return S_OK;
}
STDMETHODIMP CCodecs::CreateEncoder(UInt32 index, const GUID *iid, void **coder)
{
#ifdef EXPORT_CODECS
if (index < g_NumCodecs)
return CreateCoder2(true, index, iid, coder);
#endif
const CDllCodecInfo &ci = Codecs[index
#ifdef EXPORT_CODECS
- g_NumCodecs
#endif
];
if (ci.EncoderIsAssigned)
return Libs[ci.LibIndex].CreateObject(&ci.Encoder, iid, (void **)coder);
return S_OK;
}
HRESULT CCodecs::CreateCoder(const UString &name, bool encode, CMyComPtr<ICompressCoder> &coder) const
{
for (int i = 0; i < Codecs.Size(); i++)
{
const CDllCodecInfo &codec = Codecs[i];
if (encode && !codec.EncoderIsAssigned || !encode && !codec.DecoderIsAssigned)
continue;
const CCodecLib &lib = Libs[codec.LibIndex];
UString res;
NWindows::NCOM::CPropVariant prop;
RINOK(lib.GetMethodProperty(codec.CodecIndex, NMethodPropID::kName, &prop));
if (prop.vt == VT_BSTR)
res = prop.bstrVal;
else if (prop.vt != VT_EMPTY)
continue;
if (name.CompareNoCase(res) == 0)
return lib.CreateObject(encode ? &codec.Encoder : &codec.Decoder, &IID_ICompressCoder, (void **)&coder);
}
return CLASS_E_CLASSNOTAVAILABLE;
}
int CCodecs::GetCodecLibIndex(UInt32 index)
{
#ifdef EXPORT_CODECS
if (index < g_NumCodecs)
return -1;
#endif
#ifdef EXTERNAL_CODECS
const CDllCodecInfo &ci = Codecs[index
#ifdef EXPORT_CODECS
- g_NumCodecs
#endif
];
return ci.LibIndex;
#else
return -1;
#endif
}
bool CCodecs::GetCodecEncoderIsAssigned(UInt32 index)
{
#ifdef EXPORT_CODECS
if (index < g_NumCodecs)
{
NWindows::NCOM::CPropVariant prop;
if (GetProperty(index, NMethodPropID::kEncoder, &prop) == S_OK)
if (prop.vt != VT_EMPTY)
return true;
return false;
}
#endif
#ifdef EXTERNAL_CODECS
const CDllCodecInfo &ci = Codecs[index
#ifdef EXPORT_CODECS
- g_NumCodecs
#endif
];
return ci.EncoderIsAssigned;
#else
return false;
#endif
}
HRESULT CCodecs::GetCodecId(UInt32 index, UInt64 &id)
{
UString s;
NWindows::NCOM::CPropVariant prop;
RINOK(GetProperty(index, NMethodPropID::kID, &prop));
if (prop.vt != VT_UI8)
return E_INVALIDARG;
id = prop.uhVal.QuadPart;
return S_OK;
}
UString CCodecs::GetCodecName(UInt32 index)
{
UString s;
NWindows::NCOM::CPropVariant prop;
if (GetProperty(index, NMethodPropID::kName, &prop) == S_OK)
if (prop.vt == VT_BSTR)
s = prop.bstrVal;
return s;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
705
]
]
] |
36a2186812c2399579036733b96027a9a553d568 | 1bb21e6d6a47a9ff05b47066c9da20bc999ea8ab | /taquin Astar/Taquin Astar/SolutionGenerator.hpp | 231e8a37a0d081372f0d2327c4ac9124911e912d | [] | no_license | SouhaibDZ/taquin42 | 82766e89a431f47a5a0bddfe79ef4211983bf4bc | 8dae0b8ff2888405e3bd1d3968ce85da78d97487 | refs/heads/master | 2021-01-22T04:36:40.950015 | 2010-12-17T15:02:29 | 2010-12-17T15:02:29 | 40,320,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | hpp | #ifndef _SOLUTIONGENERATOR_HPP_
#define _SOLUTIONGENERATOR_HPP_
class SolutionGenerator
{
public:
SolutionGenerator();
~SolutionGenerator();
private:
SolutionGenerator& operator=(SolutionGenerator const&);
SolutionGenerator(SolutionGenerator const&);
private:
void FillTop();
void FillRight();
void FillBottom();
void FillLeft();
public:
short unsigned int ** GenerateSolution(unsigned int Scale = 100);
private:
int X_min, X_max, X_cur;
int Y_min, Y_max, Y_cur;
int Num;
int Limit;
short unsigned int **Witness;
unsigned int PuzzleScale;
};
#endif /* _SOLUTIONGENERATOR_HPP_ */
| [
"sikilaxx01@b4d6ab20-219d-e4c1-b8d5-e97ec591408c",
"desde42@b4d6ab20-219d-e4c1-b8d5-e97ec591408c"
] | [
[
[
1,
26
],
[
29,
33
]
],
[
[
27,
28
]
]
] |
782cc6740efa9f72ab21ea94a8b46219af226963 | 847cccd728e768dc801d541a2d1169ef562311cd | /externalLibs/ois/src/win32/Win32Mouse.cpp | ab8f9532713adeb7e5192cdbbe37d8e2881f0466 | [] | no_license | aadarshasubedi/Ocerus | 1bea105de9c78b741f3de445601f7dee07987b96 | 4920b99a89f52f991125c9ecfa7353925ea9603c | refs/heads/master | 2021-01-17T17:50:00.472657 | 2011-03-25T13:26:12 | 2011-03-25T13:26:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,033 | cpp | /*
The zlib/libpng License
Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com)
This software is provided 'as-is', without any express or implied warranty. In no event will
the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial
applications, and to alter it and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented; you must not claim that
you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "Win32/Win32Mouse.h"
#include "Win32/Win32InputManager.h"
#include "OISException.h"
#include "OISEvents.h"
using namespace OIS;
//--------------------------------------------------------------------------------------------------//
Win32Mouse::Win32Mouse( InputManager* creator, IDirectInput8* pDI, bool buffered, DWORD coopSettings, const bool fullscreen )
: Mouse(creator->inputSystemName(), buffered, 0, creator)
{
mMouse = 0;
mDirectInput = pDI;
coopSetting = coopSettings;
mHwnd = 0;
mInited = false; // HARDWIRE
mFullscreen = fullscreen;
static_cast<Win32InputManager*>(mCreator)->_setMouseUsed(true);
}
//--------------------------------------------------------------------------------------------------//
void Win32Mouse::_initialize()
{
DIPROPDWORD dipdw;
//Clear old state
mState.clear();
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = MOUSE_DX_BUFFERSIZE;
if( FAILED(mDirectInput->CreateDevice(GUID_SysMouse, &mMouse, NULL)) )
OIS_EXCEPT( E_General, "Win32Mouse::Win32Mouse >> Failed to create device" );
if( FAILED(mMouse->SetDataFormat(&c_dfDIMouse2)) )
OIS_EXCEPT( E_General, "Win32Mouse::Win32Mouse >> Failed to set format" );
mHwnd = ((Win32InputManager*)mCreator)->getWindowHandle();
if( FAILED(mMouse->SetCooperativeLevel(mHwnd, coopSetting)) )
OIS_EXCEPT( E_General, "Win32Mouse::Win32Mouse >> Failed to set coop level" );
if( FAILED(mMouse->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph )) )
OIS_EXCEPT( E_General, "Win32Mouse::Win32Mouse >> Failed to set property" );
HRESULT hr = mMouse->Acquire();
if (FAILED(hr) && hr != DIERR_OTHERAPPHASPRIO)
OIS_EXCEPT( E_General, "Win32Mouse::Win32Mouse >> Failed to aquire mouse!" );
}
//--------------------------------------------------------------------------------------------------//
Win32Mouse::~Win32Mouse()
{
if (mMouse)
{
mMouse->Unacquire();
mMouse->Release();
mMouse = 0;
}
static_cast<Win32InputManager*>(mCreator)->_setMouseUsed(false);
}
//--------------------------------------------------------------------------------------------------//
void Win32Mouse::capture()
{
//Clear old relative values
mState.X.rel = mState.Y.rel = mState.Z.rel = 0;
DIDEVICEOBJECTDATA diBuff[MOUSE_DX_BUFFERSIZE];
DWORD entries = MOUSE_DX_BUFFERSIZE;
HRESULT hr = mMouse->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), diBuff, &entries, 0 );
if( hr != DI_OK )
{
hr = mMouse->Acquire();
while( hr == DIERR_INPUTLOST )
hr = mMouse->Acquire();
hr = mMouse->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), diBuff, &entries, 0 );
//Perhaps the user just tabbed away, and coop settings
//are nonexclusive..so just ignore
if( FAILED(hr) )
return;
}
bool axesMoved = false;
//Accumulate all axis movements for one axesMove message..
//Buttons are fired off as they are found
for(unsigned int i = 0; i < entries; ++i )
{
switch( diBuff[i].dwOfs )
{
case DIMOFS_BUTTON0:
if(!_doMouseClick(0, diBuff[i])) return;
break;
case DIMOFS_BUTTON1:
if(!_doMouseClick(1, diBuff[i])) return;
break;
case DIMOFS_BUTTON2:
if(!_doMouseClick(2, diBuff[i])) return;
break;
case DIMOFS_BUTTON3:
if(!_doMouseClick(3, diBuff[i])) return;
break;
case DIMOFS_BUTTON4:
if(!_doMouseClick(4, diBuff[i])) return;
break;
case DIMOFS_BUTTON5:
if(!_doMouseClick(5, diBuff[i])) return;
break;
case DIMOFS_BUTTON6:
if(!_doMouseClick(6, diBuff[i])) return;
break;
case DIMOFS_BUTTON7:
if(!_doMouseClick(7, diBuff[i])) return;
break;
case DIMOFS_X:
mState.X.rel += diBuff[i].dwData;
axesMoved = true;
break;
case DIMOFS_Y:
mState.Y.rel += diBuff[i].dwData;
axesMoved = true;
break;
case DIMOFS_Z:
mState.Z.rel += diBuff[i].dwData;
axesMoved = true;
break;
default: break;
} //end switch
}//end for
if( axesMoved || !mInited ) // HARDWIRE
{
if( (coopSetting & DISCL_NONEXCLUSIVE)
&& (!mInited || !mFullscreen)) // MUHE
{
//DirectInput provides us with meaningless values, so correct that
POINT point;
GetCursorPos(&point);
ScreenToClient(mHwnd, &point);
mState.X.abs = point.x;
mState.Y.abs = point.y;
}
else
{
mState.X.abs += mState.X.rel;
mState.Y.abs += mState.Y.rel;
}
mState.Z.abs += mState.Z.rel;
//Clip values to window
if (mFullscreen)
{
if( mState.X.abs < 0 )
mState.X.abs = 0;
else if( mState.X.abs > mState.width )
mState.X.abs = mState.width;
if( mState.Y.abs < 0 )
mState.Y.abs = 0;
else if( mState.Y.abs > mState.height )
mState.Y.abs = mState.height;
}
//Do the move
if( mListener && mBuffered )
mListener->mouseMoved( MouseEvent( this, mState ) );
}
mInited = true; // HARDWIRE
}
//--------------------------------------------------------------------------------------------------//
bool Win32Mouse::_doMouseClick( int mouseButton, DIDEVICEOBJECTDATA& di )
{
// HARDWIRE
if (GetFocus() != ((Win32InputManager*)mCreator)->getWindowHandle())
{
// our window is out of focus, so limit the clicks
return false;
}
// ~HARDWIRE
if( di.dwData & 0x80 )
{
mState.buttons |= 1 << mouseButton; //turn the bit flag on
if( mListener && mBuffered )
return mListener->mousePressed( MouseEvent( this, mState ), (MouseButtonID)mouseButton );
}
else
{
mState.buttons &= ~(1 << mouseButton); //turn the bit flag off
if( mListener && mBuffered )
return mListener->mouseReleased( MouseEvent( this, mState ), (MouseButtonID)mouseButton );
}
return true;
}
//--------------------------------------------------------------------------------------------------//
void Win32Mouse::setBuffered(bool buffered)
{
mBuffered = buffered;
}
| [
"[email protected]"
] | [
[
[
1,
232
]
]
] |
79db24f88727c94e6d763d340f307b4bfb217368 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /CrashRpt/crashrpt/src/SimSmtp.cpp | a46da6a806b8fffc83d3e2579d6a0f5fc7d9f9bc | [
"Zlib"
] | permissive | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,465 | cpp | //////////////////////////////////////////////////////////////////////
/*
Smtp.cpp: implementation of the CSimSmtp and CSmtpMessage classes
Written by Robert Simpson ([email protected])
Created 11/1/2000
Version 1.7 -- Last Modified 06/18/2001
1.7 - Modified the code that gets the GMT offset and the code that
parses the date/time as per Noa Karsten's suggestions on
codeguru.
- Added an FD_ZERO(&set) to the last part of SendCmd(), since
I use the set twice and only zero it out once. Submitted by
Marc Allen.
- Removed the requirement that a message have a body and/or an
attachment. This allows for sending messages with only a
subject line. Submitted by Marc Allen.
1.6 - Apparently older versions of the STL do not have the clear()
method for basic_string's. I modified the code to use
erase() instead.
- Added #include <atlbase.h> to the smtp.h file, which will
allow any app to use these classes without problems.
1.5 - Guess I should have checked EncodeQuotedPrintable() as well,
since it did the same thing BreakMessage() did in adding an
extranneous CRLF to the end of any text it processed. Fixed.
1.4 - BreakMesage() added an extranneous CRLF to the end of any
text it processed, which is now fixed. Certainly not a big
deal, but it caused text attachments to not be 100% identical
to the original.
1.3 - Added a new class, CSmtpMimePart, to which the CSmtpAttachment
and CSmtpMessageBody classes inherit. This was done for
future expansion. CSmtpMimePart has a new ContentId string
value for optionally assigning a unique content ID value to
body parts and attachments. This was done to support the
multipart/related enhancement
- Support for multipart/related messages, which can be used
for sending html messages with embedded images.
- Modifed CSmtpMessage, adding a new MimeType member variable
so the user can specify a certain type of MIME format to use
when coding the message.
- Fixed a bug where multipart/alternative messages with multiple
message bodies were not properly processed when attachments
were also included in the message.
- Some small optimizations during the CSmtpMessage::Parse routine
1.2 - Vastly improved the time it takes to break a message,
which was dog slow with large attachments. My bad.
- Added another overridable, SmtpProgress() which is
called during the CSimSmtp::SendCmd() function when there
is a large quantity of data being sent over the wire.
Added CMD_BLOCK_SIZE to support the above new feature
- Added support for UNICODE
- Added the CSmtpAttachment class for better control and
expandability for attachments.
- Added alternative implementations for CSimSmtp::SendMessage
which make it easier to send simple messages via a single
function call.
- Added a constructor to CSmtpAddress for assigning default
values during initialization.
- Added a #pragma comment(lib,"wsock32.lib") to the smtp.h
file so existing projects don't have to have their linker
options modified.
1.1 - Rearranged the headers so they are written out as:
From,To,Subject,Date,MimeVersion,
followed by all remaining headers
- Modified the class to support multipart/alternative with
multiple message bodies.
Note that CSimpleMap does not sort the key values, and CSimSmtp
takes advantage of this by writing the headers out in the reverse
order of how they will be parsed before being sent to the SMTP
server. If you modify the code to use std::map or any other map
class, the headers may be alphabetized by key, which may cause
some mail clients to show the headers in the body of the message
or cause other undesirable results when viewing the message.
*/
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "SimSmtp.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction for CSmtpMessageBody
//////////////////////////////////////////////////////////////////////
CSmtpMessageBody::CSmtpMessageBody(LPCTSTR pszBody, LPCTSTR pszEncoding, LPCTSTR pszCharset, EncodingEnum encode)
{
// Set the default message encoding method
// To transfer html messages, make Encoding = _T("text/html")
if (pszEncoding) Encoding = pszEncoding;
if (pszCharset) Charset = pszCharset;
if (pszBody) Data = pszBody;
TransferEncoding = encode;
}
const CSmtpMessageBody& CSmtpMessageBody::operator=(LPCTSTR pszBody)
{
Data = pszBody;
return *this;
}
const CSmtpMessageBody& CSmtpMessageBody::operator=(const String& strBody)
{
Data = strBody;
return *this;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction for CSmtpAttachment
//////////////////////////////////////////////////////////////////////
CSmtpAttachment::CSmtpAttachment(LPCTSTR pszFilename, LPCTSTR pszAltName, BOOL bIsInline, LPCTSTR pszEncoding, LPCTSTR pszCharset, EncodingEnum encode)
{
if (pszFilename) FileName = pszFilename;
if (pszAltName) AltName = pszAltName;
if (pszEncoding) Encoding = pszEncoding;
if (pszCharset) Charset = pszCharset;
TransferEncoding = encode;
Inline = bIsInline;
}
const CSmtpAttachment& CSmtpAttachment::operator=(LPCTSTR pszFilename)
{
FileName = pszFilename;
return *this;
}
const CSmtpAttachment& CSmtpAttachment::operator=(const String& strFilename)
{
FileName = strFilename;
return *this;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction for CSmtpAddress
//////////////////////////////////////////////////////////////////////
CSmtpAddress::CSmtpAddress(LPCTSTR pszAddress, LPCTSTR pszName)
{
if (pszAddress) Address = pszAddress;
if (pszName) Name = pszName;
}
const CSmtpAddress& CSmtpAddress::operator=(LPCTSTR pszAddress)
{
Address = pszAddress;
return *this;
}
const CSmtpAddress& CSmtpAddress::operator=(const String& strAddress)
{
Address = strAddress;
return *this;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction for CSmtpMessage
//////////////////////////////////////////////////////////////////////
CSmtpMessage::CSmtpMessage()
{
TIME_ZONE_INFORMATION tzi;
DWORD dwRet;
long Offset;
// Get local time and timezone offset
GetLocalTime(&Timestamp);
GMTOffset = 0;
dwRet = GetTimeZoneInformation(&tzi);
Offset = tzi.Bias;
if (dwRet == TIME_ZONE_ID_STANDARD) Offset += tzi.StandardBias;
if (dwRet == TIME_ZONE_ID_DAYLIGHT) Offset += tzi.DaylightBias;
GMTOffset = -((Offset / 60) * 100 + (Offset % 60));
MimeType = mimeGuess;
}
// Write all the headers to the e-mail message.
// This is done just before sending it, when we're sure the user wants it to go out.
void CSmtpMessage::CommitHeaders()
{
TCHAR szTime[64];
TCHAR szDate[64];
TCHAR szOut[1024];
String strHeader;
String strValue;
int n;
// Assign a few standard headers to the message
strHeader = _T("X-Priority");
strValue = _T("3 (Normal)");
// Only add the key if it doesn't exist already in the headers map
if (Headers.FindKey(strHeader) == -1) Headers.Add(strHeader,strValue);
strHeader = _T("X-MSMail-Priority");
strValue = _T("Normal");
if (Headers.FindKey(strHeader) == -1) Headers.Add(strHeader,strValue);
strHeader = _T("X-Mailer");
//strValue = _T("ATL CSimSmtp Class Mailer by Robert Simpson ([email protected])");
strValue = _T("MaxTime Mailer");
if (Headers.FindKey(strHeader) == -1) Headers.Add(strHeader,strValue);
strHeader = _T("Importance");
strValue = _T("Normal");
if (Headers.FindKey(strHeader) == -1) Headers.Add(strHeader,strValue);
// Get the time/date stamp and GMT offset for the Date header.
GetDateFormat(MAKELCID(LANG_ENGLISH, SORT_DEFAULT),0,&Timestamp,_T("ddd, d MMM yyyy"),szDate,64);
GetTimeFormat(MAKELCID(LANG_ENGLISH, SORT_DEFAULT),0,&Timestamp,_T("H:mm:ss"),szTime,64);
// Add the date/time stamp to the message headers
wsprintf(szOut,_T("%s %s%s%4.4d"),szDate,szTime,(GMTOffset>0)?" +":" ",GMTOffset);
strHeader = _T("Date");
strValue = szOut;
Headers.Remove(strHeader);
Headers.Add(strHeader,strValue);
// Write out the subject header
strHeader = _T("Subject");
strValue = Subject;
Headers.Remove(strHeader);
Headers.Add(strHeader,strValue);
// Write out the TO header
strValue.erase();
strHeader = _T("To");
if (Recipient.Name.length())
{
wsprintf(szOut,_T("\"%s\" "),Recipient.Name.c_str());
strValue += szOut;
}
if (Recipient.Address.length())
{
wsprintf(szOut,_T("<%s>"),Recipient.Address.c_str());
strValue += szOut;
}
// Write out all the CC'd names
for (n = 0;n < CC.GetSize();n++)
{
if (strValue.length()) strValue += _T(",\r\n\t");
if (CC[n].Name.length())
{
wsprintf(szOut,_T("\"%s\" "),CC[n].Name.c_str());
strValue += szOut;
}
wsprintf(szOut,_T("<%s>"),CC[n].Address.c_str());
strValue += szOut;
}
Headers.Remove(strHeader);
Headers.Add(strHeader,strValue);
// Write out the FROM header
strValue.erase();
strHeader = _T("From");
if (Sender.Name.length())
{
wsprintf(szOut,_T("\"%s\" "),Sender.Name.c_str());
strValue += szOut;
}
wsprintf(szOut,_T("<%s>"),Sender.Address.c_str());
strValue += szOut;
Headers.Remove(strHeader);
Headers.Add(strHeader,strValue);
}
// Parse a message into a single string
void CSmtpMessage::Parse(String& strDest)
{
String strHeader;
String strValue;
String strTemp;
String strBoundary;
String strInnerBoundary;
TCHAR szOut[1024];
int n;
strDest.erase();
// Get a count of the sections to see if this will be a multipart message
n = Message.GetSize();
n += Attachments.GetSize();
// Remove this header in case the message is being reused
strHeader = _T("Content-Type");
Headers.Remove(strHeader);
// If we have more than one section, then this is a multipart MIME message
if (n > 1)
{
wsprintf(szOut,_T("CSmtpMsgPart123X456_000_%8.8X"),GetTickCount());
strBoundary = szOut;
lstrcpy(szOut,_T("multipart/"));
if (MimeType == mimeGuess)
{
if (Attachments.GetSize() == 0) MimeType = mimeAlternative;
else MimeType = mimeMixed;
}
switch(MimeType)
{
case mimeAlternative:
lstrcat(szOut,_T("alternative"));
break;
case mimeMixed:
lstrcat(szOut,_T("mixed"));
break;
case mimeRelated:
lstrcat(szOut,_T("related"));
break;
}
lstrcat(szOut,_T(";\r\n\tboundary=\""));
lstrcat(szOut,strBoundary.c_str());
lstrcat(szOut,_T("\""));
strValue = szOut;
Headers.Add(strHeader,strValue);
}
strHeader = _T("MIME-Version");
strValue = MIME_VERSION;
Headers.Remove(strHeader);
Headers.Add(strHeader,strValue);
// Remove any message ID in the header and replace it with this message ID, if it exists
strHeader = _T("Message-ID");
Headers.Remove(strHeader);
if (MessageId.length())
{
wsprintf(szOut,_T("<%s>"),MessageId.c_str());
strValue = szOut;
Headers.Add(strHeader,strValue);
}
// Finalize the message headers
CommitHeaders();
// Write out all the message headers -- done backwards on purpose!
for (n = Headers.GetSize();n > 0;n--)
{
wsprintf(szOut,_T("%s: %s\r\n"),Headers.GetKeyAt(n-1).c_str(),Headers.GetValueAt(n-1).c_str());
strDest += szOut;
}
if (strBoundary.length())
{
wsprintf(szOut,_T("\r\n%s\r\n"),MULTIPART_MESSAGE);
strDest += szOut;
}
// If we have attachments and multiple message bodies, create a new multipart section
// This is done so we can display our multipart/alternative section separate from the
// main multipart/mixed environment, and support both attachments and alternative bodies.
if (Attachments.GetSize() && Message.GetSize() > 1 && strBoundary.length())
{
wsprintf(szOut,_T("CSmtpMsgPart123X456_001_%8.8X"),GetTickCount());
strInnerBoundary = szOut;
wsprintf(szOut,_T("\r\n--%s\r\nContent-Type: multipart/alternative;\r\n\tboundary=\"%s\"\r\n"),strBoundary.c_str(),strInnerBoundary.c_str());
strDest += szOut;
}
for (n = 0;n < Message.GetSize();n++)
{
// If we're multipart, then write the boundary line
if (strBoundary.length() || strInnerBoundary.length())
{
strDest += _T("\r\n--");
// If we have an inner boundary, write that one. Otherwise write the outer one
if (strInnerBoundary.length()) strDest += strInnerBoundary;
else strDest += strBoundary;
strDest += _T("\r\n");
}
strValue.erase();
strDest += _T("Content-Type: ");
strDest += Message[n].Encoding;
// Include the character set if the message is text
if (_tcsnicmp(Message[n].Encoding.c_str(),_T("text/"),5) == 0)
{
wsprintf(szOut,_T(";\r\n\tcharset=\"%s\""),Message[n].Charset.c_str());
strDest += szOut;
}
strDest += _T("\r\n");
// Encode the message
strValue = Message[n].Data;
EncodeMessage(Message[n].TransferEncoding,strValue,strTemp);
// Write out the encoding method used and the encoded message
strDest += _T("Content-Transfer-Encoding: ");
strDest += strTemp;
// If the message body part has a content ID, write it out
if (Message[n].ContentId.length())
{
wsprintf(szOut,_T("\r\nContent-ID: <%s>"),Message[n].ContentId.c_str());
strDest += szOut;
}
strDest += _T("\r\n\r\n");
strDest += strValue;
}
// If we have multiple message bodies, write out the trailing inner end sequence
if (strInnerBoundary.length())
{
wsprintf(szOut,_T("\r\n--%s--\r\n"),strInnerBoundary.c_str());
strDest += szOut;
}
// Process any attachments
for (n = 0;n < Attachments.GetSize();n++)
{
HANDLE hFile;
LPBYTE pData;
LPTSTR pszFile;
LPTSTR pszExt;
DWORD dwSize;
DWORD dwBytes;
CRegKey cKey;
TCHAR szType[MAX_PATH];
TCHAR szFilename[MAX_PATH];
// Get the filename of the attachment
strValue = Attachments[n].FileName;
// Open the file
lstrcpy(szFilename,strValue.c_str());
hFile = CreateFile(szFilename,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
// Get the size of the file, allocate the memory and read the contents.
dwSize = GetFileSize(hFile,NULL);
pData = (LPBYTE)malloc(dwSize + 1);
ZeroMemory(pData,dwSize+1);
if (ReadFile(hFile,pData,dwSize,&dwBytes,NULL))
{
// Write out our boundary marker
if (strBoundary.length())
{
wsprintf(szOut,_T("\r\n--%s\r\n"),strBoundary.c_str());
strDest += szOut;
}
// If no alternate name is supplied, strip the path to get the base filename
if (!Attachments[n].AltName.length())
{
// Strip the path from the filename
pszFile = _tcsrchr(szFilename,'\\');
if (!pszFile) pszFile = szFilename;
else pszFile ++;
}
else pszFile = (LPTSTR)Attachments[n].AltName.c_str();
// Set the content type for the attachment.
lstrcpy(szType,_T("application/octet-stream"));
// Check the registry for a content type that overrides the above default
pszExt = _tcschr(pszFile,'.');
if (pszExt)
{
if (!cKey.Open(HKEY_CLASSES_ROOT,pszExt,KEY_READ))
{
DWORD dwSize = MAX_PATH;
cKey.QueryValue(szType,_T("Content Type"),&dwSize);
cKey.Close();
}
}
// If the attachment has a specific encoding method, use it instead
if (Attachments[n].Encoding.length())
lstrcpy(szType,Attachments[n].Encoding.c_str());
// Write out the content type and attachment types to the message
wsprintf(szOut,_T("Content-Type: %s"),szType);
strDest += szOut;
// If the content type is text, write the charset
if (_tcsnicmp(szType,_T("text/"),5) == 0)
{
wsprintf(szOut,_T(";\r\n\tcharset=\"%s\""),Attachments[n].Charset.c_str());
strDest += szOut;
}
wsprintf(szOut,_T(";\r\n\tname=\"%s\"\r\n"),pszFile);
strDest += szOut;
// Encode the attachment
EncodeMessage(Attachments[n].TransferEncoding,strValue,strTemp,pData,dwSize);
// Write out the transfer encoding method
wsprintf(szOut,_T("Content-Transfer-Encoding: %s\r\n"),strTemp.c_str());
strDest += szOut;
// Write out the attachment's disposition
strDest += _T("Content-Disposition: ");
if (Attachments[n].Inline) strDest += _T("inline");
else strDest += _T("attachment");
strDest += _T(";\r\n\tfilename=\"");
strDest += pszFile;
// If the attachment has a content ID, write it out
if (Attachments[n].ContentId.length())
{
wsprintf(szOut,_T("\r\nContent-ID: <%s>"),Attachments[n].ContentId.c_str());
strDest += szOut;
}
strDest += _T("\r\n\r\n");
// Write out the encoded attachment
strDest += strValue;
strTemp.erase();
strValue.erase();
}
// Close the file and clear the temp buffer
CloseHandle(hFile);
free(pData);
}
}
// If we are multipart, write out the trailing end sequence
if (strBoundary.length())
{
wsprintf(szOut,_T("\r\n--%s--\r\n"),strBoundary.c_str());
strDest += szOut;
}
}
// Parses text into quoted-printable lines.
// See RFC 1521 for full details on how this works.
void CSmtpMessage::EncodeQuotedPrintable(String& strDest, String& strSrc)
{
String strTemp;
String strTemp2;
LPTSTR pszTok1;
LPTSTR pszTok2;
TCHAR szSub[16];
TCHAR ch;
int n;
strDest.erase();
if (!strSrc.length()) return;
// Change = signs and non-printable characters to =XX
pszTok1 = (LPTSTR)strSrc.c_str();
pszTok2 = pszTok1;
do
{
if (*pszTok2 == '=' || *pszTok2 > 126 ||
(*pszTok2 < 32 && (*pszTok2 != '\r' && *pszTok2 != '\n' && *pszTok2 != '\t')))
{
ch = *pszTok2;
*pszTok2 = 0;
strTemp += pszTok1;
*pszTok2 = ch;
wsprintf(szSub,_T("=%2.2X"),(BYTE)*pszTok2);
strTemp += szSub;
pszTok1 = pszTok2 + 1;
}
pszTok2 ++;
} while (*pszTok2);
// Append anything left after the search
if (_tcslen(pszTok1)) strTemp += pszTok1;
pszTok1 = (LPTSTR)strTemp.c_str();
while (pszTok1)
{
pszTok2 = _tcschr(pszTok1,'\r');
if (pszTok2) *pszTok2 = 0;
while (1)
{
if (_tcslen(pszTok1) > 76)
{
n = 75; // Breaking at the 75th character
if (pszTok1[n-1] == '=') n -= 1; // If the last character is an =, don't break the line there
else if (pszTok1[n-2] == '=') n -= 2; // If we're breaking in the middle of a = sequence, back up!
// Append the first section of the line to the total string
ch = pszTok1[n];
pszTok1[n] = 0;
strDest += pszTok1;
pszTok1[n] = ch;
strDest += _T("=\r\n");
pszTok1 += n;
}
else // Line is less than or equal to 76 characters
{
n = _tcslen(pszTok1); // If we have some trailing data, process it.
if (n)
{
if (pszTok1[n-1] == ' ' || pszTok1[n-1] == '\t') // Last character is a space or tab
{
wsprintf(szSub,_T("=%2.2X"),(BYTE)pszTok1[n-1]);
// Replace the last character with an =XX sequence
pszTok1[n-1] = 0;
strTemp2 = pszTok1;
strTemp2 += szSub;
// Since the string may now be larger than 76 characters, we have to reprocess the line
pszTok1 = (LPTSTR)strTemp2.c_str();
}
else // Last character is not a space or tab
{
strDest += pszTok1;
if (pszTok2) strDest += _T("\r\n");
break; // Exit the loop which processes this line, and move to the next line
}
}
else
{
if (pszTok2) strDest += _T("\r\n");
break; // Move to the next line
}
}
}
if (pszTok2)
{
*pszTok2 = '\r';
pszTok2 ++;
if (*pszTok2 == '\n') pszTok2 ++;
}
pszTok1 = pszTok2;
}
}
// Breaks a message's lines into a maximum of 76 characters
// Does some semi-intelligent wordwrapping to ensure the text is broken properly.
// If a line contains no break characters, it is forcibly truncated at the 76th char
void CSmtpMessage::BreakMessage(String& strDest, String& strSrc, int nLength)
{
String strTemp = strSrc;
String strLine;
LPTSTR pszTok1;
LPTSTR pszTok2;
LPTSTR pszBreak;
LPTSTR pszBreaks = _T(" -;.,?!");
TCHAR ch;
BOOL bNoBreaks;
int nLen;
strDest.erase();
if (!strSrc.length()) return;
nLen = strTemp.length();
nLen += (nLen / 60) * 2;
strDest.reserve(nLen);
// Process each line one at a time
pszTok1 = (LPTSTR)strTemp.c_str();
while (pszTok1)
{
pszTok2 = _tcschr(pszTok1,'\r');
if (pszTok2) *pszTok2 = 0;
bNoBreaks = (!_tcspbrk(pszTok1,pszBreaks));
nLen = _tcslen(pszTok1);
while (nLen > nLength)
{
// Start at the 76th character, and move backwards until we hit a break character
pszBreak = &pszTok1[nLength - 1];
// If there are no break characters in the string, skip the backward search for them!
if (!bNoBreaks)
{
while (!_tcschr(pszBreaks,*pszBreak) && pszBreak > pszTok1)
pszBreak--;
}
pszBreak ++;
ch = *pszBreak;
*pszBreak = 0;
strDest += pszTok1;
strDest += _T("\r\n");
*pszBreak = ch;
nLen -= (pszBreak - pszTok1);
// Advance the search to the next segment of text after the break
pszTok1 = pszBreak;
}
strDest += pszTok1;
if (pszTok2)
{
strDest += _T("\r\n");
*pszTok2 = '\r';
pszTok2 ++;
if (*pszTok2 == '\n') pszTok2 ++;
}
pszTok1 = pszTok2;
}
}
// Makes the message into a 7bit stream
void CSmtpMessage::Make7Bit(String& strDest, String& strSrc)
{
LPTSTR pszTok;
strDest = strSrc;
pszTok = (LPTSTR)strDest.c_str();
do
{
// Replace any characters above 126 with a ? character
if (*pszTok > 126 || *pszTok < 0)
*pszTok = '?';
pszTok ++;
} while (*pszTok);
}
// Encodes a message or binary stream into a properly-formatted message
// Takes care of breaking the message into 76-byte lines of text, encoding to
// Base64, quoted-printable and etc.
void CSmtpMessage::EncodeMessage(EncodingEnum code, String& strMsg, String& strMethod, LPBYTE pByte, DWORD dwSize)
{
String strTemp;
LPTSTR pszTok1;
LPTSTR pszTok2;
LPSTR pszBuffer = NULL;
LPSTR pszTemp;
DWORD dwStart = GetTickCount();
if (!pByte)
{
pszBuffer = (LPSTR)malloc(strMsg.length() + 1);
_T2A(pszBuffer,strMsg.c_str());
pByte = (LPBYTE)pszBuffer;
dwSize = strMsg.length();
}
// Guess the encoding scheme if we have to
if (code == encodeGuess) code = GuessEncoding(pByte, dwSize);
switch(code)
{
case encodeQuotedPrintable:
strMethod = _T("quoted-printable");
pszTok1 = (LPTSTR)malloc((dwSize+1) * sizeof(TCHAR));
_A2T(pszTok1,(LPSTR)pByte);
strMsg = pszTok1;
free(pszTok1);
EncodeQuotedPrintable(strTemp, strMsg);
break;
case encodeBase64:
strMethod = _T("base64");
{
CBase64 cvt;
cvt.Encode(pByte, dwSize);
pszTemp = (LPSTR)cvt.EncodedMessage();
pszTok1 = (LPTSTR)malloc((lstrlenA(pszTemp)+1) * sizeof(TCHAR));
_A2T(pszTok1,pszTemp);
}
strMsg = pszTok1;
free(pszTok1);
BreakMessage(strTemp, strMsg);
break;
case encode7Bit:
strMethod = _T("7bit");
pszTok1 = (LPTSTR)malloc((dwSize+1) * sizeof(TCHAR));
_A2T(pszTok1,(LPSTR)pByte);
strMsg = pszTok1;
free(pszTok1);
Make7Bit(strTemp, strMsg);
strMsg = strTemp;
BreakMessage(strTemp, strMsg);
break;
case encode8Bit:
strMethod = _T("8bit");
pszTok1 = (LPTSTR)malloc((dwSize+1) * sizeof(TCHAR));
_A2T(pszTok1,(LPSTR)pByte);
strMsg = pszTok1;
free(pszTok1);
BreakMessage(strTemp, strMsg);
break;
}
if (pszBuffer) free(pszBuffer);
strMsg.erase();
// Parse the message text, replacing CRLF. sequences with CRLF.. sequences
pszTok1 = (LPTSTR)strTemp.c_str();
do
{
pszTok2 = _tcsstr(pszTok1,_T("\r\n."));
if (pszTok2)
{
*pszTok2 = 0;
strMsg += pszTok1;
*pszTok2 = '\r';
strMsg += _T("\r\n..");
pszTok1 = pszTok2 + 3;
}
} while (pszTok2);
strMsg += pszTok1;
TCHAR szOut[MAX_PATH];
wsprintf(szOut,_T("Encoding took %dms\n"),GetTickCount() - dwStart);
OutputDebugString(szOut);
}
// Makes a best-guess of the proper encoding to use for this stream of bytes
// It does this by counting the # of lines, the # of 8bit bytes and the number
// of 7bit bytes. It also records the line and the count of lines over
// 76 characters.
// If the stream is 90% or higher 7bit, it uses a text encoding method. If the stream
// is all at or under 76 characters, it uses 7bit or 8bit, depending on the content.
// If the lines are longer than 76 characters, use quoted printable.
// If the stream is under 90% 7bit characters, use base64 encoding.
EncodingEnum CSmtpMessage::GuessEncoding(LPBYTE pByte, DWORD dwLen)
{
int n7Bit = 0;
int n8Bit = 0;
int nLineStart = 0;
int nLinesOver76 = 0;
int nLines = 0;
DWORD n;
// Count the content type, byte by byte
for (n = 0;n < dwLen; n++)
{
if (pByte[n] > 126 || (pByte[n] < 32 && pByte[n] != '\t' && pByte[n] != '\r' && pByte[n] != '\n'))
n8Bit ++;
else n7Bit ++;
// New line? If so, record the line size
if (pByte[n] == '\r')
{
nLines ++;
nLineStart = (n - nLineStart) - 1;
if (nLineStart > 76) nLinesOver76 ++;
nLineStart = n + 1;
}
}
// Determine if it is mostly 7bit data
if ((n7Bit * 100) / dwLen > 89)
{
// At least 90% text, so use a text-base encoding scheme
if (!nLinesOver76)
{
if (!n8Bit) return encode7Bit;
else return encode8Bit;
}
else return encodeQuotedPrintable;
}
return encodeBase64;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction for CSimSmtp
//////////////////////////////////////////////////////////////////////
CSimSmtp::CSimSmtp()
{
LPSERVENT pEnt;
m_bExtensions = TRUE; // Use ESMTP if possible
m_dwCmdTimeout = 30; // Default to 30 second timeout
m_hSocket = INVALID_SOCKET;
// Try and get the SMTP service entry by name
pEnt = getservbyname("SMTP","tcp");
if (pEnt) m_wSmtpPort = pEnt->s_port;
else m_wSmtpPort = htons(25);
}
CSimSmtp::~CSimSmtp()
{
// Make sure any open connections are shut down
Close();
}
// Connects to a SMTP server. Returns TRUE if successfully connected, or FALSE otherwise.
BOOL CSimSmtp::Connect(LPTSTR pszServer,WORD nPort)
{
SOCKADDR_IN addr;
int nRet;
CHAR szHost[MAX_PATH];
_T2A(szHost,pszServer);
// Shut down any active connection
Close();
// Resolve the hostname
addr.sin_family = AF_INET;
if (nPort != NULL) {
addr.sin_port = htons(nPort);
}
else{
addr.sin_port = m_wSmtpPort;
}
addr.sin_addr.s_addr = inet_addr(szHost);
if (addr.sin_addr.s_addr == INADDR_NONE)
{
LPHOSTENT pHost = gethostbyname(szHost);
if (!pHost) return FALSE;
addr.sin_addr.s_addr = *(LPDWORD)pHost->h_addr;
}
// Create a socket
m_hSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (m_hSocket == INVALID_SOCKET) return FALSE;
// Connect to the host
if (connect(m_hSocket,(LPSOCKADDR)&addr,sizeof(addr)) == SOCKET_ERROR)
{
Close();
return FALSE;
}
// Get the initial response string
nRet = SendCmd(NULL);
if (nRet != 220)
{
RaiseError(nRet);
Close();
return FALSE;
}
// Send a HELLO message to the SMTP server
if (SendHello())
{
Close();
return FALSE;
}
return TRUE;
}
// Closes any active SMTP sessions and shuts down the socket.
void CSimSmtp::Close()
{
if (m_hSocket != INVALID_SOCKET)
{
// If we're connected to a server, tell them we're quitting
if (m_bConnected) SendQuitCmd();
// Shutdown and close the socket
shutdown(m_hSocket,2);
closesocket(m_hSocket);
}
m_hSocket = INVALID_SOCKET;
}
// Send a command to the SMTP server and wait for a response
int CSimSmtp::SendCmd(LPTSTR pszCmd)
{
USES_CONVERSION;
FD_SET set;
TIMEVAL tv;
int nRet = 0;
DWORD dwTick;
CHAR szResult[CMD_RESPONSE_SIZE];
LPSTR pszPos;
LPSTR pszTok;
DWORD dwPosition;
DWORD dwLen;
DWORD dwMax;
BOOL bReportProgress = FALSE;
LPSTR pszBuff;
ZeroMemory(szResult,CMD_RESPONSE_SIZE);
FD_ZERO(&set);
// If we have a command to send, then send it.
if (pszCmd)
{
pszBuff = (LPSTR)malloc(lstrlen(pszCmd)+1);
_T2A(pszBuff,pszCmd);
// Make sure the input buffer is clear before sending
nRet = 1;
while (nRet > 0)
{
FD_SET(m_hSocket,&set);
tv.tv_sec = 0;
tv.tv_usec = 0;
nRet = select(1,&set,NULL,NULL,&tv);
if (nRet == 1) nRet = recv(m_hSocket,szResult,CMD_RESPONSE_SIZE,0);
}
dwPosition = 0;
dwLen = lstrlen(pszCmd);
if (dwLen > CMD_BLOCK_SIZE) bReportProgress = TRUE;
while (dwLen != dwPosition)
{
dwMax = min(CMD_BLOCK_SIZE,dwLen - dwPosition);
nRet = send(m_hSocket,&pszBuff[dwPosition],dwMax,0);
if (nRet == SOCKET_ERROR)
{
free(pszBuff);
return nRet;
}
dwPosition += dwMax;
if (bReportProgress)
{
if (!SmtpProgress(pszBuff,dwPosition,dwLen))
{
free(pszBuff);
return -1;
}
}
}
// Wait for the CMD to finish being sent
FD_ZERO(&set);
FD_SET(m_hSocket,&set);
nRet = select(1,NULL,&set,NULL,NULL);
free(pszBuff);
}
// Prepare to receive a response
ZeroMemory(szResult,CMD_RESPONSE_SIZE);
pszPos = szResult;
// Wait for the specified timeout for a full response string
dwTick = GetTickCount();
while (GetTickCount() - dwTick < (m_dwCmdTimeout * 1000))
{
FD_SET(m_hSocket,&set);
tv.tv_sec = m_dwCmdTimeout - ((GetTickCount() - dwTick) / 1000);
tv.tv_usec = 0;
// Check the socket for readability
nRet = select(1,&set,NULL,NULL,&tv);
if (nRet == SOCKET_ERROR) break;
// If the socket has data, read it.
if (nRet == 1)
{
nRet = recv(m_hSocket,pszPos,CMD_RESPONSE_SIZE - (pszPos - szResult),0);
// Treats a graceful shutdown as an error
if (nRet == 0) nRet = SOCKET_ERROR;
if (nRet == SOCKET_ERROR) break;
// Add the data to the total response string & check for a LF
pszPos += nRet;
pszTok = strrchr(szResult,'\n');
if (pszTok)
{
// Truncate CRLF combination and exit our wait loop
pszTok --;
pszTok[0] = 0;
break;
}
}
}
// Assign the response string
m_strResult = A2CT(szResult);
// Evaluate the numeric response code
if (nRet && nRet != SOCKET_ERROR)
{
szResult[3] = 0;
nRet = atoi(szResult);
SmtpCommandResponse(pszCmd, nRet, (LPTSTR)m_strResult.c_str());
}
else nRet = -1;
return nRet;
}
// Placeholder function -- overridable
// This function is called when the SMTP server gives us an unexpected error
// The <nError> value is the SMTP server's numeric error response, and the <pszErr>
// is the descriptive error text
//
// <pszErr> may be NULL if the server failed to respond before the timeout!
// <nError> will be -1 if a catastrophic failure occurred.
//
// Return 0, or nError. The return value is currently ignored.
int CSimSmtp::SmtpError(int /*nError*/, LPTSTR pszErr)
{
#ifdef _DEBUG
if (pszErr)
{
OutputDebugString(_T("SmtpError: "));
OutputDebugString(pszErr);
OutputDebugString(_T("\n"));
}
#endif
return 0;
}
// Placeholder function -- overridable
// Currently the only warning condition that this class is designed for is
// an authentication failure. In that case, <nWarning> will be 535,
// which is the RFC error for authentication failure. If authentication
// fails, you can override this function to prompt the user for a new
// username and password. Change the <m_strUser> and <m_strPass> member
// variables and return TRUE to retry authentication.
//
// <pszWarning> may be NULL if the server did not respond in time!
//
// Return FALSE to abort authentication, or TRUE to retry.
int CSimSmtp::SmtpWarning(int /*nWarning*/, LPTSTR pszWarning)
{
#ifdef _DEBUG
if (pszWarning)
{
OutputDebugString(_T("SmtpWarning: "));
OutputDebugString(pszWarning);
OutputDebugString(_T("\n"));
}
#endif
return 0;
}
// Placeholder function -- overridable
// This is an informational callback only, and provides a means to inform
// the caller as the SMTP session progresses.
// ALWAYS check for NULL values on <pszCmd> and <pszResponse> before performing
// any actions!
// <nResponse> will be -1 if a catastrophic failure occurred, but that will
// be raised in the SmtpError() event later on during processing.
void CSimSmtp::SmtpCommandResponse(LPTSTR pszCmd, int /*nResponse*/, LPTSTR pszResponse)
{
#ifdef _DEBUG
if (pszCmd)
{
TCHAR szOut[MAX_PATH+1];
OutputDebugString(_T("SmtpCommand : "));
while (lstrlen(pszCmd) > MAX_PATH)
{
lstrcpyn(szOut,pszCmd,MAX_PATH+1);
OutputDebugString(szOut);
Sleep(100);
pszCmd += MAX_PATH;
}
OutputDebugString(pszCmd);
}
OutputDebugString(_T("SmtpResponse: "));
OutputDebugString(pszResponse);
OutputDebugString(_T("\n"));
#endif
}
// Placeholder function -- overridable
// This is a progress callback to indicate that data is being sent over the wire
// and that the operation may take some time.
// Return TRUE to continue sending, or FALSE to abort the transfer
BOOL CSimSmtp::SmtpProgress(LPSTR /*pszBuffer*/, DWORD /*dwBytesSent*/, DWORD /*dwBytesTotal*/)
{
return TRUE; // Continue sending the data
}
// Raises a SmtpError() condition
int CSimSmtp::RaiseError(int nError)
{
// If the error code is -1, something catastrophic happened
// so we're effectively not connected to any SMTP server.
if (nError == -1) m_bConnected = FALSE;
return SmtpError(nError, (LPTSTR)m_strResult.c_str());
}
// Warnings are recoverable errors that we may be able to continue working with
int CSimSmtp::RaiseWarning(int nWarning)
{
return SmtpWarning(nWarning, (LPTSTR)m_strResult.c_str());
}
// E-Mail's a message
// Returns 0 if successful, -1 if an internal error occurred, or a positive
// error value if the SMTP server gave an error or failure response.
int CSimSmtp::SendMessage(CSmtpMessage &msg)
{
int nRet;
int n;
// int nRecipients = 0;
int nRecipientCount = 0;
// Check if we have a sender
if (!msg.Sender.Address.length()) return -1;
// Check if we have recipients
if (!msg.Recipient.Address.length() && !msg.CC.GetSize()) return -1;
// Check if we have a message body or attachments
// *** Commented out to remove the requirement that a message have a body or attachments
// if (!msg.Message.GetSize() && !msg.Attachments.GetSize()) return -1;
// Send the sender's address
nRet = SendFrom((LPTSTR)msg.Sender.Address.c_str());
if (nRet) return nRet;
// If we have a recipient, send it
nRecipientCount = 0; // Count of recipients
if (msg.Recipient.Address.length())
{
nRet = SendTo((LPTSTR)msg.Recipient.Address.c_str());
if (!nRet) nRecipientCount ++;
}
// If we have any CC's, send those.
for (n = 0;n < msg.CC.GetSize();n++)
{
nRet = SendTo((LPTSTR)msg.CC[n].Address.c_str());
if (!nRet) nRecipientCount ++;
}
// If we have any bcc's, send those.
for (n = 0;n < msg.BCC.GetSize();n++)
{
nRet = SendTo((LPTSTR)msg.BCC[n].Address.c_str());
if (!nRet) nRecipientCount ++;
}
// If we failed on all recipients, we must abort.
if (!nRecipientCount)
RaiseError(nRet);
else
nRet = SendData(msg);
return nRet;
}
// Simplified way to send a message.
// <pvAttachments> can be either an LPTSTR containing NULL terminated strings, in which
// case <dwAttachmentCount> should be zero, or <pvAttachments> can be an LPTSTR *
// containing an array of LPTSTR's, in which case <dwAttachmentCount> should equal the
// number of strings in the array.
int CSimSmtp::SendMessage(CSmtpAddress &addrFrom, CSmtpAddress &addrTo, LPCTSTR pszSubject, LPCTSTR pszMessage, LPVOID pvAttachments, DWORD dwAttachmentCount)
{
CSmtpMessage message;
CSmtpMessageBody body;
CSmtpAttachment attach;
body = pszMessage;
message.Sender = addrFrom;
message.Recipient = addrTo;
message.Message.Add(body);
message.Subject = pszSubject;
// If the attachment count is zero, but the pvAttachments variable is not NULL,
// assume that the ppvAttachments variable is a string value containing NULL terminated
// strings. A double NULL ends the list.
// Example: LPTSTR pszAttachments = "foo.exe\0bar.zip\0autoexec.bat\0\0";
if (!dwAttachmentCount && pvAttachments)
{
LPTSTR pszAttachments = (LPTSTR)pvAttachments;
while (lstrlen(pszAttachments))
{
attach.FileName = pszAttachments;
message.Attachments.Add(attach);
pszAttachments = &pszAttachments[lstrlen(pszAttachments)];
}
}
// dwAttachmentCount is not zero, so assume pvAttachments is an array of LPTSTR's
// Example: LPTSTR *ppszAttachments = {"foo.exe","bar.exe","autoexec.bat"};
if (pvAttachments && dwAttachmentCount)
{
LPTSTR *ppszAttachments = (LPTSTR *)pvAttachments;
while (dwAttachmentCount-- && ppszAttachments)
{
attach.FileName = ppszAttachments[dwAttachmentCount];
message.Attachments.Add(attach);
}
}
return SendMessage(message);
}
// Yet an even simpler method for sending a message
// <pszAddrFrom> and <pszAddrTo> should be e-mail addresses with no decorations
// Example: "[email protected]"
// <pvAttachments> and <dwAttachmentCount> are described above in the alternative
// version of this function
int CSimSmtp::SendMessage(LPCTSTR pszAddrFrom, LPCTSTR pszAddrTo, LPCTSTR pszSubject, LPCTSTR pszMessage, LPVOID pvAttachments, DWORD dwAttachmentCount)
{
CSmtpAddress addrFrom(pszAddrFrom);
CSmtpAddress addrTo(pszAddrTo);
return SendMessage(addrFrom,addrTo,pszSubject,pszMessage,pvAttachments,dwAttachmentCount);
}
// Tell the SMTP server we're quitting
// Returns 0 if successful, or a positive
// error value if the SMTP server gave an error or failure response.
int CSimSmtp::SendQuitCmd()
{
int nRet;
if (!m_bConnected) return 0;
nRet = SendCmd(_T("QUIT\r\n"));
if (nRet != 221) RaiseError(nRet);
m_bConnected = FALSE;
return (nRet == 221) ? 0:nRet;
}
// Initiate a conversation with the SMTP server
// Returns 0 if successful, or a positive
// error value if the SMTP server gave an error or failure response.
int CSimSmtp::SendHello()
{
int nRet = 0;
TCHAR szName[64];
TCHAR szMsg[MAX_PATH];
DWORD dwSize = 64;
GetComputerName(szName,&dwSize);
// First try a EHLO if we're using ESMTP
wsprintf(szMsg,_T("EHLO %s\r\n"),szName);
if (m_bExtensions) nRet = SendCmd(szMsg);
// If we got a 250 response, we're using ESMTP, otherwise revert to regular SMTP
if (nRet != 250)
{
m_bUsingExtensions = FALSE;
szMsg[0] = 'H';
szMsg[1] = 'E';
nRet = SendCmd(szMsg);
}
else m_bUsingExtensions = TRUE;
// Raise any unexpected responses
if (nRet != 250)
{
RaiseError(nRet);
return nRet;
}
// We're connected!
m_bConnected = TRUE;
// Send authentication if we have any.
// We don't fail just because authentication failed, however.
if (m_bUsingExtensions) SendAuthentication();
return 0;
}
// Requests authentication for the session if the server supports it,
// and attempts to submit the user's credentials.
// Returns 0 if successful, or a positive
// error value if the SMTP server gave an error or failure response.
int CSimSmtp::SendAuthentication()
{
USES_CONVERSION;
int nRet = 0;
CBase64 cvt;
LPCSTR pszTemp;
TCHAR szMsg[MAX_PATH];
CHAR szAuthType[MAX_PATH];
// This is an authentication loop, we can authenticate multiple times in case of failure.
while(1)
{
// If we don't have a username, skip authentication
if (!m_strUser.length()) return 0;
// Make the authentication request
nRet = SendCmd(_T("AUTH LOGIN\r\n"));
// If it was rejected, we have to abort.
if (nRet != 334)
{
RaiseWarning(nRet);
return nRet;
}
// Authentication has 2 stages for username and password.
// It is possible if the authentication fails here that we can
// resubmit proper credentials.
while (1)
{
// Decode the authentication string being requested
_T2A(szAuthType,&(m_strResult.c_str())[4]);
cvt.Decode(szAuthType);
pszTemp = cvt.DecodedMessage();
if (!lstrcmpiA(pszTemp,"Username:"))
cvt.Encode(T2CA(m_strUser.c_str()));
else if (!lstrcmpiA(pszTemp,"Password:"))
cvt.Encode(T2CA(m_strPass.c_str()));
else break;
wsprintf(szMsg,_T("%s\r\n"),A2CT(cvt.EncodedMessage()));
nRet = SendCmd(szMsg);
// If we got a failed authentication request, raise a warning.
// this gives the owner a chance to change the username and password.
if (nRet == 535)
{
// Return FALSE to fail, or TRUE to retry
nRet = RaiseWarning(nRet);
if (!nRet)
{
// Reset the error back to 535. It's now an error rather than a warning
nRet = 535;
break;
}
}
// Break on any response other than 334, which indicates a request for more information
if (nRet != 334) break;
}
// Break if we're not retrying a failed authentication
if (nRet != TRUE) break;
}
// Raise an error if we failed to authenticate
if (nRet != 235) RaiseError(nRet);
return (nRet == 235) ? 0:nRet;
}
// Send a MAIL FROM command to the server
// Returns 0 if successful, or a positive
// error value if the SMTP server gave an error or failure response.
int CSimSmtp::SendFrom(LPTSTR pszFrom)
{
int nRet = 0;
TCHAR szMsg[MAX_PATH];
wsprintf(szMsg,_T("MAIL FROM: <%s>\r\n"),pszFrom);
while (1)
{
nRet = SendCmd(szMsg);
// Send authentication if required, and retry the command
if (nRet == 530) nRet = SendAuthentication();
else break;
}
// Raise an error if we failed
if (nRet != 250) RaiseError(nRet);
return (nRet == 250) ? 0:nRet;
}
// Send a RCPT TO command to the server
// Returns 0 if successful, or a positive
// error value if the SMTP server gave an error or failure response.
int CSimSmtp::SendTo(LPTSTR pszTo)
{
int nRet;
TCHAR szMsg[MAX_PATH];
wsprintf(szMsg,_T("RCPT TO: <%s>\r\n"),pszTo);
nRet = SendCmd(szMsg);
if (nRet != 250 && nRet != 251) RaiseWarning(nRet);
return (nRet == 250 || nRet == 251) ? 0:nRet;
}
// Send the body of an e-mail message to the server
// Returns 0 if successful, or a positive
// error value if the SMTP server gave an error or failure response.
int CSimSmtp::SendData(CSmtpMessage &msg)
{
int nRet;
String strMsg;
// Send the DATA command. We need a 354 to proceed
nRet = SendCmd(_T("DATA\r\n"));
if (nRet != 354)
{
RaiseError(nRet);
return nRet;
}
// Parse the body of the email message
msg.Parse(strMsg);
strMsg += _T("\r\n.\r\n");
// Send the body and expect a 250 OK reply.
nRet = SendCmd((LPTSTR)strMsg.c_str());
if (nRet != 250) RaiseError(nRet);
return (nRet == 250) ? 0:nRet;
}
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] | [
[
[
1,
1477
]
]
] |
dba90e86448f440854846169f2849dd2fbcfb658 | 113b284df51a798c943e36aaa21273e7379391a9 | /RecycleBinGadget/RecycleBinDLL/stdafx.cpp | 2c54571eda157f4731ab85318f4218bc141f2335 | [] | no_license | ccMatrix/desktopgadgets | bf171b75b446faf16443202c06e98c0a4b5eef7c | f5fa36e042ce274910f62e5d3510072ae07acf5e | refs/heads/master | 2020-12-25T19:26:10.514144 | 2010-03-01T23:24:15 | 2010-03-01T23:24:15 | 32,254,664 | 1 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 206 | cpp | // stdafx.cpp : Quelltextdatei, die nur die Standard-Includes einbindet
// RecycleBinDLL.pch ist der vorcompilierte Header
// stdafx.obj enthält die vorcompilierte Typinformation
#include "stdafx.h"
| [
"codename.matrix@e00a1d1f-563d-0410-a555-bbce3309907e"
] | [
[
[
1,
5
]
]
] |
7796d197578aeeb2d1696189536f8b0d14f208aa | 9df2486e5d0489f83cc7dcfb3ccc43374ab2500c | /src/input/joystick.cpp | 3a5a5daae8735bdc5f15f13ded33caeb429d03ba | [] | no_license | renardchien/Eta-Chronicles | 27ad4ffb68385ecaafae4f12b0db67c096f62ad1 | d77d54184ec916baeb1ab7cc00ac44005d4f5624 | refs/heads/master | 2021-01-10T19:28:28.394781 | 2011-09-05T14:40:38 | 2011-09-05T14:40:38 | 1,914,623 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 13,318 | cpp | /***************************************************************************
* joystick.cpp - Joystick handling class
*
* Copyright (C) 2003 - 2009 Florian Richter
***************************************************************************/
/*
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.
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 "../core/globals.h"
#include "../input/keyboard.h"
#include "../input/joystick.h"
#include "../user/preferences.h"
#include "../core/game_core.h"
#include "../player/player.h"
#include "../gui/hud.h"
#include "../gui/menu.h"
#include "../level/level.h"
#include "../overworld/overworld.h"
namespace SMC
{
/* *** *** *** *** *** *** cJoystick *** *** *** *** *** *** *** *** *** *** *** */
cJoystick :: cJoystick( void )
{
joystick = NULL;
stick_open = 0;
cur_stick = 0;
num_buttons = 0;
num_axes = 0;
num_balls = 0;
debug = 0;
Reset_keys();
Init();
}
cJoystick :: ~cJoystick( void )
{
Close();
}
int cJoystick :: Init( void )
{
// if not enabled
if( !pPreferences->m_joy_enabled )
{
return 0;
}
int joy_count = SDL_NumJoysticks();
// no joystick available
if( joy_count <= 0 )
{
printf( "No joysticks available\n" );
pPreferences->m_joy_enabled = 0;
return 0;
}
if( debug )
{
printf( "Joysticks found : %d\n\n", joy_count );
}
unsigned int default_joy = 0;
// if default joy name is given
if( !pPreferences->m_joy_name.empty() )
{
vector<std::string> joy_names = Get_Names();
for( unsigned int i = 0; i < joy_names.size(); i++ )
{
// found default joy
if( joy_names[i].compare( pPreferences->m_joy_name ) == 0 )
{
default_joy = i;
break;
}
}
}
// setup
SDL_JoystickEventState( SDL_ENABLE );
Stick_Open( default_joy );
if( debug )
{
printf( "Joypad System Initialized\n" );
}
return 1;
}
void cJoystick :: Close( void )
{
Stick_Close();
}
bool cJoystick :: Stick_Open( unsigned int index )
{
// if a joystick is already opened close it first
if( stick_open )
{
Stick_Close();
}
joystick = SDL_JoystickOpen( index );
if( !joystick )
{
printf( "Couldn't open joystick %d\n", index );
stick_open = 0;
return 0;
}
cur_stick = index;
num_buttons = SDL_JoystickNumButtons( joystick );
num_axes = SDL_JoystickNumAxes( joystick );
num_balls = SDL_JoystickNumBalls( joystick );
// setup available buttons
buttons.assign( num_buttons, 0 );
if( debug )
{
printf( "Opened Joystick %d\n", cur_stick );
printf( "Name: %s\n", Get_Name().c_str() );
printf( "Number of Buttons: %d\n", num_buttons );
printf( "Number of Axes: %d\n", num_axes );
printf( "Number of Balls: %d\n\n", num_balls );
}
stick_open = 1;
return 1;
}
void cJoystick :: Stick_Close( void )
{
// not available
if( !joystick )
{
return;
}
SDL_JoystickClose( joystick );
joystick = NULL;
Reset_keys();
num_buttons = 0;
num_axes = 0;
num_balls = 0;
buttons.clear();
stick_open = 0;
if( debug )
{
printf( "Joystick %d closed\n", cur_stick );
}
cur_stick = 0;
}
void cJoystick :: Reset_keys( void )
{
// clear buttons
std::fill( buttons.begin(), buttons.end(), static_cast<bool>(0) );
left = 0;
right = 0;
up = 0;
down = 0;
}
void cJoystick :: Handle_Hat( SDL_Event *ev )
{
// up
if( ev->jhat.value == SDL_HAT_UP )
{
if( !up )
{
pKeyboard->Key_Down( pPreferences->m_key_up );
up = 1;
}
if( down )
{
pKeyboard->Key_Up( pPreferences->m_key_down );
down = 0;
}
}
else
{
if( up )
{
pKeyboard->Key_Up( pPreferences->m_key_up );
up = 0;
}
}
// down
if( ev->jhat.value == SDL_HAT_DOWN )
{
if( !down )
{
pKeyboard->Key_Down( pPreferences->m_key_down );
down = 1;
}
if( up )
{
pKeyboard->Key_Up( pPreferences->m_key_up );
up = 0;
}
}
else
{
if( down )
{
pKeyboard->Key_Up( pPreferences->m_key_down );
down = 0;
}
}
// left
if( ev->jhat.value == SDL_HAT_LEFT )
{
if( !left )
{
pKeyboard->Key_Down( pPreferences->m_key_left );
left = 1;
}
if( right )
{
pKeyboard->Key_Up( pPreferences->m_key_right );
right = 0;
}
}
else
{
if( left )
{
pKeyboard->Key_Up( pPreferences->m_key_left );
left = 0;
}
}
// right
if( ev->jhat.value == SDL_HAT_RIGHT)
{
if( !right )
{
pKeyboard->Key_Down( pPreferences->m_key_right );
right = 1;
}
if( left )
{
pKeyboard->Key_Up( pPreferences->m_key_left );
left = 0;
}
}
else
{
if( right )
{
pKeyboard->Key_Up( pPreferences->m_key_right );
right = 0;
}
}
}
void cJoystick :: Handle_Motion( SDL_Event *ev )
{
// Vertical Axis
if( ev->jaxis.axis == pPreferences->m_joy_axis_ver )
{
// Up
if( ev->jaxis.value < -pPreferences->m_joy_axis_threshold )
{
if( debug )
{
printf( "Joystick %d : Up Button pressed\n", cur_stick );
}
if( !up )
{
pKeyboard->Key_Down( pPreferences->m_key_up );
up = 1;
}
if( down )
{
pKeyboard->Key_Up( pPreferences->m_key_down );
down = 0;
}
}
// Down
else if( ev->jaxis.value > pPreferences->m_joy_axis_threshold )
{
if( debug )
{
printf( "Joystick %d : Down Button pressed\n", cur_stick );
}
if( !down )
{
pKeyboard->Key_Down( pPreferences->m_key_down );
down = 1;
}
if( up )
{
pKeyboard->Key_Up( pPreferences->m_key_up );
up = 0;
}
}
// No Down/Left
else
{
if( down )
{
pKeyboard->Key_Up( pPreferences->m_key_down );
down = 0;
}
if( up )
{
pKeyboard->Key_Up( pPreferences->m_key_up );
up = 0;
}
}
}
// Horizontal Axis
else if( ev->jaxis.axis == pPreferences->m_joy_axis_hor )
{
// Left
if( ev->jaxis.value < -pPreferences->m_joy_axis_threshold )
{
if( debug )
{
printf( "Joystick %d : Left Button pressed\n", cur_stick );
}
if( !left )
{
pKeyboard->Key_Down( pPreferences->m_key_left );
left = 1;
}
if( right )
{
pKeyboard->Key_Up( pPreferences->m_key_right );
right = 0;
}
}
// Right
else if( ev->jaxis.value > pPreferences->m_joy_axis_threshold )
{
if( debug )
{
printf( "Joystick %d : Right Button pressed\n", cur_stick );
}
if( !right )
{
pKeyboard->Key_Down( pPreferences->m_key_right );
right = 1;
}
if( left )
{
pKeyboard->Key_Up( pPreferences->m_key_left );
left = 0;
}
}
// No Left/Right
else
{
if( left )
{
pKeyboard->Key_Up( pPreferences->m_key_left );
left = 0;
}
if( right )
{
pKeyboard->Key_Up( pPreferences->m_key_right );
right = 0;
}
}
}
}
bool cJoystick :: Handle_Button_Down_Event( SDL_Event *ev )
{
// not enabled or opened
if( !pPreferences->m_joy_enabled || !stick_open )
{
return 0;
}
Set_Button( ev->jbutton.button, 1 );
// handle button in the current mode
if( Game_Mode == MODE_LEVEL )
{
// processed by the level
if( pActive_Level->Joy_Button_Down( ev->jbutton.button ) )
{
return 1;
}
}
else if( Game_Mode == MODE_OVERWORLD )
{
// processed by the overworld
if( pActive_Overworld->Joy_Button_Down( ev->jbutton.button ) )
{
return 1;
}
}
else if( Game_Mode == MODE_MENU )
{
// processed by the menu
if( pMenuCore->Joy_Button_Down( ev->jbutton.button ) )
{
return 1;
}
}
if( ev->jbutton.button < buttons.size() )
{
// Jump
if( ev->jbutton.button == pPreferences->m_joy_button_jump )
{
//
}
// Shoot
else if( ev->jbutton.button == pPreferences->m_joy_button_shoot )
{
pKeyboard->Key_Down( pPreferences->m_key_shoot );
return 1;
}
// Request Itembox Item
else if( ev->jbutton.button == pPreferences->m_joy_button_item )
{
// not handled
return 1;
}
// Interaction
else if( ev->jbutton.button == pPreferences->m_joy_button_action )
{
pKeyboard->Key_Down( pPreferences->m_key_action );
return 1;
}
// Exit
else if( ev->jbutton.button == pPreferences->m_joy_button_exit )
{
pKeyboard->Key_Down( SDLK_ESCAPE );
return 1;
}
// Pause
else if( ev->jbutton.button == 9 )
{
pKeyboard->Key_Down( SDLK_PAUSE );
return 1;
}
}
return 0;
}
bool cJoystick :: Handle_Button_Up_Event( SDL_Event *ev )
{
// not enabled or opened
if( !pPreferences->m_joy_enabled || !stick_open )
{
return 0;
}
Set_Button( ev->jbutton.button, 0 );
// handle button in the current mode
if( Game_Mode == MODE_LEVEL )
{
// processed by the level
if( pActive_Level->Joy_Button_Up( ev->jbutton.button ) )
{
return 1;
}
}
else if( Game_Mode == MODE_OVERWORLD )
{
// processed by the overworld
if( pActive_Overworld->Joy_Button_Up( ev->jbutton.button ) )
{
return 1;
}
}
else if( Game_Mode == MODE_MENU )
{
// processed by the menu
if( pMenuCore->Joy_Button_Up( ev->jbutton.button ) )
{
return 1;
}
}
if( ev->jbutton.button < buttons.size() )
{
if( ev->jbutton.button == pPreferences->m_joy_button_jump )
{
pKeyboard->Key_Up( pPreferences->m_key_jump );
return 1;
}
else if( ev->jbutton.button == pPreferences->m_joy_button_shoot )
{
pKeyboard->Key_Up( pPreferences->m_key_shoot );
return 1;
}
else if( ev->jbutton.button == pPreferences->m_joy_button_item )
{
// not handled
}
else if( ev->jbutton.button == pPreferences->m_joy_button_action )
{
pKeyboard->Key_Up( pPreferences->m_key_action );
return 1;
}
else if( ev->jbutton.button == pPreferences->m_joy_button_exit )
{
pKeyboard->Key_Up( SDLK_ESCAPE );
return 1;
}
}
return 0;
}
std::string cJoystick :: Get_Name( void ) const
{
return SDL_JoystickName( cur_stick );
}
vector<std::string> cJoystick :: Get_Names( void ) const
{
vector<std::string> names;
// get joy count
int joy_count = SDL_NumJoysticks();
// joystick names
for( int i = 0; i < joy_count; i++ )
{
names.push_back( SDL_JoystickName( i ) );
}
return names;
}
void cJoystick :: Set_Button( Uint8 num, bool pressed )
{
// not available
if( num >= buttons.size() )
{
return;
}
if( debug )
{
if( pressed )
{
printf( "Joystick %d : Joy Button %d pressed\n", cur_stick, num );
}
else
{
printf( "Joystick %d : Joy Button %d released\n", cur_stick, num );
}
}
buttons[num] = pressed;
}
Uint8 *cJoystick :: Get_Shortcut( input_identifier shortcut_id ) const
{
if( shortcut_id == INP_JUMP )
{
return &pPreferences->m_joy_button_jump;
}
else if( shortcut_id == INP_ITEM )
{
return &pPreferences->m_joy_button_item;
}
else if( shortcut_id == INP_SHOOT )
{
return &pPreferences->m_joy_button_shoot;
}
else if( shortcut_id == INP_ACTION )
{
return &pPreferences->m_joy_button_action;
}
else if( shortcut_id == INP_EXIT )
{
return &pPreferences->m_joy_button_exit;
}
return NULL;
}
void cJoystick :: Assign_Shortcut( input_identifier shortcut_id, Uint8 new_button )
{
Uint8 *button = Get_Shortcut( shortcut_id );
*button = new_button;
}
bool cJoystick :: Left( void ) const
{
if( pPreferences->m_joy_enabled && input_event.type == SDL_JOYAXISMOTION && input_event.jaxis.value < -pPreferences->m_joy_axis_threshold &&
input_event.jaxis.axis == pPreferences->m_joy_axis_hor )
{
return 1;
}
return 0;
}
bool cJoystick :: Right( void ) const
{
if( pPreferences->m_joy_enabled && input_event.type == SDL_JOYAXISMOTION && input_event.jaxis.value > pPreferences->m_joy_axis_threshold &&
input_event.jaxis.axis == pPreferences->m_joy_axis_hor )
{
return 1;
}
return 0;
}
bool cJoystick :: Up( void ) const
{
if( pPreferences->m_joy_enabled && input_event.type == SDL_JOYAXISMOTION && input_event.jaxis.value < -pPreferences->m_joy_axis_threshold &&
input_event.jaxis.axis == pPreferences->m_joy_axis_ver )
{
return 1;
}
return 0;
}
bool cJoystick :: Down( void ) const
{
if( pPreferences->m_joy_enabled && input_event.type == SDL_JOYAXISMOTION && input_event.jaxis.value > pPreferences->m_joy_axis_threshold &&
input_event.jaxis.axis == pPreferences->m_joy_axis_ver )
{
return 1;
}
return 0;
}
bool cJoystick :: Button( Uint8 num )
{
// if available and pressed
if( num < buttons.size() && buttons[num] )
{
return 1;
}
return 0;
}
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
cJoystick *pJoystick = NULL;
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
} // namespace SMC
| [
"[email protected]"
] | [
[
[
1,
693
]
]
] |
b693f3293a3bfe2d9caa2a39cbde75ed483059c0 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /dingus/dingus/resource/SharedCubeTextureBundle.cpp | 528f1b28c0893f83d323c5b34fec4f152da47f4f | [
"MIT"
] | permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | cpp | // --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#include "stdafx.h"
#include "SharedCubeTextureBundle.h"
#include "../utils/Errors.h"
#include "../kernel/D3DDevice.h"
using namespace dingus;
void CSharedCubeTextureBundle::registerCubeTexture( const CResourceId& id, ICubeTextureCreator& creator )
{
assert( &creator );
IDirect3DCubeTexture9* tex = creator.createTexture();
registerResource( id, *(new CD3DCubeTexture(tex)), &creator );
}
void CSharedCubeTextureBundle::createResource()
{
}
void CSharedCubeTextureBundle::activateResource()
{
// recreate all objects
TResourceMap::iterator it;
for( it = mResourceMap.begin(); it != mResourceMap.end(); ++it ) {
ICubeTextureCreator& creator = *it->second.first;
assert( &creator );
CD3DCubeTexture& res = *it->second.second;
if( !res.isNull() )
continue; // kind of HACK
res.setObject( creator.createTexture() );
assert( !res.isNull() );
}
}
void CSharedCubeTextureBundle::passivateResource()
{
// unload all objects
TResourceMap::iterator it;
for( it = mResourceMap.begin(); it != mResourceMap.end(); ++it ) {
CD3DCubeTexture& res = *it->second.second;
assert( !res.isNull() );
res.getObject()->Release();
res.setObject( NULL );
}
}
void CSharedCubeTextureBundle::deleteResource()
{
}
| [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
e66812ff1ba82a28253a7f2e20e3b8544caf363e | 6a4bb1498d9cb21d9ef4b3cb0b325c7013cf3a13 | /src/game/gamewindow.h | bf6a3ae2eff4d46a1a9b9cde0e00792cf8b82b3e | [] | no_license | argontus/3S3K3D | 663fea3b79a152d2ca26cd05242d931cbe9c402f | 6d5fb09546e7f70d038e8cf89ff102088c03258a | refs/heads/master | 2021-01-01T16:56:10.674766 | 2011-04-21T14:37:38 | 2011-04-21T14:37:38 | 1,295,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,534 | h | /**
* @file game/gamwindow.h
* @author Marko Silokunnas
*/
#ifndef GAMEWINDOW_H
#define GAMEWINDOW_H
#include <SDL/SDL.h>
#include "input/sdlkeyboard.h"
#include "input/sdlmouse.h"
/**
* Pure virtual class representing a game window. Contains basic functionality
* for resizing a window and receiving events. Handling single events
* can be achieved by overloading the function responsible for that event
* in the inherited class.
*/
class GameWindow
{
public:
GameWindow();
virtual ~GameWindow();
/**
*
* Initializes SDL, window and OpenGL.
* Will read configuration file at some point as well
*
* @return bool returns true if initialization is successful, otherwise
* return false.
*/
bool init();
/**
*
* This function is called before exiting the program. Makes sure that
* the program frees all of it's memory etc.
*/
void cleanup();
/**
* Calculates window's aspect ratio and resets glViewport according to
* new window size.
*/
void resizeWindow( const int width, const int height );
/**
* Main handler for SDL events. Calls appropriate function based on
* event type. (eg. onWindowEvent for SDL_WindowEvents)
*/
void onEvent( const SDL_Event& event );
/**
* Called whenever the window changes size. Calls resizeWindow by
* default. It's recommended to call resizeWindow in the overloading
* function as well
*/
virtual void onWindowResize( const int width, const int height );
/**
* Handles window events
*
* @param windowEvent window event to handle
*/
//virtual void onWindowEvent( const SDL_WindowEvent& windowEvent );
/**
* Called whenever user presses a key down.
*
* @param keyboardEvent keyboard event to process. Contains info on
* which key was pressed.
*/
virtual void onKeyDown( const SDL_KeyboardEvent& keyboardEvent );
/**
* Called whenever user releases a key that is pressed down
*
* @param keyboardEvent keyboard event to process. Contains info on
* on which key was released.
*/
virtual void onKeyUp( const SDL_KeyboardEvent& keyboardEvent );
/**
* Pure virtual event handler for quit events.
*/
virtual void onQuit() = 0;
/**
* Called whenever window gains focus
*/
virtual void onFocusGained();
/**
* Called whenever window loses focus
*/
virtual void onFocusLost();
/**
* Called whenever window is minimized.
*/
virtual void onWindowMinimized();
/**
* Called whenever window is maximized.
*/
virtual void onWindowMaximized();
/**
* Called whenever mouse is moved
*
* @param mouseMotionEvent mouse movement event
*/
virtual void onMouseMoved(const SDL_MouseMotionEvent& mouseMotionEvent);
/**
* Called whenever one of the mouse buttons is pressed
*
* @param mouseButtonEvent mouse button event
*/
virtual void onMouseButtonDown(
const SDL_MouseButtonEvent& mouseButtonEvent
);
/**
* Called whenever one of the mouse buttons is released
*
* @param mouseButtonEvent mouse button event
*/
virtual void onMouseButtonUp(
const SDL_MouseButtonEvent& mouseButtonEvent
);
/**
* Centers the mouse pointer to the center of the window
*/
virtual void centerMouse();
protected:
//SDL_WindowID mainwindow; /* window handle */
//SDL_GLContext maincontext; /* opengl context handle */
SDL_Surface* mainwindow;
float aspectRatio;
int width;
int height;
bool mouseVisible;
bool mouseBoundToScreen;
bool fullscreen;
SDLKeyboard keyboard;
SDLMouse mouse;
};
#endif // GAMEWINDOW_H
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
6
],
[
9,
9
],
[
12,
17
],
[
23,
65
],
[
67,
120
],
[
122,
129
],
[
131,
131
],
[
138,
139
]
],
[
[
7,
8
],
[
10,
11
],
[
18,
22
],
[
66,
66
],
[
121,
121
],
[
130,
130
],
[
132,
137
],
[
140,
153
]
]
] |
e32564aac13ea63b5feb50891f7105395d33915c | 3a72cb54a5209f8d5be90df8b0bbac116119a36d | /core/ghost/map.cpp | a8952b62b16ebef57210721880ed9e3e2979e3c5 | [] | no_license | luqasn/ghost4mac | 43409b56f7f1fb8783af467741246a198ae87470 | ccfc153ccd5274b09eabbc749e80db23d9c163b5 | refs/heads/master | 2021-03-12T20:17:03.261275 | 2011-07-06T11:02:59 | 2011-07-06T11:02:59 | 2,005,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,330 | cpp | /*
Copyright [2008] [Trevor Hogan]
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.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#include "ghost.h"
#include "util.h"
#include "crc32.h"
#include "sha1.h"
#include "config.h"
#include "map.h"
#define __STORMLIB_SELF__
#include <stormlib/StormLib.h>
#define ROTL(x,n) ((x)<<(n))|((x)>>(32-(n))) // this won't work with signed types
#define ROTR(x,n) ((x)>>(n))|((x)<<(32-(n))) // this won't work with signed types
//
// CMap
//
CMap :: CMap( CGHost *nGHost )
{
CONSOLE_Print( "[MAP] using hardcoded Emerald Gardens map data for Warcraft 3 version 1.24" );
m_GHost = nGHost;
m_Valid = true;
m_MapPath = "Maps\\FrozenThrone\\(12)EmeraldGardens.w3x";
m_MapSize = UTIL_ExtractNumbers( "174 221 4 0", 4 );
m_MapInfo = UTIL_ExtractNumbers( "251 57 68 98", 4 );
m_MapCRC = UTIL_ExtractNumbers( "108 250 204 59", 4 );
m_MapSHA1 = UTIL_ExtractNumbers( "35 81 104 182 223 63 204 215 1 17 87 234 220 66 3 185 82 99 6 13", 20 );
m_MapSpeed = MAPSPEED_FAST;
m_MapVisibility = MAPVIS_DEFAULT;
m_MapObservers = MAPOBS_NONE;
m_MapFlags = MAPFLAG_TEAMSTOGETHER | MAPFLAG_FIXEDTEAMS;
m_MapGameType = 9;
m_MapWidth = UTIL_ExtractNumbers( "172 0", 2 );
m_MapHeight = UTIL_ExtractNumbers( "172 0", 2 );
m_MapLoadInGame = false;
m_MapNumPlayers = 12;
m_MapNumTeams = 12;
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 0, 0, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 1, 1, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 2, 2, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 3, 3, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 4, 4, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 5, 5, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 6, 6, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 7, 7, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 8, 8, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 9, 9, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 10, 10, SLOTRACE_RANDOM ) );
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 11, 11, SLOTRACE_RANDOM ) );
}
CMap :: CMap( CGHost *nGHost, CConfig *CFG, string nCFGFile )
{
m_GHost = nGHost;
Load( CFG, nCFGFile );
}
CMap :: ~CMap( )
{
}
BYTEARRAY CMap :: GetMapGameFlags( )
{
/*
Speed: (mask 0x00000003) cannot be combined
0x00000000 - Slow game speed
0x00000001 - Normal game speed
0x00000002 - Fast game speed
Visibility: (mask 0x00000F00) cannot be combined
0x00000100 - Hide terrain
0x00000200 - Map explored
0x00000400 - Always visible (no fog of war)
0x00000800 - Default
Observers/Referees: (mask 0x40003000) cannot be combined
0x00000000 - No Observers
0x00002000 - Observers on Defeat
0x00003000 - Additional players as observer allowed
0x40000000 - Referees
Teams/Units/Hero/Race: (mask 0x07064000) can be combined
0x00004000 - Teams Together (team members are placed at neighbored starting locations)
0x00060000 - Fixed teams
0x01000000 - Unit share
0x02000000 - Random hero
0x04000000 - Random races
*/
uint32_t GameFlags = 0;
// speed
if( m_MapSpeed == MAPSPEED_SLOW )
GameFlags = 0x00000000;
else if( m_MapSpeed == MAPSPEED_NORMAL )
GameFlags = 0x00000001;
else
GameFlags = 0x00000002;
// visibility
if( m_MapVisibility == MAPVIS_HIDETERRAIN )
GameFlags |= 0x00000100;
else if( m_MapVisibility == MAPVIS_EXPLORED )
GameFlags |= 0x00000200;
else if( m_MapVisibility == MAPVIS_ALWAYSVISIBLE )
GameFlags |= 0x00000400;
else
GameFlags |= 0x00000800;
// observers
if( m_MapObservers == MAPOBS_ONDEFEAT )
GameFlags |= 0x00002000;
else if( m_MapObservers == MAPOBS_ALLOWED )
GameFlags |= 0x00003000;
else if( m_MapObservers == MAPOBS_REFEREES )
GameFlags |= 0x40000000;
// teams/units/hero/race
if( m_MapFlags & MAPFLAG_TEAMSTOGETHER )
GameFlags |= 0x00004000;
if( m_MapFlags & MAPFLAG_FIXEDTEAMS )
GameFlags |= 0x00060000;
if( m_MapFlags & MAPFLAG_UNITSHARE )
GameFlags |= 0x01000000;
if( m_MapFlags & MAPFLAG_RANDOMHERO )
GameFlags |= 0x02000000;
if( m_MapFlags & MAPFLAG_RANDOMRACES )
GameFlags |= 0x04000000;
return UTIL_CreateByteArray( GameFlags, false );
}
void CMap :: Load( CConfig *CFG, string nCFGFile )
{
m_Valid = true;
m_CFGFile = nCFGFile;
// load the map data
m_MapLocalPath = CFG->GetString( "map_localpath", string( ) );
m_MapData.clear( );
if( !m_MapLocalPath.empty( ) )
m_MapData = UTIL_FileRead( m_GHost->m_MapPath + m_MapLocalPath );
// load the map MPQ
string MapMPQFileName = m_GHost->m_MapPath + m_MapLocalPath;
HANDLE MapMPQ;
bool MapMPQReady = false;
if( SFileOpenArchive( MapMPQFileName.c_str( ), 0, 0, &MapMPQ ) )
{
CONSOLE_Print( "[MAP] loading MPQ file [" + MapMPQFileName + "]" );
MapMPQReady = true;
}
else
CONSOLE_Print( "[MAP] warning - unable to load MPQ file [" + MapMPQFileName + "]" );
// try to calculate map_size, map_info, map_crc, map_sha1
BYTEARRAY MapSize;
BYTEARRAY MapInfo;
BYTEARRAY MapCRC;
BYTEARRAY MapSHA1;
if( !m_MapData.empty( ) )
{
m_GHost->m_SHA->Reset( );
// calculate map_size
MapSize = UTIL_CreateByteArray( (uint32_t)m_MapData.size( ), false );
CONSOLE_Print( "[MAP] calculated map_size = " + UTIL_ByteArrayToDecString( MapSize ) );
// calculate map_info (this is actually the CRC)
MapInfo = UTIL_CreateByteArray( (uint32_t)m_GHost->m_CRC->FullCRC( (unsigned char *)m_MapData.c_str( ), m_MapData.size( ) ), false );
CONSOLE_Print( "[MAP] calculated map_info = " + UTIL_ByteArrayToDecString( MapInfo ) );
// calculate map_crc (this is not the CRC) and map_sha1
// a big thank you to Strilanc for figuring the map_crc algorithm out
string CommonJ = UTIL_FileRead( m_GHost->m_MapCFGPath + "common.j" );
if( CommonJ.empty( ) )
CONSOLE_Print( "[MAP] unable to calculate map_crc/sha1 - unable to read file [" + m_GHost->m_MapCFGPath + "common.j]" );
else
{
string BlizzardJ = UTIL_FileRead( m_GHost->m_MapCFGPath + "blizzard.j" );
if( BlizzardJ.empty( ) )
CONSOLE_Print( "[MAP] unable to calculate map_crc/sha1 - unable to read file [" + m_GHost->m_MapCFGPath + "blizzard.j]" );
else
{
uint32_t Val = 0;
// update: it's possible for maps to include their own copies of common.j and/or blizzard.j
// this code now overrides the default copies if required
bool OverrodeCommonJ = false;
bool OverrodeBlizzardJ = false;
if( MapMPQReady )
{
HANDLE SubFile;
// override common.j
if( SFileOpenFileEx( MapMPQ, "Scripts\\common.j", 0, &SubFile ) )
{
uint32_t FileLength = SFileGetFileSize( SubFile, NULL );
if( FileLength > 0 && FileLength != 0xFFFFFFFF )
{
char *SubFileData = new char[FileLength];
DWORD BytesRead = 0;
if( SFileReadFile( SubFile, SubFileData, FileLength, &BytesRead ) )
{
CONSOLE_Print( "[MAP] overriding default common.j with map copy while calculating map_crc/sha1" );
OverrodeCommonJ = true;
Val = Val ^ XORRotateLeft( (unsigned char *)SubFileData, BytesRead );
m_GHost->m_SHA->Update( (unsigned char *)SubFileData, BytesRead );
}
delete [] SubFileData;
}
SFileCloseFile( SubFile );
}
}
if( !OverrodeCommonJ )
{
Val = Val ^ XORRotateLeft( (unsigned char *)CommonJ.c_str( ), CommonJ.size( ) );
m_GHost->m_SHA->Update( (unsigned char *)CommonJ.c_str( ), CommonJ.size( ) );
}
if( MapMPQReady )
{
HANDLE SubFile;
// override blizzard.j
if( SFileOpenFileEx( MapMPQ, "Scripts\\blizzard.j", 0, &SubFile ) )
{
uint32_t FileLength = SFileGetFileSize( SubFile, NULL );
if( FileLength > 0 && FileLength != 0xFFFFFFFF )
{
char *SubFileData = new char[FileLength];
DWORD BytesRead = 0;
if( SFileReadFile( SubFile, SubFileData, FileLength, &BytesRead ) )
{
CONSOLE_Print( "[MAP] overriding default blizzard.j with map copy while calculating map_crc/sha1" );
OverrodeBlizzardJ = true;
Val = Val ^ XORRotateLeft( (unsigned char *)SubFileData, BytesRead );
m_GHost->m_SHA->Update( (unsigned char *)SubFileData, BytesRead );
}
delete [] SubFileData;
}
SFileCloseFile( SubFile );
}
}
if( !OverrodeBlizzardJ )
{
Val = Val ^ XORRotateLeft( (unsigned char *)BlizzardJ.c_str( ), BlizzardJ.size( ) );
m_GHost->m_SHA->Update( (unsigned char *)BlizzardJ.c_str( ), BlizzardJ.size( ) );
}
Val = ROTL( Val, 3 );
Val = ROTL( Val ^ 0x03F1379E, 3 );
m_GHost->m_SHA->Update( (unsigned char *)"\x9E\x37\xF1\x03", 4 );
if( MapMPQReady )
{
vector<string> FileList;
FileList.push_back( "war3map.j" );
FileList.push_back( "scripts\\war3map.j" );
FileList.push_back( "war3map.w3e" );
FileList.push_back( "war3map.wpm" );
FileList.push_back( "war3map.doo" );
FileList.push_back( "war3map.w3u" );
FileList.push_back( "war3map.w3b" );
FileList.push_back( "war3map.w3d" );
FileList.push_back( "war3map.w3a" );
FileList.push_back( "war3map.w3q" );
bool FoundScript = false;
for( vector<string> :: iterator i = FileList.begin( ); i != FileList.end( ); i++ )
{
// don't use scripts\war3map.j if we've already used war3map.j (yes, some maps have both but only war3map.j is used)
if( FoundScript && *i == "scripts\\war3map.j" )
continue;
HANDLE SubFile;
if( SFileOpenFileEx( MapMPQ, (*i).c_str( ), 0, &SubFile ) )
{
uint32_t FileLength = SFileGetFileSize( SubFile, NULL );
if( FileLength > 0 && FileLength != 0xFFFFFFFF )
{
char *SubFileData = new char[FileLength];
DWORD BytesRead = 0;
if( SFileReadFile( SubFile, SubFileData, FileLength, &BytesRead ) )
{
if( *i == "war3map.j" || *i == "scripts\\war3map.j" )
FoundScript = true;
Val = ROTL( Val ^ XORRotateLeft( (unsigned char *)SubFileData, BytesRead ), 3 );
m_GHost->m_SHA->Update( (unsigned char *)SubFileData, BytesRead );
// DEBUG_Print( "*** found: " + *i );
}
delete [] SubFileData;
}
SFileCloseFile( SubFile );
}
else
{
// DEBUG_Print( "*** not found: " + *i );
}
}
if( !FoundScript )
CONSOLE_Print( "[MAP] couldn't find war3map.j or scripts\\war3map.j in MPQ file, calculated map_crc/sha1 is probably wrong" );
MapCRC = UTIL_CreateByteArray( Val, false );
CONSOLE_Print( "[MAP] calculated map_crc = " + UTIL_ByteArrayToDecString( MapCRC ) );
m_GHost->m_SHA->Final( );
unsigned char SHA1[20];
memset( SHA1, 0, sizeof( unsigned char ) * 20 );
m_GHost->m_SHA->GetHash( SHA1 );
MapSHA1 = UTIL_CreateByteArray( SHA1, 20 );
CONSOLE_Print( "[MAP] calculated map_sha1 = " + UTIL_ByteArrayToDecString( MapSHA1 ) );
}
else
CONSOLE_Print( "[MAP] unable to calculate map_crc/sha1 - map MPQ file not loaded" );
}
}
}
else
CONSOLE_Print( "[MAP] no map data available, using config file for map_size, map_info, map_crc, map_sha1" );
// try to calculate map_width, map_height, map_slot<x>, map_numplayers, map_numteams
BYTEARRAY MapWidth;
BYTEARRAY MapHeight;
uint32_t MapNumPlayers = 0;
uint32_t MapNumTeams = 0;
vector<CGameSlot> Slots;
if( !m_MapData.empty( ) )
{
if( MapMPQReady )
{
HANDLE SubFile;
if( SFileOpenFileEx( MapMPQ, "war3map.w3i", 0, &SubFile ) )
{
uint32_t FileLength = SFileGetFileSize( SubFile, NULL );
if( FileLength > 0 && FileLength != 0xFFFFFFFF )
{
char *SubFileData = new char[FileLength];
DWORD BytesRead = 0;
if( SFileReadFile( SubFile, SubFileData, FileLength, &BytesRead ) )
{
istringstream ISS( string( SubFileData, BytesRead ) );
// war3map.w3i format found at http://www.wc3campaigns.net/tools/specs/index.html by Zepir/PitzerMike
string GarbageString;
uint32_t FileFormat;
uint32_t RawMapWidth;
uint32_t RawMapHeight;
uint32_t RawMapFlags;
uint32_t RawMapNumPlayers;
uint32_t RawMapNumTeams;
ISS.read( (char *)&FileFormat, 4 ); // file format (18 = ROC, 25 = TFT)
if( FileFormat == 18 || FileFormat == 25 )
{
ISS.seekg( 4, ios :: cur ); // number of saves
ISS.seekg( 4, ios :: cur ); // editor version
getline( ISS, GarbageString, '\0' ); // map name
getline( ISS, GarbageString, '\0' ); // map author
getline( ISS, GarbageString, '\0' ); // map description
getline( ISS, GarbageString, '\0' ); // players recommended
ISS.seekg( 32, ios :: cur ); // camera bounds
ISS.seekg( 16, ios :: cur ); // camera bounds complements
ISS.read( (char *)&RawMapWidth, 4 ); // map width
ISS.read( (char *)&RawMapHeight, 4 ); // map height
ISS.read( (char *)&RawMapFlags, 4 ); // flags
ISS.seekg( 1, ios :: cur ); // map main ground type
if( FileFormat == 18 )
ISS.seekg( 4, ios :: cur ); // campaign background number
else if( FileFormat == 25 )
{
ISS.seekg( 4, ios :: cur ); // loading screen background number
getline( ISS, GarbageString, '\0' ); // path of custom loading screen model
}
getline( ISS, GarbageString, '\0' ); // map loading screen text
getline( ISS, GarbageString, '\0' ); // map loading screen title
getline( ISS, GarbageString, '\0' ); // map loading screen subtitle
if( FileFormat == 18 )
ISS.seekg( 4, ios :: cur ); // map loading screen number
else if( FileFormat == 25 )
{
ISS.seekg( 4, ios :: cur ); // used game data set
getline( ISS, GarbageString, '\0' ); // prologue screen path
}
getline( ISS, GarbageString, '\0' ); // prologue screen text
getline( ISS, GarbageString, '\0' ); // prologue screen title
getline( ISS, GarbageString, '\0' ); // prologue screen subtitle
if( FileFormat == 25 )
{
ISS.seekg( 4, ios :: cur ); // uses terrain fog
ISS.seekg( 4, ios :: cur ); // fog start z height
ISS.seekg( 4, ios :: cur ); // fog end z height
ISS.seekg( 4, ios :: cur ); // fog density
ISS.seekg( 1, ios :: cur ); // fog red value
ISS.seekg( 1, ios :: cur ); // fog green value
ISS.seekg( 1, ios :: cur ); // fog blue value
ISS.seekg( 1, ios :: cur ); // fog alpha value
ISS.seekg( 4, ios :: cur ); // global weather id
getline( ISS, GarbageString, '\0' ); // custom sound environment
ISS.seekg( 1, ios :: cur ); // tileset id of the used custom light environment
ISS.seekg( 1, ios :: cur ); // custom water tinting red value
ISS.seekg( 1, ios :: cur ); // custom water tinting green value
ISS.seekg( 1, ios :: cur ); // custom water tinting blue value
ISS.seekg( 1, ios :: cur ); // custom water tinting alpha value
}
ISS.read( (char *)&RawMapNumPlayers, 4 ); // number of players
uint32_t ClosedSlots = 0;
for( uint32_t i = 0; i < RawMapNumPlayers; i++ )
{
CGameSlot Slot( 0, 255, SLOTSTATUS_OPEN, 0, 0, 1, SLOTRACE_RANDOM );
uint32_t Colour;
uint32_t Status;
uint32_t Race;
ISS.read( (char *)&Colour, 4 ); // colour
Slot.SetColour( Colour );
ISS.read( (char *)&Status, 4 ); // status
if( Status == 1 )
Slot.SetSlotStatus( SLOTSTATUS_OPEN );
else if( Status == 2 )
{
Slot.SetSlotStatus( SLOTSTATUS_OCCUPIED );
Slot.SetComputer( 1 );
Slot.SetComputerType( SLOTCOMP_NORMAL );
}
else
{
Slot.SetSlotStatus( SLOTSTATUS_CLOSED );
ClosedSlots++;
}
ISS.read( (char *)&Race, 4 ); // race
if( Race == 1 )
Slot.SetRace( SLOTRACE_HUMAN );
else if( Race == 2 )
Slot.SetRace( SLOTRACE_ORC );
else if( Race == 3 )
Slot.SetRace( SLOTRACE_UNDEAD );
else if( Race == 4 )
Slot.SetRace( SLOTRACE_NIGHTELF );
else
Slot.SetRace( SLOTRACE_RANDOM );
ISS.seekg( 4, ios :: cur ); // fixed start position
getline( ISS, GarbageString, '\0' ); // player name
ISS.seekg( 4, ios :: cur ); // start position x
ISS.seekg( 4, ios :: cur ); // start position y
ISS.seekg( 4, ios :: cur ); // ally low priorities
ISS.seekg( 4, ios :: cur ); // ally high priorities
if( Slot.GetSlotStatus( ) != SLOTSTATUS_CLOSED )
Slots.push_back( Slot );
}
ISS.read( (char *)&RawMapNumTeams, 4 ); // number of teams
for( uint32_t i = 0; i < RawMapNumTeams; i++ )
{
uint32_t Flags;
uint32_t PlayerMask;
ISS.read( (char *)&Flags, 4 ); // flags
ISS.read( (char *)&PlayerMask, 4 ); // player mask
for( unsigned char j = 0; j < 12; j++ )
{
if( PlayerMask & 1 )
{
for( vector<CGameSlot> :: iterator k = Slots.begin( ); k != Slots.end( ); k++ )
{
if( (*k).GetColour( ) == j )
(*k).SetTeam( i );
}
}
PlayerMask >>= 1;
}
getline( ISS, GarbageString, '\0' ); // team name
}
MapWidth = UTIL_CreateByteArray( (uint16_t)RawMapWidth, false );
CONSOLE_Print( "[MAP] calculated map_width = " + UTIL_ByteArrayToDecString( MapWidth ) );
MapHeight = UTIL_CreateByteArray( (uint16_t)RawMapHeight, false );
CONSOLE_Print( "[MAP] calculated map_height = " + UTIL_ByteArrayToDecString( MapHeight ) );
MapNumPlayers = RawMapNumPlayers - ClosedSlots;
CONSOLE_Print( "[MAP] calculated map_numplayers = " + UTIL_ToString( MapNumPlayers ) );
MapNumTeams = RawMapNumTeams;
CONSOLE_Print( "[MAP] calculated map_numteams = " + UTIL_ToString( MapNumTeams ) );
uint32_t SlotNum = 1;
for( vector<CGameSlot> :: iterator i = Slots.begin( ); i != Slots.end( ); i++ )
{
CONSOLE_Print( "[MAP] calculated map_slot" + UTIL_ToString( SlotNum ) + " = " + UTIL_ByteArrayToDecString( (*i).GetByteArray( ) ) );
SlotNum++;
}
// if it's a melee map...
if( RawMapFlags & 4 )
{
CONSOLE_Print( "[MAP] found melee map, initializing slots" );
// give each slot a different team and set the race to random
unsigned char Team = 0;
for( vector<CGameSlot> :: iterator i = Slots.begin( ); i != Slots.end( ); i++ )
{
(*i).SetTeam( Team++ );
(*i).SetRace( SLOTRACE_RANDOM );
}
}
}
}
else
CONSOLE_Print( "[MAP] unable to calculate map_width, map_height, map_slot<x>, map_numplayers, map_numteams - unable to extract war3map.w3i from MPQ file" );
delete [] SubFileData;
}
SFileCloseFile( SubFile );
}
else
CONSOLE_Print( "[MAP] unable to calculate map_width, map_height, map_slot<x>, map_numplayers, map_numteams - couldn't find war3map.w3i in MPQ file" );
}
else
CONSOLE_Print( "[MAP] unable to calculate map_width, map_height, map_slot<x>, map_numplayers, map_numteams - map MPQ file not loaded" );
}
else
CONSOLE_Print( "[MAP] no map data available, using config file for map_width, map_height, map_slot<x>, map_numplayers, map_numteams" );
// close the map MPQ
if( MapMPQReady )
SFileCloseArchive( MapMPQ );
m_MapPath = CFG->GetString( "map_path", string( ) );
if( MapSize.empty( ) )
MapSize = UTIL_ExtractNumbers( CFG->GetString( "map_size", string( ) ), 4 );
else if( CFG->Exists( "map_size" ) )
{
CONSOLE_Print( "[MAP] overriding calculated map_size with config value map_size = " + CFG->GetString( "map_size", string( ) ) );
MapSize = UTIL_ExtractNumbers( CFG->GetString( "map_size", string( ) ), 4 );
}
m_MapSize = MapSize;
if( MapInfo.empty( ) )
MapInfo = UTIL_ExtractNumbers( CFG->GetString( "map_info", string( ) ), 4 );
else if( CFG->Exists( "map_info" ) )
{
CONSOLE_Print( "[MAP] overriding calculated map_info with config value map_info = " + CFG->GetString( "map_info", string( ) ) );
MapInfo = UTIL_ExtractNumbers( CFG->GetString( "map_info", string( ) ), 4 );
}
m_MapInfo = MapInfo;
if( MapCRC.empty( ) )
MapCRC = UTIL_ExtractNumbers( CFG->GetString( "map_crc", string( ) ), 4 );
else if( CFG->Exists( "map_crc" ) )
{
CONSOLE_Print( "[MAP] overriding calculated map_crc with config value map_crc = " + CFG->GetString( "map_crc", string( ) ) );
MapCRC = UTIL_ExtractNumbers( CFG->GetString( "map_crc", string( ) ), 4 );
}
m_MapCRC = MapCRC;
if( MapSHA1.empty( ) )
MapSHA1 = UTIL_ExtractNumbers( CFG->GetString( "map_sha1", string( ) ), 20 );
else if( CFG->Exists( "map_sha1" ) )
{
CONSOLE_Print( "[MAP] overriding calculated map_sha1 with config value map_sha1 = " + CFG->GetString( "map_sha1", string( ) ) );
MapSHA1 = UTIL_ExtractNumbers( CFG->GetString( "map_sha1", string( ) ), 20 );
}
m_MapSHA1 = MapSHA1;
m_MapSpeed = CFG->GetInt( "map_speed", MAPSPEED_FAST );
m_MapVisibility = CFG->GetInt( "map_visibility", MAPVIS_DEFAULT );
m_MapObservers = CFG->GetInt( "map_observers", MAPOBS_NONE );
m_MapFlags = CFG->GetInt( "map_flags", MAPFLAG_TEAMSTOGETHER | MAPFLAG_FIXEDTEAMS );
m_MapGameType = CFG->GetInt( "map_gametype", 1 );
if( MapWidth.empty( ) )
MapWidth = UTIL_ExtractNumbers( CFG->GetString( "map_width", string( ) ), 2 );
else if( CFG->Exists( "map_width" ) )
{
CONSOLE_Print( "[MAP] overriding calculated map_width with config value map_width = " + CFG->GetString( "map_width", string( ) ) );
MapWidth = UTIL_ExtractNumbers( CFG->GetString( "map_width", string( ) ), 2 );
}
m_MapWidth = MapWidth;
if( MapHeight.empty( ) )
MapHeight = UTIL_ExtractNumbers( CFG->GetString( "map_height", string( ) ), 2 );
else if( CFG->Exists( "map_height" ) )
{
CONSOLE_Print( "[MAP] overriding calculated map_height with config value map_height = " + CFG->GetString( "map_height", string( ) ) );
MapHeight = UTIL_ExtractNumbers( CFG->GetString( "map_height", string( ) ), 2 );
}
m_MapHeight = MapHeight;
m_MapType = CFG->GetString( "map_type", string( ) );
m_MapMatchMakingCategory = CFG->GetString( "map_matchmakingcategory", string( ) );
m_MapStatsW3MMDCategory = CFG->GetString( "map_statsw3mmdcategory", string( ) );
m_MapDefaultHCL = CFG->GetString( "map_defaulthcl", string( ) );
m_MapLoadInGame = CFG->GetInt( "map_loadingame", 0 ) == 0 ? false : true;
if( MapNumPlayers == 0 )
MapNumPlayers = CFG->GetInt( "map_numplayers", 0 );
else if( CFG->Exists( "map_numplayers" ) )
{
CONSOLE_Print( "[MAP] overriding calculated map_numplayers with config value map_numplayers = " + CFG->GetString( "map_numplayers", string( ) ) );
MapNumPlayers = CFG->GetInt( "map_numplayers", 0 );
}
m_MapNumPlayers = MapNumPlayers;
if( MapNumTeams == 0 )
MapNumTeams = CFG->GetInt( "map_numteams", 0 );
else if( CFG->Exists( "map_numteams" ) )
{
CONSOLE_Print( "[MAP] overriding calculated map_numteams with config value map_numteams = " + CFG->GetString( "map_numteams", string( ) ) );
MapNumTeams = CFG->GetInt( "map_numteams", 0 );
}
m_MapNumTeams = MapNumTeams;
if( Slots.empty( ) )
{
for( uint32_t Slot = 1; Slot <= 12; Slot++ )
{
string SlotString = CFG->GetString( "map_slot" + UTIL_ToString( Slot ), string( ) );
if( SlotString.empty( ) )
break;
BYTEARRAY SlotData = UTIL_ExtractNumbers( SlotString, 9 );
Slots.push_back( CGameSlot( SlotData ) );
}
}
else if( CFG->Exists( "map_slot1" ) )
{
CONSOLE_Print( "[MAP] overriding slots" );
Slots.clear( );
for( uint32_t Slot = 1; Slot <= 12; Slot++ )
{
string SlotString = CFG->GetString( "map_slot" + UTIL_ToString( Slot ), string( ) );
if( SlotString.empty( ) )
break;
BYTEARRAY SlotData = UTIL_ExtractNumbers( SlotString, 9 );
Slots.push_back( CGameSlot( SlotData ) );
}
}
m_Slots = Slots;
// if random races is set force every slot's race to random + fixed
if( m_MapFlags & MAPFLAG_RANDOMRACES )
{
CONSOLE_Print( "[MAP] forcing races to random" );
for( vector<CGameSlot> :: iterator i = m_Slots.begin( ); i != m_Slots.end( ); i++ )
(*i).SetRace( SLOTRACE_RANDOM | SLOTRACE_FIXED );
}
// add observer slots
if( m_MapObservers == MAPOBS_ALLOWED || m_MapObservers == MAPOBS_REFEREES )
{
CONSOLE_Print( "[MAP] adding " + UTIL_ToString( 12 - m_Slots.size( ) ) + " observer slots" );
while( m_Slots.size( ) < 12 )
m_Slots.push_back( CGameSlot( 0, 255, SLOTSTATUS_OPEN, 0, 12, 12, SLOTRACE_RANDOM ) );
}
CheckValid( );
}
void CMap :: CheckValid( )
{
if( m_MapPath.empty( ) )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_path detected" );
}
else if( m_MapPath[0] == '\\' )
CONSOLE_Print( "[MAP] warning - map_path starts with '\\', any replays saved by GHost++ will not be playable in Warcraft III" );
if( m_MapSize.size( ) != 4 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_size detected" );
}
/*
else if( !m_MapData.empty( ) && m_MapData.size( ) != UTIL_ByteArrayToUInt32( m_MapSize, false ) )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_size detected - size mismatch with map data" );
}
*/
if( m_MapInfo.size( ) != 4 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_info detected" );
}
if( m_MapCRC.size( ) != 4 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_crc detected" );
}
if( m_MapSHA1.size( ) != 20 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_sha1 detected" );
}
if( m_MapSpeed != MAPSPEED_SLOW && m_MapSpeed != MAPSPEED_NORMAL && m_MapSpeed != MAPSPEED_FAST )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_speed detected" );
}
if( m_MapVisibility != MAPVIS_HIDETERRAIN && m_MapVisibility != MAPVIS_EXPLORED && m_MapVisibility != MAPVIS_ALWAYSVISIBLE && m_MapVisibility != MAPVIS_DEFAULT )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_visibility detected" );
}
if( m_MapObservers != MAPOBS_NONE && m_MapObservers != MAPOBS_ONDEFEAT && m_MapObservers != MAPOBS_ALLOWED && m_MapObservers != MAPOBS_REFEREES )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_observers detected" );
}
// todotodo: m_MapFlags
if( m_MapGameType != 1 && m_MapGameType != 2 && m_MapGameType != 9 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_gametype detected" );
}
if( m_MapWidth.size( ) != 2 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_width detected" );
}
if( m_MapHeight.size( ) != 2 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_height detected" );
}
if( m_MapNumPlayers == 0 || m_MapNumPlayers > 12 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_numplayers detected" );
}
if( m_MapNumTeams == 0 || m_MapNumTeams > 12 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_numteams detected" );
}
if( m_Slots.empty( ) || m_Slots.size( ) > 12 )
{
m_Valid = false;
CONSOLE_Print( "[MAP] invalid map_slot<x> detected" );
}
}
uint32_t CMap :: XORRotateLeft( unsigned char *data, uint32_t length )
{
// a big thank you to Strilanc for figuring this out
uint32_t i = 0;
uint32_t Val = 0;
if( length > 3 )
{
while( i < length - 3 )
{
Val = ROTL( Val ^ ( (uint32_t)data[i] + (uint32_t)( data[i + 1] << 8 ) + (uint32_t)( data[i + 2] << 16 ) + (uint32_t)( data[i + 3] << 24 ) ), 3 );
i += 4;
}
}
while( i < length )
{
Val = ROTL( Val ^ data[i], 3 );
i++;
}
return Val;
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
39
],
[
41,
45
],
[
48,
54
],
[
56,
680
],
[
683,
774
],
[
785,
883
]
],
[
[
40,
40
],
[
46,
47
],
[
55,
55
],
[
681,
682
],
[
775,
784
]
]
] |
df08ea29c33951dda93f8975b69728c10f07dcb7 | 3a4f758867cea56d94e09eaa52da885ead606855 | /src/game/server/DeBugger.cpp | aa0c9d0cc66074290740ff09cbe56bd1773c9407 | [
"Zlib",
"LicenseRef-scancode-other-permissive"
] | permissive | EliteKuchen/AiP-DDRace | 4496baf79d73997b76e001e11c9a1b61a2f38692 | e17f5db8244511e6eb30ca960006df702cfa1139 | refs/heads/master | 2021-01-18T09:39:03.310356 | 2011-04-09T15:12:59 | 2011-04-09T15:12:59 | 1,432,193 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,521 | cpp | #include <iostream>
#include <cstring>
#include <fstream>
#include <sys/stat.h>
bool file_exists(const char* strFilename)
{
struct stat stFileInfo;
bool blnReturn;
int intStat;
intStat = stat(strFilename,&stFileInfo);
if(intStat == 0) {
blnReturn = true;
}
else
blnReturn = false;
return(blnReturn);
}
#include <string>
#include <sstream>
#include "gamecontext.h"
#include <string.h>
#include <engine/shared/config.h>
#include <engine/server/server.h>
#include "DeBugger.h"
using namespace std;
std::string DeBugger::get_temp_path(const char* art)
{
std::ostringstream oss;
char buf[256];
str_format(buf, sizeof(buf), "%s", art);
oss << buf << ".txt";
return oss.str();
}
void DeBugger::Add(int id,const char* msg, const char* art)
{
char TmpIP[128];
GameServer()->Server()->GetClientIP(id, TmpIP, sizeof(TmpIP));
std::ofstream ofs(get_temp_path(art).c_str(), ios_base::in | ios_base::out | ios_base::app);
ofs << "IP : " << TmpIP << std::endl << "NAME : " << GameServer()->Server()->ClientName(id) << std::endl
<< "MSG : " << msg << std::endl << "--------------------------------------------------" << std::endl ;
ofs.close();
}
void DeBugger::AddNoId(const char* msg, const char* art)
{
std::ofstream ofs(get_temp_path(art).c_str(), ios_base::in | ios_base::out | ios_base::app);
ofs << std::endl << "MSG : " << msg << std::endl << "--------------------------------------------------" << std::endl ;
ofs.close();
}
| [
"[email protected]"
] | [
[
[
1,
60
]
]
] |
51a940dd4019054985b6953ab6243c9da2566cb8 | 65c92f6c171a0565fe5275ecc48033907090d69d | /Client/Plugins/Mail/Implementation/MailSmallWidget.h | b46c94eff89cc74996a8c0856ab51ec6205912a6 | [] | no_license | freakyzoidberg/horus-edu | 653ac573887d83a803ddff1881924ab82b46f5f6 | 2757766a6cb8c1f1a1b0a8e209700e6e3ccea6bc | refs/heads/master | 2020-05-20T03:08:15.276939 | 2010-01-07T14:34:51 | 2010-01-07T14:34:51 | 32,684,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | #ifndef __MAILSMALLWIDGET_H__
# define __MAILSMALLWIDGET_H__
# include <QWidget>
# include "../../../../Common/DataImplementations/MailData/MailDataPlugin.h"
class MailSmallWidget : public QWidget
{
Q_OBJECT
public:
MailSmallWidget(MailDataPlugin *mailPlugin);
private:
MailDataPlugin *_mailPlugin;
};
#endif
| [
"val@cb2ab776-01a4-11df-b136-7f7962f7bc17"
] | [
[
[
1,
19
]
]
] |
4beae60bf04547d908b349da051d2d14611e4e26 | 5b61b21b4ee18488e9bc1074ea32ed20c62f9633 | /Reader/mainprogram.cpp | d7fc4e178c9cd31bd3a33661c56e679877328b95 | [] | no_license | mohammadharisbaig/opencv-kinect | ca8905e0c32b65b6410adf2a73e70562f1633fb0 | e1dab326d44351da8dec4fa11a8ad1cb65dcfdcb | refs/heads/master | 2016-09-06T17:33:51.809798 | 2011-09-01T21:22:55 | 2011-09-01T21:22:55 | 32,089,782 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | cpp | #include <iostream>
#include <cstdlib>
#include "reader.h"
#include <cv.h>
#include <highgui.h>
int main()
{
// Opening a file
Reader aReader("E:\\OldDesktop\\UniquePosesFromEntireCMUMocap\\Unique_01_01.bvh","Unique_01_01.bvh");
// Reading the file
aReader.readFile();
// Obtaining a bvh file with unique poses only
aReader.uniquePoseIdentification();
// code for visualization of a certain structure is given below
// make a window
for (int runView=0;runView<aReader.getTotalFrames();runView++)
{
// Code for applying a frame and then viewing it
FrameBVH aFrame = aReader.getFrame(runView);
Pose testPose;
Structure poseStructure = testPose.adoptPose(aReader.getStructure(),aFrame);
cv::Mat thePoseImage = poseStructure.visualizeStructure();
// display the image
cv::namedWindow("The Output",CV_WINDOW_AUTOSIZE);
cv::imshow("The Output",thePoseImage);
cv::waitKey(2000);
}
// function for visualization of the Mat
system("PAUSE");
}
| [
"[email protected]@b19eb72c-7a23-c4c4-98cb-0a5561f3c209"
] | [
[
[
1,
42
]
]
] |
77c71be7c9ccc41f2405df6a7d79e226c50d757c | d9a78f212155bb978f5ac27d30eb0489bca87c3f | /PB/src/PbFt/ftlistclicker.cpp | c34a05ee909e08febd196ec49436c6e835950449 | [] | no_license | marchon/pokerbridge | 1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c | 97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9 | refs/heads/master | 2021-01-10T07:15:26.496252 | 2010-05-17T20:01:29 | 2010-05-17T20:01:29 | 36,398,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,466 | cpp | #include "stdafx.h"
#include "ftlist.h"
#include "ftlistclicker.h"
#include "ftlobby.h"
#include "fttourneys.h"
#include "fttourneylobby.h"
#include "fttourneylist.h"
#include "fttables.h"
#include "fttable.h"
void FTListFilter::add(QString column, QString value)
{
_filters[column].append(value);
}
bool FTListFilter::filter(FTList *list, int row)
{
bool include = false;
bool exclude = false;
Q_FOREACH(QString scol, _filters.keys())
{
QList<QString> &filts = _filters[scol];
int col = list->indexOfColumn(scol);
if(col>=0)
{
QString value = list->value(row,col);
if(filts.indexOf(value)>=0)
{
qLog(Debug)<<"INCL: "<<value;
include=true;
}else
{
qLog(Debug)<<"EXCL: "<<value;
exclude=true;
}
}
}
return include && !exclude;
}
/////////
FTListClicker::FTListClicker(QObject *parent) : FTTask(parent)
{
_listName = ftSngLobbyModel;
_firstRow = 0;
_deltaRow = 1;
_currentRow = 0;
_currentColumn = 0;
_timer = -1;
_speed = 2000;
_state = Inactive;
connect(lobby()->lists(), SIGNAL(listUpdatedEvent(FTList*)), this, SLOT(onListUpdated(FTList*)));
}
FTListClicker::~FTListClicker()
{
if(isRunning())
stop();
}
bool FTListClicker::isRunning()
{
return _state!=Inactive;
}
FTLobby *FTListClicker::lobby()
{
return FTLobby::instance();
}
void FTListClicker::start()
{
if(_timer!=-1)
{
//qLog(Info)<<"FTListClicker failed to start, timer=="<<_timer;
return;
}
if(_state!=Inactive)
{
//qLog(Info)<<"FTListClicker failed to start, Inactive!=state="<<_state;
return;
}
_timer = startTimer(_speed);
_state = WaitListUpdate;
srand(QTime::currentTime().msec());
//qLog(Info)<<"FTListClicker started";
}
void FTListClicker::stop()
{
if(_timer==-1)
{
qLog(Info)<<"FTListClicker stop() called without start()";
return;
}
//qLog(Info)<<"FTListClicker timer stopping";
killTimer(_timer);
_state = Inactive;
_timer=-1;
}
void FTListClicker::timerEvent(QTimerEvent *e)
{
checkState();
if(_state==Inactive)
{
return;
}
//qLog(Info)<<metaObject()->className()<<"::timerEvent()";
if(_state==Idle)
{
_state = WaitListUpdate;
qLog(Info)<<"waiting for list";
}
if(_state==Click)
if(!isPaused())
{
Q_ASSERT(_list);
if(_list)
{
if(_filter.filter(_list, _currentRow))
{
qLog(Info)<<"click row "<<_currentRow <<" of "<<_list->rowCount();
_list->dblClick(_currentRow, _currentColumn);
}
int group = _currentRow/_deltaRow;
int totgroups = _list->rowCount()/_deltaRow+1;
group = rand()%totgroups;
group--;
_currentRow=(group+1)*_deltaRow+_firstRow;
qLog(Debug)<<"next row=("<<group+1<<")*"<<_deltaRow<<"+"<<_firstRow<<"="<<_currentRow;
if(_currentRow>=_list->rowCount())
{
_currentRow = _firstRow;
//_state=Idle;
//qLog(Info)<<" state->Idle, end of the list at row="<<_list->rowCount();
qLog(Info)<<" rolling to start of the list";
}
}
}
}
void FTListClicker::checkState()
{
}
bool FTListClicker::isPaused()
{
return false;
}
void FTListClicker::onListUpdated(FTList *list)
{
if(_state==WaitListUpdate)
{
if(list->objectName()==_listName)
{
_list = list;
listFound();
}
}
}
void FTListClicker::listFound()
{
_currentRow = _firstRow;
_state = Click;
//qLog(Info)<<"FTListClicker state->Click";
}
| [
"mikhail.mitkevich@a5377438-2eb2-11df-b28a-19025b8c0740",
"[email protected]"
] | [
[
[
1,
28
],
[
33,
33
],
[
37,
37
],
[
39,
40
],
[
42,
89
],
[
91,
135
],
[
137,
138
],
[
141,
178
]
],
[
[
29,
32
],
[
34,
36
],
[
38,
38
],
[
41,
41
],
[
90,
90
],
[
136,
136
],
[
139,
140
]
]
] |
c4ace824e94759a7e753dbdafd12e2ca05c65d63 | bdb3285ca82652273884660e0473ed66337f6532 | /tokamaksrc/src/cylinder.cpp | feda324e3f72fc7ba563545408b0c1b02b63aa66 | [
"Zlib",
"BSD-3-Clause"
] | permissive | svn2github/tokamak | 77171475d580a8dedbb5aca9d08e1e24c96f4a7c | 3a43e7c8afa6686ff68ed3a6e11b701067d3f7f8 | refs/heads/master | 2020-06-03T11:00:08.483224 | 2010-03-22T10:46:59 | 2010-03-22T10:46:59 | 26,491,875 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 17,901 | cpp | /*************************************************************************
* *
* Tokamak Physics Engine, Copyright (C) 2002-2007 David Lam. *
* All rights reserved. Email: [email protected] *
* Web: www.tokamakphysics.com *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *
* LICENSE.TXT for more details. *
* *
*************************************************************************/
#include "tokamak.h"
#include "containers.h"
#include "scenery.h"
#include "collision.h"
#include "collision2.h"
#include "constraint.h"
#include "rigidbody.h"
#include <assert.h>
#include <stdio.h>
//extern void DrawLine(const neV3 & colour, neV3 * startpoint, s32 count);
void Cylinder2TerrainTest(neCollisionResult & result, TConvex & cylinderA, neT3 & transA, TConvex & terrainB)
{
neSimpleArray<s32> & _triIndex = *terrainB.as.terrain.triIndex;
s32 triangleCount = _triIndex.GetUsedCount();
neArray<neTriangle_> & triangleArray = *terrainB.as.terrain.triangles;
ConvexTestResult res[2];
s32 finalTriIndex = -1;
s32 currentRes = 1;
s32 testRes = 0;
res[currentRes].depth = -1.0e6f;
res[currentRes].valid = false;
res[testRes].depth = 1.0e6f;
s32 terrainMatID = 0;
for (s32 i = 0; i < triangleCount; i++)
{
s32 test = _triIndex[i];
neTriangle_ * t = &triangleArray[_triIndex[i]];
TriangleParam triParam;
triParam.vert[0] = terrainB.vertices[t->indices[0]];
triParam.vert[1] = terrainB.vertices[t->indices[1]];
triParam.vert[2] = terrainB.vertices[t->indices[2]];
triParam.edges[0] = triParam.vert[1] - triParam.vert[0];
triParam.edges[1] = triParam.vert[2] - triParam.vert[1];
triParam.edges[2] = triParam.vert[0] - triParam.vert[2];
triParam.normal = triParam.edges[0].Cross(triParam.edges[1]);
triParam.normal.Normalize();
triParam.d = triParam.normal.Dot(triParam.vert[0]);
if (t->flag == neTriangle::NE_TRI_TRIANGLE)
{
if (CylinderTriTest(cylinderA, transA, res[testRes], triParam))
{
if (res[testRes].depth > res[currentRes].depth)
{
s32 tmp = testRes;
testRes = currentRes;
currentRes = tmp;
terrainMatID = t->materialID;
finalTriIndex = _triIndex[i];
}
}
}
else if (t->flag == neTriangle::NE_TRI_HEIGHT_MAP)
{
}
else
{
ASSERT(0);
}
}
if (res[currentRes].valid)
{
/* {
neV3 points[4];
neV3 red;
neTriangle_ * t = &triangleArray[finalTriIndex];
points[0] = terrainB.vertices[t->indices[0]];
points[1] = terrainB.vertices[t->indices[1]];
points[2] = terrainB.vertices[t->indices[2]];
points[3] = terrainB.vertices[t->indices[0]];
DrawLine(red, points, 4);
}
*/ result.penetrate = true;
result.depth = res[currentRes].depth;
result.collisionFrame[2] = res[currentRes].contactNormal;
result.materialIdB = terrainMatID;
result.contactA = res[currentRes].contactA;
result.contactB = res[currentRes].contactB;
}
else
{
result.penetrate = false;
}
}
neBool CylinderTriTest_PlaneEnd(TConvex & cylinder, neT3 & trans, ConvexTestResult & result, TriangleParam & tri)
{
f32 dist = trans.pos.Dot(tri.normal) - tri.d;
neV3 dir;
if (dist >= 0.0f)
{
dir = tri.normal * -1.0f;
dist *= -1.0f;
}
else
{
dir = tri.normal;
}
if (neAbs(dist) >= ( cylinder.CylinderHalfHeight() + cylinder.CylinderRadius()))
return false;
neV3 contactPoint = trans.pos;
neV3 l = trans.rot[1] * cylinder.CylinderHalfHeight();
f32 dot = l.Dot(dir);
if (dot > 0.0f)
{
contactPoint += l;
dist += dot;
}
else
{
contactPoint -= l;
dist -= dot;
}
contactPoint += dir * cylinder.CylinderRadius();
dist += cylinder.CylinderRadius();
if (dist <= 0.0f)
return false;
if (dist >= result.depth)
return true;
neV3 project = contactPoint - dir * dist;
if (tri.IsPointInside(project) != -1)
return true;
neV3 project2;
project2.GetIntersectPlane(dir, tri.vert[0], trans.pos, contactPoint);
s32 region = tri.IsPointInside(project2);
if (region != -1)
return true;
result.valid = true;
result.depth = dist;
result.contactA = contactPoint; // on the cylinder
result.contactB = project; // on the triangle
result.contactNormal = dir * -1.0f;
return true;
}
neBool CylinderTriTest_Line(TConvex & cylinder, neT3 & trans, ConvexTestResult & result, neV3 & point1, neV3 & point2)
{
ConvexTestResult cr;
cr.edgeA[0] = trans.pos + trans.rot[1] * cylinder.CylinderHalfHeight();
cr.edgeA[1] = trans.pos - trans.rot[1] * cylinder.CylinderHalfHeight();
cr.edgeB[0] = point1;
cr.edgeB[1] = point2;
f32 au, bu;
if (!cr.ComputerEdgeContactPoint2(au, bu))
return true;
f32 depth = cylinder.CylinderRadius() - cr.depth;
if (depth <= 0.0f)
return false;
if (depth >= result.depth)
return true;
if (cr.valid)
{
result.depth = depth;
result.valid = true;
result.contactA = cr.contactA;
result.contactB = cr.contactB;
result.contactNormal = trans.rot[1].Cross(point1 - point2);
result.contactNormal.Normalize();
neV3 diff = cr.contactA - cr.contactB;
if (diff.Dot(result.contactNormal) < 0.0f)
{
result.contactNormal *= -1.0f;
}
result.contactA -= result.contactNormal * cylinder.CylinderRadius();
}
else
{
if (au > 0.0f && au < 1.0f)
{
// vertex of line and trunk of cylinder
neV3 vert;
if (bu <= 0.0f)
{
//point1
vert = point1;
}
else
{
//point2
vert = point2;
}
neV3 project;
f32 depth = vert.GetDistanceFromLine2(project, cr.edgeA[0], cr.edgeA[1]);
depth = cylinder.CylinderRadius() - depth;
if (depth <= 0.0f)
return false;
if (depth >= result.depth)
return true;
result.depth = depth;
result.valid = true;
result.contactB = vert;
result.contactNormal = project - vert;
result.contactNormal.Normalize();
result.contactA = project - result.contactNormal * cylinder.CylinderRadius();
}
else
{
neV3 cylinderVert;
if (au <= 0.0f)
{
cylinderVert = cr.edgeA[0];
}
else // au >= 1.0f
{
cylinderVert = cr.edgeA[1];
}
if (bu > 0.0f && bu < 1.0f)
{
// cylinderVert and edge
neV3 project;
f32 depth = cylinderVert.GetDistanceFromLine2(project, cr.edgeB[0], cr.edgeB[1]);
depth = cylinder.CylinderRadius() - depth;
if (depth <= 0.0f)
return false;
if (depth >= result.depth)
return true;
result.depth = depth;
result.valid = true;
result.contactB = project;
result.contactNormal = cylinderVert - project;
result.contactNormal.Normalize();
result.contactA = cylinderVert - result.contactNormal * cylinder.CylinderRadius();
}
else
{
neV3 lineVert;
if (bu <= 0.0f)
{
//point1
lineVert = point1;
}
else
{
//point2
lineVert = point2;
}
neV3 diff = cylinderVert - lineVert;
f32 depth = diff.Dot(diff);
if (depth >= cylinder.CylinderRadiusSq())
return false;
depth = sqrtf(depth);
depth = cylinder.CylinderRadius() - depth;
if (depth >= result.depth)
return true;
result.depth = depth;
result.valid = true;
result.contactB = lineVert;
result.contactNormal = diff;
result.contactNormal.Normalize();
result.contactA = cylinderVert - result.contactNormal * cylinder.CylinderRadius();
}
}
}
return true;
}
neBool CylinderTriTest(TConvex & cylinder, neT3 & trans, ConvexTestResult & result, TriangleParam & tri)
{
// test plane of triangle and rim of cylinder
result.valid = false;
result.depth = 1.0e6f;
result.needTransform = false;
if (!CylinderTriTest_PlaneEnd(cylinder, trans, result, tri))
return false;
if (!result.valid)
{
result.valid = false;
result.depth = 1.0e6f;
result.needTransform = false;
for (s32 i = 0; i < 3; i++)
{
CylinderTriTest_Line(cylinder, trans, result, tri.vert[i], tri.vert[neNextDim1[i]]);
}
}
return result.valid;
}
void TestCylinderVertEdge(neCollisionResult & result, neV3 & edgeA1, neV3 & edgeA2, neV3 & vertB,
TConvex & cA, TConvex & cB, neT3 & transA, neT3 & transB, neBool flip)
{
neV3 project;
f32 dist = vertB.GetDistanceFromLine2(project, edgeA1, edgeA2);
f32 depth = cA.CylinderRadius() + cB.CylinderRadius() - dist;
if (depth <= 0.0f)
return;
if (depth <= result.depth)
return;
result.penetrate = true;
result.depth = depth;
if (!flip)
{
result.collisionFrame[2] = project - vertB;
result.collisionFrame[2].Normalize();
result.contactA = project - result.collisionFrame[2] * cA.CylinderRadius();
result.contactB = vertB + result.collisionFrame[2] * cB.CylinderRadius();
}
else
{
result.collisionFrame[2] = vertB - project;
result.collisionFrame[2].Normalize();
result.contactA = vertB - result.collisionFrame[2] * cB.CylinderRadius();
result.contactB = project + result.collisionFrame[2] * cA.CylinderRadius();
}
}
void TestCylinderVertVert(neCollisionResult & result, neV3 & vertA, neV3 & vertB,
TConvex & cA, TConvex & cB, neT3 & transA, neT3 & transB)
{
neV3 diff = vertA - vertB;
f32 dist = diff.Length();
f32 depth = cA.CylinderRadius() + cB.CylinderRadius() - dist;
if (depth <= 0.0f)
return;
if (depth <= result.depth)
return;
result.penetrate = true;
result.depth = depth;
result.collisionFrame[2] = diff * (1.0f / dist);
result.contactA = vertA - result.collisionFrame[2] * cA.CylinderRadius();
result.contactB = vertB + result.collisionFrame[2] * cB.CylinderRadius();
}
void Cylinder2CylinderTest(neCollisionResult & result, TConvex & cA, neT3 & transA, TConvex & cB, neT3 & transB)
{
result.penetrate = false;
neV3 dir = transA.rot[1].Cross(transB.rot[1]);
f32 len = dir.Length();
neBool isParallel = neIsConsiderZero(len);
s32 doVertCheck = 0;
ConvexTestResult cr;
cr.edgeA[0] = transA.pos + transA.rot[1] * cA.CylinderHalfHeight();
cr.edgeA[1] = transA.pos - transA.rot[1] * cA.CylinderHalfHeight();
cr.edgeB[0] = transB.pos + transB.rot[1] * cB.CylinderHalfHeight();
cr.edgeB[1] = transB.pos - transB.rot[1] * cB.CylinderHalfHeight();
f32 dot = transA.rot[1].Dot(transB.rot[1]);
if (!neIsConsiderZero(len))
{
f32 au, bu;
cr.ComputerEdgeContactPoint2(au, bu);
if (cr.valid)
{
f32 depth = cA.CylinderRadius() + cB.CylinderRadius() - cr.depth;
if (depth <= 0.0f)
return;
result.depth = depth;
result.penetrate = true;
result.collisionFrame[2] = cr.contactA - cr.contactB;
result.collisionFrame[2] *= (1.0f / cr.depth);
result.contactA = cr.contactA - result.collisionFrame[2] * cA.CylinderRadius();
result.contactB = cr.contactB + result.collisionFrame[2] * cB.CylinderRadius();
return;
}
}
result.depth = -1.0e6f;
s32 i;
for (i = 0; i < 2; i++)
{
//project onto edge b
neV3 diff = cr.edgeA[i] - cr.edgeB[1];
f32 dot = diff.Dot(transB.rot[1]);
if (dot < 0.0f)
{
TestCylinderVertVert(result, cr.edgeA[i], cr.edgeB[1], cA, cB, transA, transB);
}
else if (dot > (2.0f * cB.CylinderHalfHeight()))
{
TestCylinderVertVert(result, cr.edgeA[i], cr.edgeB[0], cA, cB, transA, transB);
}
else
{
TestCylinderVertEdge(result, cr.edgeB[0], cr.edgeB[1], cr.edgeA[i], cB, cA, transB, transA, true);
}
}
for (i = 0; i < 2; i++)
{
//project onto edge b
neV3 diff = cr.edgeB[i] - cr.edgeA[1];
f32 dot = diff.Dot(transA.rot[1]);
if (dot < 0.0f)
{
TestCylinderVertVert(result, cr.edgeB[i], cr.edgeA[1], cA, cB, transA, transB);
}
else if (dot > (2.0f * cB.CylinderHalfHeight()))
{
TestCylinderVertVert(result, cr.edgeB[i], cr.edgeA[0], cA, cB, transA, transB);
}
else
{
TestCylinderVertEdge(result, cr.edgeA[0], cr.edgeA[1], cr.edgeB[i], cA, cB, transA, transB, false);
}
}
}
void Cylinder2SphereTest(neCollisionResult & result, TConvex & cylinderA, neT3 & transA, TConvex & sphereB, neT3 & transB)
{
result.penetrate = false;
neV3 cylinderTop = transA.pos + transA.rot[1] * cylinderA.CylinderHalfHeight();
neV3 cylinderBottom = transA.pos - transA.rot[1] * cylinderA.CylinderHalfHeight();
neV3 diff0 = transB.pos - cylinderBottom;
f32 k = diff0.Dot(transA.rot[1]);
if (k >= (2.0f * cylinderA.CylinderHalfHeight() + cylinderA.CylinderRadius() + sphereB.Radius()))
return;
if (k <= -(cylinderA.CylinderRadius() + sphereB.Radius()))
return;
neV3 project;
if (k > 2.0f * cylinderA.CylinderHalfHeight()) //cylinderTop
{
project = cylinderTop;
}
else if (k < 0.0f)
{
project = cylinderBottom;
}
else
{
project = cylinderBottom + k * transA.rot[1];
}
neV3 diff1 = project - transB.pos;
f32 dist = diff1.Dot(diff1);
dist = sqrtf(dist);
if (dist >= (cylinderA.CylinderRadius() + sphereB.Radius()))
return;
f32 depth = cylinderA.CylinderRadius() + sphereB.Radius() - dist;
ASSERT(depth > 0.0f);
result.penetrate = true;
result.depth = depth;
if (!neIsConsiderZero(dist))
result.collisionFrame[2] = diff1 * (1.0f / dist);
else
result.collisionFrame[2] = transA.rot[0];
result.contactA = project - result.collisionFrame[2] * cylinderA.CylinderRadius();
result.contactB = transB.pos + result.collisionFrame[2] * cylinderA.CylinderRadius();
}
/*
void Box2CylinderTest(neCollisionResult & result, TConvex & boxA, neT3 & transA, TConvex & cylinderB, neT3 & transB)
{
result.penetrate = false;
ConvexTestResult res;
res.valid = false;
res.depth = 1.0e6f;
BoxTestParam boxParamA;
boxParamA.convex = &boxA;
boxParamA.trans = &transA;
boxParamA.radii[0] = transA.rot[0] * boxA.BoxSize(0);
boxParamA.radii[1] = transA.rot[1] * boxA.BoxSize(1);
boxParamA.radii[2] = transA.rot[2] * boxA.BoxSize(2);
for (s32 i = 0; i < 3; i++)
{
if (!boxParamA.CylinderFaceTest(res, cylinderB, transB, i))
return;
}
if (!res.valid)
{
for (s32 i = 0; i < 3; i++)
{
if (!boxParamA.CylinderEdgeTest(res, cylinderB, transB, i))
return;
}
}
if (res.valid)
{
result.penetrate = true;
result.depth = res.depth;
result.collisionFrame[2] = res.contactNormal;
result.contactA = res.contactA;
result.contactB = res.contactB;
}
}
*/
void ClosestLine2Box(const neV3 & p1, const neV3 & p2, const neV3 & boxSize, neV3 & lret, neV3 & bret)
{
neV3 sign, s, v;
s = p1;
v = p2 - p1;
s32 i;
for (i = 0; i < 3; i++)
{
if (v[i] < 0.0f)
{
s[i] = -s[i];
v[i] = -v[i];
sign[i] = -1.0f;
}
else
{
sign[i] = 1.0f;
}
}
neV3 v2; v2 = v * v;
neV3 h; h = boxSize;
int region[3];
neV3 tanchor;
for (i = 0; i < 3; i++)
{
if (v[i] > 0.0f)
{
if (s[i] < -h[i])
{
region[i] = -1;
tanchor[i] = (-h[i] - s[i]) / v[i];
}
else
{
region[i] = (s[i] > h[i]);
tanchor[i] = (h[i] - s[i]) / v[i];
}
}
else
{
region[i] = 0;
tanchor[i] = 2;
}
}
f32 t = 0;
f32 dd2dt = 0;
for (i = 0; i < 3; i++)
{
dd2dt -= (region[i] ? v2[i] : 0) * tanchor[i];
}
if (dd2dt >= 0.0f)
goto got_answer;
do {
f32 next_t = 1;
for (i = 0; i < 3; i++)
{
if (tanchor[i] > t && tanchor[i] < 1 && tanchor[i] < next_t)
next_t = tanchor[i];
}
f32 next_dd2dt = 0;
for (i=0; i<3; i++)
{
next_dd2dt += (region[i] ? v2[i] : 0) * (next_t - tanchor[i]);
}
if (next_dd2dt >= 0)
{
f32 m = (next_dd2dt-dd2dt)/(next_t - t);
t -= dd2dt/m;
goto got_answer;
}
for (i=0; i<3; i++) {
if (tanchor[i] == next_t)
{
tanchor[i] = (h[i]-s[i])/v[i];
region[i]++;
}
}
t = next_t;
dd2dt = next_dd2dt;
} while(t < 1);
t = 1;
got_answer:
neV3 diff = p2 - p1;
lret = p1 + diff * t;
for (i=0; i<3; i++)
{
bret[i] = sign[i] * (s[i] + t*v[i]);
if (bret[i] < -h[i])
bret[i] = -h[i];
else if (bret[i] > h[i])
bret[i] = h[i];
}
}
void Box2CylinderTest(neCollisionResult & result, TConvex & boxA, neT3 & transA, TConvex & cylinderB, neT3 & transB)
{
result.penetrate = false;
ConvexTestResult res;
res.valid = false;
res.depth = 1.0e6f;
neT3 cylinder2box;
cylinder2box = transA.FastInverse();
cylinder2box = cylinder2box * transB;
neV3 c1, c2;
c1 = cylinder2box.pos - cylinder2box.rot[1] * cylinderB.as.cylinder.halfHeight;
c2 = cylinder2box.pos + cylinder2box.rot[1] * cylinderB.as.cylinder.halfHeight;
neV3 lret, bret;
ClosestLine2Box(c1, c2, boxA.as.box.boxSize, lret, bret);
bret = transA * bret;
lret = transA * lret;
neV3 diff;
diff = bret - lret;
f32 dist = diff.Length();
if (dist > cylinderB.as.cylinder.radius)
{
return;
}
result.depth = cylinderB.as.cylinder.radius - dist;
result.penetrate = true;
f32 d1 = 1.0f / dist;
result.contactA = bret;
result.collisionFrame[2] = diff * d1;
result.contactB = (lret + result.collisionFrame[2] * cylinderB.as.cylinder.radius) ;
} | [
"kenshin1987@59b4d5e5-9359-492d-972b-49872f59beb6"
] | [
[
[
1,
803
]
]
] |
ecf3b40631f7d0dba0ea21c7d07647cb51e9925d | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SESharedArrays/SEPlaneArray.cpp | 164b05e222d7ef900d672b5ceebfd0dae40fb21b | [] | no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,170 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEFoundationPCH.h"
#include "SEPlaneArray.h"
using namespace Swing;
SE_IMPLEMENT_TEMPLATE_RTTI(Swing, SEPlane3fArray, SEObject);
SE_IMPLEMENT_TEMPLATE_STREAM(SEPlane3fArray);
//SE_REGISTER_STREAM(SEPlane3fArray);
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
29
]
]
] |
782955ad5dee24b1a6f19607192df44da32c6554 | 03f442e60a836172561ef833ae7eb7e7ed434d49 | /Sudoku/NodeTable.cpp | 7b91a54b8516bcc60dae53087c221007f7bf3eb7 | [] | no_license | wooodblr/sudoku-xiu | b72bed616e437e8ee734bf2b039c3572ad6887d3 | f76d8106d62d422733552eeab675840d8a5e7f20 | refs/heads/master | 2020-04-06T03:40:36.806144 | 2011-04-12T13:44:45 | 2011-04-12T13:44:45 | 42,170,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,225 | cpp | #include "StdAfx.h"
#include "NodeTable.h"
using namespace std;
CNodeTable::CNodeTable(void)
: m_bOne(false)
{
for(int i = 0;i < 9;i ++)
{
for(int j = 0;j < 9;j ++)
{
m_node[i][j].setLoc(i, j);
}
}
}
CNodeTable::~CNodeTable(void)
{
}
CNode* CNodeTable::GetNode(int col, int row)
{
return &m_node[col][row];
}
CNode* CNodeTable::GetFirstNode(int col, int row)
{
return &m_firstNode[col][row];
}
void CNodeTable::initTable(int num[9][9])
{
for(int i = 0;i < 9;i ++)
{
for(int j= 0;j < 9;j ++)
{
if(num[i][j] == 0)
{
m_nodeList[8].AddNode(&m_node[i][j]);
}
else
{
m_node[i][j].setNum(num[i][j]);
m_nodeList[0].AddNode(&m_node[i][j]);
}
}
}
for(CNode* pt = m_nodeList[0].GetHead();pt != NULL;pt = pt->next)
{
delSurround(pt->getData(), pt->getCol(), pt->getRow());
}
while (ConfirmNode());
}
bool CNodeTable::delSurround(int num, int col, int row)
{
for(int i = 0;i < 9;i ++)
{
if(m_node[i][row].removeNum(num))
{
m_nodeList[m_node[i][row].getLen()].RemoveNode(&m_node[i][row]);
m_nodeList[m_node[i][row].getLen() - 1].AddNode(&m_node[i][row]);
if(m_node[i][row].getLen() == 1 &&
!delSurround(m_node[i][row].getData(), m_node[i][row].getCol(), m_node[i][row].getRow()))
{
return false;
}
}
else if(i != col && m_node[i][row].getLen() == 1 && m_node[i][row].getData() == num)
{
return false;
}
}
for(int i = 0;i < 9;i ++)
{
if(m_node[col][i].removeNum(num))
{
m_nodeList[m_node[col][i].getLen()].RemoveNode(&m_node[col][i]);
m_nodeList[m_node[col][i].getLen() - 1].AddNode(&m_node[col][i]);
if(m_node[col][i].getLen() == 1 &&
!delSurround(m_node[col][i].getData(), m_node[col][i].getCol(), m_node[col][i].getRow()))
{
return false;
}
}
else if(i != row && m_node[col][i].getLen() == 1 && m_node[col][i].getData() == num)
{
return false;
}
}
int baseCol = col / 3 * 3;
int baseRow = row / 3 * 3;
//cout << "BaseCol:" << baseCol << "BaseRow:" << baseRow << endl;
for(int i = 0;i < 3;i ++)
{
for(int j = 0;j < 3;j ++)
{
if(m_node[baseCol + i][baseRow + j].removeNum(num))
{
m_nodeList[m_node[baseCol + i][baseRow + j].getLen()].RemoveNode(&m_node[baseCol + i][baseRow + j]);
m_nodeList[m_node[baseCol + i][baseRow + j].getLen() - 1].AddNode(&m_node[baseCol + i][baseRow + j]);
if(m_node[baseCol + i][baseRow + j].getLen() == 1 &&
!delSurround(m_node[baseCol + i][baseRow + j].getData(), m_node[baseCol + i][baseRow + j].getCol(), m_node[baseCol + i][baseRow + j].getRow()))
{
return false;
}
}
else if(!((baseCol + i) == col && (baseRow + j) == row) &&
m_node[baseCol + i][baseRow + j].getLen() == 1 && m_node[baseCol + i][baseRow + j].getData() == num)
{
return false;
}
}
}
return true;
}
int CNodeTable::AwrNum()
{
if(m_nodeList[0].getLen() == 81)
{
if(!m_bOne)
{
for(int i = 0;i < 9;i ++)
{
for(int j = 0;j < 9;j ++)
{
m_firstNode[i][j] = m_node[i][j];
}
}
m_bOne = true;
}
//check whether it's right.
for(int i = 0;i < 9;i ++)
{
bool rowBl[9] = {false};
bool rowCl[9] = {false};
for(int j = 0;j < 9;j ++)
{
if(!rowBl[m_node[i][j].getData() - 1])
{
rowBl[m_node[i][j].getData() - 1] = true;
}
else
{
return 0;
}
if(!rowCl[m_node[j][i].getData() - 1])
{
rowCl[m_node[j][i].getData() - 1] = true;
}
else
{
return 0;
}
}
}
for(int i = 0;i < 3;i ++)
{
for(int j = 0;j < 3;j ++)
{
bool num[9] = {false};
for(int k = 0;k < 3;k ++)
{
for(int l = 0;l < 3;l ++)
{
if(!num[m_node[i * 3 + k][j * 3 + l].getData() - 1])
{
num[m_node[i * 3 + k][j * 3 + l].getData() - 1] = true;
}
else
{
return 0;
}
}
}
}
}
return 1;
}
int lev = 1;
for(lev;m_nodeList[lev].getLen() == 0;lev ++);
/*
for(int lev = 1;lev < 9;lev ++)
{
for(int inListIndex = 0;inListIndex < m_nodeList[lev].getLen();inListIndex ++)
{*/
int result;
bool hasOne = false;
for(int hasNum = 1;hasNum < 10;hasNum ++)
{
if(m_nodeList[lev].GetHead()->hasNum(hasNum))
{
CNode tempNode[9][9];
CNodeList tempNodeList[9];
for(int i = 0;i < 9;i ++)
{
for(int j = 0;j < 9;j ++)
{
tempNode[i][j] = m_node[i][j];
}
tempNodeList[i] = m_nodeList[i];
}
CNode *tempN = m_nodeList[lev].GetHead();
tempN->setNum(hasNum);
m_nodeList[lev].RemoveNode(tempN);
m_nodeList[0].AddNode(tempN);
if(!delSurround(hasNum, tempN->getCol(), tempN->getRow()))
{
result = 0;
}
else
{
//while (ConfirmNode());
result = AwrNum();
}
//Check next.
if(result == 0)
{
for(int i = 0;i < 9;i ++)
{
for(int j = 0;j < 9;j ++)
{
m_node[i][j] = tempNode[i][j];
}
m_nodeList[i] = tempNodeList[i];
}
}
else if(result == 2)
{
return 2;
}
else
{
if(!hasOne)
{
hasOne = true;
for(int i = 0;i < 9;i ++)
{
for(int j = 0;j < 9;j ++)
{
m_node[i][j] = tempNode[i][j];
}
m_nodeList[i] = tempNodeList[i];
}
}
else
{
return 2;
}
}
}
}
if(hasOne)
{
return 1;
}
else
{
//This doesn't have an answer.
return 0;
}
/*
}
}*/
}
bool CNodeTable::ConfirmNode(void)
{
int lev = 1;
for(int lev = 1;lev < 9;lev ++)
{
for(CNode *pt = m_nodeList[lev].GetHead();pt != NULL;pt = pt->next)
{
for(int num = 1;num < 10;num ++)
{
if(pt->hasNum(num))
{
bool otherHas = false;
for(int i = 0;i < 9;i ++)
{
if(m_node[i][pt->getRow()].hasNum(num) && i != pt->getCol())
{
otherHas = true;
break;
}
}
if(otherHas)
{
otherHas = false;
for(int i = 0;i < 9;i ++)
{
if(m_node[pt->getCol()][i].hasNum(num) && i != pt->getRow())
{
otherHas = true;
break;
}
}
}
else
{
goto labelEnd2;
}
if(otherHas)
{
otherHas = false;
int baseRow = pt->getRow() / 3 * 3;
int baseCol = pt->getCol() / 3 * 3;
for(int i = baseRow;i < baseRow + 3;i ++)
{
for(int j = baseCol;j < baseCol + 3;j ++)
{
if(m_node[j][i].hasNum(num) && !(i == pt->getRow() && j == pt->getCol()))
{
otherHas = true;
goto labelEnd2;
}
}
}
}
else
{
goto labelEnd2;
}
labelEnd2:
if(!otherHas)
{
m_nodeList[pt->getLen() - 1].RemoveNode(pt);
pt->setNum(num);
m_nodeList[0].AddNode(pt);
delSurround(num, pt->getCol(), pt->getRow());
return true;
}
}
}
}
}
return false;
}
| [
"[email protected]"
] | [
[
[
1,
373
]
]
] |
6c40416df426805989a9dd1960974df80c425353 | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/CryEngine/CryCommon/Cry_Matrix.h | 3e188393692cf8d9a7485ba256fa16d680968e1b | [] | no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 93,936 | h | //////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:Cry_Matrix.h
// Description: Common matrix class
//
// History:
// -Feb 27,2003: Created by Ivo Herzeg
//
//
//////////////////////////////////////////////////////////////////////
#ifndef MATRIX_H
#define MATRIX_H
#if _MSC_VER > 1000
# pragma once
#endif
template<typename F> struct Matrix33_tpl;
template<typename F, class A> struct Matrix34_tpl;
template<typename F, class A> struct Matrix44_tpl;
//for PS3, the intrinsics generate larger and slower code unfortunately
#if (defined(PS3) || defined(XENON)) && defined(XENON_INTRINSICS)
// #define XENON_INTRINSICS_ENABLED
// #undef XENON_INTRINSICS
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Diag33_tpl
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template<typename F> struct Diag33_tpl {
F x,y,z;
#if defined(_DEBUG) && !defined(__SPU__)
ILINE Diag33_tpl()
{
if (sizeof(F)==4)
{
uint32* p=(uint32*)&x; p[0]=F32NAN; p[1]=F32NAN; p[2]=F32NAN;
}
if (sizeof(F)==8)
{
uint64* p=(uint64*)&x; p[0]=F64NAN; p[1]=F64NAN; p[2]=F64NAN;
}
}
#else
ILINE Diag33_tpl() {};
#endif
Diag33_tpl(F dx,F dy,F dz) { x=dx; y=dy; z=dz; }
Diag33_tpl(const Vec3_tpl<F> &v) { x=v.x; y=v.y; z=v.z; }
template<class F1> const Diag33_tpl& operator=(const Vec3_tpl<F1>& v) { x=v.x; y=v.y; z = v.z; return *this; }
Diag33_tpl& operator=(const Diag33_tpl<F> &diag) { x=diag.x; y=diag.y; z=diag.z; return *this; }
template<class F1> Diag33_tpl& operator=(const Diag33_tpl<F1>& diag) { x=diag.x; y=diag.y; z=diag.z; return *this; }
const void SetIdentity() { x=y=z=1; }
Diag33_tpl(type_identity) { x=y=z=1; }
const Diag33_tpl& zero() { x=y=z=0; return *this; }
Diag33_tpl& fabs() { x=fabs_tpl(x); y=fabs_tpl(y); z=fabs_tpl(z); return *this; }
Diag33_tpl& invert() { // in-place inversion
F det = determinant();
if (det==0) return *this;
det = (F)1.0/det;
F oldata[3]; oldata[0]=x; oldata[1]=y; oldata[2]=z;
x = oldata[1]*oldata[2]*det;
y = oldata[0]*oldata[2]*det;
z = oldata[0]*oldata[1]*det;
return *this;
}
/*!
* Linear-Interpolation between Diag33(lerp)
*
* Example:
* Diag33 r=Diag33::CreateLerp( p, q, 0.345f );
*/
ILINE void SetLerp( const Diag33_tpl<F> &p, const Diag33_tpl<F> &q, F t )
{
const float lerp = (1.0f-t);
x = p.x*lerp + q.x*t;
y = p.y*lerp + q.y*t;
z = p.z*lerp + q.z*t;
}
static ILINE Diag33_tpl<F> CreateLerp( const Diag33_tpl<F> &p, const Diag33_tpl<F> &q, F t )
{
Diag33_tpl<F> d;
const float lerp = (1.0f-t);
d.x = p.x*lerp + q.x*t;
d.y = p.y*lerp + q.y*t;
d.z = p.z*lerp + q.z*t;
return d;
}
F determinant() const { return x*y*z; }
bool IsValid() const
{
if (!NumberValid(x)) return false;
if (!NumberValid(y)) return false;
if (!NumberValid(z)) return false;
return true;
}
};
///////////////////////////////////////////////////////////////////////////////
// Typedefs //
///////////////////////////////////////////////////////////////////////////////
typedef Diag33_tpl<f32> Diag33;
typedef Diag33_tpl<f64> Diag33_f64;
typedef Diag33_tpl<real> Diag33r;
template<class F1, class F2>
Diag33_tpl<F1> operator*(const Diag33_tpl<F1> &l, const Diag33_tpl<F2> &r) {
return Diag33_tpl<F1>( l.x*r.x, l.y*r.y, l.z*r.z );
}
template<class F1, class F2>
Matrix33_tpl<F2> operator*(const Diag33_tpl<F1> &l, const Matrix33_tpl<F2> &r) {
Matrix33_tpl<F2> res;
res.m00 = r.m00*l.x; res.m01 = r.m01*l.x; res.m02 = r.m02*l.x;
res.m10 = r.m10*l.y; res.m11 = r.m11*l.y; res.m12 = r.m12*l.y;
res.m20 = r.m20*l.z; res.m21 = r.m21*l.z; res.m22 = r.m22*l.z;
return res;
}
template<class F1, class F2, class B, class C>
Matrix34_tpl<F2, B> operator*(const Diag33_tpl<F1> &l, const Matrix34_tpl<F2, C> &r) {
Matrix34_tpl<F2, B> m;
m.m00=l.x*r.m00; m.m01=l.x*r.m01; m.m02=l.x*r.m02; m.m03=l.x*r.m03;
m.m10=l.y*r.m10; m.m11=l.y*r.m11; m.m12=l.y*r.m12; m.m13=l.y*r.m13;
m.m20=l.z*r.m20; m.m21=l.z*r.m21; m.m22=l.z*r.m22; m.m23=l.z*r.m23;
return m;
}
template<class F1,class F2>
Vec3_tpl<F2> operator *(const Diag33_tpl<F1> &mtx, const Vec3_tpl<F2> &vec) {
return Vec3_tpl<F2>(mtx.x*vec.x, mtx.y*vec.y, mtx.z*vec.z);
}
template<class F1,class F2>
Vec3_tpl<F1> operator *(const Vec3_tpl<F1> &vec, const Diag33_tpl<F2> &mtx) {
return Vec3_tpl<F1>(mtx.x*vec.x, mtx.y*vec.y, mtx.z*vec.z);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Matrix33_tpl
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template<typename F> struct Matrix33_tpl
{
#ifndef XENON_INTRINSICS
F m00,m01,m02;
F m10,m11,m12;
F m20,m21,m22;
#endif
//---------------------------------------------------------------------------------
#if defined(_DEBUG) && !defined(__SPU__)
ILINE Matrix33_tpl()
{
if (sizeof(F)==4)
{
uint32* p=(uint32*)&m00;
p[0]=F32NAN; p[1]=F32NAN; p[2]=F32NAN;
p[3]=F32NAN; p[4]=F32NAN; p[5]=F32NAN;
p[6]=F32NAN; p[7]=F32NAN; p[8]=F32NAN;
}
if (sizeof(F)==8)
{
uint64* p=(uint64*)&m00;
p[0]=F64NAN; p[1]=F64NAN; p[2]=F64NAN;
p[3]=F64NAN; p[4]=F64NAN; p[5]=F64NAN;
p[6]=F64NAN; p[7]=F64NAN; p[8]=F64NAN;
}
}
#else
ILINE Matrix33_tpl(){};
#endif
#if (defined (PS3)) || defined (XENON)
ILINE Matrix33_tpl(const Matrix33_tpl<F>& m) {
assert(m.IsValid());
m00=F(m.m00); m01=F(m.m01); m02=F(m.m02);
m10=F(m.m10); m11=F(m.m11); m12=F(m.m12);
m20=F(m.m20); m21=F(m.m21); m22=F(m.m22);
}
#endif
//assignment operator is needed since default operator = has precedence over assignment constructor
ILINE Matrix33_tpl& operator = (const Matrix33_tpl<F> &m) {
assert(m.IsValid());
m00=m.m00; m01=m.m01; m02=m.m02;
m10=m.m10; m11=m.m11; m12=m.m12;
m20=m.m20; m21=m.m21; m22=m.m22;
return *this;
}
template<class F1> ILINE Matrix33_tpl(const Diag33_tpl<F1> &d) {
assert(d.IsValid());
m00=F(d.x); m01=0; m02=0;
m10=0; m11=F(d.y); m12=0;
m20=0; m21=0; m22=F(d.z);
}
template<class F1> ILINE Matrix33_tpl(const Matrix33_tpl<F1>& m) {
assert(m.IsValid());
m00=F(m.m00); m01=F(m.m01); m02=F(m.m02);
m10=F(m.m10); m11=F(m.m11); m12=F(m.m12);
m20=F(m.m20); m21=F(m.m21); m22=F(m.m22);
}
template<class F1, class B> ILINE explicit Matrix33_tpl(const Matrix34_tpl<F1, B>& m ) {
assert(m.IsValid());
m00=F(m.m00); m01=F(m.m01); m02=F(m.m02);
m10=F(m.m10); m11=F(m.m11); m12=F(m.m12);
m20=F(m.m20); m21=F(m.m21); m22=F(m.m22);
}
template<class F1, class B> ILINE explicit Matrix33_tpl(const Matrix44_tpl<F1, B>& m ) {
assert(m.IsValid());
m00=F(m.m00); m01=F(m.m01); m02=F(m.m02);
m10=F(m.m10); m11=F(m.m11); m12=F(m.m12);
m20=F(m.m20); m21=F(m.m21); m22=F(m.m22);
}
template<class F1> explicit ILINE Matrix33_tpl(const Vec3_tpl<F1>& vx, const Vec3_tpl<F1>& vy, const Vec3_tpl<F1>& vz) {
m00=F(vx.x); m01=F(vy.x); m02=F(vz.x);
m10=F(vx.y); m11=F(vy.y); m12=F(vz.y);
m20=F(vx.z); m21=F(vy.z); m22=F(vz.z);
}
explicit ILINE Matrix33_tpl(F x00, F x01, F x02, F x10, F x11, F x12, F x20, F x21, F x22)
{
m00 = x00; m01 = x01; m02 = x02;
m10 = x10; m11 = x11; m12 = x12;
m20 = x20; m21 = x21; m22 = x22;
}
template<class F1>
static ILINE Matrix33_tpl CreateFromRows(const Vec3_tpl<F1>& r0, const Vec3_tpl<F1>& r1, const Vec3_tpl<F1>& r2)
{
Matrix33_tpl m(r0.x, r0.y, r0.z,
r1.x, r1.y, r1.z,
r2.x, r2.y, r2.z);
return m;
}
//Convert unit quaternion to matrix (23-flops).
template<class F1> explicit Matrix33_tpl( const Quat_tpl<F1>& q ) {
assert(q.IsValid(0.05f));
Vec3r v2=q.v+q.v;
f64 xx=1-v2.x*q.v.x; f64 yy=v2.y*q.v.y; f64 xw=v2.x*q.w;
f64 xy=v2.y*q.v.x; f64 yz=v2.z*q.v.y; f64 yw=v2.y*q.w;
f64 xz=v2.z*q.v.x; f64 zz=v2.z*q.v.z; f64 zw=v2.z*q.w;
m00=F(1-yy-zz); m01=F(xy-zw); m02=F(xz+yw);
m10=F(xy+zw); m11=F(xx-zz); m12=F(yz-xw);
m20=F(xz-yw); m21=F(yz+xw); m22=F(xx-yy);
}
ILINE explicit Matrix33_tpl( const Ang3_tpl<F>& rad )
{
assert(rad.IsValid());
SetRotationXYZ(rad);
}
template<class F1> ILINE Matrix33_tpl& operator = (const Vec3_tpl<F1> &v) {
m00=F(v.x); m01=0; m02=0;
m10=0; m11=F(v.y); m12=0;
m20=0; m21=0; m22=F(v.z);
return *this;
}
//---------------------------------------------------------------------------------------
ILINE void SetIdentity(void) {
m00=1; m01=0; m02=0;
m10=0; m11=1; m12=0;
m20=0; m21=0; m22=1;
}
ILINE static Matrix33_tpl<F> CreateIdentity() { Matrix33_tpl<F> m33; m33.SetIdentity(); return m33; }
ILINE Matrix33_tpl(type_identity) { SetIdentity(); }
ILINE void SetZero() {
m00=0; m01=0; m02=0;
m10=0; m11=0; m12=0;
m20=0; m21=0; m22=0;
}
/*!
* Create a rotation matrix around an arbitrary axis (Eulers Theorem).
* The axis is specified as a normalized Vec3. The angle is assumed to be in radians.
*
* Example:
* Matrix34 m34;
* Vec3 axis=GetNormalized( Vec3(-1.0f,-0.3f,0.0f) );
* m34.SetRotationAA( rad, axis );
*/
void SetRotationAA(F angle, Vec3_tpl<F> const& axis) {
f64 s,c; sincos_tpl(angle,&s,&c); f64 mc=1.0-c;
f64 mcx=mc*axis.x; f64 mcy=mc*axis.y; f64 mcz=mc*axis.z;
f64 tcx=axis.x*s; f64 tcy=axis.y*s; f64 tcz=axis.z*s;
m00=F(mcx*axis.x+c); m01=F(mcx*axis.y-tcz); m02=F(mcx*axis.z+tcy);
m10=F(mcy*axis.x+tcz); m11=F(mcy*axis.y+c); m12=F(mcy*axis.z-tcx);
m20=F(mcz*axis.x-tcy); m21=F(mcz*axis.y+tcx); m22=F(mcz*axis.z+c);
}
ILINE static Matrix33_tpl<F> CreateRotationAA( const F rad, Vec3_tpl<F> const& axis ) {
Matrix33_tpl<F> m33; m33.SetRotationAA(rad,axis); return m33;
}
void SetRotationAA(F c, F s, Vec3_tpl<F> const& axis) {
assert(axis.IsUnit(0.001f));
F mc = 1-c;
m00=mc*axis.x*axis.x + c; m01=mc*axis.x*axis.y - axis.z*s; m02=mc*axis.x*axis.z + axis.y*s;
m10=mc*axis.y*axis.x + axis.z*s; m11=mc*axis.y*axis.y + c; m12=mc*axis.y*axis.z - axis.x*s;
m20=mc*axis.z*axis.x - axis.y*s; m21=mc*axis.z*axis.y + axis.x*s; m22=mc*axis.z*axis.z + c;
}
ILINE static Matrix33_tpl<F> CreateRotationAA(F c, F s, Vec3_tpl<F> const& axis) {
Matrix33_tpl<F> m33; m33.SetRotationAA(c,s,axis); return m33;
}
ILINE void SetRotationAA(Vec3_tpl<F> const& rot) {
F angle = rot.GetLength();
if (angle == F(0))
SetIdentity();
else
SetRotationAA(angle, rot / angle);
}
ILINE static Matrix33_tpl<F> CreateRotationAA(Vec3_tpl<F> const& rot) {
Matrix33_tpl<F> m33; m33.SetRotationAA(rot); return m33;
}
/*!
*
* Create rotation-matrix about X axis using an angle.
* The angle is assumed to be in radians.
*
* Example:
* Matrix m33;
* m33.SetRotationX(0.5f);
*/
void SetRotationX(const f32 rad ) {
F s,c; sincos_tpl(rad,&s,&c);
m00=1.0f; m01=0.0f; m02= 0.0f;
m10=0.0f; m11=c; m12=-s;
m20=0.0f; m21=s; m22= c;
}
ILINE static Matrix33_tpl<F> CreateRotationX(const f32 rad ) {
Matrix33_tpl<F> m33; m33.SetRotationX(rad); return m33;
}
void SetRotationY(const f32 rad ) {
F s,c; sincos_tpl(rad,&s,&c);
m00 = c; m01 = 0; m02 = s;
m10 = 0; m11 = 1; m12 = 0;
m20 =-s; m21 = 0; m22 = c;
}
ILINE static Matrix33_tpl<F> CreateRotationY(const f32 rad ) {
Matrix33_tpl<F> m33; m33.SetRotationY(rad); return m33;
}
void SetRotationZ( const f32 rad ) {
F s,c; sincos_tpl(rad,&s,&c);
m00 = c; m01 =-s; m02 = 0.0f;
m10 = s; m11 = c; m12 = 0.0f;
m20 = 0.0f; m21 = 0.0f; m22 = 1.0f;
}
ILINE static Matrix33_tpl<F> CreateRotationZ(const f32 rad) {
Matrix33_tpl<F> m33; m33.SetRotationZ(rad); return m33;
}
void SetRotationXYZ( const Ang3_tpl<F>& rad )
{
assert(rad.IsValid());
F sx,cx; sincos_tpl(rad.x,&sx,&cx);
F sy,cy; sincos_tpl(rad.y,&sy,&cy);
F sz,cz; sincos_tpl(rad.z,&sz,&cz);
F sycz =(sy*cz), sysz =(sy*sz);
m00=cy*cz; m01=sycz*sx-cx*sz; m02=sycz*cx+sx*sz;
m10=cy*sz; m11=sysz*sx+cx*cz; m12=sysz*cx-sx*cz;
m20=-sy; m21=cy*sx; m22=cy*cx;
}
ILINE static Matrix33_tpl<F> CreateRotationXYZ( const Ang3_tpl<F>& rad )
{
assert(rad.IsValid());
Matrix33_tpl<F> m33; m33.SetRotationXYZ(rad); return m33;
}
/*!
* Creates a rotation matrix that rotates the vector "v0" into "v1".
*
* a) If both vectors are exactly parallel it returns an identity-matrix
* b) CAUTION: If both vectors are exactly diametrical it returns a matrix that rotates
* pi-radians about a "random" axis that is orthogonal to v0.
* c) CAUTION: If both vectors are almost diametrical we have to normalize
* a very small vector and the result is inaccurate. It is recommended to use this
* function with 64-bit precision.
*/
void SetRotationV0V1( const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1 ) {
assert((fabs_tpl(1-(v0|v0)))<0.01); //check if unit-vector
assert((fabs_tpl(1-(v1|v1)))<0.01); //check if unit-vector
f64 dot = v0|v1;
if ( dot < -0.9999) {
Vec3r axis = v0.GetOrthogonal().GetNormalized();
m00=F(2*axis.x*axis.x-1); m01=F(2*axis.x*axis.y); m02=F(2*axis.x*axis.z);
m10=F(2*axis.y*axis.x); m11=F(2*axis.y*axis.y-1); m12=F(2*axis.y*axis.z);
m20=F(2*axis.z*axis.x); m21=F(2*axis.z*axis.y); m22=F(2*axis.z*axis.z-1);
} else {
Vec3r v = v0%v1; f64 h = 1/(1 + dot);
m00=F(dot+h*v.x*v.x); m01=F(h*v.x*v.y-v.z); m02=F(h*v.x*v.z+v.y);
m10=F(h*v.x*v.y+v.z); m11=F(dot+h*v.y*v.y); m12=F(h*v.y*v.z-v.x);
m20=F(h*v.x*v.z-v.y); m21=F(h*v.y*v.z+v.x); m22=F(dot+h*v.z*v.z);
}
}
ILINE static Matrix33_tpl<F> CreateRotationV0V1( const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1 ) { Matrix33_tpl<F> m33; m33.SetRotationV0V1(v0,v1); return m33; }
/*!
*
* \param vdir normalized view direction.
* \param roll radiant to rotate about Y-axis.
*
* Given a view-direction and a radiant to rotate about Y-axis, this function builds a 3x3 look-at matrix
* using only simple vector arithmetic. This function is always using the implicit up-vector Vec3(0,0,1).
* The view-direction is always stored in column(1).
* IMPORTANT: The view-vector is assumed to be normalized, because all trig-values for the orientation are beeing
* extracted directly out of the vector. This function must NOT be called with a view-direction
* that is close to Vec3(0,0,1) or Vec3(0,0,-1). If one of these rules is broken, the function returns a matrix
* with an undifined rotation about the Z-axis.
*
* Rotation order for the look-at-matrix is Z-X-Y. (Zaxis=YAW / Xaxis=PITCH / Yaxis=ROLL)
*
* COORDINATE-SYSTEM
*
* z-axis
* ^
* |
* | y-axis
* | /
* | /
* |/
* +---------------> x-axis
*
* Example:
* Matrix33 orientation=Matrix33::CreateRotationVDir( Vec3(0,1,0), 0 );
*/
void SetRotationVDir( const Vec3_tpl<F>& vdir ) {
assert((fabs_tpl(1-(vdir|vdir)))<0.01); //check if unit-vector
//set default initialisation for up-vector
m00=1; m01=0; m02=0;
m10=0; m11=0; m12=-vdir.z;
m20=0; m21=vdir.z; m22=0;
//calculate look-at matrix
f64 l = sqrt(vdir.x*vdir.x+vdir.y*vdir.y);
if (l>0.0001)
{
f64 xl=-vdir.x/l; f64 yl=vdir.y/l;
m00=F(yl); m01=F(vdir.x); m02=F(xl*vdir.z);
m10=F(xl); m11=F(vdir.y); m12=F(-vdir.z*yl);
m20=0; m21=F(vdir.z); m22=F(l);
}
}
ILINE static Matrix33_tpl<F> CreateRotationVDir( const Vec3_tpl<F>& vdir ) {
Matrix33_tpl<F> m33; m33.SetRotationVDir(vdir); return m33;
}
//look-at matrix with roll
void SetRotationVDir( const Vec3_tpl<F>& vdir, F roll ) {
SetRotationVDir( vdir );
F s,c; sincos_tpl(roll,&s,&c);
F x00=m00,x10=m10;
m00=m00*c-m02*s; m02=x00*s+m02*c;
m10=m10*c-m12*s; m12=x10*s+m12*c;
m20=-m22*s; m22=m22*c;
}
ILINE static Matrix33_tpl<F> CreateRotationVDir( const Vec3_tpl<F>& vdir, F roll ) {
Matrix33_tpl<F> m33; m33.SetRotationVDir(vdir,roll ); return m33;
}
//////////////////////////////////////////////////////////////////////////
static Matrix33_tpl<F> CreateOrientation( const Vec3_tpl<F> &dir,const Vec3_tpl<F> &up,float rollAngle )
{
// LookAt transform.
Vec3 xAxis,yAxis,zAxis;
Vec3 upVector = up;
if (dir.IsZero())
{
Matrix33_tpl<F> tm;
tm.SetIdentity();
return tm;
}
yAxis = dir.GetNormalized();
if (yAxis.x == 0 && yAxis.y == 0 && up.IsEquivalent(Vec3_tpl<F>(0,0,1.0f)))
upVector.Set( -yAxis.z,0,0 );
xAxis = (upVector % yAxis).GetNormalized();
zAxis = (xAxis % yAxis).GetNormalized();
Matrix33_tpl<F> tm;
tm.SetFromVectors( xAxis,yAxis,zAxis );
if (rollAngle != 0)
{
Matrix33_tpl<F> RollMtx;
RollMtx.SetRotationY(rollAngle);
tm = tm * RollMtx;
}
return tm;
}
/*!
* Direct-Matrix-Slerp: for the sake of completeness, I have included the following expression
* for Spherical-Linear-Interpolation without using quaternions. This is much faster then converting
* both matrices into quaternions in order to do a quaternion slerp and then converting the slerped
* quaternion back into a matrix.
* This is a high-precision calculation. Given two orthonormal 3x3 matrices this function calculates
* the shortest possible interpolation-path between the two rotations. The interpolation curve forms
* a great arc on the rotation sphere (geodesic). Not only does Slerp follow a great arc it follows
* the shortest great arc. Furthermore Slerp has constant angular velocity. All in all Slerp is the
* optimal interpolation curve between two rotations.
*
* STABILITY PROBLEM: There are two singularities at angle=0 and angle=PI. At 0 the interpolation-axis
* is arbitrary, which means any axis will produce the same result because we have no rotation. Thats
* why I'm using (1,0,0). At PI the rotations point away from each other and the interpolation-axis
* is unpredictable. In this case I'm also using the axis (1,0,0). If the angle is ~0 or ~PI, then we
* have to normalize a very small vector and this can cause numerical instability. The quaternion-slerp
* has exactly the same problems.
* Ivo
* Example:
* Matrix33 slerp=Matrix33::CreateSlerp( m,n,0.333f );
*/
ILINE static Matrix33_tpl<F> CreateSlerp( const Matrix33_tpl<F>& m, const Matrix33_tpl<F>& n, F t) { Matrix33_tpl<F> m33; m33.SetSlerp(m,n,t); return m33; }
void SetSlerp( const Matrix33_tpl<F>& m, const Matrix33_tpl<F>& n, F t)
{
assert(m.IsValid());
assert(n.IsValid());
//calculate delta-rotation between m and n (=39 flops)
Matrix33_tpl<real> d,i;
d.m00=m.m00*n.m00+m.m10*n.m10+m.m20*n.m20; d.m01=m.m00*n.m01+m.m10*n.m11+m.m20*n.m21; d.m02=m.m00*n.m02+m.m10*n.m12+m.m20*n.m22;
d.m10=m.m01*n.m00+m.m11*n.m10+m.m21*n.m20; d.m11=m.m01*n.m01+m.m11*n.m11+m.m21*n.m21; d.m12=m.m01*n.m02+m.m11*n.m12+m.m21*n.m22;
d.m20=d.m01*d.m12-d.m02*d.m11; d.m21=d.m02*d.m10-d.m00*d.m12; d.m22=d.m00*d.m11-d.m01*d.m10;
assert( d.IsOrthonormalRH(0.0001f) );
//extract angle and axis
f64 cosine = clamp((d.m00+d.m11+d.m22-1.0)*0.5,-1.0,+1.0);
f64 angle = atan2(sqrt(1.0-cosine*cosine),cosine);
Vec3r axis(d.m21-d.m12,d.m02-d.m20,d.m10-d.m01);
f64 l = sqrt(axis|axis); if (l>0.00001) axis/=l; else axis(1,0,0);
i.SetRotationAA(angle*t,axis); //angle interpolation and calculation of new delta-matrix (=26 flops)
//final concatenation (=39 flops)
m00=F(m.m00*i.m00+m.m01*i.m10+m.m02*i.m20); m01=F(m.m00*i.m01+m.m01*i.m11+m.m02*i.m21); m02=F(m.m00*i.m02+m.m01*i.m12+m.m02*i.m22);
m10=F(m.m10*i.m00+m.m11*i.m10+m.m12*i.m20); m11=F(m.m10*i.m01+m.m11*i.m11+m.m12*i.m21); m12=F(m.m10*i.m02+m.m11*i.m12+m.m12*i.m22);
m20=m01*m12-m02*m11; m21=m02*m10-m00*m12; m22=m00*m11-m01*m10;
assert( this->IsOrthonormalRH(0.0001f) );
}
//! calculate 2 vector that form a orthogonal base with a given input vector (by M.M.)
//! /param invDirection input direction (has to be normalized)
//! /param outvA first output vector that is perpendicular to the input direction
//! /param outvB second output vector that is perpendicular the input vector and the first output vector
static Matrix33_tpl<F> CreateOrthogonalBase( const Vec3& invDirection )
{
Vec3 outvA;
if(invDirection.z<-0.5f || invDirection.z>0.5f) outvA=Vec3(invDirection.z,invDirection.y,-invDirection.x);
else outvA=Vec3(invDirection.y,-invDirection.x,invDirection.z);
Vec3 outvB = (invDirection % outvA).GetNormalized();
outvA = (invDirection % outvB).GetNormalized();
return CreateFromVectors(invDirection,outvA,outvB);
}
ILINE void SetScale( const Vec3_tpl<F> &s ) {
m00=s.x; m01=0; m02=0;
m10=0; m11=s.y; m12=0;
m20=0; m21=0; m22=s.z;
}
ILINE static Matrix33_tpl<F> CreateScale( const Vec3_tpl<F> &s ) { Matrix33_tpl<F> m; m.SetScale(s); return m; }
//NOTE: all vectors are stored in columns
ILINE void SetFromVectors(const Vec3_tpl<F>& vx, const Vec3_tpl<F>& vy, const Vec3_tpl<F>& vz) {
m00=vx.x; m01=vy.x; m02=vz.x;
m10=vx.y; m11=vy.y; m12=vz.y;
m20=vx.z; m21=vy.z; m22=vz.z;
}
ILINE static Matrix33_tpl<F> CreateFromVectors( const Vec3_tpl<F>& vx, const Vec3_tpl<F>& vy, const Vec3_tpl<F>& vz ) { Matrix33_tpl<F> dst; dst.SetFromVectors(vx,vy,vz); return dst; }
ILINE void Transpose() { // in-place transposition
F t;
t=m01; m01=m10; m10=t;
t=m02; m02=m20; m20=t;
t=m12; m12=m21; m21=t;
}
ILINE Matrix33_tpl<F> GetTransposed() const {
Matrix33_tpl<F> dst;
dst.m00=m00; dst.m01=m10; dst.m02=m20;
dst.m10=m01; dst.m11=m11; dst.m12=m21;
dst.m20=m02; dst.m21=m12; dst.m22=m22;
return dst;
}
ILINE Matrix33_tpl<F> T() const { return GetTransposed(); }
Matrix33_tpl& Fabs() {
m00=fabs_tpl(m00); m01=fabs_tpl(m01); m02=fabs_tpl(m02);
m10=fabs_tpl(m10); m11=fabs_tpl(m11); m12=fabs_tpl(m12);
m20=fabs_tpl(m20); m21=fabs_tpl(m21); m22=fabs_tpl(m22);
return *this;
}
ILINE Matrix33_tpl<F> GetFabs() const { Matrix33_tpl<F> m=*this; m.Fabs(); return m; }
void Adjoint( void ) {
//rescue members
Matrix33_tpl<F> m=*this;
//calculate the adjoint-matrix
m00=m.m11*m.m22-m.m12*m.m21; m01=m.m12*m.m20-m.m10*m.m22; m02=m.m10*m.m21-m.m11*m.m20;
m10=m.m21*m.m02-m.m22*m.m01; m11=m.m22*m.m00-m.m20*m.m02; m12=m.m20*m.m01-m.m21*m.m00;
m20=m.m01*m.m12-m.m02*m.m11; m21=m.m02*m.m10-m.m00*m.m12; m22=m.m00*m.m11-m.m01*m.m10;
}
ILINE Matrix33_tpl<F> GetAdjoint() const { Matrix33_tpl<F> dst=*this; dst.Adjoint(); return dst; }
/*!
*
* calculate a real inversion of a Matrix33.
* an inverse-matrix is an UnDo-matrix for all kind of transformations
* NOTE: if the return value of Invert33() is zero, then the inversion failed!
*
* Example 1:
* Matrix33 im33;
* bool st=i33.Invert();
* assert(st);
*
* Example 2:
* matrix33 im33=Matrix33::GetInverted(m33);
*/
bool Invert( void ) {
//rescue members
Matrix33_tpl<F> m=*this;
//calculate the cofactor-matrix (=transposed adjoint-matrix)
m00=m.m22*m.m11-m.m12*m.m21; m01=m.m02*m.m21-m.m22*m.m01; m02=m.m12*m.m01-m.m02*m.m11;
m10=m.m12*m.m20-m.m22*m.m10; m11=m.m22*m.m00-m.m02*m.m20; m12=m.m02*m.m10-m.m12*m.m00;
m20=m.m10*m.m21-m.m20*m.m11; m21=m.m20*m.m01-m.m00*m.m21; m22=m.m00*m.m11-m.m10*m.m01;
// calculate determinant
F det=(m.m00*m00 + m.m10*m01 + m.m20*m02);
if (fabs_tpl(det)<1E-20f)
return 0;
//devide the cofactor-matrix by the determinat
F idet=(F)1.0/det;
m00*=idet; m01*=idet; m02*=idet;
m10*=idet; m11*=idet; m12*=idet;
m20*=idet; m21*=idet; m22*=idet;
return 1;
}
ILINE Matrix33_tpl<F> GetInverted() const { Matrix33_tpl<F> dst=*this; dst.Invert(); return dst; }
ILINE Vec3_tpl<F> TransformVector(const Vec3_tpl<F> &v) const {
return Vec3_tpl<F>(m00*v.x+m01*v.y+m02*v.z, m10*v.x+m11*v.y+m12*v.z, m20*v.x+m21*v.y+m22*v.z);
}
//! make a right-handed orthonormal matrix.
void OrthonormalizeFast()
{
Vec3 x = Vec3(m00,m10,m20).GetNormalized();
Vec3 y = (Vec3(m02,m12,m22)%x).GetNormalized();
Vec3 z = (x%y);
m00=x.x; m01=y.x; m02=z.x;
m10=x.y; m11=y.y; m12=z.y;
m20=x.z; m21=y.z; m22=z.z;
}
ILINE f32 Determinant() const {
return (m00*m11*m22) + (m01*m12*m20) + (m02*m10*m21) - (m02*m11*m20) - (m00*m12*m21) - (m01*m10*m22);
}
//--------------------------------------------------------------------------------
//---- helper functions to access matrix-members ------------
//--------------------------------------------------------------------------------
F *GetData() { return &m00; }
const F *GetData() const { return &m00; }
ILINE F operator () (uint32 i, uint32 j) const { assert ((i<3) && (j<3)); F* p_data=(F*)(&m00); return p_data[i*3+j]; }
ILINE F& operator () (uint32 i, uint32 j) { assert ((i<3) && (j<3)); F* p_data=(F*)(&m00); return p_data[i*3+j]; }
ILINE void SetRow(int i, const Vec3_tpl<F> &v) { assert(i<3); F* p=(F*)(&m00); p[0+3*i]=v.x; p[1+3*i]=v.y; p[2+3*i]=v.z; }
ILINE const Vec3_tpl<F>& GetRow(int i) const { assert(i<3); return *(const Vec3_tpl<F>*)(&m00 + 3*i); }
ILINE void SetColumn(int i, const Vec3_tpl<F> &v) { assert(i<3); F* p=(F*)(&m00); p[i+3*0]=v.x; p[i+3*1]=v.y; p[i+3*2]=v.z; }
ILINE Vec3_tpl<F> GetColumn(int i) const { assert(i<3); F* p=(F*)(&m00); return Vec3_tpl<F>(p[i+3*0],p[i+3*1],p[i+3*2]); }
ILINE Vec3_tpl<F> GetColumn0() const { return Vec3_tpl<F> (m00,m10,m20); }
ILINE Vec3_tpl<F> GetColumn1() const { return Vec3_tpl<F> (m01,m11,m21); }
ILINE Vec3_tpl<F> GetColumn2() const { return Vec3_tpl<F> (m02,m12,m22); }
ILINE Matrix33_tpl<F>& operator *= (F op) {
m00*=op; m01*=op; m02*=op;
m10*=op; m11*=op; m12*=op;
m20*=op; m21*=op; m22*=op;
return *this;
}
ILINE Matrix33_tpl<F>& operator /= (F op) {
F iop=(F)1.0/op;
m00*=iop; m01*=iop; m02*=iop;
m10*=iop; m11*=iop; m12*=iop;
m20*=iop; m21*=iop; m22*=iop;
return *this;
}
bool IsEquivalent( const Matrix33_tpl<F>& m, F e=VEC_EPSILON) const {
return (
(fabs_tpl(m00-m.m00)<=e) && (fabs_tpl(m01-m.m01)<=e) && (fabs_tpl(m02-m.m02)<=e) &&
(fabs_tpl(m10-m.m10)<=e) && (fabs_tpl(m11-m.m11)<=e) && (fabs_tpl(m12-m.m12)<=e) &&
(fabs_tpl(m20-m.m20)<=e) && (fabs_tpl(m21-m.m21)<=e) && (fabs_tpl(m22-m.m22)<=e)
);
}
bool IsIdentity() const {
return 0 == (fabs_tpl((F)1-m00) + fabs_tpl(m01) + fabs_tpl(m02)+ fabs_tpl(m10) + fabs_tpl((F)1-m11) + fabs_tpl(m12)+ fabs_tpl(m20) + fabs_tpl(m21) + fabs_tpl((F)1-m22));
}
int IsZero() const {
return 0 == (fabs_tpl(m00)+fabs_tpl(m01)+fabs_tpl(m02)+fabs_tpl(m10)+fabs_tpl(m11)+fabs_tpl(m12)+fabs_tpl(m20)+fabs_tpl(m21)+fabs_tpl(m22));
}
//check if we have an orthonormal-base (general case, works even with reflection matrices)
int IsOrthonormal(F threshold=0.001) const {
f32 d0=fabs_tpl(GetColumn0()|GetColumn1()); if (d0>threshold) return 0;
f32 d1=fabs_tpl(GetColumn0()|GetColumn2()); if (d1>threshold) return 0;
f32 d2=fabs_tpl(GetColumn1()|GetColumn2()); if (d2>threshold) return 0;
int a=(fabs_tpl(1-(GetColumn0()|GetColumn0())))<threshold;
int b=(fabs_tpl(1-(GetColumn1()|GetColumn1())))<threshold;
int c=(fabs_tpl(1-(GetColumn2()|GetColumn2())))<threshold;
return a&b&c;
}
//check if we have an orthonormal-base (assuming we are using a right-handed coordinate system)
int IsOrthonormalRH(F threshold=0.002) const {
Vec3_tpl<F> x=GetColumn0();
Vec3_tpl<F> y=GetColumn1();
Vec3_tpl<F> z=GetColumn2();
bool a=x.IsEquivalent(y%z,threshold);
bool b=y.IsEquivalent(z%x,threshold);
bool c=z.IsEquivalent(x%y,threshold);
a&=x.IsUnit(0.01f);
b&=y.IsUnit(0.01f);
c&=z.IsUnit(0.01f);
return a&b&c;
}
//////////////////////////////////////////////////////////////////////////
// Remove uniform scale from matrix.
ILINE void NoScale()
{
*this /= GetColumn(0).GetLength();
}
bool IsValid() const
{
if (!NumberValid(m00)) return false; if (!NumberValid(m01)) return false; if (!NumberValid(m02)) return false;
if (!NumberValid(m10)) return false; if (!NumberValid(m11)) return false; if (!NumberValid(m12)) return false;
if (!NumberValid(m20)) return false; if (!NumberValid(m21)) return false; if (!NumberValid(m22)) return false;
return true;
}
// Gram Schmitt Orthogonalization
// - favors the x axis over the y axis over the z axis (property of the algorithm but favoring can be changed)
// - parity (left handed or right handed) remains from input
// - degenerated matrix input (point,line,plane) results in degenerated output
template<class F1, class F2> void Orthogonalization_GramSchmidt();
AUTO_STRUCT_INFO
};
///////////////////////////////////////////////////////////////////////////////
// Typedefs //
///////////////////////////////////////////////////////////////////////////////
typedef Matrix33_tpl<f32> Matrix33;
typedef Matrix33_tpl<f64> Matrix33_f64;
typedef Matrix33_tpl<real> Matrix33r;
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//------------- implementation of Matrix33 ------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
template<class F1, class F2>
Matrix33_tpl<F1> operator*(const Matrix33_tpl<F1> &l, const Diag33_tpl<F2> &r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix33_tpl<F1> res;
res.m00 = l.m00*r.x; res.m01 = l.m01*r.y; res.m02 = l.m02*r.z;
res.m10 = l.m10*r.x; res.m11 = l.m11*r.y; res.m12 = l.m12*r.z;
res.m20 = l.m20*r.x; res.m21 = l.m21*r.y; res.m22 = l.m22*r.z;
return res;
}
template<class F1, class F2>
Matrix33_tpl<F1>& operator *= (Matrix33_tpl<F1> &l, const Diag33_tpl<F2> &r) {
assert(l.IsValid());
assert(r.IsValid());
l.m00*=r.x; l.m01*=r.y; l.m02*=r.z;
l.m10*=r.x; l.m11*=r.y; l.m12*=r.z;
l.m20*=r.x; l.m21*=r.y; l.m22*=r.z;
return l;
}
//Matrix33 operations with another Matrix33
template<class F1, class F2>
Matrix33_tpl<F1> operator*(const Matrix33_tpl<F1> &l, const Matrix33_tpl<F2> &r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix33_tpl<F1> m;
m.m00 = l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20;
m.m01 = l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21;
m.m02 = l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22;
m.m10 = l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20;
m.m11 = l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21;
m.m12 = l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22;
m.m20 = l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20;
m.m21 = l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21;
m.m22 = l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22;
return m;
}
/*!
*
* Implements the multiplication operator: Matrix34=Matrix33*Matrix34
*
* Matrix33 and Matrix34 are specified in collumn order for a right-handed coordinate-system.
* AxB = operation B followed by operation A.
* A multiplication takes 36 muls and 24 adds.
*
* Example:
* Matrix33 m33=Matrix33::CreateRotationX(1.94192f);;
* Matrix34 m34=Matrix34::CreateRotationZ(3.14192f);
* Matrix34 result=m33*m34;
*
*/
template<class F1, class F2, class B>
Matrix34_tpl<F2, B> operator * (const Matrix33_tpl<F1>& l, const Matrix34_tpl<F2, B>& r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix34_tpl<F2, B> m;
m.m00 = l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20;
m.m10 = l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20;
m.m20 = l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20;
m.m01 = l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21;
m.m11 = l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21;
m.m21 = l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21;
m.m02 = l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22;
m.m12 = l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22;
m.m22 = l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22;
m.m03 = l.m00*r.m03 + l.m01*r.m13 + l.m02*r.m23;
m.m13 = l.m10*r.m03 + l.m11*r.m13 + l.m12*r.m23;
m.m23 = l.m20*r.m03 + l.m21*r.m13 + l.m22*r.m23;
return m;
}
/*!
*
* Implements the multiplication operator: Matrix44=Matrix33*Matrix44
*
* Matrix33 and Matrix44 are specified in collumn order for a right-handed coordinate-system.
* AxB = operation B followed by operation A.
* A multiplication takes 36 muls and 24 adds.
*
* Example:
* Matrix33 m33=Matrix33::CreateRotationX(1.94192f);;
* Matrix44 m44=Matrix33::CreateRotationZ(3.14192f);
* Matrix44 result=m33*m44;
*
*/
template<class F1, class F2, class B, class C>
Matrix44_tpl<F2, C> operator * (const Matrix33_tpl<F1>& l, const Matrix44_tpl<F2, B>& r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix44_tpl<F2, C> m;
m.m00 = l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20;
m.m10 = l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20;
m.m20 = l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20;
m.m30 = r.m30;
m.m01 = l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21;
m.m11 = l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21;
m.m21 = l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21;
m.m31 = r.m31;
m.m02 = l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22;
m.m12 = l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22;
m.m22 = l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22;
m.m32 = r.m32;
m.m03 = l.m00*r.m03 + l.m01*r.m13 + l.m02*r.m23;
m.m13 = l.m10*r.m03 + l.m11*r.m13 + l.m12*r.m23;
m.m23 = l.m20*r.m03 + l.m21*r.m13 + l.m22*r.m23;
m.m33 = r.m33;
return m;
}
template<class F1, class F2>
Matrix33_tpl<F1>& operator *= (Matrix33_tpl<F1> &l, const Matrix33_tpl<F2> &r)
{
assert(l.IsValid());
assert(r.IsValid());
F1 oldata[9];
oldata[0]=l.m00; oldata[1]=l.m01; oldata[2]=l.m02;
oldata[3]=l.m10; oldata[4]=l.m11; oldata[5]=l.m12;
oldata[6]=l.m20; oldata[7]=l.m21; oldata[8]=l.m22;
l.m00 = oldata[0]*r.m00 + oldata[1]*r.m10 + oldata[2]*r.m20;
l.m01 = oldata[0]*r.m01 + oldata[1]*r.m11 + oldata[2]*r.m21;
l.m02 = oldata[0]*r.m02 + oldata[1]*r.m12 + oldata[2]*r.m22;
l.m10 = oldata[3]*r.m00 + oldata[4]*r.m10 + oldata[5]*r.m20;
l.m11 = oldata[3]*r.m01 + oldata[4]*r.m11 + oldata[5]*r.m21;
l.m12 = oldata[3]*r.m02 + oldata[4]*r.m12 + oldata[5]*r.m22;
l.m20 = oldata[6]*r.m00 + oldata[7]*r.m10 + oldata[8]*r.m20;
l.m21 = oldata[6]*r.m01 + oldata[7]*r.m11 + oldata[8]*r.m21;
l.m22 = oldata[6]*r.m02 + oldata[7]*r.m12 + oldata[8]*r.m22;
return l;
}
template<class F1, class F2>
ILINE Matrix33_tpl<F1> operator+(const Matrix33_tpl<F1> &l, const Matrix33_tpl<F2> &r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix33_tpl<F1> res;
res.m00=l.m00+r.m00; res.m01=l.m01+r.m01; res.m02=l.m02+r.m02;
res.m10=l.m10+r.m10; res.m11=l.m11+r.m11; res.m12=l.m12+r.m12;
res.m20=l.m20+r.m20; res.m21=l.m21+r.m21; res.m22=l.m22+r.m22;
return res;
}
template<class F1, class F2>
ILINE Matrix33_tpl<F1>& operator+=(Matrix33_tpl<F1> &l, const Matrix33_tpl<F2> &r) {
assert(l.IsValid());
assert(r.IsValid());
l.m00+=r.m00; l.m01+=r.m01; l.m02+=r.m02;
l.m10+=r.m10; l.m11+=r.m11; l.m12+=r.m12;
l.m20+=r.m20; l.m21+=r.m21; l.m22+=r.m22;
return l;
}
template<class F1, class F2>
ILINE Matrix33_tpl<F1> operator - (const Matrix33_tpl<F1> &l, const Matrix33_tpl<F2> &r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix33_tpl<F1> res;
res.m00 = l.m00-r.m00; res.m01 = l.m01-r.m01; res.m02 = l.m02-r.m02;
res.m10 = l.m10-r.m10; res.m11 = l.m11-r.m11; res.m12 = l.m12-r.m12;
res.m20 = l.m20-r.m20; res.m21 = l.m21-r.m21; res.m22 = l.m22-r.m22;
return res;
}
template<class F1, class F2>
ILINE Matrix33_tpl<F1>& operator-=(Matrix33_tpl<F1> &l, const Matrix33_tpl<F2> &r)
{
assert(l.IsValid());
assert(r.IsValid());
l.m00-=r.m00; l.m01-=r.m01; l.m02-=r.m02;
l.m10-=r.m10; l.m11-=r.m11; l.m12-=r.m12;
l.m20-=r.m20; l.m21-=r.m21; l.m22-=r.m22;
return l;
}
template<class F>
ILINE Matrix33_tpl<F> operator*(const Matrix33_tpl<F> &m, F op) {
assert(m.IsValid());
Matrix33_tpl<F> res;
res.m00=m.m00*op; res.m01=m.m01*op; res.m02=m.m02*op;
res.m10=m.m10*op; res.m11=m.m11*op; res.m12=m.m12*op;
res.m20=m.m20*op; res.m21=m.m21*op; res.m22=m.m22*op;
return res;
}
template<class F>
ILINE Matrix33_tpl<F> operator/(const Matrix33_tpl<F> &src, F op) { return src*((F)1.0/op); }
//post-multiply
template<class F1, class F2>
Vec3_tpl<F1> operator*(const Matrix33_tpl<F2> &m, const Vec3_tpl<F1> &v) {
assert(m.IsValid());
assert(v.IsValid());
return Vec3_tpl<F1>(v.x*m.m00 + v.y*m.m01 + v.z*m.m02,
v.x*m.m10 + v.y*m.m11 + v.z*m.m12,
v.x*m.m20 + v.y*m.m21 + v.z*m.m22);
}
//pre-multiply
template<class F1, class F2>
Vec3_tpl<F1> operator*(const Vec3_tpl<F1> &v, const Matrix33_tpl<F2> &m) {
assert(m.IsValid());
assert(v.IsValid());
return Vec3_tpl<F1>(v.x*m.m00 + v.y*m.m10 + v.z*m.m20,
v.x*m.m01 + v.y*m.m11 + v.z*m.m21,
v.x*m.m02 + v.y*m.m12 + v.z*m.m22);
}
//post-multiply
template<class F1, class F2>
ILINE Vec2_tpl<F1> operator*(const Matrix33_tpl<F2> &m, const Vec2_tpl<F1> &v) {
assert(m.IsValid());
assert(v.IsValid());
return Vec2_tpl<F1>(v.x*m.m00+v.y*m.m01, v.x*m.m10 + v.y*m.m11);
}
//pre-multiply
template<class F1, class F2>
ILINE Vec2_tpl<F1> operator*(const Vec2_tpl<F1> &v, const Matrix33_tpl<F2> &m) {
assert(m.IsValid());
assert(v.IsValid());
return Vec2_tpl<F1>(v.x*m.m00 + v.y*m.m10, v.x*m.m01 + v.y*m.m11);
}
template<class F1>
Matrix33_tpl<F1>& crossproduct_matrix(const Vec3_tpl<F1> &v, Matrix33_tpl<F1> &m) {
m.m00=0; m.m01=-v.z; m.m02=v.y;
m.m10=v.z; m.m11=0; m.m12=-v.x;
m.m20=-v.y; m.m21=v.x; m.m22=0;
return m;
}
template<class F1>
Matrix33_tpl<F1>& dotproduct_matrix(const Vec3_tpl<F1> &v, const Vec3_tpl<F1> &op, Matrix33_tpl<F1> &m) {
m.m00=v.x*op.x; m.m10=v.y*op.x; m.m20=v.z*op.x;
m.m01=v.x*op.y; m.m11=v.y*op.y; m.m21=v.z*op.y;
m.m02=v.x*op.z; m.m12=v.y*op.z; m.m22=v.z*op.z;
return m;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Matrix34_tpl
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
template <typename F, class A=XMVec4A> struct Matrix34_tpl
{
#ifndef XENON_INTRINSICS
F m00,m01,m02,m03;
F m10,m11,m12,m13;
F m20,m21,m22,m23;
#endif
//default constructor
#if defined(_DEBUG) && !defined(__SPU__)
ILINE Matrix34_tpl()
{
if (sizeof(F)==4)
{
uint32* p=(uint32*)&m00;
p[ 0]=F32NAN; p[ 1]=F32NAN; p[ 2]=F32NAN; p[ 3]=F32NAN;
p[ 4]=F32NAN; p[ 5]=F32NAN; p[ 6]=F32NAN; p[ 7]=F32NAN;
p[ 8]=F32NAN; p[ 9]=F32NAN; p[10]=F32NAN; p[11]=F32NAN;
}
if (sizeof(F)==8)
{
uint64* p=(uint64*)&m00;
p[ 0]=F64NAN; p[ 1]=F64NAN; p[ 2]=F64NAN; p[ 3]=F64NAN;
p[ 4]=F64NAN; p[ 5]=F64NAN; p[ 6]=F64NAN; p[ 7]=F64NAN;
p[ 8]=F64NAN; p[ 9]=F64NAN; p[10]=F64NAN; p[11]=F64NAN;
}
}
#else
ILINE Matrix34_tpl(){};
#endif
template<class F1> ILINE Matrix34_tpl(const Matrix33_tpl<F1>& m)
{
assert(m.IsValid());
#ifndef XENON_INTRINSICS
m00=F(m.m00); m01=F(m.m01); m02=F(m.m02); m03=0;
m10=F(m.m10); m11=F(m.m11); m12=F(m.m12); m13=0;
m20=F(m.m20); m21=F(m.m21); m22=F(m.m22); m23=0;
#endif
}
template<class B> ILINE Matrix34_tpl( const Matrix34_tpl<F, B>& m )
{
assert(m.IsValid());
#ifndef XENON_INTRINSICS
m00=m.m00; m01=m.m01; m02=m.m02; m03=m.m03;
m10=m.m10; m11=m.m11; m12=m.m12; m13=m.m13;
m20=m.m20; m21=m.m21; m22=m.m22; m23=m.m23;
#endif
}
template<class F1, class B> ILINE explicit Matrix34_tpl( const Matrix34_tpl<F1, B>& m )
{
assert(m.IsValid());
#ifndef XENON_INTRINSICS
m00=F(m.m00); m01=F(m.m01); m02=F(m.m02); m03=F(m.m03);
m10=F(m.m10); m11=F(m.m11); m12=F(m.m12); m13=F(m.m13);
m20=F(m.m20); m21=F(m.m21); m22=F(m.m22); m23=F(m.m23);
#endif
}
template<class F1, class B> ILINE explicit Matrix34_tpl(const Matrix44_tpl<F1, B>& m )
{
assert(m.IsValid());
#ifndef XENON_INTRINSICS
m00=F(m.m00); m01=F(m.m01); m02=F(m.m02); m03=F(m.m03);
m10=F(m.m10); m11=F(m.m11); m12=F(m.m12); m13=F(m.m13);
m20=F(m.m20); m21=F(m.m21); m22=F(m.m22); m23=F(m.m23);
#endif
}
template<class F1> ILINE Matrix34_tpl(const Matrix33_tpl<F1>& m, const Vec3_tpl<F1>& t)
{
assert(m.IsValid());
assert(t.IsValid());
#ifndef XENON_INTRINSICS
m00=F(m.m00); m01=F(m.m01); m02=F(m.m02); m03=F(t.x);
m10=F(m.m10); m11=F(m.m11); m12=F(m.m12); m13=F(t.y);
m20=F(m.m20); m21=F(m.m21); m22=F(m.m22); m23=F(t.z);
#endif
}
ILINE Matrix34_tpl& operator = (const Matrix34_tpl &m) {
assert(m.IsValid());
m00=m.m00; m01=m.m01; m02=m.m02; m03=m.m03;
m10=m.m10; m11=m.m11; m12=m.m12; m13=m.m13;
m20=m.m20; m21=m.m21; m22=m.m22; m23=m.m23;
return *this;
}
explicit ILINE Matrix34_tpl( const Quat_tpl<F>& q ) { *this=Matrix33(q); }
//Convert unit quaternion to matrix.
template<class F1> explicit Matrix34_tpl( const QuatT_tpl<F1>& q ) {
assert(q.q.IsValid());
Vec3_tpl<F1> v2=q.q.v+q.q.v;
F1 xx=1-v2.x*q.q.v.x; F1 yy=v2.y*q.q.v.y; F1 xw=v2.x*q.q.w;
F1 xy=v2.y*q.q.v.x; F1 yz=v2.z*q.q.v.y; F1 yw=v2.y*q.q.w;
F1 xz=v2.z*q.q.v.x; F1 zz=v2.z*q.q.v.z; F1 zw=v2.z*q.q.w;
m00=F(1-yy-zz); m01=F(xy-zw); m02=F(xz+yw); m03=F(q.t.x);
m10=F(xy+zw); m11=F(xx-zz); m12=F(yz-xw); m13=F(q.t.y);
m20=F(xz-yw); m21=F(yz+xw); m22=F(xx-yy); m23=F(q.t.z);
}
template<class F1> explicit Matrix34_tpl( const QuatTS_tpl<F1>& q ) {
assert(q.q.IsValid());
Vec3_tpl<F1> v2=q.q.v+q.q.v;
F1 xx=1-v2.x*q.q.v.x; F1 yy=v2.y*q.q.v.y; F1 xw=v2.x*q.q.w;
F1 xy=v2.y*q.q.v.x; F1 yz=v2.z*q.q.v.y; F1 yw=v2.y*q.q.w;
F1 xz=v2.z*q.q.v.x; F1 zz=v2.z*q.q.v.z; F1 zw=v2.z*q.q.w;
m00=F((1-yy-zz)*q.s); m01=F((xy-zw)*q.s); m02=F((xz+yw)*q.s); m03=F(q.t.x);
m10=F((xy+zw)*q.s); m11=F((xx-zz)*q.s); m12=F((yz-xw)*q.s); m13=F(q.t.y);
m20=F((xz-yw)*q.s); m21=F((yz+xw)*q.s); m22=F((xx-yy)*q.s); m23=F(q.t.z);
}
template<class F1> explicit Matrix34_tpl( const QuatD_tpl<F1>& q )
{
assert((fabs_tpl(1-(q.nq|q.nq)))<0.01); //check if unit-quaternion
Vec3 t=(q.nq.w*q.dq.v - q.dq.w*q.nq.v + q.nq.v%q.dq.v); //perfect for HLSL
Vec3_tpl<F1> v2=q.nq.v+q.nq.v;
F1 xx=1-v2.x*q.nq.v.x; F1 yy=v2.y*q.nq.v.y; F1 xw=v2.x*q.nq.w;
F1 xy=v2.y*q.nq.v.x; F1 yz=v2.z*q.nq.v.y; F1 yw=v2.y*q.nq.w;
F1 xz=v2.z*q.nq.v.x; F1 zz=v2.z*q.nq.v.z; F1 zw=v2.z*q.nq.w;
m00=F(1-yy-zz); m01=F(xy-zw); m02=F(xz+yw); m03=F(t.x+t.x);
m10=F(xy+zw); m11=F(xx-zz); m12=F(yz-xw); m13=F(t.y+t.y);
m20=F(xz-yw); m21=F(yz+xw); m22=F(xx-yy); m23=F(t.z+t.z);
}
//! build a matrix from 12 f32s
ILINE Matrix34_tpl( f32 v00, f32 v01, f32 v02, f32 v03, f32 v10, f32 v11, f32 v12, f32 v13, f32 v20, f32 v21, f32 v22, f32 v23) :
m00(v00), m01(v01), m02(v02), m03(v03),
m10(v10), m11(v11), m12(v12), m13(v13),
m20(v20), m21(v21), m22(v22), m23(v23)
{
}
Matrix34_tpl( const Vec3_tpl<F>& s, const Quat_tpl<F>& q, const Vec3_tpl<F>& t=Vec3(ZERO) ) { Set(s, q, t); }
//apply scaling to the columns of the matrix.
ILINE void ScaleColumn( const Vec3_tpl<F>& s)
{
#ifndef XENON_INTRINSICS
m00*=s.x; m01*=s.y; m02*=s.z;
m10*=s.x; m11*=s.y; m12*=s.z;
m20*=s.x; m21*=s.y; m22*=s.z;
#endif
}
//apply scaling to matrix.
ILINE void Scale( const Vec3_tpl<F>& s )
{
#ifndef XENON_INTRINSICS
m00*=s.x; m01*=s.y; m02*=s.z;
m10*=s.x; m11*=s.y; m12*=s.z;
m20*=s.x; m21*=s.y; m22*=s.z;
#endif
}
/*!
*
* Initializes the Matrix34 with the identity.
*
*/
void SetIdentity( void )
{
#ifndef XENON_INTRINSICS
m00=1.0f; m01=0.0f; m02=0.0f; m03=0.0f;
m10=0.0f; m11=1.0f; m12=0.0f; m13=0.0f;
m20=0.0f; m21=0.0f; m22=1.0f; m23=0.0f;
#endif
}
ILINE static Matrix34_tpl<F> CreateIdentity( void ) {
Matrix34_tpl<F> m34; m34.SetIdentity(); return m34;
}
ILINE Matrix34_tpl(type_identity) { SetIdentity(); }
/*!
* Create a rotation matrix around an arbitrary axis (Eulers Theorem).
* The axis is specified as an normalized Vec3. The angle is assumed to be in radians.
* This function also assumes a translation-vector and stores it in the right column.
*
* Example:
* Matrix34 m34;
* Vec3 axis=GetNormalized( Vec3(-1.0f,-0.3f,0.0f) );
* m34.SetRotationAA( 3.14314f, axis, Vec3(5,5,5) );
*/
ILINE void SetRotationAA(const F rad, const Vec3_tpl<F>& axis, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
*this=Matrix33_tpl<F>::CreateRotationAA(rad,axis); this->SetTranslation(t);
}
ILINE static Matrix34_tpl<F> CreateRotationAA( const F rad, const Vec3_tpl<F>& axis, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
Matrix34_tpl<F> m34; m34.SetRotationAA(rad,axis,t); return m34;
}
ILINE void SetRotationAA(const Vec3_tpl<F>& rot, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
*this=Matrix33_tpl<F>::CreateRotationAA(rot); this->SetTranslation(t);
}
ILINE static Matrix34_tpl<F> CreateRotationAA( const Vec3_tpl<F>& rot, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
Matrix34_tpl<F> m34; m34.SetRotationAA(rot,t); return m34;
}
/*!
* Create rotation-matrix about X axis using an angle.
* The angle is assumed to be in radians.
* The translation-vector is set to zero.
*
* Example:
* Matrix34 m34;
* m34.SetRotationX(0.5f);
*/
ILINE void SetRotationX(const f32 rad, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
*this=Matrix33_tpl<F>::CreateRotationX(rad); this->SetTranslation(t);
}
ILINE static Matrix34_tpl<F> CreateRotationX( const f32 rad, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
Matrix34_tpl<F> m34; m34.SetRotationX(rad,t); return m34;
}
/*!
* Create rotation-matrix about Y axis using an angle.
* The angle is assumed to be in radians.
* The translation-vector is set to zero.
*
* Example:
* Matrix34 m34;
* m34.SetRotationY(0.5f);
*/
ILINE void SetRotationY(const f32 rad, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
*this=Matrix33_tpl<F>::CreateRotationY(rad); this->SetTranslation(t);
}
ILINE static Matrix34_tpl<F> CreateRotationY( const f32 rad, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
Matrix34_tpl<F> m34; m34.SetRotationY(rad,t); return m34;
}
/*!
* Create rotation-matrix about Z axis using an angle.
* The angle is assumed to be in radians.
* The translation-vector is set to zero.
*
* Example:
* Matrix34 m34;
* m34.SetRotationZ(0.5f);
*/
ILINE void SetRotationZ(const f32 rad, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
*this=Matrix33_tpl<F>::CreateRotationZ(rad); this->SetTranslation(t);
}
ILINE static Matrix34_tpl<F> CreateRotationZ( const f32 rad, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
Matrix34_tpl<F> m34; m34.SetRotationZ(rad,t); return m34;
}
/*!
*
* Convert three Euler angle to mat33 (rotation order:XYZ)
* The Euler angles are assumed to be in radians.
* The translation-vector is set to zero.
*
* Example 1:
* Matrix34 m34;
* m34.SetRotationXYZ( Ang3(0.5f,0.2f,0.9f), translation );
*
* Example 2:
* Matrix34 m34=Matrix34::CreateRotationXYZ( Ang3(0.5f,0.2f,0.9f), translation );
*/
ILINE void SetRotationXYZ( const Ang3_tpl<F>& rad, const Vec3_tpl<F>& t=Vec3(ZERO) )
{
assert(rad.IsValid());
assert(t.IsValid());
*this=Matrix33_tpl<F>::CreateRotationXYZ(rad); this->SetTranslation(t);
}
ILINE static Matrix34_tpl<F> CreateRotationXYZ( const Ang3_tpl<F>& rad, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
assert(rad.IsValid());
assert(t.IsValid());
Matrix34_tpl<F> m34; m34.SetRotationXYZ(rad,t); return m34;
}
ILINE void SetRotationAA(F c, F s, Vec3_tpl<F> axis, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
assert(axis.IsValid());
assert(t.IsValid());
*this=Matrix33_tpl<F>::CreateRotationAA(c, s, axis);
m03=t.x; m13=t.y; m23=t.z;
}
ILINE static Matrix34_tpl<F> CreateRotationAA(F c, F s, Vec3_tpl<F> axis, const Vec3_tpl<F>& t=Vec3(ZERO) ) {
Matrix34_tpl<F> m34; m34.SetRotationAA(c,s,axis,t); return m34;
}
void Set( const Vec3_tpl<F>& s, const Quat_tpl<F>& q, const Vec3_tpl<F>& t=Vec3(ZERO) );
static Matrix34_tpl<F> Create( const Vec3_tpl<F>& s, const Quat_tpl<F>& q, const Vec3_tpl<F>& t=Vec3(ZERO) );
void SetScale( const Vec3_tpl<F> &s, const Vec3_tpl<F>& t=Vec3(ZERO) );
static Matrix34_tpl<F> CreateScale( const Vec3_tpl<F> &s, const Vec3_tpl<F>& t=Vec3(ZERO) );
ILINE void SetTranslationMat( const Vec3_tpl<F>& v ) {
m00=1.0f; m01=0.0f; m02=0.0f; m03=v.x;
m10=0.0f; m11=1.0f; m12=0.0f; m13=v.y;
m20=0.0f; m21=0.0f; m22=1.0f; m23=v.z;
}
ILINE static Matrix34_tpl<F, A> CreateTranslationMat( const Vec3_tpl<F>& v ) { Matrix34_tpl<F, A> m34; m34.SetTranslationMat(v); return m34; }
//NOTE: all vectors are stored in columns
ILINE void SetFromVectors(const Vec3& vx, const Vec3& vy, const Vec3& vz, const Vec3& pos) {
m00=vx.x; m01=vy.x; m02=vz.x; m03 = pos.x;
m10=vx.y; m11=vy.y; m12=vz.y; m13 = pos.y;
m20=vx.z; m21=vy.z; m22=vz.z; m23 = pos.z;
}
ILINE static Matrix34_tpl<F> CreateFromVectors(const Vec3_tpl<F>& vx, const Vec3_tpl<F>& vy, const Vec3_tpl<F>& vz, const Vec3_tpl<F>& pos) {
Matrix34_tpl<F> m; m.SetFromVectors(vx,vy,vz,pos); return m;
}
void InvertFast() { // in-place transposition
assert(IsOrthonormal());
F t; Vec3 v(m03,m13,m23);
t=m01; m01=m10; m10=t; m03=-v.x*m00-v.y*m01-v.z*m20;
t=m02; m02=m20; m20=t; m13=-v.x*m10-v.y*m11-v.z*m21;
t=m12; m12=m21; m21=t; m23=-v.x*m20-v.y*m21-v.z*m22;
}
Matrix34_tpl<F> GetInvertedFast() const {
assert(IsOrthonormal());
Matrix34_tpl<F> dst;
dst.m00=m00; dst.m01=m10; dst.m02=m20; dst.m03=-m03*m00-m13*m10-m23*m20;
dst.m10=m01; dst.m11=m11; dst.m12=m21; dst.m13=-m03*m01-m13*m11-m23*m21;
dst.m20=m02; dst.m21=m12; dst.m22=m22; dst.m23=-m03*m02-m13*m12-m23*m22;
return dst;
}
void Invert( void );
Matrix34_tpl<F> GetInverted() const;
//! transforms a vector. the translation is not beeing considered
ILINE Vec3_tpl<F> TransformVector(const Vec3_tpl<F> &v) const {
assert(v.IsValid());
return Vec3_tpl<F>(m00*v.x+m01*v.y+m02*v.z, m10*v.x+m11*v.y+m12*v.z, m20*v.x+m21*v.y+m22*v.z);
}
//! transforms a point and add translation vector
ILINE Vec3_tpl<F> TransformPoint(const Vec3_tpl<F> &p) const {
assert(p.IsValid());
return Vec3_tpl<F>( m00*p.x+m01*p.y+m02*p.z+m03, m10*p.x+m11*p.y+m12*p.z+m13, m20*p.x+m21*p.y+m22*p.z+m23);
}
//! Remove scale from matrix.
void OrthonormalizeFast()
{
Vec3 x( m00,m10,m20 );
Vec3 y( m01,m11,m21 );
Vec3 z;
x = x.GetNormalized();
z = (x % y).GetNormalized();
y = (z % x).GetNormalized();
m00=x.x; m10=x.y; m20=x.z;
m01=y.x; m11=y.y; m21=y.z;
m02=z.x; m12=z.y; m22=z.z;
}
//determinant is ambiguous: only the upper-left-submatrix's determinant is calculated
ILINE f32 Determinant() const {
return (m00*m11*m22) + (m01*m12*m20) + (m02*m10*m21) - (m02*m11*m20) - (m00*m12*m21) - (m01*m10*m22);
}
/*!
* Direct-Matrix-Slerp: for the sake of completeness, I have included the following expression
* for Spherical-Linear-Interpolation without using quaternions. This is much faster then converting
* both matrices into quaternions in order to do a quaternion slerp and then converting the slerped
* quaternion back into a matrix.
* This is a high-precision calculation. Given two orthonormal 3x3 matrices this function calculates
* the shortest possible interpolation-path between the two rotations. The interpolation curve forms
* a great arc on the rotation sphere (geodesic). Not only does Slerp follow a great arc it follows
* the shortest great arc. Furthermore Slerp has constant angular velocity. All in all Slerp is the
* optimal interpolation curve between two rotations.
*
* STABILITY PROBLEM: There are two singularities at angle=0 and angle=PI. At 0 the interpolation-axis
* is arbitrary, which means any axis will produce the same result because we have no rotation. Thats
* why I'm using (1,0,0). At PI the rotations point away from each other and the interpolation-axis
* is unpredictable. In this case I'm also using the axis (1,0,0). If the angle is ~0 or ~PI, then we
* have to normalize a very small vector and this can cause numerical instability. The quaternion-slerp
* has exactly the same problems.
* Ivo
* Example:
* Matrix33 slerp=Matrix33::CreateSlerp( m,n,0.333f );
*/
ILINE static Matrix34_tpl<F> CreateSlerp( const Matrix34_tpl<F>& m, const Matrix34_tpl<F>& n, F t) { Matrix34_tpl<F> m33; m33.SetSlerp(m,n,t); return m33; }
void SetSlerp( const Matrix34_tpl<F>& m, const Matrix34_tpl<F>& n, F t)
{
//calculate delta-rotation between m and n (=39 flops)
Matrix33_tpl<real> d,i;
d.m00=m.m00*n.m00+m.m10*n.m10+m.m20*n.m20; d.m01=m.m00*n.m01+m.m10*n.m11+m.m20*n.m21; d.m02=m.m00*n.m02+m.m10*n.m12+m.m20*n.m22;
d.m10=m.m01*n.m00+m.m11*n.m10+m.m21*n.m20; d.m11=m.m01*n.m01+m.m11*n.m11+m.m21*n.m21; d.m12=m.m01*n.m02+m.m11*n.m12+m.m21*n.m22;
d.m20=d.m01*d.m12-d.m02*d.m11; d.m21=d.m02*d.m10-d.m00*d.m12; d.m22=d.m00*d.m11-d.m01*d.m10;
assert( d.IsOrthonormalRH(0.0001f) );
//extract angle and axis
f64 cosine = clamp_tpl((d.m00+d.m11+d.m22-1.0)*0.5,-1.0,+1.0);
f64 angle = atan2(sqrt(1.0-cosine*cosine),cosine);
Vec3r axis(d.m21-d.m12,d.m02-d.m20,d.m10-d.m01);
f64 l = sqrt(axis|axis); if (l>0.00001) axis/=l; else axis(1,0,0);
i.SetRotationAA(angle*t,axis); //angle interpolation and calculation of new delta-matrix (=26 flops)
//final concatenation (=39 flops)
m00=F(m.m00*i.m00+m.m01*i.m10+m.m02*i.m20); m01=F(m.m00*i.m01+m.m01*i.m11+m.m02*i.m21); m02=F(m.m00*i.m02+m.m01*i.m12+m.m02*i.m22);
m10=F(m.m10*i.m00+m.m11*i.m10+m.m12*i.m20); m11=F(m.m10*i.m01+m.m11*i.m11+m.m12*i.m21); m12=F(m.m10*i.m02+m.m11*i.m12+m.m12*i.m22);
m20=m01*m12-m02*m11; m21=m02*m10-m00*m12; m22=m00*m11-m01*m10;
assert( this->IsOrthonormalRH(0.0001f) );
m03=m.m03*(1-t) + n.m03*t;
m13=m.m13*(1-t) + n.m13*t;
m23=m.m23*(1-t) + n.m23*t;
}
//--------------------------------------------------------------------------------
//---- helper functions to access matrix-members ------------
//--------------------------------------------------------------------------------
F *GetData() { return &m00; }
const F *GetData() const { return &m00; }
ILINE F operator () (uint32 i, uint32 j) const { assert ((i<3) && (j<4)); F* p_data=(F*)(&m00); return p_data[i*4+j]; }
ILINE F& operator () (uint32 i, uint32 j) { assert ((i<3) && (j<4)); F* p_data=(F*)(&m00); return p_data[i*4+j]; }
ILINE void SetRow(int i, const Vec3_tpl<F> &v) { assert(i<3); F* p=(F*)(&m00); p[0+4*i]=v.x; p[1+4*i]=v.y; p[2+4*i]=v.z; }
ILINE const Vec3_tpl<F>& GetRow(int i) const { assert(i<3); return *(const Vec3_tpl<F>*)(&m00 + 4*i); }
ILINE const Vec4_tpl<F>& GetRow4(int i) const { assert(i<3); return *(const Vec4_tpl<F>*)(&m00 + 4*i); }
ILINE void SetColumn(int i, const Vec3_tpl<F> &v) { assert(i<4); F* p=(F*)(&m00); p[i+4*0]=v.x; p[i+4*1]=v.y; p[i+4*2]=v.z; }
ILINE Vec3_tpl<F> GetColumn(int i) const { assert(i<4); F* p=(F*)(&m00); return Vec3(p[i+4*0],p[i+4*1],p[i+4*2]); }
ILINE Vec3_tpl<F> GetColumn0() const { return Vec3_tpl<F> (m00,m10,m20); }
ILINE Vec3_tpl<F> GetColumn1() const { return Vec3_tpl<F> (m01,m11,m21); }
ILINE Vec3_tpl<F> GetColumn2() const { return Vec3_tpl<F> (m02,m12,m22); }
ILINE Vec3_tpl<F> GetColumn3() const { return Vec3_tpl<F> (m03,m13,m23); }
ILINE void SetTranslation( const Vec3_tpl<F>& t ) { m03=t.x; m13=t.y; m23=t.z; }
ILINE Vec3_tpl<F> GetTranslation() const { return Vec3_tpl<F>(m03,m13,m23); }
ILINE void ScaleTranslation (F s) { m03*=s; m13*=s; m23*=s; }
ILINE Matrix34_tpl<F> AddTranslation( const Vec3_tpl<F>& t ) { m03+=t.x; m13+=t.y; m23+=t.z; return *this; }
ILINE void SetRotation33( const Matrix33_tpl<F>& m33 ) {
m00=m33.m00; m01=m33.m01; m02=m33.m02;
m10=m33.m10; m11=m33.m11; m12=m33.m12;
m20=m33.m20; m21=m33.m21; m22=m33.m22;
}
//check if we have an orthonormal-base (general case, works even with reflection matrices)
int IsOrthonormal(F threshold=0.001) const {
f32 d0=fabs_tpl(GetColumn0()|GetColumn1()); if (d0>threshold) return 0;
f32 d1=fabs_tpl(GetColumn0()|GetColumn2()); if (d1>threshold) return 0;
f32 d2=fabs_tpl(GetColumn1()|GetColumn2()); if (d2>threshold) return 0;
int a=(fabs_tpl(1-(GetColumn0()|GetColumn0())))<threshold;
int b=(fabs_tpl(1-(GetColumn1()|GetColumn1())))<threshold;
int c=(fabs_tpl(1-(GetColumn2()|GetColumn2())))<threshold;
return a&b&c;
}
//check if we have an orthonormal-base (assuming we are using a right-handed coordinate system)
int IsOrthonormalRH(F threshold=0.001) const {
int a=GetColumn0().IsEquivalent(GetColumn1()%GetColumn2(),threshold);
int b=GetColumn1().IsEquivalent(GetColumn2()%GetColumn0(),threshold);
int c=GetColumn2().IsEquivalent(GetColumn0()%GetColumn1(),threshold);
return a&b&c;
}
bool IsEquivalent( const Matrix34_tpl<F>& m, F e=VEC_EPSILON) const {
return (
(fabs_tpl(m00-m.m00)<=e) && (fabs_tpl(m01-m.m01)<=e) && (fabs_tpl(m02-m.m02)<=e) && (fabs_tpl(m03-m.m03)<=e) &&
(fabs_tpl(m10-m.m10)<=e) && (fabs_tpl(m11-m.m11)<=e) && (fabs_tpl(m12-m.m12)<=e) && (fabs_tpl(m13-m.m13)<=e) &&
(fabs_tpl(m20-m.m20)<=e) && (fabs_tpl(m21-m.m21)<=e) && (fabs_tpl(m22-m.m22)<=e) && (fabs_tpl(m23-m.m23)<=e)
);
}
bool IsValid() const
{
if (!NumberValid(m00)) return false; if (!NumberValid(m01)) return false; if (!NumberValid(m02)) return false; if (!NumberValid(m03)) return false;
if (!NumberValid(m10)) return false; if (!NumberValid(m11)) return false; if (!NumberValid(m12)) return false; if (!NumberValid(m13)) return false;
if (!NumberValid(m20)) return false; if (!NumberValid(m21)) return false; if (!NumberValid(m22)) return false; if (!NumberValid(m23)) return false;
return true;
}
AUTO_STRUCT_INFO
};
///////////////////////////////////////////////////////////////////////////////
// Typedefs //
///////////////////////////////////////////////////////////////////////////////
typedef Matrix34_tpl<f32, XMVec4> Matrix34;
typedef Matrix34_tpl<f32, XMVec4A> Matrix34A;
typedef Matrix34_tpl<f64, XMVec4> Matrix34_f64;
typedef Matrix34_tpl<real, XMVec4> Matrix34r;
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//------------- implementation of Matrix34 ------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
/*!
* multiplication of Matrix34 by a (column) Vec3.
* This function transforms the given input Vec3
* into the coordinate system defined by this matrix.
*
* Example:
* Matrix34 m34;
* Vec3 vector(44,55,66);
* Vec3 result = m34*vector;
*/
template<class F, class B>
ILINE Vec3_tpl<F> operator * (const Matrix34_tpl<F, B>& m, const Vec3_tpl<F> &p) {
assert(m.IsValid());
assert(p.IsValid());
Vec3_tpl<F> tp;
tp.x = m.m00*p.x + m.m01*p.y + m.m02*p.z + m.m03;
tp.y = m.m10*p.x + m.m11*p.y + m.m12*p.z + m.m13;
tp.z = m.m20*p.x + m.m21*p.y + m.m22*p.z + m.m23;
return tp;
}
template<class F1, class F2, class B>
ILINE Matrix34_tpl<F1> operator*(const Matrix34_tpl<F1, B> &l, const Diag33_tpl<F2> &r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix34_tpl<F1> m;
m.m00=l.m00*r.x; m.m01=l.m01*r.y; m.m02=l.m02*r.z; m.m03=l.m03;
m.m10=l.m10*r.x; m.m11=l.m11*r.y; m.m12=l.m12*r.z; m.m13=l.m13;
m.m20=l.m20*r.x; m.m21=l.m21*r.y; m.m22=l.m22*r.z; m.m23=l.m23;
return m;
}
template<class F1, class F2, class B>
ILINE Matrix34_tpl<F1>& operator *= (Matrix34_tpl<F1, B>& l, const Diag33_tpl<F2>& r) {
assert(l.IsValid());
assert(r.IsValid());
l.m00*=r.x; l.m01*=r.y; l.m02*=r.z;
l.m10*=r.x; l.m11*=r.y; l.m12*=r.z;
l.m20*=r.x; l.m21*=r.y; l.m22*=r.z;
return l;
}
/*!
* Implements the multiplication operator: Matrix34=Matrix34*Matrix33
*
* Matrix33 and Matrix44 are specified in collumn order for a right-handed coordinate-system.
* AxB = operation B followed by operation A.
* A multiplication takes 27 muls and 24 adds.
*
* Example:
* Matrix34 m34=Matrix33::CreateRotationX(1.94192f);;
* Matrix33 m33=Matrix34::CreateRotationZ(3.14192f);
* Matrix34 result=m34*m33;
*/
template<class F, class B>
Matrix34_tpl<F> operator * (const Matrix34_tpl<F, B>& l, const Matrix33_tpl<F>& r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix34_tpl<F> m;
m.m00 = l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20;
m.m10 = l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20;
m.m20 = l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20;
m.m01 = l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21;
m.m11 = l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21;
m.m21 = l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21;
m.m02 = l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22;
m.m12 = l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22;
m.m22 = l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22;
m.m03 = l.m03;
m.m13 = l.m13;
m.m23 = l.m23;
return m;
}
/*!
* Implements the multiplication operator: Matrix34=Matrix34*Matrix34
*
* Matrix34 is specified in collumn order.
* AxB = rotation B followed by rotation A.
* This operation takes 36 mults and 27 adds.
*
* Example:
* Matrix34 m34=Matrix34::CreateRotationX(1.94192f, Vec3(11,22,33));;
* Matrix34 m34=Matrix33::CreateRotationZ(3.14192f);
* Matrix34 result=m34*m34;
*/
template<class F, class B, class C>
Matrix34_tpl<F> operator * (const Matrix34_tpl<F, B>& l, const Matrix34_tpl<F, C>& r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix34_tpl<F> m;
m.m00 = l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20;
m.m10 = l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20;
m.m20 = l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20;
m.m01 = l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21;
m.m11 = l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21;
m.m21 = l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21;
m.m02 = l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22;
m.m12 = l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22;
m.m22 = l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22;
m.m03 = l.m00*r.m03 + l.m01*r.m13 + l.m02*r.m23 + l.m03;
m.m13 = l.m10*r.m03 + l.m11*r.m13 + l.m12*r.m23 + l.m13;
m.m23 = l.m20*r.m03 + l.m21*r.m13 + l.m22*r.m23 + l.m23;
return m;
}
/*!
* Implements the multiplication operator: Matrix44=Matrix34*Matrix44
*
* Matrix44 and Matrix34 are specified in collumn order.
* AxB = rotation B followed by rotation A.
* This operation takes 48 mults and 36 adds.
*
* Example:
* Matrix34 m34=Matrix33::CreateRotationX(1.94192f);;
* Matrix44 m44=Matrix33::CreateRotationZ(3.14192f);
* Matrix44 result=m34*m44;
*/
template<class F, class B, class C>
Matrix44_tpl<F, XMVec4A> operator * (const Matrix34_tpl<F, B>& l, const Matrix44_tpl<F, C>& r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix44_tpl<F, XMVec4A> m;
m.m00 = l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20 + l.m03*r.m30;
m.m10 = l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20 + l.m13*r.m30;
m.m20 = l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20 + l.m23*r.m30;
m.m30 = r.m30;
m.m01 = l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21 + l.m03*r.m31;
m.m11 = l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21 + l.m13*r.m31;
m.m21 = l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21 + l.m23*r.m31;
m.m31 = r.m31;
m.m02 = l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22 + l.m03*r.m32;
m.m12 = l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22 + l.m13*r.m32;
m.m22 = l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22 + l.m23*r.m32;
m.m32 = r.m32;
m.m03 = l.m00*r.m03 + l.m01*r.m13 + l.m02*r.m23 + l.m03*r.m33;
m.m13 = l.m10*r.m03 + l.m11*r.m13 + l.m12*r.m23 + l.m13*r.m33;
m.m23 = l.m20*r.m03 + l.m21*r.m13 + l.m22*r.m23 + l.m23*r.m33;
m.m33 = r.m33;
return m;
}
/*!
* Create a matrix with SCALING, ROTATION and TRANSLATION (in this order).
*
* Example 1:
* Matrix m34;
* m34.SetMatrix( Vec3(1,2,3), quat, Vec3(11,22,33) );
*/
template<class F, class A>
void Matrix34_tpl<F, A>::Set( const Vec3_tpl<F>& s, const Quat_tpl<F>& q, const Vec3_tpl<F>& t ) {
assert(s.IsValid());
assert(q.IsUnit(0.1f));
assert(t.IsValid());
F vxvx=q.v.x*q.v.x; F vzvz=q.v.z*q.v.z; F vyvy=q.v.y*q.v.y;
F vxvy=q.v.x*q.v.y; F vxvz=q.v.x*q.v.z; F vyvz=q.v.y*q.v.z;
F svx=q.w*q.v.x; F svy=q.w*q.v.y; F svz=q.w*q.v.z;
m00=(1-(vyvy+vzvz)*2)*s.x; m01=(vxvy-svz)*2*s.y; m02=(vxvz+svy)*2*s.z; m03=t.x;
m10=(vxvy+svz)*2*s.x; m11=(1-(vxvx+vzvz)*2)*s.y; m12=(vyvz-svx)*2*s.z; m13=t.y;
m20=(vxvz-svy)*2*s.x; m21=(vyvz+svx)*2*s.y; m22=(1-(vxvx+vyvy)*2)*s.z; m23=t.z;
}
template<class F, class A>
ILINE Matrix34_tpl<F> Matrix34_tpl<F, A>::Create( const Vec3_tpl<F>& s, const Quat_tpl<F>& q, const Vec3_tpl<F>& t ) { Matrix34_tpl<F, A> m34; m34.Set(s,q,t); return m34; }
/*!
* Create scaling-matrix.
* The translation-vector is set to zero.
*
* Example 1:
* Matrix m34;
* m34.SetScale( Vec3(0.5f, 1.0f, 2.0f) );
*
* Example 2:
* Matrix34 m34 = Matrix34::CreateScale( Vec3(0.5f, 1.0f, 2.0f) );
*/
template<class F, class B>
ILINE void Matrix34_tpl<F, B>::SetScale( const Vec3_tpl<F> &s, const Vec3_tpl<F>& t ) {
*this=Matrix33::CreateScale(s); this->SetTranslation(t);
}
template<class F, class A>
ILINE Matrix34_tpl<F> Matrix34_tpl<F, A>::CreateScale( const Vec3_tpl<F> &s, const Vec3_tpl<F>& t ) { Matrix34_tpl<F, A> m34; m34.SetScale(s,t); return m34; }
/*!
* calculate a real inversion of a Matrix34
* an inverse-matrix is an UnDo-matrix for all kind of transformations
*
* Example 1:
* Matrix34 im34;
* im34.Invert();
*
* Example 2:
* Matrix34 im34=m34.GetInverted();
*/
template<class F, class B>
void Matrix34_tpl<F, B>::Invert( void ) {
//rescue members
Matrix34_tpl<F> m=*this;
// calculate 12 cofactors
m00= m.m22*m.m11-m.m12*m.m21;
m10= m.m12*m.m20-m.m22*m.m10;
m20= m.m10*m.m21-m.m20*m.m11;
m01= m.m02*m.m21-m.m22*m.m01;
m11= m.m22*m.m00-m.m02*m.m20;
m21= m.m20*m.m01-m.m00*m.m21;
m02= m.m12*m.m01-m.m02*m.m11;
m12= m.m02*m.m10-m.m12*m.m00;
m22= m.m00*m.m11-m.m10*m.m01;
m03= (m.m22*m.m13*m.m01 + m.m02*m.m23*m.m11 + m.m12*m.m03*m.m21) - (m.m12*m.m23*m.m01 + m.m22*m.m03*m.m11 + m.m02*m.m13*m.m21);
m13= (m.m12*m.m23*m.m00 + m.m22*m.m03*m.m10 + m.m02*m.m13*m.m20) - (m.m22*m.m13*m.m00 + m.m02*m.m23*m.m10 + m.m12*m.m03*m.m20);
m23= (m.m20*m.m11*m.m03 + m.m00*m.m21*m.m13 + m.m10*m.m01*m.m23) - (m.m10*m.m21*m.m03 + m.m20*m.m01*m.m13 + m.m00*m.m11*m.m23);
// calculate determinant
F det=1.0f/(m.m00*m00+m.m10*m01+m.m20*m02);
assert( fabs_tpl(det)>(F)0.00000001 );
// calculate matrix inverse/
m00*=det; m01*=det; m02*=det; m03*=det;
m10*=det; m11*=det; m12*=det; m13*=det;
m20*=det; m21*=det; m22*=det; m23*=det;
}
template<class F, class A>
ILINE Matrix34_tpl<F> Matrix34_tpl<F, A>::GetInverted() const { Matrix34_tpl<F> dst=*this; dst.Invert(); return dst; }
/*!
* Name: ReflectMat34
* Description: reflect a rotation matrix with respect to a plane.
*
* Example:
* Vec3 normal( 0.0f,-1.0f, 0.0f);
* Vec3 pos(0,1000,0);
* Matrix34 m34=CreateReflectionMat( pos, normal );
*/
static Matrix34 CreateReflectionMat ( const Vec3& p, const Vec3& n )
{
Matrix34 m;
f32 vxy = -2.0f * n.x * n.y;
f32 vxz = -2.0f * n.x * n.z;
f32 vyz = -2.0f * n.y * n.z;
f32 pdotn = 2.0f * (p|n);
m.m00=1.0f-2.0f*n.x*n.x; m.m01=vxy; m.m02=vxz; m.m03=pdotn*n.x;
m.m10=vxy; m.m11=1.0f-2.0f*n.y*n.y; m.m12=vyz; m.m13=pdotn*n.y;
m.m20=vxz; m.m21=vyz; m.m22=1.0f-2.0f*n.z*n.z; m.m23=pdotn*n.z;
return m;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Matrix44_tpl
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template<typename F, class A=XMVec4A> struct Matrix44_tpl
{
#ifndef XENON_INTRINSICS
F m00,m01,m02,m03;
F m10,m11,m12,m13;
F m20,m21,m22,m23;
F m30,m31,m32,m33;
#endif
//---------------------------------------------------------------------------------
#if defined(_DEBUG) && !defined(__SPU__)
ILINE Matrix44_tpl()
{
if (sizeof(F)==4)
{
uint32* p=(uint32*)&m00;
p[ 0]=F32NAN; p[ 1]=F32NAN; p[ 2]=F32NAN; p[ 3]=F32NAN;
p[ 4]=F32NAN; p[ 5]=F32NAN; p[ 6]=F32NAN; p[ 7]=F32NAN;
p[ 8]=F32NAN; p[ 9]=F32NAN; p[10]=F32NAN; p[11]=F32NAN;
p[12]=F32NAN; p[13]=F32NAN; p[14]=F32NAN; p[15]=F32NAN;
}
if (sizeof(F)==8)
{
uint64* p=(uint64*)&m00;
p[ 0]=F64NAN; p[ 1]=F64NAN; p[ 2]=F64NAN; p[ 3]=F64NAN;
p[ 4]=F64NAN; p[ 5]=F64NAN; p[ 6]=F64NAN; p[ 7]=F64NAN;
p[ 8]=F64NAN; p[ 9]=F64NAN; p[10]=F64NAN; p[11]=F64NAN;
p[12]=F64NAN; p[13]=F64NAN; p[14]=F64NAN; p[15]=F64NAN;
}
}
#else
ILINE Matrix44_tpl(){};
#endif
template<class F1> ILINE Matrix44_tpl(const Matrix33_tpl<F1>& m ) {
assert(m.IsValid());
m00=(F)m.m00; m01=(F)m.m01; m02=(F)m.m02; m03=0;
m10=(F)m.m10; m11=(F)m.m11; m12=(F)m.m12; m13=0;
m20=(F)m.m20; m21=(F)m.m21; m22=(F)m.m22; m23=0;
m30=0; m31=0; m32=0; m33=1;
}
template<class F1, class B> explicit ILINE Matrix44_tpl(const Matrix34_tpl<F1, B>& m ) {
assert(m.IsValid());
#ifndef XENON_INTRINSICS
m00=(F)m.m00; m01=(F)m.m01; m02=(F)m.m02; m03=(F)m.m03;
m10=(F)m.m10; m11=(F)m.m11; m12=(F)m.m12; m13=(F)m.m13;
m20=(F)m.m20; m21=(F)m.m21; m22=(F)m.m22; m23=(F)m.m23;
m30=0; m31=0; m32=0; m33=1;
#endif
}
template<class F1, class B> ILINE Matrix44_tpl(const Matrix44_tpl<F1, B>& m ) {
assert(m.IsValid());
#ifndef XENON_INTRINSICS
m00=(F)m.m00; m01=(F)m.m01; m02=(F)m.m02; m03=(F)m.m03;
m10=(F)m.m10; m11=(F)m.m11; m12=(F)m.m12; m13=(F)m.m13;
m20=(F)m.m20; m21=(F)m.m21; m22=(F)m.m22; m23=(F)m.m23;
m30=(F)m.m30; m31=(F)m.m31; m32=(F)m.m32; m33=(F)m.m33;
#endif
}
//---------------------------------------------------------------------------------
//! build a matrix from 16 f32s
Matrix44_tpl( f32 v00, f32 v01, f32 v02, f32 v03,
f32 v10, f32 v11, f32 v12, f32 v13,
f32 v20, f32 v21, f32 v22, f32 v23,
f32 v30, f32 v31, f32 v32, f32 v33) :
m00(v00), m01(v01), m02(v02), m03(v03),
m10(v10), m11(v11), m12(v12), m13(v13),
m20(v20), m21(v21), m22(v22), m23(v23),
m30(v30), m31(v31), m32(v32), m33(v33)
{
}
//---------------------------------------------------------------------
//! multiply all m1 matrix's values by f and return the matrix
friend Matrix44_tpl<F> operator * (const Matrix44_tpl<F, A>& m, const f32 f) {
assert(m.IsValid());
Matrix44_tpl<F> r;
#if 1 //ndef XENON_INTRINSICS
r.m00=m.m00*f; r.m01=m.m01*f; r.m02=m.m02*f; r.m03=m.m03*f;
r.m10=m.m10*f; r.m11=m.m11*f; r.m12=m.m12*f; r.m13=m.m13*f;
r.m20=m.m20*f; r.m21=m.m21*f; r.m22=m.m22*f; r.m23=m.m23*f;
r.m30=m.m30*f; r.m31=m.m31*f; r.m32=m.m32*f; r.m33=m.m33*f;
#else
XMVECTOR xm0 = A::LoadVec4(&m.m0);
XMVECTOR xm1 = A::LoadVec4(&m.m1);
XMVECTOR xm2 = A::LoadVec4(&m.m2);
XMVECTOR xm3 = A::LoadVec4(&m.m3);
XMVECTOR v = XMVectorReplicate(f);
XMVec4A::StoreVec4(&r.m0, xm0*v);
XMVec4A::StoreVec4(&r.m1, xm1*v);
XMVec4A::StoreVec4(&r.m2, xm2*v);
XMVec4A::StoreVec4(&r.m3, xm3*v);
#endif
return r;
}
template<class B> ILINE Matrix44_tpl& operator = (const Matrix44_tpl<F, B> &m) {
assert(m.IsValid());
#if 1 //ndef XENON_INTRINSICS
m00=m.m00; m01=m.m01; m02=m.m02; m03=m.m03;
m10=m.m10; m11=m.m11; m12=m.m12; m13=m.m13;
m20=m.m20; m21=m.m21; m22=m.m22; m23=m.m23;
m30=m.m30; m31=m.m31; m32=m.m32; m33=m.m33;
#else
XMVECTOR xm0 = B::LoadVec4(&m.m0);
XMVECTOR xm1 = B::LoadVec4(&m.m1);
XMVECTOR xm2 = B::LoadVec4(&m.m2);
XMVECTOR xm3 = B::LoadVec4(&m.m3);
A::StoreVec4(&m0, xm0);
A::StoreVec4(&m1, xm1);
A::StoreVec4(&m2, xm2);
A::StoreVec4(&m3, xm3);
#endif
return *this;
}
template<class F1, class B> ILINE Matrix44_tpl& operator = (const Matrix34_tpl<F1, B> &m) {
assert(m.IsValid());
#if 1 //ndef XENON_INTRINSICS
m00=m.m00; m01=m.m01; m02=m.m02; m03=m.m03;
m10=m.m10; m11=m.m11; m12=m.m12; m13=m.m13;
m20=m.m20; m21=m.m21; m22=m.m22; m23=m.m23;
m30=0; m31=0; m32=0; m33=1;
#else
XMVECTOR xm0 = B::LoadVec4(&m.m0);
XMVECTOR xm1 = B::LoadVec4(&m.m1);
XMVECTOR xm2 = B::LoadVec4(&m.m2);
XMVECTOR xm3 = g_XMIdentityR3;
A::StoreVec4(&m0, xm0);
A::StoreVec4(&m1, xm1);
A::StoreVec4(&m2, xm2);
A::StoreVec4(&m3, xm3);
#endif
return *this;
}
//! add all m matrix's values and return the matrix
template<class B> friend Matrix44_tpl<F> operator + (const Matrix44_tpl<F, A>& mm0, const Matrix44_tpl<F, B>& mm1) {
assert(mm0.IsValid());
assert(mm1.IsValid());
Matrix44_tpl<F> r;
r.m00=mm0.m00 + mm1.m00; r.m01=mm0.m01 + mm1.m01; r.m02=mm0.m02 + mm1.m02; r.m03=mm0.m03 + mm1.m03;
r.m10=mm0.m10 + mm1.m10; r.m11=mm0.m11 + mm1.m11; r.m12=mm0.m12 + mm1.m12; r.m13=mm0.m13 + mm1.m13;
r.m20=mm0.m20 + mm1.m20; r.m21=mm0.m21 + mm1.m21; r.m22=mm0.m22 + mm1.m22; r.m23=mm0.m23 + mm1.m23;
r.m30=mm0.m30 + mm1.m30; r.m31=mm0.m31 + mm1.m31; r.m32=mm0.m32 + mm1.m32; r.m33=mm0.m33 + mm1.m33;
return r;
}
ILINE void SetIdentity() {
m00=1; m01=0; m02=0; m03=0;
m10=0; m11=1; m12=0; m13=0;
m20=0; m21=0; m22=1; m23=0;
m30=0; m31=0; m32=0; m33=1;
}
ILINE Matrix44_tpl(type_identity) { SetIdentity(); }
_inline void Transpose()
{
Transpose(*this);
}
template <class B> _inline void Transpose(const Matrix44_tpl<float, B>& M)
{
Matrix44_tpl<F> m;
m.m00=M.m00; m.m01=M.m10; m.m02=M.m20; m.m03=M.m30;
m.m10=M.m01; m.m11=M.m11; m.m12=M.m21; m.m13=M.m31;
m.m20=M.m02; m.m21=M.m12; m.m22=M.m22; m.m23=M.m32;
m.m30=M.m03; m.m31=M.m13; m.m32=M.m23; m.m33=M.m33;
m00=m.m00; m01=m.m01; m02=m.m02; m03=m.m03;
m10=m.m10; m11=m.m11; m12=m.m12; m13=m.m13;
m20=m.m20; m21=m.m21; m22=m.m22; m23=m.m23;
m30=m.m30; m31=m.m31; m32=m.m32; m33=m.m33;
}
template <class B> _inline void Transpose(const Matrix34_tpl<float, B>& M)
{
Matrix44_tpl<F> m;
m.m00=M.m00; m.m01=M.m10; m.m02=M.m20;
m.m10=M.m01; m.m11=M.m11; m.m12=M.m21;
m.m20=M.m02; m.m21=M.m12; m.m22=M.m22;
m.m30=M.m03; m.m31=M.m13; m.m32=M.m23;
m00=m.m00; m01=m.m01; m02=m.m02; m03=0;
m10=m.m10; m11=m.m11; m12=m.m12; m13=0;
m20=m.m20; m21=m.m21; m22=m.m22; m23=0;
m30=m.m30; m31=m.m31; m32=m.m32; m33=1;
}
friend Matrix44_tpl<F, XMVec4A> GetTransposed44( const Matrix44_tpl<F, A>& m ) {
Matrix44_tpl<F, XMVec4A> dst;
dst.m00=m.m00; dst.m01=m.m10; dst.m02=m.m20; dst.m03=m.m30;
dst.m10=m.m01; dst.m11=m.m11; dst.m12=m.m21; dst.m13=m.m31;
dst.m20=m.m02; dst.m21=m.m12; dst.m22=m.m22; dst.m23=m.m32;
dst.m30=m.m03; dst.m31=m.m13; dst.m32=m.m23; dst.m33=m.m33;
return dst;
}
/*!
*
* calculate a real inversion of a Matrix44.
* an inverse-matrix is an UnDo-matrix for all kind of transformations
*
* Example 1:
* Matrix44 im44;
* im44.Invert();
*
* Example 2:
* Matrix44 im44=m33.GetInverted();
*/
void Invert( void ) {
F tmp[12];
Matrix44_tpl<F> m=*this;
/* calculate pairs for first 8 elements (cofactors) */
tmp[0] = m.m22 * m.m33;
tmp[1] = m.m32 * m.m23;
tmp[2] = m.m12 * m.m33;
tmp[3] = m.m32 * m.m13;
tmp[4] = m.m12 * m.m23;
tmp[5] = m.m22 * m.m13;
tmp[6] = m.m02 * m.m33;
tmp[7] = m.m32 * m.m03;
tmp[8] = m.m02 * m.m23;
tmp[9] = m.m22 * m.m03;
tmp[10]= m.m02 * m.m13;
tmp[11]= m.m12 * m.m03;
/* calculate first 8 elements (cofactors) */
m00 = tmp[0]*m.m11 + tmp[3]*m.m21 + tmp[ 4]*m.m31;
m00-= tmp[1]*m.m11 + tmp[2]*m.m21 + tmp[ 5]*m.m31;
m01 = tmp[1]*m.m01 + tmp[6]*m.m21 + tmp[ 9]*m.m31;
m01-= tmp[0]*m.m01 + tmp[7]*m.m21 + tmp[ 8]*m.m31;
m02 = tmp[2]*m.m01 + tmp[7]*m.m11 + tmp[10]*m.m31;
m02-= tmp[3]*m.m01 + tmp[6]*m.m11 + tmp[11]*m.m31;
m03 = tmp[5]*m.m01 + tmp[8]*m.m11 + tmp[11]*m.m21;
m03-= tmp[4]*m.m01 + tmp[9]*m.m11 + tmp[10]*m.m21;
m10 = tmp[1]*m.m10 + tmp[2]*m.m20 + tmp[ 5]*m.m30;
m10-= tmp[0]*m.m10 + tmp[3]*m.m20 + tmp[ 4]*m.m30;
m11 = tmp[0]*m.m00 + tmp[7]*m.m20 + tmp[ 8]*m.m30;
m11-= tmp[1]*m.m00 + tmp[6]*m.m20 + tmp[ 9]*m.m30;
m12 = tmp[3]*m.m00 + tmp[6]*m.m10 + tmp[11]*m.m30;
m12-= tmp[2]*m.m00 + tmp[7]*m.m10 + tmp[10]*m.m30;
m13 = tmp[4]*m.m00 + tmp[9]*m.m10 + tmp[10]*m.m20;
m13-= tmp[5]*m.m00 + tmp[8]*m.m10 + tmp[11]*m.m20;
/* calculate pairs for second 8 elements (cofactors) */
tmp[ 0] = m.m20*m.m31;
tmp[ 1] = m.m30*m.m21;
tmp[ 2] = m.m10*m.m31;
tmp[ 3] = m.m30*m.m11;
tmp[ 4] = m.m10*m.m21;
tmp[ 5] = m.m20*m.m11;
tmp[ 6] = m.m00*m.m31;
tmp[ 7] = m.m30*m.m01;
tmp[ 8] = m.m00*m.m21;
tmp[ 9] = m.m20*m.m01;
tmp[10] = m.m00*m.m11;
tmp[11] = m.m10*m.m01;
/* calculate second 8 elements (cofactors) */
m20 = tmp[ 0]*m.m13 + tmp[ 3]*m.m23 + tmp[ 4]*m.m33;
m20-= tmp[ 1]*m.m13 + tmp[ 2]*m.m23 + tmp[ 5]*m.m33;
m21 = tmp[ 1]*m.m03 + tmp[ 6]*m.m23 + tmp[ 9]*m.m33;
m21-= tmp[ 0]*m.m03 + tmp[ 7]*m.m23 + tmp[ 8]*m.m33;
m22 = tmp[ 2]*m.m03 + tmp[ 7]*m.m13 + tmp[10]*m.m33;
m22-= tmp[ 3]*m.m03 + tmp[ 6]*m.m13 + tmp[11]*m.m33;
m23 = tmp[ 5]*m.m03 + tmp[ 8]*m.m13 + tmp[11]*m.m23;
m23-= tmp[ 4]*m.m03 + tmp[ 9]*m.m13 + tmp[10]*m.m23;
m30 = tmp[ 2]*m.m22 + tmp[ 5]*m.m32 + tmp[ 1]*m.m12;
m30-= tmp[ 4]*m.m32 + tmp[ 0]*m.m12 + tmp[ 3]*m.m22;
m31 = tmp[ 8]*m.m32 + tmp[ 0]*m.m02 + tmp[ 7]*m.m22;
m31-= tmp[ 6]*m.m22 + tmp[ 9]*m.m32 + tmp[ 1]*m.m02;
m32 = tmp[ 6]*m.m12 + tmp[11]*m.m32 + tmp[ 3]*m.m02;
m32-= tmp[10]*m.m32 + tmp[ 2]*m.m02 + tmp[ 7]*m.m12;
m33 = tmp[10]*m.m22 + tmp[ 4]*m.m02 + tmp[ 9]*m.m12;
m33-= tmp[ 8]*m.m12 + tmp[11]*m.m22 + tmp[ 5]*m.m02;
/* calculate determinant */
F det=(m.m00*m00+m.m10*m01+m.m20*m02+m.m30*m03);
//if (fabs_tpl(det)<0.0001f) assert(0);
//devide the cofactor-matrix by the determinat
F idet=(F)1.0/det;
m00*=idet; m01*=idet; m02*=idet; m03*=idet;
m10*=idet; m11*=idet; m12*=idet; m13*=idet;
m20*=idet; m21*=idet; m22*=idet; m23*=idet;
m30*=idet; m31*=idet; m32*=idet; m33*=idet;
}
ILINE Matrix44_tpl<F> GetInverted() const { Matrix44_tpl<F> dst=*this; dst.Invert(); return dst; }
template <class B> _inline void Invert(const Matrix44_tpl<float, B>& M)
{
*this = M.GetInverted();
}
template <class F1, class F2, class B, class C> _inline void Multiply(const Matrix44_tpl<F1, B>& l, const Matrix44_tpl<F2, C>& r)
{
Matrix44_tpl<F> res;
res.m00 = l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20 + l.m03*r.m30;
res.m10 = l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20 + l.m13*r.m30;
res.m20 = l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20 + l.m23*r.m30;
res.m30 = l.m30*r.m00 + l.m31*r.m10 + l.m32*r.m20 + l.m33*r.m30;
res.m01 = l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21 + l.m03*r.m31;
res.m11 = l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21 + l.m13*r.m31;
res.m21 = l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21 + l.m23*r.m31;
res.m31 = l.m30*r.m01 + l.m31*r.m11 + l.m32*r.m21 + l.m33*r.m31;
res.m02 = l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22 + l.m03*r.m32;
res.m12 = l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22 + l.m13*r.m32;
res.m22 = l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22 + l.m23*r.m32;
res.m32 = l.m30*r.m02 + l.m31*r.m12 + l.m32*r.m22 + l.m33*r.m32;
res.m03 = l.m00*r.m03 + l.m01*r.m13 + l.m02*r.m23 + l.m03*r.m33;
res.m13 = l.m10*r.m03 + l.m11*r.m13 + l.m12*r.m23 + l.m13*r.m33;
res.m23 = l.m20*r.m03 + l.m21*r.m13 + l.m22*r.m23 + l.m23*r.m33;
res.m33 = l.m30*r.m03 + l.m31*r.m13 + l.m32*r.m23 + l.m33*r.m33;
*this = res;
}
ILINE f32 Determinant() const {
//determinant is ambiguous: only the upper-left-submatrix's determinant is calculated
return (m00*m11*m22) + (m01*m12*m20) + (m02*m10*m21) - (m02*m11*m20) - (m00*m12*m21) - (m01*m10*m22);
}
//! transform a vector
Vec3 TransformVector(const Vec3 &b) const {
assert(b.IsValid());
Vec3 v;
v.x = m00*b.x + m01*b.y + m02*b.z;
v.y = m10*b.x + m11*b.y + m12*b.z;
v.z = m20*b.x + m21*b.y + m22*b.z;
return v;
}
//! transform a point
Vec3 TransformPoint(const Vec3 &b) const {
assert(b.IsValid());
Vec3 v;
v.x = m00*b.x + m01*b.y + m02* b.z + m03;
v.y = m10*b.x + m11*b.y + m12* b.z + m13;
v.z = m20*b.x + m21*b.y + m22* b.z + m23;
return v;
}
//--------------------------------------------------------------------------------
//---- helper functions to access matrix-members ------------
//--------------------------------------------------------------------------------
F *GetData() { return &m00; }
const F *GetData() const { return &m00; }
ILINE F operator () (uint32 i, uint32 j) const { assert ((i<4) && (j<4)); F* p_data=(F*)(&m00); return p_data[i*4+j]; }
ILINE F& operator () (uint32 i, uint32 j) { assert ((i<4) && (j<4)); F* p_data=(F*)(&m00); return p_data[i*4+j]; }
ILINE void SetRow(int i, const Vec3_tpl<F> &v) { assert(i<4); F* p=(F*)(&m00); p[0+4*i]=v.x; p[1+4*i]=v.y; p[2+4*i]=v.z; }
ILINE const Vec3_tpl<F>& GetRow(int i) const { assert(i<4); return *(const Vec3_tpl<F>*)(&m00 + 4*i); }
ILINE void SetColumn(int i, const Vec3_tpl<F> &v) { assert(i<4); F* p=(F*)(&m00); p[i+4*0]=v.x; p[i+4*1]=v.y; p[i+4*2]=v.z; }
ILINE Vec3_tpl<F> GetColumn(int i) const { assert(i<4); F* p=(F*)(&m00); return Vec3(p[i+4*0],p[i+4*1],p[i+4*2]); }
ILINE Vec4_tpl<F> GetColumn4(int i) const { assert(i<4); F* p=(F*)(&m00); return Vec4(p[i+4*0],p[i+4*1],p[i+4*2],p[i+4*3]); }
ILINE Vec3 GetTranslation() const { return Vec3( m03, m13, m23 ); }
ILINE void SetTranslation( const Vec3& t ) { m03=t.x; m13=t.y; m23=t.z; }
bool IsValid() const
{
if (!NumberValid(m00)) return false; if (!NumberValid(m01)) return false; if (!NumberValid(m02)) return false; if (!NumberValid(m03)) return false;
if (!NumberValid(m10)) return false; if (!NumberValid(m11)) return false; if (!NumberValid(m12)) return false; if (!NumberValid(m13)) return false;
if (!NumberValid(m20)) return false; if (!NumberValid(m21)) return false; if (!NumberValid(m22)) return false; if (!NumberValid(m23)) return false;
if (!NumberValid(m30)) return false; if (!NumberValid(m31)) return false; if (!NumberValid(m32)) return false; if (!NumberValid(m33)) return false;
return true;
}
// new operators
inline void* operator new ( size_t s ) { return A::New(s); }
inline void* operator new[] ( size_t s ) { return A::New(s); }
inline void* operator new ( size_t s, void *pMem ) { return pMem; };
inline void* operator new[]( size_t s, void *pMem ) { return pMem; }
// delete operators
inline void operator delete ( void* p ) { A::Del(p); }
inline void operator delete[] ( void* p ) { A::Del(p); }
inline void operator delete ( void* p, void* p1 ) { }
inline void operator delete[] ( void* p, void* p1 ) { }
AUTO_STRUCT_INFO
};
template<class F1, class B>
_inline Matrix44_tpl<float, XMVec4A> GetTransposed44A( const Matrix34_tpl<F1, B>& m )
{
Matrix44_tpl<float, XMVec4A> dst;
dst.Transpose(m);
return dst;
}
///////////////////////////////////////////////////////////////////////////////
// Typedefs //
///////////////////////////////////////////////////////////////////////////////
typedef Matrix44_tpl<f32, XMVec4> Matrix44;
typedef Matrix44_tpl<f64, XMVec4> Matrix44_f64;
typedef Matrix44_tpl<real, XMVec4> Matrix44r;
typedef Matrix44_tpl<f32, XMVec4A> Matrix44A;
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//------------- implementation of Matrix44 ------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
/*!
* Implements the multiplication operator: Matrix44=Matrix44*Matrix33diag
*
* Matrix44 and Matrix33diag are specified in collumn order.
* AxB = operation B followed by operation A.
* This operation takes 12 mults.
*
* Example:
* Matrix33diag diag(1,2,3);
* Matrix44 m44=CreateRotationZ33(3.14192f);
* Matrix44 result=m44*diag;
*/
template<class F1, class F2, class B>
Matrix44_tpl<F1> operator * (const Matrix44_tpl<F1>& l, const Diag33_tpl<F2>& r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix44_tpl<F1> m;
m.m00=l.m00*r.x; m.m01=l.m01*r.y; m.m02=l.m02*r.z; m.m03=l.m03;
m.m10=l.m10*r.x; m.m11=l.m11*r.y; m.m12=l.m12*r.z; m.m13=l.m13;
m.m20=l.m20*r.x; m.m21=l.m21*r.y; m.m22=l.m22*r.z; m.m23=l.m23;
m.m30=l.m30*r.x; m.m31=l.m31*r.y; m.m32=l.m32*r.z; m.m33=l.m33;
return m;
}
template<class F1, class F2, class B>
Matrix44_tpl<F1>& operator *= (Matrix44_tpl<F1, B>& l, const Diag33_tpl<F2>& r) {
assert(l.IsValid());
assert(r.IsValid());
l.m00*=r.x; l.m01*=r.y; l.m02*=r.z;
l.m10*=r.x; l.m11*=r.y; l.m12*=r.z;
l.m20*=r.x; l.m21*=r.y; l.m22*=r.z;
l.m30*=r.x; l.m31*=r.y; l.m32*=r.z;
return l;
}
/*!
* Implements the multiplication operator: Matrix44=Matrix44*Matrix33
*
* Matrix44 and Matrix33 are specified in collumn order.
* AxB = rotation B followed by rotation A.
* This operation takes 48 mults and 24 adds.
*
* Example:
* Matrix33 m34=CreateRotationX33(1.94192f);;
* Matrix44 m44=CreateRotationZ33(3.14192f);
* Matrix44 result=m44*m33;
*/
template<class F1, class F2, class B>
Matrix44_tpl<F1> operator * (const Matrix44_tpl<F1, B>& l, const Matrix33_tpl<F2>& r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix44_tpl<F1> m;
m.m00 =l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20;
m.m10 =l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20;
m.m20 =l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20;
m.m30 =l.m30*r.m00 + l.m31*r.m10 + l.m32*r.m20;
m.m01 =l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21;
m.m11 =l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21;
m.m21 =l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21;
m.m31 =l.m30*r.m01 + l.m31*r.m11 + l.m32*r.m21;
m.m02 =l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22;
m.m12 =l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22;
m.m22 =l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22;
m.m32 =l.m30*r.m02 + l.m31*r.m12 + l.m32*r.m22;
m.m03 =l.m03;
m.m13 =l.m13;
m.m23 =l.m23;
m.m33 =l.m33;
return m;
}
/*!
* Implements the multiplication operator: Matrix44=Matrix44*Matrix34
*
* Matrix44 and Matrix34 are specified in collumn order.
* AxB = rotation B followed by rotation A.
* This operation takes 48 mults and 36 adds.
*
* Example:
* Matrix34 m34=CreateRotationX33(1.94192f);;
* Matrix44 m44=CreateRotationZ33(3.14192f);
* Matrix44 result=m44*m34;
*/
template<class F, class B, class C>
Matrix44_tpl<F> operator * (const Matrix44_tpl<F, B>& l, const Matrix34_tpl<F, C>& r) {
assert(l.IsValid());
assert(r.IsValid());
Matrix44_tpl<F> m;
m.m00 = l.m00*r.m00 + l.m01*r.m10 + l.m02*r.m20;
m.m10 = l.m10*r.m00 + l.m11*r.m10 + l.m12*r.m20;
m.m20 = l.m20*r.m00 + l.m21*r.m10 + l.m22*r.m20;
m.m30 = l.m30*r.m00 + l.m31*r.m10 + l.m32*r.m20;
m.m01 = l.m00*r.m01 + l.m01*r.m11 + l.m02*r.m21;
m.m11 = l.m10*r.m01 + l.m11*r.m11 + l.m12*r.m21;
m.m21 = l.m20*r.m01 + l.m21*r.m11 + l.m22*r.m21;
m.m31 = l.m30*r.m01 + l.m31*r.m11 + l.m32*r.m21;
m.m02 = l.m00*r.m02 + l.m01*r.m12 + l.m02*r.m22;
m.m12 = l.m10*r.m02 + l.m11*r.m12 + l.m12*r.m22;
m.m22 = l.m20*r.m02 + l.m21*r.m12 + l.m22*r.m22;
m.m32 = l.m30*r.m02 + l.m31*r.m12 + l.m32*r.m22;
m.m03 = l.m00*r.m03 + l.m01*r.m13 + l.m02*r.m23 + l.m03;
m.m13 = l.m10*r.m03 + l.m11*r.m13 + l.m12*r.m23 + l.m13;
m.m23 = l.m20*r.m03 + l.m21*r.m13 + l.m22*r.m23 + l.m23;
m.m33 = l.m30*r.m03 + l.m31*r.m13 + l.m32*r.m23 + l.m33;
return m;
}
/*!
* Implements the multiplication operator: Matrix44=Matrix44*Matrix44
*
* Matrix44 and Matrix34 are specified in collumn order.
* AxB = rotation B followed by rotation A.
* This operation takes 48 mults and 36 adds.
*
* Example:
* Matrix44 m44=CreateRotationX33(1.94192f);;
* Matrix44 m44=CreateRotationZ33(3.14192f);
* Matrix44 result=m44*m44;
*/
template<class F1, class F2, class B, class C>
ILINE Matrix44_tpl<F1> operator * (const Matrix44_tpl<F1, B>& l, const Matrix44_tpl<F2, C>& r)
{
assert(l.IsValid());
assert(r.IsValid());
Matrix44_tpl<F1> m;
m.Multiply(l, r);
return m;
}
//post-multiply
template<class F1, class F2, class B>
ILINE Vec4_tpl<F1> operator*(const Matrix44_tpl<F2, B> &m, const Vec4_tpl<F1> &v)
{
CHECK_SIMD_ALIGNMENT_P(&v);
assert(m.IsValid());
assert(v.IsValid());
return Vec4_tpl<F1>(v.x*m.m00 + v.y*m.m01 + v.z*m.m02 + v.w*m.m03,
v.x*m.m10 + v.y*m.m11 + v.z*m.m12 + v.w*m.m13,
v.x*m.m20 + v.y*m.m21 + v.z*m.m22 + v.w*m.m23,
v.x*m.m30 + v.y*m.m31 + v.z*m.m32 + v.w*m.m33);
}
//pre-multiply
template<class F1, class F2, class B>
ILINE Vec4_tpl<F1> operator*(const Vec4_tpl<F1> &v, const Matrix44_tpl<F2, B> &m)
{
CHECK_SIMD_ALIGNMENT_P(&v);
assert(m.IsValid());
assert(v.IsValid());
return Vec4_tpl<F1>(v.x*m.m00 + v.y*m.m10 + v.z*m.m20 + v.w*m.m30,
v.x*m.m01 + v.y*m.m11 + v.z*m.m21 + v.w*m.m31,
v.x*m.m02 + v.y*m.m12 + v.z*m.m22 + v.w*m.m32,
v.x*m.m03 + v.y*m.m13 + v.z*m.m23 + v.w*m.m33);
}
//reenable intrinsics
//union used to signal gcc aliasing (instead of c-style reinterpret_casts)
typedef union {Matrix44A *pM; Vec4 *pV;} conv_m44a_vec4_union;
typedef union {Matrix44 *pM; Vec4 *pV;} conv_m44_vec4_union;
#endif //MATRIX_H
| [
"[email protected]"
] | [
[
[
1,
2591
]
]
] |
1b201068d260e69a3a468adf5f4db3832223207c | c70941413b8f7bf90173533115c148411c868bad | /core/include/vtxFactoryManager.h | 3c71daf60a0cfba782b9a1189010fccc8c31a8dd | [] | no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,277 | h | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
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 __vtxFactoryManager_H__
#define __vtxFactoryManager_H__
#include "vtxLogManager.h"
namespace vtx
{
//-----------------------------------------------------------------------
/** A template for managing Factory instances */
template<typename T>
class FactoryManager
{
public:
//-----------------------------------------------------------------------
typedef std::map<String, T*> FactoryMap;
//-----------------------------------------------------------------------
FactoryManager(const String& base_type) : mBaseType(base_type) {}
//-----------------------------------------------------------------------
virtual ~FactoryManager()
{
typename FactoryMap::const_iterator it = mFactories.begin();
typename FactoryMap::const_iterator end = mFactories.end();
while(it != end)
{
delete it->second;
++it;
}
}
//-----------------------------------------------------------------------
virtual bool addFactory(T* factory)
{
typename FactoryMap::iterator it = mFactories.find(factory->getName());
if(it == mFactories.end())
{
mFactories.insert(typename FactoryMap::value_type(factory->getName(), factory));
// LOG: Factory added successfully
VTX_LOG("Added %sFactory '%s'.", mBaseType.c_str(), factory->getName().c_str());
return true;
}
// WARN: Factory already added
VTX_WARN("Tried to add %sFactory '%s' twice!", mBaseType.c_str(), factory->getName().c_str());
return false;
}
//-----------------------------------------------------------------------
virtual bool removeFactory(T* factory)
{
typename FactoryMap::iterator it = mFactories.find(factory->getName());
if(it != mFactories.end())
{
mFactories.erase(it);
// LOG: Factory removed successfully
VTX_LOG("Removed %sFactory '%s'.", mBaseType.c_str(), factory->getName().c_str());
return true;
}
// WARN: unknown Factory
VTX_WARN("Requested removal of unknown %sFactory '%s'!", mBaseType.c_str(), factory->getName().c_str());
return false;
}
//-----------------------------------------------------------------------
virtual T* getFactory(const String& name)
{
typename FactoryMap::iterator it = mFactories.find(name);
if(it != mFactories.end())
{
return it->second;
}
return NULL;
}
//-----------------------------------------------------------------------
protected:
String mBaseType;
FactoryMap mFactories;
};
//-----------------------------------------------------------------------
#define FactoryManagerImpl(name, type) \
class name : public FactoryManager<type##Factory> \
{ \
public: \
name() : FactoryManager<type##Factory>(#type){} \
};
//-----------------------------------------------------------------------
}
#endif
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
] | [
[
[
1,
124
]
]
] |
2a4e99e9bcb77ead423d88991ebbf491d1cdb9bc | 3532ae25961855b20635decd1481ed7def20c728 | /app/ClientLib/bob.cpp | 92b946624d333158a74d5ac0c99310cc8164c075 | [] | no_license | mcharmas/Bazinga | 121645a0c7bc8bd6a91322c2a7ecc56a5d3f71b7 | 1d35317422c913f28710b3182ee0e03822284ba3 | refs/heads/master | 2020-05-18T05:48:32.213937 | 2010-03-22T17:13:09 | 2010-03-22T17:13:09 | 577,323 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | cpp | #include "bob.h"
#include <QString>
BOb::BOb(quint16 x, quint16 y, quint16 width, quint16 height)
: x(x), y(y), width(width), height(height)
{}
BOb::BOb() : x(0), y(0), width(0), height(0)
{}
BOb::BOb(QByteArray &arr, int offset)
{
if(arr.size() < offset + 4 || offset < 0) {
x = y = width = height = 0;
} else {
x = (unsigned char) arr.at(offset);
y = (unsigned char) arr.at(offset + 1);
width = (unsigned char) arr.at(offset + 2);
height = (unsigned char) arr.at(offset + 3);
unsigned int rest = (unsigned char) arr.at(offset + 4);
/* 3 to binarnie 11, przesuwamy jako maske do wyciagania
kolejnych bitow po 2.
pozniej przesuwamy to o potrzebna ilosc miejsc, by znalazlo sie
jako 9-ty i 10-ty bit liczby.
*/
x |= (rest & (3 << 6)) << 2;
y |= (rest & (3 << 4)) << 4;
width |= (rest & (3 << 2)) << 6;
height |= (rest & 3 ) << 8;
}
}
void BOb::appendToArray(QByteArray &arr) const
{
char arrayTmp[] = { x & 0xff,
y & 0xff,
width & 0xff,
height & 0xff,
0 /* miejsce na "reszte" */ };
/* wyciagamy bity 10 i 9 i przesuwamy je w odpowiednie miejsce.
*/
int rest = 0;
quint16 mask = 3 << 8;
rest |= ( x & mask) >> 2;
rest |= ( y & mask) >> 4;
rest |= ( width & mask) >> 6;
rest |= (height & mask) >> 8;
arrayTmp[4] = rest & 0xff;
arr.append(arrayTmp, 5);
}
QString BOb::toString() const
{
return QString("[%1 %2 : %3 %4]").arg(x).arg(y).arg(width).arg(height);
}
| [
"santamon@ffdda973-792b-4bce-9e62-2343ac01ffa1"
] | [
[
[
1,
60
]
]
] |
d28b618bc031d6796cabf868509c516e981fda22 | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/examples/Water/src/main.cpp | 47d75f84ce18b0ed082c0d1d26fc9288411eb32d | [] | no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,030 | cpp | #define _DEBUG_NEW_REDEFINE_NEW 0
#include <boost/bind.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <sgl/State.h>
#include <sgl/Font.h>
#include <sstream>
#include "Engine.h"
#include "Graphics/Common.h"
#include "Database/Collada/Collada.h"
#include "Graphics/PhillipsSpectrum.h"
#include "Graphics/WaterEffect.h"
#include "Graphics/FogFilter.h"
#include "Graphics/ProjectedGrid.h"
#include "Graphics/SkyBox.h"
#include "Realm/BVHLocation.h"
#include "Scene/LookAtCamera.h"
#include "Scene/ReflectCamera.h"
#include "Scene/DirectionalLight.h"
#include "Input/KeyboardHandler.h"
#include "Input/MouseHandler.h"
#include "Scene/Group.h"
using namespace math;
using namespace slon;
using namespace slon::scene;
using namespace slon::graphics;
bool fullscreen;
bool benchmark;
int multisample;
int fftSize;
Vector2ui screenSize;
std::string demoModel;
// water spectrums
boost::shared_ptr<PhillipsSpectrum> phillipsSpectrum[4];
#undef CreateFont
namespace {
LookAtCamera* createMainCamera(const sgl::rectangle& viewport)
{
// create camera
LookAtCamera* camera = new LookAtCamera();
camera->setViewport(viewport);
camera->setProjectionMatrix( math::Matrix4f::perspective( 0.7853982f,
static_cast<float>(viewport.width) / viewport.height,
1.0f,
4000.0f ) );
return camera;
}
ReflectCamera* createReflectCamera(const Camera& mainCamera, sgl::Device* device)
{
using sgl::Texture;
// create camera
ReflectCamera* reflectCamera = new ReflectCamera( mainCamera, math::Planef(0.0f, 1.0f, 0.0f, 0.0f) );
reflectCamera->setViewport( sgl::rectangle(0, 0, 512, 512) );
// create refract texture
sgl::Texture2D* reflectTexture = 0;
{
sgl::Texture2D::DESC desc;
desc.format = Texture::RGBA8;
desc.width = 512;
desc.height = 512;
desc.data = 0;
reflectTexture = device->CreateTexture2D(desc);
}
sgl::SamplerState* samplerState = 0;
{
sgl::SamplerState::DESC desc;
desc.filter[0] = sgl::SamplerState::LINEAR;
desc.filter[1] = sgl::SamplerState::LINEAR;
desc.filter[2] = sgl::SamplerState::LINEAR;
desc.wrapping[0] = sgl::SamplerState::CLAMP;
desc.wrapping[1] = sgl::SamplerState::CLAMP;
samplerState = device->CreateSamplerState(desc);
}
reflectTexture->BindSamplerState(samplerState);
reflectTexture->GenerateMipmap();
// create render target
sgl::RenderTarget* renderTarget = device->CreateRenderTarget();
renderTarget->SetColorAttachment(0, reflectTexture, 0);
renderTarget->SetDepthStencil(true);
if ( sgl::SGL_OK != renderTarget->Dirty() ) {
throw std::runtime_error("Can't create render target for reflections.");
}
reflectCamera->setRenderTarget(renderTarget);
return reflectCamera;
}
SlaveCamera* createRefractCamera(const Camera& mainCamera, sgl::Device* device)
{
using sgl::Texture;
// create camera
SlaveCamera* refractCamera = new SlaveCamera(mainCamera);
refractCamera->setViewport( sgl::rectangle(0, 0, 512, 512) );
// create refract texture
sgl::Texture2D* refractTexture = 0;
{
sgl::Texture2D::DESC desc;
desc.format = Texture::RGBA8;
desc.width = 512;
desc.height = 512;
desc.data = 0;
refractTexture = device->CreateTexture2D(desc);
}
sgl::SamplerState* samplerState = 0;
{
sgl::SamplerState::DESC desc;
desc.filter[0] = sgl::SamplerState::LINEAR;
desc.filter[1] = sgl::SamplerState::LINEAR;
desc.filter[2] = sgl::SamplerState::LINEAR;
desc.wrapping[0] = sgl::SamplerState::CLAMP;
desc.wrapping[1] = sgl::SamplerState::CLAMP;
samplerState = device->CreateSamplerState(desc);
}
refractTexture->BindSamplerState(samplerState);
refractTexture->GenerateMipmap();
// create render target
sgl::RenderTarget* renderTarget = device->CreateRenderTarget();
renderTarget->SetColorAttachment(0, refractTexture, 0);
//renderTarget->SetDepthStencilAttachment(depthTexture, 0);
if ( sgl::SGL_OK != renderTarget->Dirty() ) {
throw std::runtime_error("Can't create render target for refractions.");
}
refractCamera->setRenderTarget(renderTarget);
return refractCamera;
}
sgl::Texture2D* createRefractTexture(sgl::Device* device)
{
// create refract texture
sgl::Texture2D* refractTexture = 0;
{
sgl::Texture2D::DESC desc;
desc.format = sgl::Texture::RGBA8;
desc.width = screenSize.x;
desc.height = screenSize.y;
desc.data = 0;
refractTexture = device->CreateTexture2D(desc);
}
sgl::SamplerState* samplerState = 0;
{
sgl::SamplerState::DESC desc;
desc.filter[0] = sgl::SamplerState::LINEAR;
desc.filter[1] = sgl::SamplerState::LINEAR;
desc.filter[2] = sgl::SamplerState::LINEAR;
desc.wrapping[0] = sgl::SamplerState::CLAMP;
desc.wrapping[1] = sgl::SamplerState::CLAMP;
samplerState = device->CreateSamplerState(desc);
}
refractTexture->BindSamplerState(samplerState);
refractTexture->GenerateMipmap();
return refractTexture;
}
sgl::Texture2D* createDepthTexture(sgl::Device* device)
{
// create refract texture
sgl::Texture2D* depthTexture = 0;
{
sgl::Texture2D::DESC desc;
desc.format = sgl::Texture::D24;
desc.width = screenSize.x;
desc.height = screenSize.y;
desc.data = 0;
depthTexture = device->CreateTexture2D(desc);
}
sgl::SamplerState* samplerState = 0;
{
sgl::SamplerState::DESC desc;
desc.filter[0] = sgl::SamplerState::NEAREST;
desc.filter[1] = sgl::SamplerState::NEAREST;
desc.filter[2] = sgl::SamplerState::NONE;
desc.wrapping[0] = sgl::SamplerState::CLAMP;
desc.wrapping[1] = sgl::SamplerState::CLAMP;
samplerState = device->CreateSamplerState(desc);
}
depthTexture->BindSamplerState(samplerState);
return depthTexture;
}
} // anonymous namespace
class DemoScene
{
public:
DemoScene( unsigned int windowWidth,
unsigned int windowHeight,
bool fullscreen,
unsigned int multisample ) :
time(0.0f),
fps(0.0f),
dt(0.0f),
drawHelp(true),
needToTakeScreenshot(false)
{
Engine* engine = Engine::Instance();
// setup graphics
{
using namespace slon::scene;
using namespace slon::database;
GraphicsManager& graphicsManager = currentGraphicsManager();
DatabaseManager& databaseManager = currentDatabaseManager();
// setup logging
{
log::currentLogManager().redirectOutput("database", "database_log.txt");
log::currentLogManager().redirectOutput("graphics", "graphics_log.txt");
}
graphicsManager.setVideoMode(windowWidth, windowHeight, 32, fullscreen, false, multisample);
// create renderer
{
ForwardRendererDesc desc;
desc.useDepthPass = true;
desc.makeDepthMap = true;
desc.useDebugRender = true;
Renderer* renderer = graphicsManager.initRenderer(desc);
renderer->connectPostRenderCallback( boost::bind(&DemoScene::OnPostRender, this, _1) );
}
//FreeConsole();
realm::World* world = realm::currentWorld();
realm::location_ptr location(new realm::BVHLocation);
world->addLocation(location);
// Create skybox
SkyBox* skyBox = new SkyBox();
{
const std::string SKY_BOX_MAPS[6] =
{
"Data/SkyBox/sunset_west.jpg",
"Data/SkyBox/sunset_east.jpg",
"Data/SkyBox/sunset_up.jpg",
"Data/SkyBox/sunset_down.jpg",
"Data/SkyBox/sunset_south.jpg",
"Data/SkyBox/sunset_north.jpg"
};
skyBox->MakeFromSideTextures(SKY_BOX_MAPS);
}
world->addInfiniteNode(skyBox);
// create scene
{
database::library_ptr library = database::loadLibrary("Data/Models/castle.DAE");
location->add(library->visualScenes.begin()->second, false);
// create light
scene::DirectionalLight* light = new DirectionalLight();
light->setDirection( normalize( Vector3f(-1.5f, -0.1f, 0.85f) ) );
light->setColor( Vector4f(0.8f, 0.8f, 0.8f, 1.0f) );
light->setAmbient(0.3f);
light->setIntensity(1.5f);
world->addInfiniteNode(light);
}
// Create cameras & water surface
{
sgl::rectangle viewport(0, 0, windowWidth, windowHeight);
camera.reset( createMainCamera(viewport) );
// attach post effects
fog_filter_ptr fogFilter( new FogFilter() );
fogFilter->setFogColor( math::Vector4f(1.0f, 1.0f, 1.0f, 1.0f) );
fogFilter->setFogDensity(0.001f);
fogFilter->setFogLevel(0.0f);
fogFilter->setFogHeightFalloff(0.005f);
camera->getPostEffectChain().push_back(fogFilter);
sgl::Device* device = currentDevice();
reflectCamera.reset( createReflectCamera(*camera, device) );
graphicsManager.addCamera( reflectCamera.get() );
graphicsManager.addCamera( camera.get() );
// create water
phillipsSpectrum[0].reset( new PhillipsSpectrum( 128, Vector2f(3.0f, 0.0f), Vector2f(25.6f, 25.6f) ) );
phillipsSpectrum[1].reset( new PhillipsSpectrum( 256, Vector2f(4.0f, 0.0f), Vector2f(25.6f, 25.6f) ) );
phillipsSpectrum[2].reset( new PhillipsSpectrum( 512, Vector2f(5.0f, 5.0f), Vector2f(51.2f, 51.2f) ) );
phillipsSpectrum[3].reset( new PhillipsSpectrum( 1024, Vector2f(5.0f, 5.0f), Vector2f(102.4f, 102.4f) ) );
// get reflect/refract textures
sgl::Texture2D* reflectTexture = static_cast<sgl::Texture2D*>( reflectCamera->getRenderTarget()->ColorAttachment(0) );
sgl::Texture2D* refractTexture = createRefractTexture(device);
sgl::Texture2D* depthTexture = createDepthTexture(device);
waterEffect.reset( new WaterEffect(phillipsSpectrum[1]) );
waterEffect->setEnvironmentTexture( skyBox->getCubeMap() );
waterEffect->setReflectCameraAndTexture(reflectCamera.get(), reflectTexture);
waterEffect->setRefractTexture(refractTexture);
waterEffect->setDepthTexture(depthTexture);
waterEffect->setWaterTransparency(0.5f);
waterEffect->setWaveSharpness(0.5f);
waterEffect->setSqueezing(8.0f);
waterEffect->setDistanceSmoothness(0.001f);
// choose size according to the window
int sizeX = static_cast<int>( 150 * (windowWidth / 800.0) );
int sizeY = static_cast<int>( 600 * (windowHeight / 600.0) );
ocean.reset( new ProjectedGrid(waterEffect) );
ocean->setupGrid(sizeX, sizeY);
world->addInfiniteNode(ocean);
// setup special states
sgl::RasterizerState::DESC desc;
desc.cullMode = sgl::RasterizerState::BACK;
desc.fillMode = sgl::RasterizerState::SOLID;
backFaceCullState.reset( device->CreateRasterizerState(desc) );
desc.cullMode = sgl::RasterizerState::FRONT;
desc.fillMode = sgl::RasterizerState::SOLID;
frontFaceCullState.reset( device->CreateRasterizerState(desc) );
}
camera->setPosition( Vector3f(60.0f, 20.0f, 0.0f) );
camera->setDirection( Vector3f(-1.0f, -1.0f, 1.0f) );
camera->setUp( Vector3f(0.0f, 1.0f, 0.0f) );
// create font
graphics::texture_ptr fontTexture = loadTexture("Data/Fonts/font.png");
if ( graphics::Texture2D* texture = dynamic_cast<graphics::Texture2D*>(fontTexture.get()) )
{
font.reset( currentDevice()->CreateFont() );
font->SetTexture(texture);
}
}
// setup input
{
using boost::bind;
using namespace slon::input;
using namespace slon::thread;
InputManager& inputManager = engine->getInputManager();
inputManager.showCursor(false);
// fix cursor in the window center
Vector2ui cursorPosition = screenSize / 2 ;
inputManager.setCursorPosition(cursorPosition.x, cursorPosition.y);
inputManager.fixCursorPosition(cursorPosition.x, cursorPosition.y);
keyboardHandler.reset( new KeyboardHandler() );
inputManager.addInputHandler( keyboardHandler.get() );
keyboardHandler->connectKeyPressEventHandler( input::KEY_1, bind( &DemoScene::setupGrid, this, 0, 0.5f ) );
keyboardHandler->connectKeyPressEventHandler( input::KEY_2, bind( &DemoScene::setupGrid, this, 1, 0.5f ) );
keyboardHandler->connectKeyPressEventHandler( input::KEY_3, bind( &DemoScene::setupGrid, this, 2, 1.0f ) );
keyboardHandler->connectKeyPressEventHandler( input::KEY_4, bind( &DemoScene::setupGrid, this, 3, 1.0f ) );
keyboardHandler->connectKeyPressEventHandler( input::KEY_F1, bind(&DemoScene::toggleHelpText, this) );
keyboardHandler->connectKeyPressEventHandler( input::KEY_F2, bind(&DemoScene::toggleWireframe, this) );
keyboardHandler->connectKeyPressEventHandler( input::KEY_F9, bind(&DemoScene::takeScreenShot, this) );
keyboardHandler->connectKeyPressEventHandler( input::KEY_ESCAPE, bind(&DemoScene::stopDemo, this) );
keyboardHandler->connectKeyDownHandler( input::KEY_w, bind(&DemoScene::flyCamera, this, math::Vector3f( 0.0f, 0.0f, 10.0f)) );
keyboardHandler->connectKeyDownHandler( input::KEY_s, bind(&DemoScene::flyCamera, this, math::Vector3f( 0.0f, 0.0f, -10.0f)) );
keyboardHandler->connectKeyDownHandler( input::KEY_d, bind(&DemoScene::flyCamera, this, math::Vector3f( 10.0f, 0.0f, 0.0f)) );
keyboardHandler->connectKeyDownHandler( input::KEY_a, bind(&DemoScene::flyCamera, this, math::Vector3f(-10.0f, 0.0f, 0.0f)) );
keyboardHandler->connectKeyDownHandler( input::KEY_q, bind(&DemoScene::flyCamera, this, math::Vector3f( 0.0f, 10.0f, 0.0f)) );
keyboardHandler->connectKeyDownHandler( input::KEY_e, bind(&DemoScene::flyCamera, this, math::Vector3f( 0.0f, -10.0f, 0.0f)) );
keyboardHandler->connectKeyDownHandler( input::KEY_UP, bind(&DemoScene::modifySharpness, this, 0.5f) );
keyboardHandler->connectKeyDownHandler( input::KEY_DOWN, bind(&DemoScene::modifySharpness, this, -0.5f) );
// setup mouse input
MouseHandler* mouseHandler = new MouseHandler();
inputManager.addInputHandler(mouseHandler);
mouseHandler->connectRelativeMouseMotionEventHandler( bind(&DemoScene::turnCamera, this, _1, _2) );
}
Engine::DESC desc;
desc.multithreaded = false;
desc.grabInput = false;
engine->run(desc);
}
~DemoScene()
{
}
private:
void toggleHelpText() { drawHelp = !drawHelp; } // F1
void toggleWireframe() { currentRenderer()->toggleWireframe( !currentRenderer()->isWireframe() ); } // F2
// Such a mess, because need to take screenshot after scene rendering
void takeScreenShot() { needToTakeScreenshot = true; } // F9
void stopDemo() { Engine::Instance()->stop(); } // ESC
void setupGrid( unsigned int spectrum,
float sharpness )
{
waterEffect->setFrequencySpectrum(phillipsSpectrum[spectrum]);
waterEffect->setWaveSharpness(sharpness);
}
void turnCamera(int xrel, int yrel) // on mouse motion
{
const float bottom_threshold = -0.9f;
const float top_threshold = 0.5f;
Vector2f rel = Vector2f( float(xrel), float(yrel) );
{
thread::lock_ptr lock = camera->lockForWriting();
camera->turnAroundAxis( rel.x * 0.002f, Vector3f(0.0f, 1.0f, 0.0f) );
camera->turnPitch(rel.y * 0.002f);
Vector3f direction = camera->getDirection();
if (direction.y < bottom_threshold)
{
direction.y = bottom_threshold;
camera->setDirection( normalize(direction) );
}
else if (direction.y > top_threshold)
{
direction.y = top_threshold;
camera->setDirection( normalize(direction) );
}
}
//std::cout << "turn" << std::endl;
}
void flyCamera(const math::Vector3f& speed)
{
camera->moveForward(speed.z * dt);
camera->moveRight(speed.x * dt);
camera->moveUp(speed.y * dt);
}
void modifySharpness(float modifier)
{
waterEffect->setWaveSharpness( waterEffect->getWaveSharpness() + modifier* dt );
}
void renderCommon()
{
using namespace std;
// calculate fps using frame render time
const float fpsAdaptSpeed = 0.1f;
fps = fps * (1.0f - fpsAdaptSpeed) + fpsAdaptSpeed / dt;
// draw fps
{
ostringstream ss;
ss << "FPS: " << fps << endl;
font->Bind(10, 12);
font->Print( (float)screenSize.x / 2.0f - 40.0f, 10.0f, ss.str().c_str() );
font->Unbind();
}
// draw help text
if (drawHelp)
{
ostringstream ss;
ss << "1,2,3,4: - Different weather conditions" << endl
<< "up/down - increase/decrease wave sharpness: " << waterEffect->getWaveSharpness() << endl
<< "w,s,a,d,q,e - camera movement" << endl
//<< "F9 - take screenshot" << endl
<< "F1 - toggle help text" << endl
<< "F2 - wireframe";
font->Bind(10, 12);
font->Print( 10.0f, 10.0f, ss.str().c_str() );
font->Unbind();
}
}
void OnPostRender(const Camera& renderCamera)
{
using namespace std;
if ( &renderCamera == camera )
{
// render gui
dt = static_cast<float>( Engine::Instance()->getSimulationTimer().getTime() - time );
time = static_cast<float>( Engine::Instance()->getSimulationTimer().getTime() );
//handleContiniousEvents();
renderCommon();
/*
// here we can take screenshot
if ( needToTakeScreenshot )
{
// get time
static int screenNum = 0;
ostringstream numSS;
numSS << screenNum++;
string name = string("screen_") + numSS.str() + ".jpg";
// screenshot
sgl::ref_ptr<sgl::Image> image( currentDevice()->CreateImage() );
//currentDevice()->TakeScreenshot( image.get() );
image->SaveToFile( name.c_str() );
needToTakeScreenshot = false;
}
*/
}
}
private:
// water
boost::intrusive_ptr<LookAtCamera> camera;
boost::intrusive_ptr<SlaveCamera> reflectCamera;
boost::intrusive_ptr<ProjectedGrid> ocean;
boost::intrusive_ptr<WaterEffect> waterEffect;
sgl::ref_ptr<sgl::Texture2D> refractTexture;
// modes
sgl::ref_ptr<sgl::RasterizerState> backFaceCullState;
sgl::ref_ptr<sgl::RasterizerState> frontFaceCullState;
// input
boost::intrusive_ptr<input::KeyboardHandler> keyboardHandler;
// font
sgl::ref_ptr<sgl::Font> font;
// settings
float time;
float fps;
float dt;
bool drawHelp;
bool needToTakeScreenshot;
};
void ParseCommandLine(int argc, char** argv)
{
using namespace std;
cout << "Command line arguments:" << endl
<< "--window <width> <height> - window size(default 800x600)" << endl
<< "--fullscreen - enable fullscreen mode" << endl;
//<< "--multisample <multisample> - multisample radius(default is 3)" << endl
//<< "--benchmark <size> - catch performance of the fft. Performs two fft(size^2)" << endl << endl;
for(int i = 0; i<argc; ++i)
{
string argStr = argv[i];
if (argStr == "--window")
{
if ( i + 2 >= argc ) {
throw std::runtime_error("Wrong number of arguments");
}
string input = string(argv[i+1]) + " " + argv[i+2];
istringstream ss(input);
ss >> screenSize.x >> screenSize.y;
}
else if (argStr == "--multisample")
{
if ( i + 1 >= argc ) {
throw std::runtime_error("Wrong number of arguments");
}
istringstream ss(argv[i+1]);
ss >> multisample;
}
else if (argStr == "--fullscreen") {
fullscreen = true;
}
else if (argStr == "--benchmark")
{
if ( i + 1 >= argc ) {
throw std::runtime_error("Wrong number of arguments");
}
istringstream ss(argv[i+1]);
ss >> fftSize;
benchmark = true;
}
}
}
int main(int argc, char** argv)
{
screenSize = Vector2ui(800, 600);
multisample = 0;
fullscreen = false;
benchmark = false;
try
{
ParseCommandLine(argc, argv);
}
catch(std::exception& err)
{
std::cerr << err.what() << std::endl;
return 1;
}
// init engine
Engine* engine = Engine::Instance();
/*
if (benchmark)
{
GraphicsManager& graphicsManager = engine->getGraphicsManager();
graphicsManager.setVideoMode(32, 32, 32, false, false, 3);
ppu::FFTFilter fftFilter;
fftFilter.setSize(fftSize);
// check fft performance
const int num_fft = 100;
std::cout << "Performing " << num_fft << " FFT of size (" << fftSize << "," << fftSize << ") "
<< "with 32 bit floating accuracy.\n This will take some time.\n";
std::cout.flush(); // Flush, so user can see warning
double startTime = engine->getTime();
for (int i = 0; i < num_fft; ++i)
{
fftFilter.perform();
}
currentDevice()->Sync();
double averageFFTTime = (engine->getTime() - startTime) / num_fft;
std::cout << "Average fft perform time: " << averageFFTTime << std::endl;
}
else
*/
{
try
{
DemoScene demoScene(screenSize.x, screenSize.y, fullscreen, multisample);
}
catch(std::exception& err)
{
std::cerr << err.what() << std::endl;
return 1;
}
}
Engine::Free();
return 0;
}
| [
"devnull@localhost"
] | [
[
[
1,
667
]
]
] |
9fd622b4d02e152deb76dd07a8969c760c9ba974 | 11ba7667109ae553162c7329bcd2f4902d841a66 | /AugmentedTowerDefense/include/Chrono.h | 3b7839a734331ffca60a556330344216ccdbc837 | [] | no_license | abmantis/AugmentedTowerDefense | 3cd8761034a98667a34650f6a476beb59aa7e818 | 00008495f538e0d982c0eae3025d02ae21e3dee2 | refs/heads/master | 2021-01-01T18:37:10.678181 | 2011-02-09T23:09:51 | 2011-02-09T23:09:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 259 | h | #ifndef Chrono_h__
#define Chrono_h__
#pragma once
class Chrono
{
public:
Chrono(bool _autostart = false);
void start();
unsigned int getTimeElapsed(); //in ms
private:
__int64 mFreq;
__int64 mStart;
};
#endif // Chrono_h__ | [
"[email protected]"
] | [
[
[
1,
18
]
]
] |
98b5c876b76a5f97bee96bbe1a8bc785fca39d86 | b24d5382e0575ad5f7c6e5a77ed065d04b77d9fa | /RadiantLaserCross/RLC_GameState.h | af07373f3f5d3c20849083d8b56e71d5ec601e62 | [] | no_license | Klaim/radiant-laser-cross | f65571018bf612820415e0f672c216caf35de439 | bf26a3a417412c0e1b77267b4a198e514b2c7915 | refs/heads/master | 2021-01-01T18:06:58.019414 | 2010-11-06T14:56:11 | 2010-11-06T14:56:11 | 32,205,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | h | #ifndef RLC_GAMESTATE_H
#define RLC_GAMESTATE_H
#pragma once
#include <string>
#include <boost/shared_ptr.hpp>
namespace rlc
{
/** Interface for game states.
*/
class GameState
{
public:
GameState( const std::string& state_name ) : m_name( state_name ){}
virtual void begin() = 0;
virtual void update() = 0;
virtual void render() = 0; // TODO : rendering should be orthogonal...move that elsewhere!
virtual void end() = 0;
const std::string& name() const { return m_name; }
private:
const std::string m_name;
};
typedef boost::shared_ptr< GameState > GameStatePtr;
}
#endif | [
"[email protected]"
] | [
[
[
1,
35
]
]
] |
d6a74a85ce2e0b8249f3e94639343a6d06c9c101 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /libs/STLPort-4.0/stlport/stl/_string.h | a0a4faa856a1bf569910427f5d81f6e074fea0e9 | [
"LicenseRef-scancode-stlport-4.5"
] | permissive | 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 | 51,922 | h | /*
* Copyright (c) 1997-1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef __SGI_STL_STRING_H
#define __SGI_STL_STRING_H
#ifndef __SGI_STL_MEMORY
# include <memory>
#endif
# ifndef __STLPORT_CCTYPE
# include <cctype>
# endif
#ifndef __SGI_STL_STRING_FWD_H
# include <stl/_string_fwd.h>
#endif
#ifndef __SGI_STL_INTERNAL_FUNCTION_H
# include <stl/_function.h>
#endif
# include <stl/_ctraits_fns.h>
#ifndef __SGI_STL_INTERNAL_ALGO_H
# include <stl/_algo.h>
#endif
# ifndef __STLPORT_IOSFWD
# include <iosfwd>
# endif
#if defined( __MWERKS__ ) && ! defined (__STL_USE_OWN_NAMESPACE)
// MSL implementation classes expect to see the definition of streampos
// when this header is included. We expect this to be fixed in later MSL
// implementations
# if !defined( __MSL_CPP__ ) || __MSL_CPP__ < 0x4105
# include <stl/msl_string.h>
# endif
#endif // __MWERKS__
// Standard C++ string class. This class has performance
// characteristics very much like vector<>, meaning, for example, that
// it does not perform reference-count or copy-on-write, and that
// concatenation of two strings is an O(N) operation.
// There are three reasons why basic_string is not identical to
// vector. First, basic_string always stores a null character at the
// end; this makes it possible for c_str to be a fast operation.
// Second, the C++ standard requires basic_string to copy elements
// using char_traits<>::assign, char_traits<>::copy, and
// char_traits<>::move. This means that all of vector<>'s low-level
// operations must be rewritten. Third, basic_string<> has a lot of
// extra functions in its interface that are convenient but, strictly
// speaking, redundant.
// Additionally, the C++ standard imposes a major restriction: according
// to the standard, the character type _CharT must be a POD type. This
// implementation weakens that restriction, and allows _CharT to be a
// a user-defined non-POD type. However, _CharT must still have a
// default constructor.
__STL_BEGIN_NAMESPACE
# ifdef __STL_DEBUG
# define basic_string _Nondebug_string
# endif
// A helper class to use a char_traits as a function object.
template <class _Traits>
struct _Not_within_traits
: public unary_function<typename _Traits::char_type, bool>
{
typedef typename _Traits::char_type _CharT;
const _CharT* _M_first;
const _CharT* _M_last;
_Not_within_traits(const typename _Traits::char_type* __f,
const typename _Traits::char_type* __l)
: _M_first(__f), _M_last(__l) {}
bool operator()(const typename _Traits::char_type& __x) const {
return find_if((_CharT*)_M_first, (_CharT*)_M_last,
bind1st(_Eq_traits<_Traits>(), __x)) == (_CharT*)_M_last;
}
};
// ------------------------------------------------------------
// Class _String_base.
// _String_base is a helper class that makes it it easier to write an
// exception-safe version of basic_string. The constructor allocates,
// but does not initialize, a block of memory. The destructor
// deallocates, but does not destroy elements within, a block of
// memory. The destructor assumes that _M_start either is null, or else
// points to a block of memory that was allocated using _String_base's
// allocator and whose size is _M_end_of_storage._M_data - _M_start.
// Additionally, _String_base encapsulates the difference between
// old SGI-style allocators and standard-conforming allocators.
template <class _Tp, class _Alloc> class __STL_CLASS_DECLSPEC _String_base {
public:
typedef typename _Alloc_traits<_Tp, _Alloc>::allocator_type allocator_type;
_Tp* _M_start;
_Tp* _M_finish;
_STL_alloc_proxy<_Tp*, _Tp, allocator_type> _M_end_of_storage;
// Precondition: 0 < __n <= max_size().
void _M_allocate_block(size_t __n) {
if ((__n <= (max_size()+1)) && (__n>0)){
// if (__n <= max_size()) {
_M_start = _M_end_of_storage.allocate(__n);
_M_finish = _M_start;
_M_end_of_storage._M_data = _M_start + __n;
}
else
_M_throw_length_error();
}
void _M_deallocate_block()
{ _M_end_of_storage.deallocate(_M_start, _M_end_of_storage._M_data - _M_start); }
size_t max_size() const { return (size_t(-1) / sizeof(_Tp)) - 1; }
_String_base(const allocator_type& __a)
: _M_start(0), _M_finish(0), _M_end_of_storage(__a, (_Tp*)0) { }
_String_base(const allocator_type& __a, size_t __n)
: _M_start(0), _M_finish(0), _M_end_of_storage(__a, (_Tp*)0)
{ _M_allocate_block(__n); }
~_String_base() { _M_deallocate_block(); }
void _M_throw_length_error() const;
void _M_throw_out_of_range() const;
};
# if defined (__STL_USE_TEMPLATE_EXPORT)
__STL_EXPORT_TEMPLATE_CLASS _String_base<char, allocator<char> >;
# if defined (__STL_HAS_WCHAR_T)
__STL_EXPORT_TEMPLATE_CLASS _String_base<wchar_t, allocator<wchar_t> >;
# endif
# endif /* __STL_USE_TEMPLATE_EXPORT */
// ------------------------------------------------------------
// Class basic_string.
// Class invariants:
// (1) [start, finish) is a valid range.
// (2) Each iterator in [start, finish) points to a valid object
// of type value_type.
// (3) *finish is a valid object of type value_type; in particular,
// it is value_type().
// (4) [finish + 1, end_of_storage) is a valid range.
// (5) Each iterator in [finish + 1, end_of_storage) points to
// unininitialized memory.
// Note one important consequence: a string of length n must manage
// a block of memory whose size is at least n + 1.
struct _String_reserve_t {};
template <class _CharT, class _Traits, class _Alloc>
class __STL_CLASS_DECLSPEC basic_string : protected _String_base<_CharT,_Alloc> {
private: // Protected members inherited from base.
typedef _String_base<_CharT,_Alloc> _Base;
typedef basic_string<_CharT, _Traits, _Alloc> _Self;
// fbp : used to optimize char/wchar_t cases, and to simplify
// __STL_DEFAULT_CONSTRUCTOR_BUG problem workaround
typedef typename _Is_integer<_CharT>::_Integral _Char_Is_Integral;
public:
#if defined( __STL_HAS_NAMESPACES )
__STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_allocate_block;
__STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_deallocate_block;
__STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_throw_length_error;
__STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_throw_out_of_range;
__STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_start;
__STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_finish;
__STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_end_of_storage;
#endif /* __STL_HAS_NAMESPACES */
public:
typedef _CharT value_type;
typedef _Traits traits_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef random_access_iterator_tag _Iterator_category;
typedef const value_type* const_iterator;
typedef value_type* iterator;
__STL_DECLARE_RANDOM_ACCESS_REVERSE_ITERATORS;
# ifdef __STL_STATIC_CONST_INIT_BUG
enum { npos = -1 };
# else
static const size_t npos = ~(size_t)0;
# endif
typedef _String_reserve_t _Reserve_t;
# if defined (__STL_USE_NATIVE_STRING) && ! defined (__STL_DEBUG)
// this typedef is being used for conversions
typedef __STL_VENDOR_STD::basic_string<_CharT,_Traits,
__STL_VENDOR_STD::allocator<_CharT> > __std_string;
# endif
public: // Constructor, destructor, assignment.
typedef typename _String_base<_CharT,_Alloc>::allocator_type allocator_type;
allocator_type get_allocator() const {
return __STL_CONVERT_ALLOCATOR((const allocator_type&)_M_end_of_storage, _CharT);
}
basic_string()
: _String_base<_CharT,_Alloc>(allocator_type(), 8) {
_M_terminate_string();
}
explicit basic_string(const allocator_type& __a)
: _String_base<_CharT,_Alloc>(__a, 8) {
_M_terminate_string();
}
basic_string(_Reserve_t, size_t __n,
const allocator_type& __a = allocator_type())
: _String_base<_CharT,_Alloc>(__a, __n + 1) {
_M_terminate_string();
}
basic_string(const _Self& __s)
: _String_base<_CharT,_Alloc>(__s.get_allocator())
{
_M_range_initialize(__s._M_start, __s._M_finish);
}
basic_string(const _Self& __s, size_type __pos, size_type __n = npos,
const allocator_type& __a = allocator_type())
: _String_base<_CharT,_Alloc>(__a) {
if (__pos > __s.size())
_M_throw_out_of_range();
else
_M_range_initialize(__s._M_start + __pos,
__s._M_start + __pos + min(__n, __s.size() - __pos));
}
basic_string(const _CharT* __s, size_type __n,
const allocator_type& __a = allocator_type())
: _String_base<_CharT,_Alloc>(__a)
{
__STL_FIX_LITERAL_BUG(__s)
_M_range_initialize(__s, __s + __n);
}
basic_string(const _CharT* __s,
const allocator_type& __a = allocator_type())
: _String_base<_CharT,_Alloc>(__a)
{
__STL_FIX_LITERAL_BUG(__s)
_M_range_initialize(__s, __s + traits_type::length(__s));
}
basic_string(size_type __n, _CharT __c,
const allocator_type& __a = allocator_type())
: _String_base<_CharT,_Alloc>(__a, __n + 1)
{
_M_finish = uninitialized_fill_n(_M_start, __n, __c);
_M_terminate_string();
}
// Check to see if _InputIterator is an integer type. If so, then
// it can't be an iterator.
#if defined (__STL_MEMBER_TEMPLATES)
template <class _InputIterator>
basic_string(_InputIterator __f, _InputIterator __l)
: _String_base<_CharT,_Alloc>(allocator_type())
{
typedef typename _Is_integer<_InputIterator>::_Integral _Integral;
_M_initialize_dispatch(__f, __l, _Integral());
}
template <class _InputIterator>
basic_string(_InputIterator __f, _InputIterator __l,
const allocator_type & __a)
: _String_base<_CharT,_Alloc>(__a)
{
typedef typename _Is_integer<_InputIterator>::_Integral _Integral;
_M_initialize_dispatch(__f, __l, _Integral());
}
#else /* __STL_MEMBER_TEMPLATES */
basic_string(const _CharT* __f, const _CharT* __l,
const allocator_type& __a = allocator_type())
: _String_base<_CharT,_Alloc>(__a)
{
__STL_FIX_LITERAL_BUG(__f) __STL_FIX_LITERAL_BUG(__l)
_M_range_initialize(__f, __l);
}
#endif
# if defined (__STL_USE_NATIVE_STRING) && ! defined (__STL_DEBUG)
// these conversion operations still needed for
// strstream, etc.
basic_string (const __std_string& __x): _String_base<_CharT,_Alloc>(allocator_type())
{
const _CharT* __s = __x.data();
_M_range_initialize(__s, __s + __x.size());
}
operator __std_string() const { return __std_string(this->data()); }
# endif
~basic_string() { _Destroy(_M_start, _M_finish + 1); }
_Self& operator=(const _Self& __s) {
if (&__s != this)
assign(__s._M_start, __s._M_finish);
return *this;
}
_Self& operator=(const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
return assign(__s, __s + traits_type::length(__s));
}
_Self& operator=(_CharT __c)
{ return assign(__STATIC_CAST(size_type,1), __c); }
static _CharT __STL_CALL _M_null() {
# ifndef __STL_DEFAULT_CONSTRUCTOR_BUG
return _CharT();
# else
return (_CharT) 0;
# endif
}
private: // Helper functions used by constructors
// and elsewhere.
// fbp : simplify integer types (char, wchar)
void _M_construct_null_aux(_CharT* __p, __false_type) {
_Construct(__p);
}
void _M_construct_null_aux(_CharT* __p, __true_type) {
*__p = 0;
}
void _M_construct_null(_CharT* __p) {
_M_construct_null_aux(__p, _Char_Is_Integral());
}
private:
// Helper functions used by constructors. It is a severe error for
// any of them to be called anywhere except from within constructors.
void _M_terminate_string_aux(__false_type) {
__STL_TRY {
_M_construct_null(_M_finish);
}
__STL_UNWIND(_Destroy(_M_start, _M_finish));
}
void _M_terminate_string_aux(__true_type) {
*_M_finish=0;
}
void _M_terminate_string() {
_M_terminate_string_aux(_Char_Is_Integral());
}
#ifdef __STL_MEMBER_TEMPLATES
template <class _InputIter>
void _M_range_initialize(_InputIter __f, _InputIter __l,
input_iterator_tag) {
_M_allocate_block(8);
_M_construct_null(_M_finish);
__STL_TRY {
append(__f, __l);
}
__STL_UNWIND(_Destroy(_M_start, _M_finish + 1));
}
template <class _ForwardIter>
void _M_range_initialize(_ForwardIter __f, _ForwardIter __l,
forward_iterator_tag) {
difference_type __n = 0;
distance(__f, __l, __n);
_M_allocate_block(__n + 1);
_M_finish = uninitialized_copy(__f, __l, _M_start);
_M_terminate_string();
}
template <class _InputIter>
void _M_range_initialize(_InputIter __f, _InputIter __l) {
# ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
typedef __STLPORT_STD::iterator_traits<_InputIter> _Iter_traits;
typedef typename _Iter_traits::iterator_category _Category;
_M_range_initialize(__f, __l, _Category());
# else
_M_range_initialize(__f, __l, __ITERATOR_CATEGORY(__f));
# endif
}
template <class _Integer>
void _M_initialize_dispatch(_Integer __n, _Integer __x, __true_type) {
_M_allocate_block(__n + 1);
_M_finish = uninitialized_fill_n(_M_start, __n, __x);
_M_terminate_string();
}
template <class _InputIter>
void _M_initialize_dispatch(_InputIter __f, _InputIter __l, __false_type) {
_M_range_initialize(__f, __l);
}
#else /* __STL_MEMBER_TEMPLATES */
void _M_range_initialize(const _CharT* __f, const _CharT* __l) {
ptrdiff_t __n = __l - __f;
_M_allocate_block(__n + 1);
_M_finish = uninitialized_copy(__f, __l, _M_start);
_M_terminate_string();
}
#endif /* __STL_MEMBER_TEMPLATES */
public: // Iterators.
iterator begin() { return _M_start; }
iterator end() { return _M_finish; }
const_iterator begin() const { return _M_start; }
const_iterator end() const { return _M_finish; }
reverse_iterator rbegin()
{ return reverse_iterator(_M_finish); }
reverse_iterator rend()
{ return reverse_iterator(_M_start); }
const_reverse_iterator rbegin() const
{ return const_reverse_iterator(_M_finish); }
const_reverse_iterator rend() const
{ return const_reverse_iterator(_M_start); }
public: // Size, capacity, etc.
size_type size() const { return _M_finish - _M_start; }
size_type length() const { return size(); }
size_t max_size() const { return _Base::max_size(); }
void resize(size_type __n, _CharT __c) {
if (__n <= size())
erase(begin() + __n, end());
else
append(__n - size(), __c);
}
void resize(size_type __n) { resize(__n, _M_null()); }
void reserve(size_type = 0);
size_type capacity() const { return (_M_end_of_storage._M_data - _M_start) - 1; }
void clear() {
if (!empty()) {
_Traits::assign(*_M_start, _M_null());
_Destroy(_M_start+1, _M_finish+1);
_M_finish = _M_start;
}
}
bool empty() const { return _M_start == _M_finish; }
public: // Element access.
const_reference operator[](size_type __n) const
{ return *(_M_start + __n); }
reference operator[](size_type __n)
{ return *(_M_start + __n); }
const_reference at(size_type __n) const {
if (__n >= size())
_M_throw_out_of_range();
return *(_M_start + __n);
}
reference at(size_type __n) {
if (__n >= size())
_M_throw_out_of_range();
return *(_M_start + __n);
}
public: // Append, operator+=, push_back.
_Self& operator+=(const _Self& __s) { return append(__s); }
_Self& operator+=(const _CharT* __s) { __STL_FIX_LITERAL_BUG(__s) return append(__s); }
_Self& operator+=(_CharT __c) { push_back(__c); return *this; }
_Self& append(const _Self& __s)
{ return append(__s._M_start, __s._M_finish); }
_Self& append(const _Self& __s,
size_type __pos, size_type __n)
{
if (__pos > __s.size())
_M_throw_out_of_range();
return append(__s._M_start + __pos,
__s._M_start + __pos + min(__n, __s.size() - __pos));
}
_Self& append(const _CharT* __s, size_type __n)
{ __STL_FIX_LITERAL_BUG(__s) return append(__s, __s+__n); }
_Self& append(const _CharT* __s)
{ __STL_FIX_LITERAL_BUG(__s) return append(__s, __s + traits_type::length(__s)); }
_Self& append(size_type __n, _CharT __c);
#ifdef __STL_MEMBER_TEMPLATES
// Check to see if _InputIterator is an integer type. If so, then
// it can't be an iterator.
template <class _InputIter>
_Self& append(_InputIter __first, _InputIter __last) {
typedef typename _Is_integer<_InputIter>::_Integral _Integral;
return _M_append_dispatch(__first, __last, _Integral());
}
#else /* __STL_MEMBER_TEMPLATES */
_Self& append(const _CharT* __first, const _CharT* __last);
#endif /* __STL_MEMBER_TEMPLATES */
void push_back(_CharT __c) {
if (_M_finish + 1 == _M_end_of_storage._M_data)
reserve(size() + max(size(), __STATIC_CAST(size_type,1)));
_M_construct_null(_M_finish + 1);
_Traits::assign(*_M_finish, __c);
++_M_finish;
}
void pop_back() {
_Traits::assign(*(_M_finish - 1), _M_null());
_Destroy(_M_finish);
--_M_finish;
}
private: // Helper functions for append.
#ifdef __STL_MEMBER_TEMPLATES
template <class _InputIter>
_Self& append(_InputIter __first, _InputIter __last, input_iterator_tag)
{
for ( ; __first != __last ; ++__first)
push_back(*__first);
return *this;
}
template <class _ForwardIter>
_Self& append(_ForwardIter __first, _ForwardIter __last,
forward_iterator_tag)
# ifndef __STL_INLINE_MEMBER_TEMPLATES
;
# else
{
if (__first != __last) {
const size_type __old_size = size();
difference_type __n = 0;
distance(__first, __last, __n);
if (__STATIC_CAST(size_type,__n) > max_size() || __old_size > max_size() - __STATIC_CAST(size_type,__n))
_M_throw_length_error();
if (__old_size + __n > capacity()) {
const size_type __len = __old_size +
max(__old_size, __STATIC_CAST(size_type,__n)) + 1;
pointer __new_start = _M_end_of_storage.allocate(__len);
pointer __new_finish = __new_start;
__STL_TRY {
__new_finish = uninitialized_copy(_M_start, _M_finish, __new_start);
__new_finish = uninitialized_copy(__first, __last, __new_finish);
_M_construct_null(__new_finish);
}
__STL_UNWIND((_Destroy(__new_start,__new_finish),
_M_end_of_storage.deallocate(__new_start,__len)));
_Destroy(_M_start, _M_finish + 1);
_M_deallocate_block();
_M_start = __new_start;
_M_finish = __new_finish;
_M_end_of_storage._M_data = __new_start + __len;
}
else {
_ForwardIter __f1 = __first;
++__f1;
uninitialized_copy(__f1, __last, _M_finish + 1);
__STL_TRY {
_M_construct_null(_M_finish + __n);
}
__STL_UNWIND(_Destroy(_M_finish + 1, _M_finish + __n));
_Traits::assign(*_M_finish, *__first);
_M_finish += __n;
}
}
return *this;
}
# endif /* __STL_INLINE_MEMBER_TEMPLATES */
template <class _Integer>
_Self& _M_append_dispatch(_Integer __n, _Integer __x, __true_type) {
return append((size_type) __n, (_CharT) __x);
}
template <class _InputIter>
_Self& _M_append_dispatch(_InputIter __f, _InputIter __l,
__false_type) {
# if defined ( __STL_CLASS_PARTIAL_SPECIALIZATION )
typedef typename iterator_traits<_InputIter>::iterator_category _Category;
return append(__f, __l, _Category());
# else
return append(__f, __l, __ITERATOR_CATEGORY(__f));
# endif
}
#endif /* __STL_MEMBER_TEMPLATES */
public: // Assign
_Self& assign(const _Self& __s)
{ return assign(__s._M_start, __s._M_finish); }
_Self& assign(const _Self& __s,
size_type __pos, size_type __n) {
if (__pos > __s.size())
_M_throw_out_of_range();
return assign(__s._M_start + __pos,
__s._M_start + __pos + min(__n, __s.size() - __pos));
}
_Self& assign(const _CharT* __s, size_type __n)
{ __STL_FIX_LITERAL_BUG(__s) return assign(__s, __s + __n); }
_Self& assign(const _CharT* __s)
{ __STL_FIX_LITERAL_BUG(__s) return assign(__s, __s + _Traits::length(__s)); }
_Self& assign(size_type __n, _CharT __c);
#ifdef __STL_MEMBER_TEMPLATES
// Check to see if _InputIterator is an integer type. If so, then
// it can't be an iterator.
template <class _InputIter>
_Self& assign(_InputIter __first, _InputIter __last) {
typedef typename _Is_integer<_InputIter>::_Integral _Integral;
return _M_assign_dispatch(__first, __last, _Integral());
}
#else
_Self& assign(const _CharT* __f, const _CharT* __l);
#endif /* __STL_MEMBER_TEMPLATES */
private: // Helper functions for assign.
#ifdef __STL_MEMBER_TEMPLATES
template <class _Integer>
_Self& _M_assign_dispatch(_Integer __n, _Integer __x, __true_type) {
return assign((size_type) __n, (_CharT) __x);
}
template <class _InputIter>
_Self& _M_assign_dispatch(_InputIter __f, _InputIter __l,
__false_type) {
pointer __cur = _M_start;
while (__f != __l && __cur != _M_finish) {
_Traits::assign(*__cur, *__f);
++__f;
++__cur;
}
if (__f == __l)
erase(__cur, end());
else
append(__f, __l);
return *this;
}
#endif /* __STL_MEMBER_TEMPLATES */
public: // Insert
_Self& insert(size_type __pos, const _Self& __s) {
if (__pos > size())
_M_throw_out_of_range();
if (size() > max_size() - __s.size())
_M_throw_length_error();
insert(begin() + __pos, __s._M_start, __s._M_finish);
return *this;
}
_Self& insert(size_type __pos, const _Self& __s,
size_type __beg, size_type __n) {
if (__pos > size() || __beg > __s.size())
_M_throw_out_of_range();
size_type __len = min(__n, __s.size() - __beg);
if (size() > max_size() - __len)
_M_throw_length_error();
insert(begin() + __pos,
__s._M_start + __beg, __s._M_start + __beg + __len);
return *this;
}
_Self& insert(size_type __pos, const _CharT* __s, size_type __n) {
__STL_FIX_LITERAL_BUG(__s)
if (__pos > size())
_M_throw_out_of_range();
if (size() > max_size() - __n)
_M_throw_length_error();
insert(begin() + __pos, __s, __s + __n);
return *this;
}
_Self& insert(size_type __pos, const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
if (__pos > size())
_M_throw_out_of_range();
size_type __len = _Traits::length(__s);
if (size() > max_size() - __len)
_M_throw_length_error();
insert(_M_start + __pos, __s, __s + __len);
return *this;
}
_Self& insert(size_type __pos, size_type __n, _CharT __c) {
if (__pos > size())
_M_throw_out_of_range();
if (size() > max_size() - __n)
_M_throw_length_error();
insert(begin() + __pos, __n, __c);
return *this;
}
iterator insert(iterator __p, _CharT __c) {
__STL_FIX_LITERAL_BUG(__p)
if (__p == end()) {
push_back(__c);
return _M_finish - 1;
}
else
return _M_insert_aux(__p, __c);
}
void insert(iterator __p, size_t __n, _CharT __c);
#ifdef __STL_MEMBER_TEMPLATES
// Check to see if _InputIterator is an integer type. If so, then
// it can't be an iterator.
template <class _InputIter>
void insert(iterator __p, _InputIter __first, _InputIter __last) {
typedef typename _Is_integer<_InputIter>::_Integral _Integral;
_M_insert_dispatch(__p, __first, __last, _Integral());
}
#else /* __STL_MEMBER_TEMPLATES */
void insert(iterator __p, const _CharT* __first, const _CharT* __last);
#endif /* __STL_MEMBER_TEMPLATES */
private: // Helper functions for insert.
#ifdef __STL_MEMBER_TEMPLATES
template <class _InputIter>
void insert(iterator __p, _InputIter __first, _InputIter __last,
input_iterator_tag)
{
for ( ; __first != __last; ++__first) {
__p = insert(__p, *__first);
++__p;
}
}
template <class _ForwardIter>
void insert(iterator __position, _ForwardIter __first, _ForwardIter __last,
forward_iterator_tag)
# ifndef __STL_INLINE_MEMBER_TEMPLATES
;
# else
{
if (__first != __last) {
difference_type __n = 0;
distance(__first, __last, __n);
if (_M_end_of_storage._M_data - _M_finish >= __n + 1) {
const difference_type __elems_after = _M_finish - __position;
pointer __old_finish = _M_finish;
if (__elems_after >= __n) {
uninitialized_copy((_M_finish - __n) + 1, _M_finish + 1,
_M_finish + 1);
_M_finish += __n;
_Traits::move(__position + __n,
__position, (__elems_after - __n) + 1);
_M_copy(__first, __last, __position);
}
else {
_ForwardIter __mid = __first;
advance(__mid, __elems_after + 1);
uninitialized_copy(__mid, __last, _M_finish + 1);
_M_finish += __n - __elems_after;
__STL_TRY {
uninitialized_copy(__position, __old_finish + 1, _M_finish);
_M_finish += __elems_after;
}
__STL_UNWIND((_Destroy(__old_finish + 1, _M_finish),
_M_finish = __old_finish));
_M_copy(__first, __mid, __position);
}
}
else {
const size_type __old_size = size();
const size_type __len
= __old_size + max(__old_size, __STATIC_CAST(size_type,__n)) + 1;
pointer __new_start = _M_end_of_storage.allocate(__len);
pointer __new_finish = __new_start;
__STL_TRY {
__new_finish = uninitialized_copy(_M_start, __position, __new_start);
__new_finish = uninitialized_copy(__first, __last, __new_finish);
__new_finish
= uninitialized_copy(__position, _M_finish, __new_finish);
_M_construct_null(__new_finish);
}
__STL_UNWIND((_Destroy(__new_start,__new_finish),
_M_end_of_storage.deallocate(__new_start,__len)));
_Destroy(_M_start, _M_finish + 1);
_M_deallocate_block();
_M_start = __new_start;
_M_finish = __new_finish;
_M_end_of_storage._M_data = __new_start + __len;
}
}
}
# endif /* __STL_INLINE_MEMBER_TEMPLATES */
template <class _Integer>
void _M_insert_dispatch(iterator __p, _Integer __n, _Integer __x,
__true_type) {
insert(__p, (size_type) __n, (_CharT) __x);
}
template <class _InputIter>
void _M_insert_dispatch(iterator __p, _InputIter __first, _InputIter __last,
__false_type) {
# if defined ( __STL_CLASS_PARTIAL_SPECIALIZATION )
typedef typename iterator_traits<_InputIter>::iterator_category _Category;
insert(__p, __first, __last, _Category());
# else
insert(__p, __first, __last, __ITERATOR_CATEGORY(__first));
# endif
}
template <class _InputIterator>
void
_M_copy(_InputIterator __first, _InputIterator __last, pointer __result) {
for ( ; __first != __last; ++__first, ++__result)
_Traits::assign(*__result, *__first);
}
#endif /* __STL_MEMBER_TEMPLATES */
pointer _M_insert_aux(pointer, _CharT);
void
_M_copy(const _CharT* __first, const _CharT* __last, _CharT* __result) {
_Traits::copy(__result, __first, __last - __first);
}
public: // Erase.
_Self& erase(size_type __pos = 0, size_type __n = npos) {
if (__pos > size())
_M_throw_out_of_range();
erase(begin() + __pos, begin() + __pos + min(__n, size() - __pos));
return *this;
}
iterator erase(iterator __position) {
// The move includes the terminating _CharT().
_Traits::move(__position, __position + 1, _M_finish - __position);
_Destroy(_M_finish);
--_M_finish;
return __position;
}
iterator erase(iterator __first, iterator __last) {
if (__first != __last) {
// The move includes the terminating _CharT().
traits_type::move(__first, __last, (_M_finish - __last) + 1);
pointer __new_finish = _M_finish - (__last - __first);
_Destroy(__new_finish + 1, _M_finish + 1);
_M_finish = __new_finish;
}
return __first;
}
public: // Replace. (Conceptually equivalent
// to erase followed by insert.)
_Self& replace(size_type __pos, size_type __n,
const _Self& __s) {
if (__pos > size())
_M_throw_out_of_range();
const size_type __len = min(__n, size() - __pos);
if (size() - __len >= max_size() - __s.size())
_M_throw_length_error();
return replace(begin() + __pos, begin() + __pos + __len,
__s._M_start, __s._M_finish);
}
_Self& replace(size_type __pos1, size_type __n1,
const _Self& __s,
size_type __pos2, size_type __n2) {
if (__pos1 > size() || __pos2 > __s.size())
_M_throw_out_of_range();
const size_type __len1 = min(__n1, size() - __pos1);
const size_type __len2 = min(__n2, __s.size() - __pos2);
if (size() - __len1 >= max_size() - __len2)
_M_throw_length_error();
return replace(begin() + __pos1, begin() + __pos1 + __len1,
__s._M_start + __pos2, __s._M_start + __pos2 + __len2);
}
_Self& replace(size_type __pos, size_type __n1,
const _CharT* __s, size_type __n2) {
__STL_FIX_LITERAL_BUG(__s)
if (__pos > size())
_M_throw_out_of_range();
const size_type __len = min(__n1, size() - __pos);
if (__n2 > max_size() || size() - __len >= max_size() - __n2)
_M_throw_length_error();
return replace(begin() + __pos, begin() + __pos + __len,
__s, __s + __n2);
}
_Self& replace(size_type __pos, size_type __n1,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
if (__pos > size())
_M_throw_out_of_range();
const size_type __len = min(__n1, size() - __pos);
const size_type __n2 = _Traits::length(__s);
if (__n2 > max_size() || size() - __len >= max_size() - __n2)
_M_throw_length_error();
return replace(begin() + __pos, begin() + __pos + __len,
__s, __s + _Traits::length(__s));
}
_Self& replace(size_type __pos, size_type __n1,
size_type __n2, _CharT __c) {
if (__pos > size())
_M_throw_out_of_range();
const size_type __len = min(__n1, size() - __pos);
if (__n2 > max_size() || size() - __len >= max_size() - __n2)
_M_throw_length_error();
return replace(begin() + __pos, begin() + __pos + __len, __n2, __c);
}
_Self& replace(iterator __first, iterator __last,
const _Self& __s)
{ return replace(__first, __last, __s._M_start, __s._M_finish); }
_Self& replace(iterator __first, iterator __last,
const _CharT* __s, size_type __n)
{ __STL_FIX_LITERAL_BUG(__s) return replace(__first, __last, __s, __s + __n); }
_Self& replace(iterator __first, iterator __last,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
return replace(__first, __last, __s, __s + _Traits::length(__s));
}
_Self& replace(iterator __first, iterator __last,
size_type __n, _CharT __c);
// Check to see if _InputIterator is an integer type. If so, then
// it can't be an iterator.
#ifdef __STL_MEMBER_TEMPLATES
template <class _InputIter>
_Self& replace(iterator __first, iterator __last,
_InputIter __f, _InputIter __l) {
typedef typename _Is_integer<_InputIter>::_Integral _Integral;
return _M_replace_dispatch(__first, __last, __f, __l, _Integral());
}
#else /* __STL_MEMBER_TEMPLATES */
_Self& replace(iterator __first, iterator __last,
const _CharT* __f, const _CharT* __l);
#endif /* __STL_MEMBER_TEMPLATES */
private: // Helper functions for replace.
#ifdef __STL_MEMBER_TEMPLATES
template <class _Integer>
_Self& _M_replace_dispatch(iterator __first, iterator __last,
_Integer __n, _Integer __x,
__true_type) {
return replace(__first, __last, (size_type) __n, (_CharT) __x);
}
template <class _InputIter>
_Self& _M_replace_dispatch(iterator __first, iterator __last,
_InputIter __f, _InputIter __l,
__false_type) {
# ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
typedef typename iterator_traits<_InputIter>::iterator_category _Category;
return replace(__first, __last, __f, __l, _Category());
# else
return replace(__first, __last, __f, __l, __ITERATOR_CATEGORY(__f));
# endif
}
template <class _InputIter>
_Self& replace(iterator __first, iterator __last,
_InputIter __f, _InputIter __l, input_iterator_tag) {
for ( ; __first != __last && __f != __l; ++__first, ++__f)
_Traits::assign(*__first, *__f);
if (__f == __l)
erase(__first, __last);
else
insert(__last, __f, __l);
return *this;
}
template <class _ForwardIter>
_Self& replace(iterator __first, iterator __last,
_ForwardIter __f, _ForwardIter __l,
forward_iterator_tag) {
difference_type __n = 0;
distance(__f, __l, __n);
const difference_type __len = __last - __first;
if (__len >= __n) {
_M_copy(__f, __l, __first);
erase(__first + __n, __last);
}
else {
_ForwardIter __m = __f;
advance(__m, __len);
_M_copy(__f, __m, __first);
insert(__last, __m, __l);
}
return *this;
}
#endif /* __STL_MEMBER_TEMPLATES */
public: // Other modifier member functions.
size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const {
__STL_FIX_LITERAL_BUG(__s)
if (__pos > size())
_M_throw_out_of_range();
const size_type __len = min(__n, size() - __pos);
_Traits::copy(__s, _M_start + __pos, __len);
return __len;
}
void swap(_Self& __s) {
__STLPORT_STD::swap(_M_start, __s._M_start);
__STLPORT_STD::swap(_M_finish, __s._M_finish);
__STLPORT_STD::swap(_M_end_of_storage, __s._M_end_of_storage);
}
public: // Conversion to C string.
const _CharT* c_str() const { return _M_start; }
const _CharT* data() const { return _M_start; }
public: // find.
size_type find(const _Self& __s, size_type __pos = 0) const
{ return find(__s._M_start, __pos, __s.size()); }
size_type find(const _CharT* __s, size_type __pos = 0) const
{ __STL_FIX_LITERAL_BUG(__s) return find(__s, __pos, _Traits::length(__s)); }
size_type find(const _CharT* __s, size_type __pos, size_type __n) const;
size_type find(_CharT __c, size_type __pos = 0) const;
public: // rfind.
size_type rfind(const _Self& __s, size_type __pos = npos) const
{ return rfind(__s._M_start, __pos, __s.size()); }
size_type rfind(const _CharT* __s, size_type __pos = npos) const
{ __STL_FIX_LITERAL_BUG(__s) return rfind(__s, __pos, _Traits::length(__s)); }
size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const;
size_type rfind(_CharT __c, size_type __pos = npos) const;
public: // find_first_of
size_type find_first_of(const _Self& __s, size_type __pos = 0) const
{ return find_first_of(__s._M_start, __pos, __s.size()); }
size_type find_first_of(const _CharT* __s, size_type __pos = 0) const
{ __STL_FIX_LITERAL_BUG(__s) return find_first_of(__s, __pos, _Traits::length(__s)); }
size_type find_first_of(const _CharT* __s, size_type __pos,
size_type __n) const;
size_type find_first_of(_CharT __c, size_type __pos = 0) const
{ return find(__c, __pos); }
public: // find_last_of
size_type find_last_of(const _Self& __s,
size_type __pos = npos) const
{ return find_last_of(__s._M_start, __pos, __s.size()); }
size_type find_last_of(const _CharT* __s, size_type __pos = npos) const
{ __STL_FIX_LITERAL_BUG(__s) return find_last_of(__s, __pos, _Traits::length(__s)); }
size_type find_last_of(const _CharT* __s, size_type __pos,
size_type __n) const;
size_type find_last_of(_CharT __c, size_type __pos = npos) const {
return rfind(__c, __pos);
}
public: // find_first_not_of
size_type find_first_not_of(const _Self& __s,
size_type __pos = 0) const
{ return find_first_not_of(__s._M_start, __pos, __s.size()); }
size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const
{ __STL_FIX_LITERAL_BUG(__s) return find_first_not_of(__s, __pos, _Traits::length(__s)); }
size_type find_first_not_of(const _CharT* __s, size_type __pos,
size_type __n) const;
size_type find_first_not_of(_CharT __c, size_type __pos = 0) const;
public: // find_last_not_of
size_type find_last_not_of(const _Self& __s,
size_type __pos = npos) const
{ return find_last_not_of(__s._M_start, __pos, __s.size()); }
size_type find_last_not_of(const _CharT* __s, size_type __pos = npos) const
{ __STL_FIX_LITERAL_BUG(__s) return find_last_not_of(__s, __pos, _Traits::length(__s)); }
size_type find_last_not_of(const _CharT* __s, size_type __pos,
size_type __n) const;
size_type find_last_not_of(_CharT __c, size_type __pos = npos) const;
public: // Substring.
_Self substr(size_type __pos = 0, size_type __n = npos) const {
if (__pos > size())
_M_throw_out_of_range();
return _Self(_M_start + __pos,
_M_start + __pos + min(__n, size() - __pos));
}
public: // Compare
int compare(const _Self& __s) const
{ return _M_compare(_M_start, _M_finish, __s._M_start, __s._M_finish); }
int compare(size_type __pos1, size_type __n1,
const _Self& __s) const {
if (__pos1 > size())
_M_throw_out_of_range();
return _M_compare(_M_start + __pos1,
_M_start + __pos1 + min(__n1, size() - __pos1),
__s._M_start, __s._M_finish);
}
int compare(size_type __pos1, size_type __n1,
const _Self& __s,
size_type __pos2, size_type __n2) const {
if (__pos1 > size() || __pos2 > __s.size())
_M_throw_out_of_range();
return _M_compare(_M_start + __pos1,
_M_start + __pos1 + min(__n1, size() - __pos1),
__s._M_start + __pos2,
__s._M_start + __pos2 + min(__n2, size() - __pos2));
}
int compare(const _CharT* __s) const {
__STL_FIX_LITERAL_BUG(__s)
return _M_compare(_M_start, _M_finish, __s, __s + _Traits::length(__s));
}
int compare(size_type __pos1, size_type __n1, const _CharT* __s) const {
__STL_FIX_LITERAL_BUG(__s)
if (__pos1 > size())
_M_throw_out_of_range();
return _M_compare(_M_start + __pos1,
_M_start + __pos1 + min(__n1, size() - __pos1),
__s, __s + _Traits::length(__s));
}
int compare(size_type __pos1, size_type __n1, const _CharT* __s,
size_type __n2) const {
__STL_FIX_LITERAL_BUG(__s)
if (__pos1 > size())
_M_throw_out_of_range();
return _M_compare(_M_start + __pos1,
_M_start + __pos1 + min(__n1, size() - __pos1),
__s, __s + __n2);
}
public: // Helper functions for compare.
static int __STL_CALL _M_compare(const _CharT* __f1, const _CharT* __l1,
const _CharT* __f2, const _CharT* __l2) {
const ptrdiff_t __n1 = __l1 - __f1;
const ptrdiff_t __n2 = __l2 - __f2;
const int cmp = _Traits::compare(__f1, __f2, min(__n1, __n2));
return cmp != 0 ? cmp : (__n1 < __n2 ? -1 : (__n1 > __n2 ? 1 : 0));
}
};
# if defined (__STL_USE_TEMPLATE_EXPORT)
__STL_EXPORT_TEMPLATE_CLASS basic_string<char, char_traits<char>, allocator<char> >;
# if defined (__STL_HAS_WCHAR_T)
__STL_EXPORT_TEMPLATE_CLASS basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >;
# endif
# endif /* __STL_USE_TEMPLATE_EXPORT */
// ------------------------------------------------------------
// Non-member functions.
template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc> __STL_CALL
operator+(const basic_string<_CharT,_Traits,_Alloc>& __s,
const basic_string<_CharT,_Traits,_Alloc>& __y)
{
typedef basic_string<_CharT,_Traits,_Alloc> _Str;
typedef typename _Str::_Reserve_t _Reserve_t;
# ifdef __GNUC__
// gcc counts this as a function
_Str __result = _Str(_Reserve_t(),__s.size() + __y.size());
# else
_Str __result(_Reserve_t(), __s.size() + __y.size());
# endif
__result.append(__s);
__result.append(__y);
return __result;
}
# if defined (__GNUC__) || defined (__MLCCPP__)
# define __STL_INIT_AMBIGUITY 1
# endif
template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc> __STL_CALL
operator+(const _CharT* __s,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
__STL_FIX_LITERAL_BUG(__s)
typedef basic_string<_CharT,_Traits,_Alloc> _Str;
typedef typename _Str::_Reserve_t _Reserve_t;
const size_t __n = _Traits::length(__s);
# ifdef __STL_INIT_AMBIGUITY
_Str __result = _Str(_Reserve_t(), __n + __y.size());
# else
_Str __result(_Reserve_t(), __n + __y.size());
# endif
__result.append(__s, __s + __n);
__result.append(__y);
return __result;
}
template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc> __STL_CALL
operator+(_CharT __c,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
typedef basic_string<_CharT,_Traits,_Alloc> _Str;
typedef typename _Str::_Reserve_t _Reserve_t;
# ifdef __STL_INIT_AMBIGUITY
_Str __result = _Str(_Reserve_t(), 1 + __y.size());
# else
_Str __result(_Reserve_t(), 1 + __y.size());
# endif
__result.push_back(__c);
__result.append(__y);
return __result;
}
template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc> __STL_CALL
operator+(const basic_string<_CharT,_Traits,_Alloc>& __x,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
typedef basic_string<_CharT,_Traits,_Alloc> _Str;
typedef typename _Str::_Reserve_t _Reserve_t;
const size_t __n = _Traits::length(__s);
# ifdef __STL_INIT_AMBIGUITY
_Str __result = _Str(_Reserve_t(), __x.size() + __n, __x.get_allocator());
# else
_Str __result(_Reserve_t(), __x.size() + __n, __x.get_allocator());
# endif
__result.append(__x);
__result.append(__s, __s + __n);
return __result;
}
template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc> __STL_CALL
operator+(const basic_string<_CharT,_Traits,_Alloc>& __x,
const _CharT __c) {
typedef basic_string<_CharT,_Traits,_Alloc> _Str;
typedef typename _Str::_Reserve_t _Reserve_t;
# ifdef __STL_INIT_AMBIGUITY
_Str __result = _Str(_Reserve_t(), __x.size() + 1, __x.get_allocator());
# else
_Str __result(_Reserve_t(), __x.size() + 1, __x.get_allocator());
# endif
__result.append(__x);
__result.push_back(__c);
return __result;
}
# undef __STL_INIT_AMBIGUITY
// Operator== and operator!=
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator==(const basic_string<_CharT,_Traits,_Alloc>& __x,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
return __x.size() == __y.size() &&
_Traits::compare(__x.data(), __y.data(), __x.size()) == 0;
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator==(const _CharT* __s,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
__STL_FIX_LITERAL_BUG(__s)
size_t __n = _Traits::length(__s);
return __n == __y.size() && _Traits::compare(__s, __y.data(), __n) == 0;
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator==(const basic_string<_CharT,_Traits,_Alloc>& __x,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
size_t __n = _Traits::length(__s);
return __x.size() == __n && _Traits::compare(__x.data(), __s, __n) == 0;
}
// Operator< (and also >, <=, and >=).
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator<(const basic_string<_CharT,_Traits,_Alloc>& __x,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
return basic_string<_CharT,_Traits,_Alloc>
::_M_compare(__x.begin(), __x.end(),
__y.begin(), __y.end()) < 0;
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator<(const _CharT* __s,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
__STL_FIX_LITERAL_BUG(__s)
size_t __n = _Traits::length(__s);
return basic_string<_CharT,_Traits,_Alloc>
::_M_compare(__s, __s + __n, __y.begin(), __y.end()) < 0;
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator<(const basic_string<_CharT,_Traits,_Alloc>& __x,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
size_t __n = _Traits::length(__s);
return basic_string<_CharT,_Traits,_Alloc>
::_M_compare(__x.begin(), __x.end(), __s, __s + __n) < 0;
}
#ifdef __STL_USE_SEPARATE_RELOPS_NAMESPACE
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator!=(const basic_string<_CharT,_Traits,_Alloc>& __x,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
return !(__x == __y);
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator>(const basic_string<_CharT,_Traits,_Alloc>& __x,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
return __y < __x;
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator<=(const basic_string<_CharT,_Traits,_Alloc>& __x,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
return !(__y < __x);
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator>=(const basic_string<_CharT,_Traits,_Alloc>& __x,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
return !(__x < __y);
}
#endif /* __STL_USE_SEPARATE_RELOPS_NAMESPACE */
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator!=(const _CharT* __s,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
__STL_FIX_LITERAL_BUG(__s)
return !(__s == __y);
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator!=(const basic_string<_CharT,_Traits,_Alloc>& __x,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
return !(__x == __s);
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator>(const _CharT* __s,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
__STL_FIX_LITERAL_BUG(__s)
return __y < __s;
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator>(const basic_string<_CharT,_Traits,_Alloc>& __x,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
return __s < __x;
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator<=(const _CharT* __s,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
__STL_FIX_LITERAL_BUG(__s)
return !(__y < __s);
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator<=(const basic_string<_CharT,_Traits,_Alloc>& __x,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
return !(__s < __x);
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator>=(const _CharT* __s,
const basic_string<_CharT,_Traits,_Alloc>& __y) {
__STL_FIX_LITERAL_BUG(__s)
return !(__s < __y);
}
template <class _CharT, class _Traits, class _Alloc>
inline bool __STL_CALL
operator>=(const basic_string<_CharT,_Traits,_Alloc>& __x,
const _CharT* __s) {
__STL_FIX_LITERAL_BUG(__s)
return !(__x < __s);
}
// Swap.
#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER
template <class _CharT, class _Traits, class _Alloc>
inline void __STL_CALL
swap(basic_string<_CharT,_Traits,_Alloc>& __x,
basic_string<_CharT,_Traits,_Alloc>& __y) {
__x.swap(__y);
}
#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */
template <class _CharT, class _Traits, class _Alloc>
void __STL_CALL _S_string_copy(const basic_string<_CharT,_Traits,_Alloc>& __s,
_CharT* __buf,
size_t __n);
# undef basic_string
__STL_END_NAMESPACE
# ifdef __STL_DEBUG
# include <stl/debug/_string.h>
# endif
# if !defined (__STL_LINK_TIME_INSTANTIATION)
# include <stl/_string.c>
# endif
# include <stl/_string_io.h>
# include <stl/_string_hash.h>
#endif /* __SGI_STL_STRING */
// Local Variables:
// mode:C++
// End:
| [
"[email protected]"
] | [
[
[
1,
1542
]
]
] |
6d110de37578764f6cbd2d4618c3903c9cb196a6 | fcdddf0f27e52ece3f594c14fd47d1123f4ac863 | /terralib/src/DSDK/include/filters/lti_multiresFilter.h | 394ef5b794535094df45c322c2037b3c13e9b4c0 | [] | 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 | 5,160 | h | /* $Id: lti_multiresFilter.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_MULTIRESFILTER_H
#define LTI_MULTIRESFILTER_H
// lt_lib_mrsid_core
#include "lti_imageFilter.h"
#include "lti_scene.h"
#if defined(LT_COMPILER_MS)
#pragma warning(push,4)
#endif
LT_BEGIN_NAMESPACE(LizardTech)
class LTIResampler;
/**
* add resolutions to the image
*
* Extends the magnification range of an image, to allow decodes at different
* resolutions than the image stage would normally allow.
*
* Note that this class is not the same as at the LTIStaticZoomFilter class,
* which scales the magnification statically for the pipeline when initially
* constructed. This class allows for the zoom level to be extended for an
* individual decode operation.
*/
class LTIMultiResFilter : public LTIImageFilter
{
public:
/**
* constructor
*
* Creates an image stage which can be decoded at arbitrary magnifications.
*
* Normally image stages will only support a limited set of magnification
* values for the LTIScene passed to LTIImageStage::read() -- often, only
* 1.0. This class will perform any needed resampling on the fly so that
* arbitrary (power-of-two) magnifications are supported.
*
* @param sourceImage the base image
* @param takeOwnership set to true to have the filter delete the \a sourceImage
*/
LTIMultiResFilter(LTIImageStage* sourceImage, bool takeOwnership);
LTIMultiResFilter(LTIImageStage* sourceImage,
double deltaMag,
double minMag,
double maxMag,
bool takeOwnership);
virtual ~LTIMultiResFilter();
virtual LT_STATUS initialize();
LT_STATUS setResampleMethod(LTIResampleMethod resampleMethod);
virtual lt_int64 getEncodingCost(const LTIScene& scene) const;
LT_STATUS projectPointAtMag(double upperLeft,
double mag,
double& newUpperLeft) const;
LT_STATUS projectDimAtMag(double dim,
double mag,
double& newDim) const;
LT_STATUS getDimsAtMag(double mag,
lt_uint32& width,
lt_uint32& height) const;
bool getReaderScene(const LTIScene &decodeScene,
LTIScene &readerScene) const;
// call this before initialize() if you want non-sq. pixels
// (the deltaMag in the constructor is ignored)
void setDeltaMagXY(double deltaMagX, double deltaMagY);
static double magForIcon(const LTIImageStage &image,
lt_uint32 iconSize);
protected:
LT_STATUS decodeBegin(const LTIScene& scene);
LT_STATUS decodeStrip(LTISceneBuffer& stripBuffer,
const LTIScene& stripScene);
LT_STATUS decodeEnd();
enum Mode
{
MODE_INVALID,
MODE_RESAMPLE,
MODE_PASSTHROUGH,
MODE_DOWNSAMPLE_FULLREAD,
MODE_ALL_AT_ONCE
};
bool getChildScene(const LTIScene &scene,
Mode &mode,
double &scaleX,
double &scaleY,
LTIScene &childScene) const;
enum
{
// The largest possible mag is based on the 2gb
// scene limitation. Thus the largest scene we
// should ever expect is approximately the square
// root of (2gb / 3) pixels on a side. If we
// assume the smallest image we'll ever encounter
// is 32x32 then the largest magnification can
// be calculated. It's big, but we need a real number!
kMaxMagnification = 512 // 51200% zoom!
};
private:
struct StripCache;
double m_mrMinMag;
double m_mrMaxMag;
double m_deltaMagX;
double m_deltaMagY;
Mode m_mode;
double m_scaleX;
double m_scaleY;
LTIScene m_childScene;
double m_curY;
lt_int32 m_childStrip;
lt_int32 m_myStrip;
StripCache *m_stripCache0;
StripCache *m_stripCache1;
LTIResampler *m_resampler;
// nope
LTIMultiResFilter(const LTIMultiResFilter&);
LTIMultiResFilter& operator=(const LTIMultiResFilter&);
};
LT_END_NAMESPACE(LizardTech)
#if defined(LT_COMPILER_MS)
#pragma warning(pop)
#endif
#endif // LTI_MULTIRESFILTER_H
| [
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
] | [
[
[
1,
161
]
]
] |
4373b7fa05be1185a99eb9b8f604c9e70313a627 | 49b6646167284329aa8644c8cf01abc3d92338bd | /SEP2_RELEASE/Tests/Test_M1.h | bfd844d8ace8e812f5f2d8692f0de9582b3c9568 | [] | no_license | StiggyB/javacodecollection | 9d017b87b68f8d46e09dcf64650bd7034c442533 | bdce3ddb7a56265b4df2202d24bf86a06ecfee2e | refs/heads/master | 2020-08-08T22:45:47.779049 | 2011-10-24T12:10:08 | 2011-10-24T12:10:08 | 32,143,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,120 | h | #ifndef TEST_M1_H_
#define TEST_M1_H_
#include "../Thread/HAWThread.h"
#include "../HAL/HALCore.h"
/**
* Testing Class for Milestone #1
*
* SE2 (+ SY and PL) Project SoSe 2011
*
* Authors: Rico Flaegel,
* Tell Mueller-Pettenpohl,
* Torsten Krane,
* Jan Quenzel
*
* Tests the Lights and some other hardware stuff.
* 1. Add lights after another.
* 2. Turn lights off instantly.
* 3. Add lights after another.
* 4. Turn off lights one at a time.
* 5. Turning on engine in right direction.
* 6. Turning on engine in left direction.
* 7. Slowing the engine.
* 8. Getting back to Normal Speed.
* 8. Stopping the engine.
* 9. Setting the engine to slow and left direction.
* 10. Switching to slow in right direction.
* 11. Opening the switch.
* 12. Closing the switch.
* 13. Resetting the hardware.
*
* Inherits: thread::HAWThread
*/
class Test_M1 : public thread::HAWThread {
public:
Test_M1();
virtual ~Test_M1();
protected:
virtual void execute(void*);
virtual void shutdown();
private:
HALCore *h;
};
#endif /* TEST_M1_H_ */
| [
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1"
] | [
[
[
1,
45
]
]
] |
eeaedd51603858cb0b946c1388751f476040029d | 62874cd4e97b2cfa74f4e507b798f6d5c7022d81 | /src/InputOIS/InputOISPlugin.cpp | ab16f20756d10678a6ecac65d7ba5b2844e233ce | [] | 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 | 3,146 | cpp | // Includes
#include "InputOISPlugin.h"
#include "JoyStick.h"
#include <libMidi-Me/DeviceManager.h>
using namespace MidiMe;
#include <OIS/OISInputManager.h>
#include <OIS/OISException.h>
/******************************
* Constructors and destructor *
******************************/
InputOISPlugin::InputOISPlugin()
: plugin::Plugin("InputOIS"), m_pInputMgr(0)
{
setDescription("This plugin uses Open Input System (OIS) to provide joystick input devices");
}
InputOISPlugin::~InputOISPlugin()
{
}
/***************************
* plugin::Plugin functions *
***************************/
bool InputOISPlugin::start(const plugin::KeyValueMap &settings)
{
m_settings = settings;
if(!initOIS())
{
cerr << "[InputOISPlugin] Error initializing OIS!" << endl;
return false;
}
m_started = true;
return true;
}
bool InputOISPlugin::stop()
{
if(!destroyOIS())
{
cerr << "[InputOISPlugin] Error destroying OIS!" << endl;
return false;
}
m_started = false;
return true;
}
/******************
* Other functions *
******************/
/**********************
* Protected functions *
**********************/
bool InputOISPlugin::initOIS()
{
// Get the window handle to use
size_t windowHandle = DeviceManager::getInstance().getWindowHandle();
// Create the input system
try
{
char windowHandleStr[256];
::sprintf(windowHandleStr, "%d", windowHandle);
OIS::ParamList params;
params.insert(std::make_pair(std::string("WINDOW"), windowHandleStr ));
#if defined OIS_WIN32_PLATFORM
params.insert(std::make_pair(std::string("w32_joystick"), std::string("DISCL_BACKGROUND")));
params.insert(std::make_pair(std::string("w32_joystick"), std::string("DISCL_NONEXCLUSIVE")));
#endif
m_pInputMgr = OIS::InputManager::createInputSystem(params);
}
catch(OIS::Exception &e)
{
cerr << "[InputOISPlugin] Error creating input system: " << string(e.eText) << endl;
return false;
}
// Create all available joysticks
//! @todo Only create joysticks that are used
try
{
//int num = m_pInputMgr->numJoySticks();
int num = m_pInputMgr->getNumberOfDevices(OIS::OISJoyStick);
for(int i = 0; i < num; ++i)
{
OIS::JoyStick *pOISJoyStick = (OIS::JoyStick *) m_pInputMgr->createInputObject(OIS::OISJoyStick, true);
JoyStick *pJoyStick = new JoyStick(pOISJoyStick);
m_joySticks.push_back(pJoyStick);
//cerr << "[InputOISPlugin] JoyStick found: " << pOISJoyStick->vendor() << endl;
}
}
catch(OIS::Exception &e)
{
cerr << "[InputOISPlugin] Error initializing joystick: " << e.eText << endl;
return false;
}
return true;
}
bool InputOISPlugin::destroyOIS()
{
// Destroy joysticks
for(unsigned int i = 0; i < m_joySticks.size(); ++i)
{
JoyStick *pJoyStick = m_joySticks.at(i);
OIS::JoyStick *pOISJoyStick = pJoyStick->getOISJoyStick();
delete pJoyStick;
m_pInputMgr->destroyInputObject(pOISJoyStick);
}
m_joySticks.clear();
// Destroy the input system
OIS::InputManager::destroyInputSystem(m_pInputMgr);
m_pInputMgr = 0;
return true;
}
| [
"Jeroen.Dierckx@d8a2fbcc-2753-0410-82a0-8bc2cd85795f"
] | [
[
[
1,
136
]
]
] |
a5fb424e4aa03a8837c8812f9f791f94daa908d3 | b23a27888195014aa5bc123d7910515e9a75959c | /Main/3rdLib/LightOPC/SAMPLE.cpp | e1cc0aac7d772cbe62a7db1ac50bcc7535c3850e | [] | no_license | fostrock/connectspot | c54bb5484538e8dd7c96b76d3096dad011279774 | 1197a196d9762942c0d61e2438c4a3bca513c4c8 | refs/heads/master | 2021-01-10T11:39:56.096336 | 2010-08-17T05:46:51 | 2010-08-17T05:46:51 | 50,015,788 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,537 | cpp | /**************************************************************************
* *
* Light OPC Server development library *
* *
* Copyright (c) 2000 Timofei Bondarenko *
*
Sample server
NOTE: the sample contains code for both in-proc and out-of-proc
servers. Therefore here is some overhead due this.
NOTE: the exe version of sample can be built for CONSOLE or WINDOWS mode.
see linker options for subsystem/entrypoint.
In console mode it will print messages to console window, when invoked
from command line, and can be terminated by Ctrl^C/Ctrl^Break.
On another hand, it will display a console window for a short time when
invoked from a windowed application.
**************************************************************************/
#define _WIN32_DCOM
#include <windows.h>
#include "unilog.h"
#define LOGID log,0
#include <ole2.h>
#include <olectl.h>
#include <oleauto.h>
#include <process.h>
#include <stdio.h>
#include <errno.h>
#include <locale.h>
#include <opcda.h>
#include <opcerror.h>
#include "lightopc.h"
#if 0
static LONG server_process;
#define CoAddRefServerProcess() (InterlockedIncrement(&server_process))
#define CoReleaseServerProcess() (InterlockedDecrement(&server_process))
#define CoQueryClientBlanket(a,b,c,d,e,userid,f) (*((const wchar_t**)userid)=L"Wine!")
#endif
unilog *log; /* logging entry */
int use_console = 0;
int test_mode = 0;
/********************* OPC vendor info ***************************************/
static const loVendorInfo vendor = {
3 /*Major */ , 2 /*Minor */ , 1 /*Build */ , 0 /*Reserv */ ,
"Sample OPC Server #9"
};
loService *my_service;
static int driver_init(int lflags);
static void driver_destroy(void);
static void simulate(unsigned pause);
/* OLE-specefic data: ***********************************************************/
// {C896CBD0-ABF5-11d4-BED0-00002120DB5C} inproc-server
static const GUID CLSID_LightOPCServerDLL =
{ 0xc896cbd0, 0xabf5, 0x11d4, {0xbe, 0xd0, 0x0, 0x0, 0x21, 0x20, 0xdb,
0x5c} };
// {4EA2713D-CA07-11d4-BEF5-00002120DB5C} exe-server
static const GUID CLSID_LightOPCServerEXE =
{ 0x4ea2713d, 0xca07, 0x11d4, {0xbe, 0xf5, 0x0, 0x0, 0x21, 0x20, 0xdb,
0x5c} };
/**** Server Counting stuff & OLE ICF implementation *****************************
The IClassFactory is unavoidable evil. Feel free to go ahead.
Basically we've to unload when the server_count being zero.
But there are different techniques for in-/out-of- proc servers.
*/
class myClassFactory: public IClassFactory
{
public:
int is_out_of_proc,
server_inuse; /* go 0 when unloading initiated */
LONG server_count;
CRITICAL_SECTION lk_count; /* protect server_count */
myClassFactory(): is_out_of_proc(0), server_inuse(0), server_count(0)
{
InitializeCriticalSection(&lk_count);
}
~myClassFactory()
{
DeleteCriticalSection(&lk_count);
}
void serverAdd(void);
void serverRemove(void);
/* Do nothing: we're static, he-he */
STDMETHODIMP_(ULONG) AddRef(void) { return 1; }
STDMETHODIMP_(ULONG) Release(void) { return 1; }
STDMETHODIMP QueryInterface(REFIID iid, LPVOID *ppInterface)
{
if (ppInterface == NULL)
return E_INVALIDARG;
if (iid == IID_IUnknown || iid == IID_IClassFactory)
{
UL_DEBUG((LOGID, "myClassFactory::QueryInterface() Ok"));
*ppInterface = this;
AddRef();
return S_OK;
}
UL_DEBUG((LOGID, "myClassFactory::QueryInterface() Failed"));
*ppInterface = NULL;
return E_NOINTERFACE;
}
STDMETHODIMP LockServer(BOOL fLock)
{
UL_DEBUG((LOGID, "myClassFactory::LockServer(%d)", fLock));
if (fLock) serverAdd();
else serverRemove();
return S_OK;
}
STDMETHODIMP CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid,
LPVOID *ppvObject);
};
static myClassFactory my_CF;
void myClassFactory::serverAdd(void)
{
EnterCriticalSection(&lk_count);
if (is_out_of_proc) CoAddRefServerProcess();
++server_count;
LeaveCriticalSection(&lk_count);
}
void myClassFactory::serverRemove(void)
{
EnterCriticalSection(&lk_count);
if (is_out_of_proc)
{
if (0 == CoReleaseServerProcess())
server_inuse = 0;
}
if (0 == --server_count && server_inuse) server_inuse = 0;
LeaveCriticalSection(&lk_count);
}
static void a_server_finished(void *arg, loService *b, loClient *c)
{
/* ARG is the same as we've passed to loClientCreate() */
UL_DEBUG((LOGID, "a_server_finished(%lu)...", my_CF.server_count));
my_CF.serverRemove();
/* OPTIONAL: */
UL_INFO((LOGID, "a_server_finished(%lu) USERID=<%ls>",
my_CF.server_count, arg? arg: L"<null>"));
if (use_console)
printf("-Detaching a client. USERID: <%ls>\n", arg? arg: L"<null>");
}
static void dll_simulator_wait(void); /* in-proc specefic */
static void dll_simulator_start(void); /* in-proc specefic */
STDMETHODIMP myClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid,
LPVOID *ppvObject)
{
IUnknown *server = 0;
HRESULT hr = S_OK;
/* OPTIONAL: security stuff */
OLECHAR *userid = 0;
wchar_t *cuserid;
LONG userno;
static LONG usercount;
userno = InterlockedIncrement(&usercount);
CoQueryClientBlanket(0, 0, 0, 0, 0, (RPC_AUTHZ_HANDLE*)&userid, 0);
if (!userid) userid = L"{unknown}";
UL_WARNING((LOGID, "USER:#%ld <%ls>", userno, userid));
if (use_console)
printf("+Attaching a client #%ld. USERID: <%ls>\n", usercount, userid);
if (cuserid = (wchar_t*)malloc((wcslen(userid) + 16) * sizeof(wchar_t)))
swprintf(cuserid, L"#%ld %ls", userno, userid);
/* -- end of security stuff */
if (pUnkOuter)
{
#if 1 /* Do we support aggregation? */
if (riid != IID_IUnknown)
#endif
return CLASS_E_NOAGGREGATION;
}
serverAdd(); /* the lock for a_server_finished() */
/***********************************************
* check other conditions (i.e. security) here *
***********************************************/
if (0 == server_inuse) /* we're stopped */
{ /* stopping initiated when there are no active instances */
if (is_out_of_proc)
{ /* a stopped EXE should exit soon and can't work anymore */
UL_MESSAGE((LOGID, "myClassFactory:: Server already finished"));
serverRemove();
return E_FAIL;
}
else /* in-proc specefic here: */
{ /* restart the server if not already running */
dll_simulator_wait(); /* wait for stopping complete */
dll_simulator_start(); /* then restart */
if (0 == server_inuse)
{
UL_MESSAGE((LOGID, "myClassFactory:: Can't start server"));
serverRemove();
return E_FAIL;
}
}
}
{
IUnknown *inner = 0;
if (loClientCreate_agg(my_service, (loClient**)&server,
pUnkOuter, &inner,
0, &vendor, a_server_finished, cuserid/*this*/))
{
serverRemove();
hr = E_OUTOFMEMORY;
UL_MESSAGE((LOGID, "myClassFactory::loClientCreate_agg() failed"));
}
else if (pUnkOuter) *ppvObject = (void*)inner; /*aggregation requested*/
else /* no aggregation */
{
/* loClientCreate(my_service, (loClient**)&server,
0, &vendor, a_server_finished, cuserid) - with no aggregation */
/* Initally the created SERVER has RefCount=1 */
hr = server->QueryInterface(riid, ppvObject); /* Then 2 (if success) */
server->Release(); /* Then 1 (on behalf of client) or 0 (if QI failed) */
if (FAILED(hr))
UL_MESSAGE((LOGID, "myClassFactory::loClient QueryInterface() failed"));
/* So we shouldn't carry about SERVER destruction at this point */
}
}
if (SUCCEEDED(hr))
{
loSetState(my_service, (loClient*)server,
loOP_OPERATE, (int)OPC_STATUS_RUNNING, /* other states are possible */
"Finished by client");
UL_DEBUG((LOGID, "myClassFactory::server_count = %ld", server_count));
}
return hr;
}
/************************* The END of OLE-specific ***************************/
/****************** The Process Data to be exported via OPC ******************
(driver's internal representation) */
static CRITICAL_SECTION lk_values; /* protects ti[] from simultaneous
access by simulator() and WriteTags() */
/* Our data tags: */
/* zero is resierved for an invalid RealTag */
#define TI_zuzu (1)
#define TI_lulu (2)
#define TI_bandwidth (3)
#define TI_array (4)
#define TI_enum (5)
#define TI_quiet (6)
#define TI_quality (7)
#define TI_string (8)
#define TI_MAX (8)
static loTagId ti[TI_MAX + 1]; /* their IDs */
static const char *tn[TI_MAX + 1] = /* their names */
{ "--not--used--", "zuzu", "lulu", "bandwidth", "array", "enum-localizable",
"quiet", "quality", "string" };
static loTagValue tv[TI_MAX + 1]; /* their values */
/**********************************************************************
sample server initiation & simulation
**********************************************************************/
/* OPTIONAL: show client's interests */
void activation_monitor(const loCaller *ca, int count, loTagPair *til)
{
int act = 1;
if (0 > count)
act = 0, count = -count;
while(count--)
{
UL_DEBUG((LOGID, "MON: %u %s %s", til[count].tpTi,
tn[(int) til[count].tpRt], act ? "On" : "Off"));
}
}
/* OPTIONAL: write back to the device */
int WriteTags(const loCaller *ca,
unsigned count, loTagPair taglist[],
VARIANT values[], HRESULT error[], HRESULT *master, LCID lcid)
{
unsigned ii;
UL_TRACE((LOGID, "WriteTags(%x) invoked"));
EnterCriticalSection(&lk_values);
for(ii = 0; ii < count; ii++)
{
HRESULT hr = S_OK;
loTagId clean = 0;
switch((int)taglist[ii].tpRt)
{
case TI_zuzu:
{ double oldval = tv[TI_zuzu].tvValue.dblVal;
hr = VariantChangeType(&tv[TI_zuzu].tvValue,
&values[ii], 0, V_VT(&tv[TI_zuzu].tvValue));
UL_INFO((LOGID, "%p:%s:WriteTags(zuzu) = %.1f old=%.1f [%x]",
ca->ca_cli, loClientName(ca->ca_cli),
tv[TI_zuzu].tvValue.dblVal, oldval, hr));
if (tv[TI_zuzu].tvValue.dblVal < 0)
hr = DISP_E_TYPEMISMATCH; /* simulate a write error */
}
break;
case TI_lulu:
hr = VariantChangeType(&tv[TI_lulu].tvValue, &values[ii], 0, VT_I2);
if (S_OK == hr)
lo_statperiod(V_I2(&tv[TI_lulu].tvValue)); /* VERY OPTIONAL, really */
/* The splining factor for bandwidth calculations/trending */
break;
case TI_quiet:
hr = VariantChangeType(&tv[TI_quiet].tvValue, &values[ii], 0,
V_VT(&tv[TI_quiet].tvValue));
break;
case TI_array:
hr = lo_variant_changetype_array(&tv[TI_array].tvValue,
&values[ii], lcid, 0,
V_VT(&tv[TI_array].tvValue));
break;
case 0: /* ignore */
default: /* preserve unhandled tags */
clean = taglist[ii].tpTi;
break;
}
if (S_OK != hr)
{
*master = S_FALSE;
error[ii] = hr;
UL_TRACE((LOGID, "%!l WriteTags(Rt=%u Ti=%u %s)",
hr, taglist[ii].tpRt, taglist[ii].tpTi,
tn[(int)taglist[ii].tpRt <= TI_MAX? (int)taglist[ii].tpRt: 0]));
}
taglist[ii].tpTi = clean; /* clean if ok */
}
LeaveCriticalSection(&lk_values);
return loDW_TOCACHE; /* put to the cache all tags unhandled here */
// loDW_ALLDONE;
}
/* OPTIONAL: example of non-trivial datatype conversion */
static void local_text(WCHAR buf[32], unsigned nn, LCID lcid);
void ConvertTags(const loCaller *ca,
unsigned count, const loTagPair taglist[],
VARIANT *values, WORD *qualities, HRESULT *errs,
HRESULT *master_err, HRESULT *master_qual,
const VARIANT src[], const VARTYPE vtypes[], LCID lcid)
{
unsigned ii;
for(ii = 0; ii < count; ii++)
{
HRESULT hr = S_OK;
VARTYPE reqtype = vtypes[ii];
if (reqtype == VT_EMPTY) reqtype = V_VT(&src[ii]);
switch((int)taglist[ii].tpRt)
{
case 0: /* ignore */
break;
case TI_array:
if (V_VT(&src[ii]) == reqtype)
{
hr = values == src? S_OK : VariantCopy(&values[ii], (VARIANT*)&src[ii]);
}
else
{
hr = lo_variant_changetype_array(&values[ii],
(VARIANT*)&src[ii], lcid, 0, reqtype);
}
break;
case TI_enum:
if (V_VT(&src[ii]) == VT_I2 && reqtype == VT_BSTR)
{
WCHAR ww[32];
int vv = V_I2(&src[ii]);
VariantClear(&values[ii]);
local_text(ww, vv, lcid);
if (V_BSTR(&values[ii]) = SysAllocString(ww))
V_VT(&values[ii]) = VT_BSTR;
else hr = E_OUTOFMEMORY;
break;
}
default:
if (reqtype == V_VT(&src[ii]))
{
if (values == src) hr = S_OK;
else hr = VariantCopy(values + ii, (VARIANT*)&src[ii]);
}
else
hr = VariantChangeType(values + ii, (VARIANT*)&src[ii], 0, reqtype);
UL_ERROR((LOGID, "ConvII NotRequested(%u %u)[%u/%u]",
taglist[ii].tpRt, taglist[ii].tpTi, ii, count));
break;
} /* end of switch( */
if (S_OK != hr)
{
errs[ii] = hr;
qualities[ii] = OPC_QUALITY_BAD;
*master_err = *master_qual = S_FALSE;
UL_WARNING((LOGID, "%!l ConvII Error(Rt=%u Ti=%u %s)[%u/%u]",
hr, taglist[ii].tpRt, taglist[ii].tpTi,
tn[(int)taglist[ii].tpRt <= TI_MAX? (int)taglist[ii].tpRt: 0],
ii, count));
}
} /* end of for(...*/
}
/* OPTIONAL: example of DS_DEVICE read(). It enforces significant delay,
sufficient for view request's queueing and test the cancellation. */
loTrid ReadTags(const loCaller *ca,
unsigned count, loTagPair taglist[],
VARIANT *values, WORD *qualities,
FILETIME *stamps, HRESULT *errs,
HRESULT *master_err, HRESULT *master_qual,
const VARTYPE vtypes[], LCID lcid)
{
UL_TRACE((LOGID, "ReadTags( ) invoked"));
Sleep(33333); /* just for Cancel() testing */
return loDR_CACHED; /* perform actual reading from cache */
}
/* OPTIONAL: example of dynamic tag creation */
HRESULT AskItemID(const loCaller *ca, loTagId *ti,
void **acpa, const loWchar *itemid,
const loWchar *accpath, int vartype, int goal) /* Dynamic tags */
{
HRESULT hr = S_OK;
VARIANT var;
VariantInit(&var);
V_R4(&var) = 3; /* God likes 3 */
V_VT(&var) = VT_R4;
UL_NOTICE((LOGID, "AskItemID %ls type = %u(0x%x)", itemid, vartype, vartype));
if (VT_EMPTY != vartype) /* check conversion */
hr = VariantChangeType(&var, &var, 0, vartype);
if (S_OK == hr) /* we got a value of requested type */
{
int rv;
rv =
loAddRealTag_aW(ca->ca_se, ti, 0, itemid, 0,
OPC_READABLE | OPC_WRITEABLE, &var, 0, 100);
if (rv)
{
if (rv == EEXIST) *ti = 0; /* Already there? - Use existing one! */
else hr = E_OUTOFMEMORY;
}
}
VariantClear(&var);
return hr;
}
/******* ******* ******* ******* ******* ******* ******* *******/
int driver_init(int lflags)
{
loDriver ld;
VARIANT var;
loTagId tti;
int ecode;
setlocale(LC_CTYPE, "");
if (my_service)
{
UL_ERROR((LOGID, "Driver already initialized!"));
return 0;
}
memset(&ld, 0, sizeof(ld)); /* basic server parameters: */
// ld.ldRefreshRate = 3;//10;
ld.ldSubscribe = activation_monitor;
ld.ldWriteTags = WriteTags;
// ld.ldReadTags = ReadTags;
ld.ldConvertTags = ConvertTags;
#if 0
ld.ldAskItemID = AskItemID;
#endif
ld.ldFlags = lflags | loDF_IGNCASE | /*loDf_FREEMARSH | loDf_BOTHMODEL | */
/*loDF_NOCOMP| */ loDf_NOFORCE & 0 /*| loDF_SUBSCRIBE_RAW*/;
/*Fix the Bug in ProTool *//*|loDF_IGNCASE */ ;
ld.ldBranchSep = '/'; /* Hierarchial branch separator */
ecode = loServiceCreate(&my_service, &ld, 64 /* number of tags in the cache */);
/* 500000 is ok too */
UL_TRACE((LOGID, "%!e loCreate()=", ecode));
if (ecode) return -1;
InitializeCriticalSection(&lk_values);
memset(tv, 0, sizeof(tv)); /* instead of VariantInit() for each of them */
VariantInit(&var);
/* OPTIONAL: Tags creation. Do you need a few tags? */
ecode = loAddRealTag_b(my_service, /* actual service context */
&tti, /* returned TagId */
0, /* != 0 driver's key */
"Just the hint / [0...999]", /* tag name (hint) */
0, /* loTF_ Flags */
OPC_READABLE | OPC_WRITEABLE, 0);
V_I1(&var) = -1; /* the good practice: set the value first, then type. */
V_VT(&var) = VT_I1; /* Do you know why? */
ecode = loAddRealTag_a(my_service,
&ti[TI_bandwidth], /* returned TagId (lightopc's identifier)*/
(loRealTag)TI_bandwidth, /* != 0 (driver's internal identifier)*/
tn[TI_bandwidth], /* tag name */
0, /* loTF_ Flags */
OPC_READABLE, /* OPC access rights */
&var, /* type and value for conversion checks */
-1, 101); /*Analog EUtype: from -1 (unknown) to 101% (overload)*/
/* Shows current bandwidth */
/* We needn't to VariantClear() for simple datatypes like numbers */
V_R8(&var) = 214.1; /* initial value. Will be used to check types conersions */
V_VT(&var) = VT_R8;
ecode = loAddRealTag_a(my_service, /* actual service context */
&ti[TI_zuzu], /* returned TagId */
(loRealTag)TI_zuzu, /* != 0 driver's key */
tn[TI_zuzu], /* tag name */
0, /* loTF_ Flags */
OPC_READABLE | OPC_WRITEABLE, &var, 12., 1200.);
UL_TRACE((LOGID, "%!e loAddRealTag_a(zuzu) = %u ", ecode, ti[TI_zuzu]));
V_I2(&var) = 1000;
V_VT(&var) = VT_I2;
ecode = loAddRealTag(my_service, /* actual service context */
&ti[TI_lulu], /* returned TagId */
(loRealTag) TI_lulu, /* != 0 driver's key */
tn[TI_lulu], /* tag name */
0, /* loTF_ Flags */
OPC_READABLE | OPC_WRITEABLE, &var, 0, 0);
UL_TRACE((LOGID, "%!e loAddRealTag(lulu) = %u ", ecode, ti[TI_lulu]));
/* This 2nd 'zuzu' will fail with EEXISTS */
ecode = loAddRealTag(my_service,
&tti, /* returned TagId */
(loRealTag) TI_zuzu, /* != 0 driver's key */
"zuzu", /* tag name */
0, /* loTF_ Flags */
OPC_READABLE | OPC_WRITEABLE, &var, 0, 0);
UL_TRACE((LOGID, "%!e loAddRealTag(zuzu) = %u (duplicated)", ecode, tti));
#if 1 /* OPTIONAL: generate several tags to test capabilites & performance */
{
char name[64];
int ii, sep;
DWORD sttime = GetTickCount();
memset(name, 0, sizeof(name));
strcpy(name, "A Huge list /");
ii = strlen(name);
memset(name + ii, 'Z', 32 - ii);
for(ecode = 0, sep = '-'; *name <= 'B'; sep = '/', (*name)++)
{
for(ii = 0; ii < 4 /*0000 */ && !ecode; ii++)
{
loTagId tt;
sprintf(name + 32, ".%010u%c@", ii, sep);
ecode = loAddRealTag_b(my_service,
&tt, 0, name, 0, OPC_READABLE,
ti[TI_bandwidth]);
/* loAddRealTag_b() inherits attributes of specified tag - ti[TI_bandwidth] */
}
UL_WARNING((LOGID, "%u tags created for %d mS",
ii * (*name - 'A' + 1), GetTickCount() - sttime));
}
}
#endif
loAddRealTag(my_service, &ti[TI_quiet], (loRealTag) TI_quiet, tn[TI_quiet],
0, OPC_READABLE, &var, 0, 0);
loAddRealTag(my_service, &tti, 0, "wr-only", 0, OPC_WRITEABLE, &var, 0, 0);
/* OPTIONAL: Create some Hierachial structure: */
#define ADD_TAG(name) loAddRealTag_b(my_service, &tti, \
0, name, 0,\
OPC_READABLE|OPC_WRITEABLE, tti)
ADD_TAG("Tree/qw/qq");
ADD_TAG("Tree/qw/zz");
ADD_TAG("Tree/qw/ii/hh");
ADD_TAG("Tree/qw/ii/yy");
ADD_TAG("Tree/qw/ii/yy/mm/dd");
ADD_TAG("Tree/eec/ii/yy/mMm/dd");
ADD_TAG("Tree/eec/ii/yy/mMm/ddd");
ADD_TAG("Tree/ee/ii/yy/mm/dd");
ADD_TAG("Tree/ee/ii/yyy/mm/dd");
/* OPTIONAL: Advanced Item Properies: defining and assignement */
{
loPLid plid;
if (0 == (plid = loPropListCreate(my_service)))
{
UL_WARNING((LOGID, "loPropListCreate() FAILED"));
}
else
{
V_R8(&var) = 999.9;
V_VT(&var) = VT_R8;
if (loPropertyAdd(my_service, plid, 102, &var, 0, 0) ||
loPropertyAdd(my_service, plid, 5001, 0, "/Two", 0) ||
loPropertyAdd(my_service, plid, 5002, 0, "//Two", 0) ||
loPropertyAdd(my_service, plid, 5003, 0, "Two",
"a Custom property Two"))
{
UL_WARNING((LOGID, "loPropertyAdd() FAILED"));
}
ADD_TAG("device/port/one/Two");
loPropListAssign(my_service, plid, tti, 1);
ADD_TAG("device/port/one");
loPropListAssign(my_service, plid, tti, 1);
ADD_TAG("device/port/Two");
loPropListAssign(my_service, plid, tti, 1);
ADD_TAG("device/port");
loPropListAssign(my_service, plid, tti, 1);
ADD_TAG("device/Two");
loPropListAssign(my_service, plid, tti, 1);
ADD_TAG("device");
loPropListAssign(my_service, plid, tti, 1);
ADD_TAG("Two");
loPropListAssign(my_service, plid, tti, 1);
}
}
#undef ADD_TAG
#if 1 /* OPTIONAL: Creation of complex datatypes */
{
SAFEARRAY *sa;
SAFEARRAYBOUND sbound[1];
sbound[0].lLbound = 0;
sbound[0].cElements = 2;
/*** VT_ARRAY type */
VariantInit(&tv[TI_array].tvValue);
if (sa = SafeArrayCreate(VT_I4, 1, sbound))
{
HRESULT hr;
long ix0 = 0, ix1 = 1, val = 333;
V_ARRAY(&tv[TI_array].tvValue) = sa;
V_VT(&tv[TI_array].tvValue) = VT_ARRAY | VT_I4;
if (S_OK != (hr = SafeArrayPutElement(sa, &ix0, &val)) ||
S_OK != (hr = SafeArrayPutElement(sa, &ix1, &val)))
{
UL_NOTICE((LOGID, "%!l SafeArray", hr));
VariantClear(&tv[TI_array].tvValue);
}
else
if (!loAddRealTag(my_service, &ti[TI_array],
(loRealTag)TI_array, tn[TI_array],
loTF_CONVERT, OPC_READABLE | OPC_WRITEABLE,
&tv[TI_array].tvValue, 0, 0))
{
tv[TI_array].tvTi = ti[TI_array];
tv[TI_array].tvState.tsError = S_OK;
tv[TI_array].tvState.tsQuality = OPC_QUALITY_GOOD;
}
}
else
{
UL_ERROR((LOGID, "driver_init(): SafeArrayCreate() failed"));
}
/*** An enumerated type (localized weekdays names) with EUinfo ***/
sbound[0].lLbound = 0;
sbound[0].cElements = 7;
VariantInit(&tv[TI_enum].tvValue);
V_I2(&tv[TI_enum].tvValue) = 6;
V_VT(&tv[TI_enum].tvValue) = VT_I2;
if (sa = SafeArrayCreate(VT_BSTR, 1, sbound))
{
VARIANT ed;
VariantInit(&ed);
long ix;
V_VT(&ed) = VT_ARRAY | VT_BSTR;
V_ARRAY(&ed) = sa;
for(ix = 0; ix < 7; ix++)
{
HRESULT hr;
BSTR bs;
WCHAR ws[32];
local_text(ws, (unsigned)ix, 0); /* generates localized name */
bs = SysAllocString(ws);
if (S_OK != (hr = SafeArrayPutElement(sa, &ix, bs)))
{
UL_NOTICE((LOGID, "%!l SafeArray PutString", hr));
}
SysFreeString(bs);
}
if (!loAddRealTag(my_service, &ti[TI_enum], (loRealTag) TI_enum,
tn[TI_enum], loTF_CONVERT/*localization request*/,
OPC_READABLE, &tv[TI_enum].tvValue, OPC_ENUMERATED, &ed))
{
tv[TI_enum].tvTi = ti[TI_enum];
tv[TI_enum].tvState.tsError = S_OK;
tv[TI_enum].tvState.tsQuality = OPC_QUALITY_GOOD;
}
VariantClear(&ed);
}
else
{
UL_ERROR((LOGID, "driver_init(): SafeArrayCreate(enum) failed"));
}
}
#endif
/*** Show differnt OPC-Qualities ***/
V_BSTR(&tv[TI_quality].tvValue) = SysAllocString(L"");
V_VT(&tv[TI_quality].tvValue) = VT_BSTR;
ecode = loAddRealTag(my_service, &ti[TI_quality],
(loRealTag) TI_quality, tn[TI_quality],
0, OPC_READABLE | OPC_WRITEABLE,
&tv[TI_quality].tvValue, 0, 0);
/*** STRING (VT_BSTR) datatype ***/
V_BSTR(&tv[TI_string].tvValue) = SysAllocString(L"");
V_VT(&tv[TI_string].tvValue) = VT_BSTR;
ecode = loAddRealTag(my_service, &ti[TI_string],
(loRealTag) TI_string, tn[TI_string],
0, OPC_READABLE | OPC_WRITEABLE,
&tv[TI_string].tvValue, 0, 0);
// VariantClear(&var);
/* don't required because we didn't assigned complex types to var */
return 0;
}
void driver_destroy(void)
{
if (my_service)
{
int ecode = loServiceDestroy(my_service);
UL_INFO((LOGID, "%!e loDelete(%p) = ", ecode));
for(ecode = 0; ecode < sizeof(tv) / sizeof(tv[0]); ecode++)
VariantClear(&tv[ecode].tvValue);
DeleteCriticalSection(&lk_values);
my_service = 0;
}
}
/********* Data simulator stuff ************************************************/
void simulate(unsigned pause)
{
DWORD hitime = 0;
unsigned starttime = GetTickCount();
UL_WARNING((LOGID, "Simulator Started..."));
EnterCriticalSection(&lk_values);
/* Set up initial values for the tags we didn't initialized in driver_init(): */
tv[TI_zuzu].tvTi = ti[TI_zuzu];
tv[TI_zuzu].tvState.tsError = S_OK;
tv[TI_zuzu].tvState.tsQuality = OPC_QUALITY_GOOD;
V_VT(&tv[TI_zuzu].tvValue) = VT_R8;
V_R8(&tv[TI_zuzu].tvValue) = -100;
tv[TI_lulu].tvTi = ti[TI_lulu];
tv[TI_lulu].tvState.tsError = S_OK;
tv[TI_lulu].tvState.tsQuality = OPC_QUALITY_GOOD;
V_VT(&tv[TI_lulu].tvValue) = VT_I2;
V_I2(&tv[TI_lulu].tvValue) = 78;
tv[TI_enum].tvTi = ti[TI_enum];
tv[TI_enum].tvState.tsError = S_OK;
tv[TI_enum].tvState.tsQuality = OPC_QUALITY_GOOD;
V_VT(&tv[TI_enum].tvValue) = VT_I2;
V_I2(&tv[TI_enum].tvValue) = 1;
tv[TI_bandwidth].tvTi = ti[TI_bandwidth];
tv[TI_bandwidth].tvState.tsError = S_OK;
tv[TI_bandwidth].tvState.tsQuality = OPC_QUALITY_GOOD;
V_VT(&tv[TI_bandwidth].tvValue) = VT_I1;
V_I1(&tv[TI_bandwidth].tvValue) = -1;
tv[TI_quiet].tvTi = ti[TI_quiet];
tv[TI_quiet].tvState.tsError = S_OK;
tv[TI_quiet].tvState.tsQuality = OPC_QUALITY_LAST_KNOWN;
V_VT(&tv[TI_quiet].tvValue) = VT_I2;
V_I2(&tv[TI_quiet].tvValue) = 1412;
tv[TI_quality].tvTi = ti[TI_quality];
tv[TI_quality].tvState.tsError = S_OK;
// tv[TI_quality].tvValue -- already assigned
tv[TI_string].tvTi = ti[TI_string];
tv[TI_string].tvState.tsQuality = OPC_QUALITY_GOOD;
tv[TI_string].tvState.tsError = S_OK;
// tv[TI_string].tvValue -- already assigned
// tv[TI_enum], tv[TI_array], string, quality, -- already assigned
LeaveCriticalSection(&lk_values);
/**** Then do simulate ***********/
while(0 != my_CF.server_inuse) /* still working? */
{
FILETIME ft;
Sleep(10); /* main delay */
GetSystemTimeAsFileTime(&ft); /* awoke */
/* OPTIONAL: reload log's configuration fromtime to time */
if (hitime != (ft.dwLowDateTime & 0xf8000000)) /* 13.5 sec */
{ /* 0xff000000 is about 1.67 sec */
hitime = ft.dwLowDateTime & 0xf8000000;
#if 0
unilog_Refresh(0); /* all logs */
#else
unilog_Refresh("LightOPC");
unilog_Refresh("Lopc-Sample-exe");
unilog_Refresh("Lopc-Sample-dll");
#endif
}
/***** The main job: update the values ******/
EnterCriticalSection(&lk_values);
double zuzu =
(V_R8(&tv[TI_zuzu].tvValue) += 1./3.); /* main simulation */
V_VT(&tv[TI_zuzu].tvValue) = VT_R8;
tv[TI_zuzu].tvState.tsTime = ft;
V_I2(&tv[TI_lulu].tvValue) = (short)zuzu;
V_VT(&tv[TI_lulu].tvValue) = VT_I2;
tv[TI_lulu].tvState.tsTime = ft;
V_I2(&tv[TI_enum].tvValue) = (short)((ft.dwLowDateTime >> 22) % 7);
V_VT(&tv[TI_enum].tvValue) = VT_I2;
tv[TI_enum].tvState.tsTime = ft;
V_I1(&tv[TI_bandwidth].tvValue) = (char)loGetBandwidth(my_service, 0);
V_VT(&tv[TI_bandwidth].tvValue) = VT_I1;
tv[TI_bandwidth].tvState.tsTime = ft;
/** OPTIONAL: enumerate all possible qualities: */
static const unsigned char legalq[] = {
OPC_QUALITY_CONFIG_ERROR , OPC_QUALITY_NOT_CONNECTED ,
OPC_QUALITY_DEVICE_FAILURE , OPC_QUALITY_SENSOR_FAILURE ,
OPC_QUALITY_LAST_KNOWN , OPC_QUALITY_COMM_FAILURE ,
OPC_QUALITY_OUT_OF_SERVICE ,
// STATUS_MASK Values for Quality = UNCERTAIN
OPC_QUALITY_LAST_USABLE , OPC_QUALITY_SENSOR_CAL ,
OPC_QUALITY_EGU_EXCEEDED , OPC_QUALITY_SUB_NORMAL ,
// STATUS_MASK Values for Quality = GOOD
OPC_QUALITY_LOCAL_OVERRIDE };
tv[TI_quality].tvState.tsTime = ft;
tv[TI_quality].tvState.tsQuality =
legalq[((unsigned)ft.dwLowDateTime >> 24) % SIZEOF_ARRAY(legalq)];
/** OPTIONAL: change the STRING variable: */
WCHAR wstr[32];
local_text(wstr, (ft.dwLowDateTime >> 24) % 7, 0);
VariantClear(&tv[TI_string].tvValue); /* don't miss it!
BSTR is not a simple type */
V_BSTR(&tv[TI_string].tvValue) = SysAllocString(wstr);
V_VT(&tv[TI_string].tvValue) = VT_BSTR;
tv[TI_string].tvState.tsTime = ft;
/** OPTIONAL: change the ARRAY variable: */
if (ti[TI_array]) /* has been successfuly initialized? */
{
long ix0 = 1, val = (long)zuzu;
SafeArrayPutElement(V_ARRAY(&tv[TI_array].tvValue), &ix0, &val);
tv[TI_array].tvTi = ti[TI_array];
tv[TI_array].tvState.tsTime = ft;
}
/** MANDATORY: send all the values into the cache: */
loCacheUpdate(my_service, TI_MAX, tv + 1, 0);
LeaveCriticalSection(&lk_values);
if (pause)
{
/* IMPORTANT: force unloading of an out-of-proc
if not connected during PAUSE millisec */
unsigned tnow = GetTickCount();
if (tnow - starttime >= pause)
{
pause = 0;
my_CF.serverRemove();
}
}
if (test_mode)
{
/* OPTIONAL: simulate client's connections to test loSetState
and track down resource leakage */
static int xx;
static IUnknown *cli;
unsigned tnow = GetTickCount();
if (tnow - starttime >= 2500)
{
starttime = tnow;
/* To test for unreleased handles / threads
run taskmgr and see what's happen...*/
if (cli)
{
cli->Release(); cli = 0;
if (5 < ++xx)
{
puts("SHUTDOWN initiated...");
loSetState(my_service, 0, loOP_SHUTDOWN,
OPC_STATUS_SUSPENDED, "forced shutdown");
my_CF.serverRemove();
test_mode = 2;
}
}
else if (test_mode == 1)
{
my_CF.CreateInstance(0, IID_IUnknown, (void **)&cli);
}
else
{
puts("DISCONNECT initiated...");
loSetState(my_service, 0, loOP_STOP | loOP_DISCONNECT,
OPC_STATUS_SUSPENDED, "forced shutdown");
}
}
} /* end of if (test_mode... */
} /* end of loop */
if (0 == my_CF.is_out_of_proc) /* For in-proc servers only! */
{
EnterCriticalSection(&my_CF.lk_count);
driver_destroy();
LeaveCriticalSection(&my_CF.lk_count);
}
UL_MESSAGE((LOGID, "All clean. exiting..."));
}
/***************************************************************************
EXE-specefic stuff
***************************************************************************/
const char eClsidName[] = "LightOPC Sample server (exe)";
const char eProgID[] = "OPC.LightOPC-exe";
HMODULE server_module = 0;
static int mymine(HINSTANCE hInstance, int argc, char *argv[]);
extern "C"
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
static char *argv[3] = { "fake.exe", NULL, NULL };
argv[1] = lpCmdLine;
return mymine(hInstance, 2, argv);
}
extern "C" int main(int argc, char *argv[])
{
return mymine(GetModuleHandle(NULL), argc, argv);
}
int mymine(HINSTANCE hInstance, int argc, char *argv[])
{
int main_rc = 0;
DWORD objid;
int daemon = 0, pause = 20;
const char *exit_msg = "Exiting...";
server_module = hInstance;
log = unilog_Create("LOPC-exe", "|LOPC-exe", "%!T", -1, /* Max filesize: -1 unlimited, -2 -don't change */
ll_MESSAGE); /* level [ll_FATAL...ll_DEBUG] */
unilog_Redirect("LOPC-exe", "LightOPC", 0);
unilog_Delete(log);
log = unilog_Create("Lopc-Sample-exe", "|Lopc-Sample-exe", "", -1, /* Max filesize: -1 unlimited, -2 -don't change */
ll_TRACE); /* level [ll_FATAL...ll_DEBUG] */
UL_DEBUG((LOGID, "WinMain(%s) invoked...", argv[0]));
if (argv[1])
{
printf("%s\nClass %s : ", argv[0], eProgID);
if (strstr(argv[1], "/r"))
{
char np[FILENAME_MAX + 32];
printf("Registering");
GetModuleFileName(NULL, np + 1, sizeof(np) - 8);
np[0] = '"'; strcat(np, "\"");
if (strstr(argv[1], "/r")[2] == 'c') strcat(np, " /c");
if (loServerRegister(&CLSID_LightOPCServerEXE,
eProgID, eClsidName, np, 0))
{
UL_ERROR((LOGID, "%!L Reg <%s> <%s> Failed", eProgID, argv[0]));
puts(" FAILED");
main_rc = 1;
}
else
{
UL_INFO((LOGID, "Reg <%s> <%s> Ok", eProgID, argv[0]));
puts(" Succeeded");
}
goto Finish;
}
else if (strstr(argv[1], "/u"))
{
printf("UnRegistering");
if (loServerUnregister(&CLSID_LightOPCServerEXE, eProgID))
{
UL_WARNING((LOGID, "%!L UnReg <%s> <%s> Failed", eProgID, argv[0]));
puts(" FAILED");
main_rc = 1;
}
else
{
UL_DEBUG((LOGID, "UnReg <%s> <%s> Ok", eProgID, argv[0]));
puts(" Success");
}
goto Finish;
}
else if (strstr(argv[1], "/c") || strstr(argv[1], "/C"))
{
UL_MESSAGE((LOGID, "Creating new console..."));
use_console = 1;
AllocConsole();
goto Cont;
}
else if (strstr(argv[1], "/daemon"))
{
UL_MESSAGE((LOGID, "Running as DAEMON"));
puts("Running as DAEMON...");
daemon = 1; use_console = 1;
goto Cont;
}
else if (strstr(argv[1], "/detach"))
{
UL_MESSAGE((LOGID, "Running as Detached DAEMON"));
puts("Running as Detached DAEMON...");
daemon = 2;
goto Cont;
}
else if (strstr(argv[1], "/test"))
{
UL_MESSAGE((LOGID, "Running in TEST mode"));
puts("Running in TEST mode...");
daemon = 1; use_console = 1; test_mode = 1;
goto Cont;
}
else
{
UL_WARNING((LOGID, "unknown option <%s>", argv[1]));
printf("Unknown option <%s>", argv[1]);
puts("\nOne of following flags can be specified:"
"\n\t/r - register;"
"\n\t/u - unregister;"
"\n\t/rc - register to start with /c key;"
"\n\t/c - create console window;"
"\n\t/daemon - run in daemon mode;"
"\n\t/test - run in test mode for 25 seconds;"
"\n\t/detach - run in unbreakable daemon mode.");
goto Cont;
}
goto Finish;
}
Cont: /* Attempt to start the server */
if (1 != daemon && 0 == use_console)
FreeConsole();
my_CF.is_out_of_proc = my_CF.server_inuse = 1;
if (FAILED(CoInitializeEx(NULL, COINIT_MULTITHREADED)))
{
exit_msg = "CoInitializeEx() failed. Exiting...";
UL_ERROR((LOGID, exit_msg));
goto Finish;
}
pause = 20; /* 20 sec can be too short for remote connections */
if (use_console && !daemon)
printf("Waiting %d seconds for connection...\n", pause);
if (driver_init(0))
{
exit_msg = "driver_init() failed. Exiting...";
UL_ERROR((LOGID, exit_msg));
}
else if (FAILED(CoRegisterClassObject(CLSID_LightOPCServerEXE, &my_CF,
CLSCTX_LOCAL_SERVER |
CLSCTX_REMOTE_SERVER |
CLSCTX_INPROC_SERVER,
REGCLS_MULTIPLEUSE, &objid)))
{
exit_msg = "CoRegisterClassObject() failed. Exiting...";
UL_ERROR((LOGID, exit_msg));
}
else
{
if (daemon) pause = 0; // infinite
my_CF.serverAdd(); /* Oops. This will prewent our server from unloading
till PAUSE elapsed and simulate() do my_CF.serverRemove() */
/* STARTing the simulator */
simulate(pause * 1000); /* sec -> millisec; */
/* FINISHED */
if (FAILED(CoRevokeClassObject(objid)))
UL_WARNING((LOGID, "CoRevokeClassObject() failed..."));
}
driver_destroy();
CoUninitialize();
Finish:
if (use_console) puts(exit_msg);
UL_DEBUG((LOGID, "WinMain(%s) finished", argv[0]));
unilog_Delete(log);
log = 0;
return main_rc;
}
/***************************************************************************
DLL-specefic stuff
***************************************************************************/
static void dll_simulator_wait(void) /* in-proc specefic */
{
for(;;)
{
int finished;
EnterCriticalSection(&my_CF.lk_count);
finished = my_service == 0 || my_CF.server_inuse;
LeaveCriticalSection(&my_CF.lk_count);
if (finished) break;
else Sleep(500);
}
/* Looking for conditional variables?
See unilog/condsb.[hc] */
}
static void dll_simulator_start(void) /* in-proc specefic */
{
int rv;
EnterCriticalSection(&my_CF.lk_count);
if (!my_service)
{
if (rv = driver_init( /* inproc only options! */
#if 1
loDf_FREEMARSH | loDf_BOTHMODEL
#else
0
#endif
))
{
UL_ERROR((LOGID, "!%e driver_init FAILED:", rv));
}
else if (-1 == (int)_beginthread((void(*)(void *))simulate, 0, (void *)0))
{
UL_ERROR((LOGID, "!%E _beginthread() FAILED:"));
driver_destroy();
}
else my_CF.server_inuse = 1;
}
LeaveCriticalSection(&my_CF.lk_count);
}
extern "C"
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
server_module = hinstDLL;
log = unilog_Create("LOPC-dll", "|LOPC-dll", "%!T", -1, /* Max filesize: -1 unlimited, -2 -don't change */
ll_DEBUG); /* level [ll_FATAL...ll_DEBUG] */
unilog_Redirect("LOPC-dll", "LightOPC", 0);
unilog_Delete(log);
log = unilog_Create("Lopc-Sample-dll", "|Lopc-Sample-dll", "", -1, /* Max filesize: -1 unlimited, -2 -don't change */
ll_DEBUG); /* level [ll_FATAL...ll_DEBUG] */
UL_DEBUG((LOGID, "DllMAin(process_attach)"));
//driver_init(); /* not the best place */
}
else if (fdwReason == DLL_PROCESS_DETACH)
{
UL_DEBUG((LOGID, "DllMAin(process_detach)"));
unilog_Delete(log);
log = 0;
//driver_destroy(); /* not the best place */
}
return TRUE;
}
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
UL_DEBUG((LOGID, "DllGetClassObject() ..."));
if (rclsid == CLSID_LightOPCServerDLL || rclsid == CLSID_LightOPCServerEXE)
{
HRESULT hr = my_CF.QueryInterface(riid, ppv);
UL_DEBUG((LOGID, "%!l DllGetClassObject() >>%04X %s", hr, hr,
FAILED(hr) ? "failed" : "Ok"));
return hr;
}
UL_DEBUG((LOGID, "DllGetClassObject() >>CLASS_E_CLASSNOTAVAILABLE"));
return CLASS_E_CLASSNOTAVAILABLE;
}
STDAPI DllCanUnloadNow(void)
{
UL_DEBUG((LOGID, "DllCanUnloadNow() invoked servers=%d", my_CF.server_count));
my_CF.serverAdd();
my_CF.serverRemove(); /* Force stopping the simulator if not used */
/* the simulator can be restarted in ICF::CreateInstance() if requested */
if (0 == my_CF.server_inuse)
{
dll_simulator_wait();
if (0 == my_CF.server_inuse) return S_OK;
}
return S_FALSE;
}
/* standard OLE registration stuff */
const char dClsidName[] = "LightOPC Sample server (dll)";
const char dProgID[] = "OPC.LightOPC-dll";
STDAPI DllRegisterServer(void)
{
char sFile[FILENAME_MAX + 16];
GetModuleFileName(server_module, sFile, sizeof(sFile) - 1);
UL_DEBUG((LOGID, "DllRegister(%s)", sFile));
return loServerRegister(&CLSID_LightOPCServerDLL, dProgID, dClsidName, sFile,
"Both") ? SELFREG_E_CLASS: S_OK;
}
STDAPI DllUnregisterServer(void)
{
return loServerUnregister(&CLSID_LightOPCServerDLL, dProgID)? SELFREG_E_CLASS: S_OK;
}
/* OPTIONAL: **************** special helpers ******************************/
static void local_text(WCHAR buf[32], unsigned nn, LCID lcid)
{
char sbt[40];
long lcp = CP_ACP;
unsigned nx;
nn %= 7;
/* Nasty Win95 doesn't have proper unicode support.
So we getting singlebyte strings and then converting them to unicode.
But we've to know the right codepage first!
CP_ACP is our cp. An OPC client may choose other. */
if (0 == GetLocaleInfoA(lcid, LOCALE_IDEFAULTANSICODEPAGE, sbt, sizeof(sbt)-1))
goto Failure;
lcp = strtoul(sbt, 0, 10);
/* How does called "Monday"+nn in LCID country? */
if (0 == GetLocaleInfoA(lcid, LOCALE_SDAYNAME1 + nn, sbt, sizeof(sbt) - 1))
goto Failure;
nx = strlen(sbt);
if (sizeof(sbt) - nx > 12)
{
sbt[nx++] = ' '; /* Append language name [OPTIONAL] */
if (0 == GetLocaleInfoA(lcid, LOCALE_SENGLANGUAGE, sbt + nx,
sizeof(sbt) - nx - 1) &&
0 == GetLocaleInfoA(lcid, LOCALE_SENGCOUNTRY, sbt + nx,
sizeof(sbt) - nx - 1) )
sbt[--nx] = 0; /* ... or the country name */
}
if (0 == MultiByteToWideChar(lcp, 0, sbt, -1, buf, 32))
{
Failure:
swprintf(buf, L"%d [string]", nn);
}
// UL_DEBUG((LOGID, "locals lcid:%x cp:%d [%s] [%ls]%d",
//lcid, lcp, sbt, buf, wcslen(buf)));
}
/******************* This is the end... ************************************/
| [
"[email protected]"
] | [
[
[
1,
1345
]
]
] |
118881a4f017ea4ff90854ee6a7c86e24f38ab19 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/devicesrv/SysLibs/ecom/TestPlugin/Inc/TestEComResolver.h | bb6496a33d32bc262858c25fed592aec1cb67452 | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,522 | h | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#if (!defined __TEST_ECOM_RESOLVER_H__)
#define __TEST_ECOM_RESOLVER_H__
#include <ECom\Resolver.h>
#define CTestEComResolver_UID 0x20003725
/**
@internalComponent
@since 7.0
Controls the identification, (resolution), of which implementation
will be used to satisfy an interface implementation instantiation.
*/
class CTestEComResolver : public CResolver
{
public:
/**
@fn NewL(MPublicRegistry& aRegistry)
Intended Usage : Standardized safe construction which leaves nothing
on the cleanup stack.
Error Condition : Cannot fully construct because of memory limitations.
@leave KErrNoMemory
@since 7.0
@return A pointer to the new class
@post CTestEComResolver is fully constructed,
and initialized.
*/
static CTestEComResolver* NewL(MPublicRegistry& aRegistry);
/**
@fn ~CTestEComResolver()
Intended Usage : Standard default d'tor
Error Condition : None
@since 7.0
*/
~CTestEComResolver();
/**
@fn IdentifyImplementationL(TUid aInterfaceUid,
const TEComResolverParams& aAdditionalParameters) const
Intended Usage : Request that the resolver identify the most appropriate
interface implementation.
Error Condition :
@since 7.0
@param aInterfaceUid The interface for which implementations are requested
@param aAdditionalParameters Data to be used to refine the search further
@return The Uid of the best fit interface implementation - KNullUid if no match is found
@pre Object is fully constructed and initialized
@post Registry contents are not modified but registry keys may be updated
*/
TUid IdentifyImplementationL(TUid aInterfaceUid, const TEComResolverParams& aAdditionalParameters) const;
/**
@fn ListAllL(TUid aInterfaceUid, const TEComResolverParams& aAdditionalParameters) const
Intended Usage : List all the implementations which satisfy the specified interface.
Error Condition :
@since 7.0
@param aInterfaceUid The interface for which implementations are requested
@param aAdditionalParameters Data to be used to refine the search further
@return Pointer to an array of suitable implementations. Ownership of this array
is passed to the calling function.
@pre Object is fully constructed and initialized
@post Registry contents are not modified but registry keys may be updated
*/
RImplInfoArray* ListAllL(TUid aInterfaceUid, const TEComResolverParams& aAdditionalParameters) const;
private:
/**
@internalComponent
@fn CTestEComResolver(MPublicRegistry& aRegistry)
Intended Usage : Standardized default c'tor
Error Condition : None
@since 7.0
@post CTestEComResolver is fully constructed
*/
explicit CTestEComResolver(MPublicRegistry& aRegistry);
/**
@fn Match(const TDesC8& aImplementationType, const TDesC8& aMatchType, TBool aUseWildcards) const
Intended Usage : Searches for a match of a data type on an implementation type.
Match returns ETrue if aMatchType is found within aImplementationType according to
the following rules:
1) aImplementationType is treated as a series of descriptors separated by double
bars (||). ETrue is returned if aMatchType matches exactly any of the short
descriptors. If no double bar is present then aImplementationType is treated as a
single descriptor.
2) If aUseWildcards == ETrue then a '?' in aMatchType will be matched to any single
character and '*' will be matched to any series of characters.
@leave KErrNoMemory
@since 7.0
@param aImplementationType The implementation data type to search for a match
@param aMatchType The data to search for
@param aUseWildcards ETrue if wildcard matching should be allowed
@return ETrue if a match was found, EFalse otherwise
@pre This object is fully constructed
*/
TBool Match(const TDesC8& aImplementationType, const TDesC8& aMatchType, TBool aUseWildcards) const;
private:
mutable RImplInfoArray* iImplementationInfoArray;
};
#endif /* __TEST_ECOM_RESOLVER_H__ */
| [
"none@none"
] | [
[
[
1,
121
]
]
] |
f2d9ca7a4de9684de107234aa21a972e66475cce | 741b36f4ddf392c4459d777930bc55b966c2111a | /incubator/deeppurple/lwplugins/lwwrapper/Panel/ControlPercent.cpp | 8de9673b261bd6dfa8512b154d7c5c1f19d4cc17 | [] | no_license | BackupTheBerlios/lwpp-svn | d2e905641f60a7c9ca296d29169c70762f5a9281 | fd6f80cbba14209d4ca639f291b1a28a0ed5404d | refs/heads/master | 2021-01-17T17:01:31.802187 | 2005-10-16T22:12:52 | 2005-10-16T22:12:52 | 40,805,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,015 | cpp | // ControlPercent.cpp: implementation of the ControlPercent class.
//
//////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "ControlPercent.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
ControlPercent::ControlPercent() :
Min(0),
Max(100)
{
}
ControlPercent::~ControlPercent()
{
}
bool ControlPercent::RegisterWithPanel(LWPanelID pan)
{
LWPanControlDesc locDesc;
locDesc.type=LWT_RANGE;
locDesc.range.min=Min;
locDesc.range.max=Max;
this->ThisControl=Lightwave3D::panf->addControl(pan,"PercentControl",&locDesc,const_cast<char *>(Name.c_str()));
if (this->ThisControl)
return true;
else
return false;
}
void ControlPercent::Initialize(const char *name, Panel* SetOwner, int min, int max)
{
Min=min;
Max=max;
Control::Initialize(name,SetOwner);
} | [
"deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61"
] | [
[
[
1,
42
]
]
] |
6a22299e7c3a8a9225bea7c3b6879d165a4fd732 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/TransitionMgr.h | 93ccb14f04ab69959f0369e1189219e8b5d5a40e | [] | no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,622 | h | // ----------------------------------------------------------------------- //
//
// MODULE : TransitionMgr.h
//
// PURPOSE : The TransitionMgr object
//
// CREATED : 11/27/01
//
// (c) 2001 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#ifndef __TRANSITIONMGR_H__
#define __TRANSITIONMGR_H__
//
// Globals...
//
class CTransitionMgr;
extern CTransitionMgr *g_pTransMgr;
class CTransitionMgr
{
public : // Methods...
CTransitionMgr( );
~CTransitionMgr( );
void TransitionFromArea( HOBJECT hTransArea );
LTBOOL PreTransitionLoad( char const* pSaveLevelFile );
LTBOOL PostTransitionLoad( char const* pRestoreLevelFile );
HOBJECT GetTransitionArea( ) const { return m_hTransArea; }
protected : // Methods...
LTBOOL SaveTransitionObjects( );
LTBOOL LoadTransitionObjects( );
LTBOOL RemoveTransitionObjects( );
LTBOOL SaveNonTransitionObjects( char const* pSaveLevelFile );
LTBOOL LoadNonTransitionObjects( char const* pRestoreLevelFile );
private : // Members...
typedef ObjRefList TransitionObjectList;
TransitionObjectList m_TransitionObjectList;
char m_szTransAreaName[32]; // The name of the transition from/to areas need to be the same
LTVector m_vTransAreaDims; // The diminsions of the transition from/to areas need to be the same
LTObjRef m_hTransArea; // The objcet we are transitioning from/to
private : // Methods...
LTBOOL IsTransitionObject( HOBJECT hObj );
};
#endif // __TRANSITIONMGR_H__ | [
"[email protected]"
] | [
[
[
1,
67
]
]
] |
e1a4bfb4a063e2eb6067803ae882f0e856fc6784 | d826e0dcc5b51f57101f2579d65ce8e010f084ec | /transcad/PmeStdSolidChamferFeatureAPI.h | 0666e77dad9c8e37f3bf02b30aad72b03c35ebe6 | [] | no_license | crazyhedgehog/macro-parametric | 308d9253b96978537a26ade55c9c235e0442d2c4 | 9c98d25e148f894b45f69094a4031b8ad938bcc9 | refs/heads/master | 2020-05-18T06:01:30.426388 | 2009-06-26T15:00:02 | 2009-06-26T15:00:02 | 38,305,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | h | #pragma once
#include ".\PmeMacro.h"
#include ".\PmeHandle.h"
#include ".\PmeChamferType.h"
class PME_API PmeStdSolidChamferFeatureAPI
{
public:
static void Create
(
PmeHPart hPart,
const CString & name,
PmeChamferType chamferType,
PmeHReference hSelectedEdge,
PmeHReference hSelectedFace,
double length,
double value,
PmeHFeature & hFeature
);
static void Create
(
PmeHPart hPart,
const CString & name,
PmeHReference hSelectedEdge,
double length,
PmeHFeature & hFeature
);
static void GetChamferType(PmeHFeature hFeature, PmeChamferType & chamferType);
static void GetSelectedEdge(PmeHFeature hFeature, PmeHReference & hSelectedEdge);
static void GetSelectedFace(PmeHFeature hFeature, PmeHReference & hSelectedFace);
static void GetLength(PmeHFeature hFeature, double & length);
static void GetValue(PmeHFeature hFeature, double & value);
static void GetStartPoint(PmeHFeature hFeature, SPAposition & position);
static void GetEndPoint(PmeHFeature hFeature, SPAposition & position);
}; | [
"surplusz@2d8c97fe-2f4b-11de-8e0c-53a27eea117e"
] | [
[
[
1,
40
]
]
] |
70920ba15985c583eeda75d238a3edbf9105fe2b | ad0076b418469ad3433daa809acba5fd2a9410e9 | /program.cpp | ff8ad28a3e726415ba3c6227a7fbbb162ffd6b52 | [] | no_license | PlumpMath/ergo | e3e8a4c43a81cb48671a13d6c7124e019b855fb7 | dc2e9a96d23b46120af94aeedcbe81e8d602c640 | refs/heads/master | 2021-01-18T20:06:09.564888 | 2008-11-03T09:09:15 | 2008-11-03T09:09:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 972 | cpp | #include "simulator.h"
#include <iostream>
using namespace std;
#define GAMES 10000
void simulate_set(int num_games);
string weights;
int main()
{
weights = "";
simulate_set(100000);
getchar();
}
void simulate_set(int num_games)
{
long start = clock();
int games[2];
games[0] = games[1] = 0;
unsigned long num_moves = 0;
Simulator simulator("", weights);
for (int i = 0; i < num_games; i++)
{
Color winner = simulator.play_game();
games[winner]++;
num_moves += simulator.num_moves();
}
weights = simulator.encode_weights();
long end = clock();
cout << "Number of games: " << num_games << endl;
cout << num_games/((float)(end-start)/CLOCKS_PER_SEC) << " games per second" << endl;
cout << "White: " << games[White]*100.0/num_games << "% Black: " << games[Black]*100.0/num_games << "%" << endl;
cout << "Average moves per game: " << num_moves/num_games << endl;
cout << endl;
}
| [
"[email protected]"
] | [
[
[
1,
49
]
]
] |
2b018cb6b8a1af91341f5bd27819921494b5fbee | c2d3b2484afb98a6447dfacfe733b98e8778e0a9 | /src/Images/SEImage.h | f575867a8a486e8b3e8ee6d2c05dbde8725c4023 | [] | no_license | soniccat/3dEngine | cfb73af5c9b25d61dd77e882a31f4a62fbd3f036 | abf1d49a1756fb0217862f829b1ec7877a59eaf4 | refs/heads/master | 2020-05-15T07:07:22.751350 | 2010-03-27T13:05:38 | 2010-03-27T13:05:38 | 469,267 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 747 | h |
#ifndef SEImage_H
#define SEImage_H
#include "SEIncludeLibrary.h"
#include "SEDefinition.h"
#include "SEIncludeOpenGL.h"
typedef shared_array<unsigned char> SEImageDataPtr;
//store original image data
class SEImage
{
protected:
uint mWidth;
uint mHeight;
GLenum mPixelFormat;
GLenum mPixelDataType;
SEImageDataPtr mData;
public:
SEImage(void);
SEImage( uint width, uint height, SEImageDataPtr data );
~SEImage(void);
void Init( uint width, uint height, SEImageDataPtr data );
void FreeData();
GLenum pixelFormat() const;
GLenum pixelDataType() const;
uint height() const;
uint width() const;
SEImageDataPtr data() const;
};
typedef shared_ptr<SEImage> SEImagePtr;
#endif SEImage_H | [
"[email protected]",
"ALEX@.(none)"
] | [
[
[
1,
40
]
],
[
[
41,
41
]
]
] |
23dafbcfe337ebbdd901ac27824a6755b2c1cb87 | 9ad9345e116ead00be7b3bd147a0f43144a2e402 | /SeedMinerIntegratedSolution/Include/connect.h | 9a6207111abcefeed9771dce124bfdcfa24d8a1e | [] | no_license | asankaf/scalable-data-mining-framework | e46999670a2317ee8d7814a4bd21f62d8f9f5c8f | 811fddd97f52a203fdacd14c5753c3923d3a6498 | refs/heads/master | 2020-04-02T08:14:39.589079 | 2010-07-18T16:44:56 | 2010-07-18T16:44:56 | 33,870,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,336 | h | //-[stdhead]-------------------------------------------------------
//Project:
//File :connect.h
//Started:17.09.02 13:52:55
//Updated:20.09.02 15:36:28
//Author :GehtSoft
//Subj :
//Version:
//Require:
//-----------------------------------------------------------------
class gsodbcexp CGOdbcConnect
{
friend class CGOdbcStmt;
public:
//constructor
CGOdbcConnect();
//destructor
~CGOdbcConnect();
//establish connect by DSN name, user identifier and password
void connect(const char *szDSN, const char *szUID, const char *szPWD);
//establish connect by connection string
void connect(const char *szString, HWND hWnd = 0);
//get connection handle
HDBC getConnect();
//set shared connection handle
void setConnect(HDBC);
CGOdbcStmt *createStatement();
void freeStatement(CGOdbcStmt *);
//execute and bind select query
CGOdbcStmt *executeSelect(const char *);
//execute query and returns number of affected rows
int executeUpdate(const char *);
//select list of datatypes
CGOdbcStmt *getListOfTypes();
//select list of tables
CGOdbcStmt *getListOfTables(const char *szTableMask = 0);
//select list of tables
CGOdbcStmt *getListOfColumns(const char *szTableMask = 0);
//set transaction processing mode
void setTransMode(bool bAutoCommit);
//commit transaction
void commit();
//rollback transaction
void rollback();
//information about DSN
bool firstDSN(char *pszDSN, int lMax);
bool nextDSN(char *pszDSN, int lMax);
//returns last error during connection
const char *getError();
//return name of the driver
const char *getDriver();
//close connection
void close();
protected:
void _throwError(); //get error description
void _getDriver(); //get database driver name
HENV m_hEnv; //database environment
HDBC m_hConn; //database connection
bool m_bShared; //connection is shared
//
_bstr_t m_sError; //error text
_bstr_t m_sDriver; //driver name
}; //
| [
"buddhi.1986@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
] | [
[
[
1,
74
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.