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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
db5130532630953f6a2877b86dc99440e939b492 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Graphics/WS/BackedUp/AppHolder.cpp | dc9af638a62042e74c6524788610528e31b25dd7 | [] | no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,933 | cpp | // AppHolder.cpp
//
// Copyright (c) 2005 Symbian Softwares Ltd. All rights reserved.
//
#include "AppHolder.h"
#include "BackedUp.h"
#include <EikStart.h>
//
// EXPORTed functions
//
EXPORT_C CApaApplication* NewApplication()
{
return new CAppholderApplication;
}
// updated for 9.1. not conditional as not expected to be used pre 9.1.
GLDEF_C TInt E32Main()
{
return EikStart::RunApplication(NewApplication);
}
////////////////////////////////////////////////////////////////
//
// Application class, CAppholderApplication
//
////////////////////////////////////////////////////////////////
TUid CAppholderApplication::AppDllUid() const
{
return KUidAppholder;
}
CApaDocument* CAppholderApplication::CreateDocumentL()
{
// Construct the document using its NewL() function, rather
// than using new(ELeave), because it requires two-phase
// construction.
return new (ELeave) CAppholderDocument(*this);
}
////////////////////////////////////////////////////////////////
//
// Document class, CAppholderDocument
//
////////////////////////////////////////////////////////////////
// C++ constructor
CAppholderDocument::CAppholderDocument(CEikApplication& aApp)
: CEikDocument(aApp)
{
}
CEikAppUi* CAppholderDocument::CreateAppUiL()
{
return new(ELeave) CAppholderAppUi;
}
CAppholderDocument::~CAppholderDocument()
{
}
////////////////////////////////////////////////////////////////
//
// App UI class, CAppholderAppUi
//
////////////////////////////////////////////////////////////////
void CAppholderAppUi::ConstructL()
{
BaseConstructL();
iClient=CExampleWsClient::NewL(ClientRect());
}
CAppholderAppUi::~CAppholderAppUi()
{
delete iClient;
}
void CAppholderAppUi::HandleCommandL(TInt aCommand)
{
switch (aCommand)
{
case EEikCmdExit:
Exit();
break;
}
}
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
94
]
]
] |
b10485a01ebb0d4c22042359885fcde169fc7fb5 | c0bd82eb640d8594f2d2b76262566288676b8395 | /src/shared/NetworkBase/BaseSocket.cpp | 4644158d3f4d9a1ba908235324187d1d800bead8 | [
"FSFUL"
] | permissive | vata/solution | 4c6551b9253d8f23ad5e72f4a96fc80e55e583c9 | 774fca057d12a906128f9231831ae2e10a947da6 | refs/heads/master | 2021-01-10T02:08:50.032837 | 2007-11-13T22:01:17 | 2007-11-13T22:01:17 | 45,352,930 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,397 | cpp | /************************************************************************/
/* Copyright (C) 2006 Burlex */
/************************************************************************/
/* * Class BaseSocket
* All listening sockets or client sockets in the server will be based off this class.
* Basically acts as a wrapper to keep code constant, easier to maintain, and simply
* looks cleaner. :)
*/
#include "BaseSocket.h"
#include "SocketHolder.h"
BaseSocket::BaseSocket(SocketHolder &SocketHolder, u32 RecvBufferSize, u32 SendBufferSize, u32 BufferSize) : _socketHolder(SocketHolder)
{
// Nullify Pointers
ReceiveBuffer = SendBuffer = INVALID_PTR;
RecvSize = SendSize = 0;
// Allocate Buffers
if(RecvBufferSize > 0) {
ASSERT(ReceiveBuffer = new u8[RecvBufferSize]);
}
if(SendBufferSize > 0) {
ASSERT(SendBuffer = new u8[SendBufferSize]);
}
SocketBufferSize = BufferSize;
Connected = FALSE;
State = TRUE;
Socket = INVALID_SOCKET;
sendBufferSize = SendBufferSize;
receiveBufferSize = RecvBufferSize;
#ifdef ASYNC_NET
_cp = 0;
_writeLock = 0;
_deleted = 0;
#endif
}
BaseSocket::~BaseSocket()
{
// Deallocate Pointers
if(ReceiveBuffer != INVALID_PTR)
delete [] ReceiveBuffer;
if(SendBuffer != INVALID_PTR)
delete [] SendBuffer;
#ifndef ASYNC_NET
_socketHolder.RemoveSocket(this);
#else
_deleted = 1;
#endif
}
// Checks if the connection to the opposite peer is still active
BOOL BaseSocket::CheckConnection()
{
if( Socket == INVALID_SOCKET )
return FALSE;
char CheckBuffer[1];
int FirstTest = recv(Socket, CheckBuffer, 1, MSG_PEEK);
if(FirstTest == 0)
return FALSE;
if(FirstTest == -1)
{
int LastError = GetLastSocketError;
switch(LastError)
{
case WSAECONNRESET:
case WSAENOTCONN:
case WSAENETRESET:
case WSAENOTSOCK:
case WSAESHUTDOWN:
case WSAEINVAL:
case WSAECONNABORTED:
return FALSE;
break;
}
}
return TRUE;
}
// Copies a just-accepted socket into this class, and adds us to our socket holder.
BOOL BaseSocket::Create(SOCKET Socket_, sockaddr_in *ClientAddress)
{
ASSERT(Socket_ != INVALID_SOCKET);
// Copy client's address into our local variable.
memcpy(&ConnectedPeer, ClientAddress, sizeof(*ClientAddress));
// Set our socket
Socket = Socket_;
Connected = TRUE;
SetOptions();
return TRUE;
}
// Sets options on socket.
BOOL BaseSocket::SetOptions()
{
// Set the appropriate buffers on our socket.
int OptionReturn = setsockopt(Socket, SOL_SOCKET, SO_SNDBUF, (const char*)&SocketBufferSize, 4);
if(OptionReturn == 0) setsockopt(Socket, SOL_SOCKET, SO_RCVBUF, (const char*)&SocketBufferSize, 4);
u32 Val = 0x1;
// Turn off internal buffering algorithms.
if(OptionReturn == 0) OptionReturn = setsockopt(Socket, 0x6, TCP_NODELAY, (const char*)&Val, 4);
#ifndef ASYNC_NET
// Set non blocking mode on the socket.
if(OptionReturn == 0) OptionReturn = ioctlsocket(Socket, FIONBIO, &Val);
#endif
if(OptionReturn != 0)
{
printf("[BaseSocket] One or more errors occured while attempting to configure options on socket %u.\n", Socket);
return FALSE;
}
#ifndef ASYNC_NET
// Call virtual onconnect before adding to socket holder, in case we're destroyed by another thread :p
OnConnect();
_socketHolder.AddSocket(this);
#endif
return TRUE;
}
BOOL BaseSocket::Connect(const char* RemoteAddress, u16 Port)
{
// WSAStartup SHOULD already be called!
struct hostent* ClientInfo = gethostbyname(RemoteAddress);
if(!ClientInfo)
{
throw "Could not resolve client address.";
return FALSE;
}
#ifdef WIN32
Socket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
#else
Socket = socket(AF_INET, SOCK_STREAM, 0);
#endif
if(Socket == INVALID_SOCKET)
{
throw "Socket could not be created.";
return FALSE;
}
struct sockaddr_in ClientAddress;
ClientAddress.sin_family = ClientInfo->h_addrtype;
memcpy(&ClientAddress.sin_addr.s_addr, ClientInfo->h_addr_list[0], ClientInfo->h_length);
ClientAddress.sin_port = ntohs(Port);
// Turn on blocking
u32 block = 0;
int ret = ioctlsocket(Socket, FIONBIO, &block);
// Attempt to connect.
int Valid = connect(Socket, (const sockaddr*)&ClientAddress, sizeof(ClientAddress));
memcpy(&ConnectedPeer, &ClientAddress, sizeof(ClientAddress));
if(Valid == -1)
{
int err = WSAGetLastError();
throw "Connection failed to remote host.";
Close();
return FALSE;
}
Connected = TRUE;
SetOptions();
#ifdef ASYNC_NET
if (_cp)
{
if (CreateIoCompletionPort((HANDLE)Socket, _cp, (DWORD)this, 0) == NULL)
{
printf("Could not assign socket to completion port\n");
Close();
return FALSE;
}
PostCompletion(IOAccept);
}
#else
OnConnect();
#endif
return TRUE;
}
void BaseSocket::Close()
{
if(CheckConnection())
{
// Disconnect socket.
shutdown(Socket, SD_BOTH);
}
closesocket(Socket);
Socket = -1;
}
void BaseSocket::Delete()
{
if(!DeleteMutex.AttemptAcquire())
return;
if(Socket != INVALID_SOCKET)
{
Close();
}
// Suicide xD
delete this;
}
bool BaseSocket::UpdateRead()
{
// First we will handle receiving.
#ifndef ASYNC_NET
State = CheckConnection();
if(Socket == INVALID_SOCKET || !Connected || !State)
{
Delete();
return false;
}
u32 ReadLength = 0;
bool ret = ioctlsocket(Socket, FIONREAD, &ReadLength);
if(ret)
ReadLength = 0;
if(ReadLength)
{
if(RecvSize + ReadLength > receiveBufferSize)
{
Disconnect();
return false;
}
#endif
// Woohoo! We got data!
RecvMutex.Acquire();
#ifndef ASYNC_NET
int RLength = recv(Socket, (char*)ReceiveBuffer + RecvSize, ReadLength, 0);
if(RLength == SOCKET_ERROR)
{
RecvMutex.Release();
Disconnect();
return false;
}
RecvSize += RLength;
OnReceive(RLength);
#else
uint32 RLength = 0;
uint32 flags = 0;
//flags = MSG_PARTIAL; // Not too sure about that one...should try it out
WSABUF buf;
buf.len = this->receiveBufferSize - RecvSize;
buf.buf = (char *)(ReceiveBuffer + RecvSize);
OverLapped *ol = new OverLapped(IOReadCompleted);
memset(ol, 0, sizeof(OVERLAPPED));
int r = WSARecv(Socket, &buf, 1, &RLength, &flags, &ol->m_ol, NULL);
if(r == SOCKET_ERROR)
{
int err = WSAGetLastError();
if (err != WSA_IO_PENDING)
{
RecvMutex.Release();
Disconnect();
PostCompletion(IOShutdownRequest);
return false;
}
}
#endif
RecvMutex.Release();
#ifndef ASYNC_NET
}
#endif
return true;
}
bool BaseSocket::UpdateWrite()
{
// First we will handle receiving.
#ifndef ASYNC_NET
State = CheckConnection();
if(!State || Socket == INVALID_SOCKET || !Connected)
{
Delete();
return false;
}
#endif
if(SendSize)
{
// We got outgoing data pending.
SendMutex.Acquire();
#ifndef ASYNC_NET
// Attempt to push all of our stored data outwards.
int WriteLength = send(Socket, (const char*)SendBuffer, SendSize, 0);
if(WriteLength > 0)
EraseSendBytes(WriteLength);
#else
uint32 WLength = 0;
uint32 flags = 0;
//flags = MSG_PARTIAL; // Not too sure about that one...should try it out
WSABUF buf;
buf.len = SendSize;
buf.buf = (char *)SendBuffer;
OverLapped *ol = new OverLapped(IOWriteCompleted);
memset(ol, 0, sizeof(OVERLAPPED));
int r = WSASend(Socket, &buf, 1, &WLength, flags, &ol->m_ol, NULL);
if(r == SOCKET_ERROR)
{
int err = WSAGetLastError();
if (err != WSA_IO_PENDING)
{
SendMutex.Release();
DecWriteLock();
Disconnect();
PostCompletion(IOShutdownRequest);
return false;
}
}
#endif
SendMutex.Release();
}
#ifdef ASYNC_NET
else
{
PostCompletion(IOWriteCompleted);
}
#endif
return true;
}
void BaseSocket::EraseReceiveBytes(u32 Size)
{
ASSERT(RecvSize >= Size);
RecvSize -= Size;
ASSERT(RecvSize + Size <= receiveBufferSize);
if(RecvSize > 0)
memmove(ReceiveBuffer, ReceiveBuffer + Size, RecvSize);
}
void BaseSocket::EraseSendBytes(u32 Size)
{
ASSERT(SendSize >= Size);
#ifdef ASYNC_NET
SendMutex.Acquire();
#endif
SendSize -= Size;
ASSERT(SendSize + Size <= sendBufferSize);
if(SendSize > 0)
memmove(SendBuffer, SendBuffer + Size, SendSize);
#ifdef ASYNC_NET
SendMutex.Release();
#endif
}
BOOL BaseSocket::SendArray(const u8* DataArray, const u16 Size, BOOL ManualLock)
{
#ifdef ASYNC_NET
if(_deleted) return FALSE;
#endif
if(ManualLock == FALSE)
SendMutex.Acquire();
ASSERT(SendSize < sendBufferSize);
ASSERT(Size + SendSize <= sendBufferSize);
memcpy(&SendBuffer[SendSize], DataArray, Size);
SendSize += Size;
if(ManualLock == FALSE)
SendMutex.Release();
#ifdef ASYNC_NET
if (!_writeLock)
{
IncWriteLock();
PostCompletion(IOWriteRequest);
}
#endif
return TRUE;
}
const char* BaseSocket::RetreiveClientIP()
{
return (const char*)inet_ntoa(ConnectedPeer.sin_addr);
}
u16 BaseSocket::RetreiveClientPort()
{
return SwapBytes(ConnectedPeer.sin_port);
}
void BaseSocket::OnDisconnect()
{
}
#ifdef ASYNC_NET
bool BaseSocket::PostCompletion(IOType type)
{
if (_deleted != 0)
return false;
_postMutex.Acquire();
if (type == IOShutdownRequest)
{
_deleted = 1;
OnDisconnect();
}
OverLapped *ol = new OverLapped(type);
memset(ol, 0, sizeof(OVERLAPPED));
if (!PostQueuedCompletionStatus(_cp, 0, (DWORD)this, &ol->m_ol))
{
_postMutex.Release();
delete ol;
return false;
}
else
{
_postMutex.Release();
return true;
}
}
void BaseSocket::PostDeletionCompletion()
{
// Cancel any pending I/O operations.
CancelIo((HANDLE)Socket);
// Push for deletion in 10 seconds.
sDeadSocketCollector.QueueSocketDeletion(this);
}
#endif
| [
"[email protected]"
] | [
[
[
1,
488
]
]
] |
49dff2b0f5cfd5e8fc7a10b0f4a914051a4f59aa | 668dc83d4bc041d522e35b0c783c3e073fcc0bd2 | /fbide-wx/sdk/include/sdk/TypeManager.h | 89df33e98e1168aa23e4a10fbe9f7a522382b8df | [] | no_license | albeva/fbide-old-svn | 4add934982ce1ce95960c9b3859aeaf22477f10b | bde1e72e7e182fabc89452738f7655e3307296f4 | refs/heads/master | 2021-01-13T10:22:25.921182 | 2009-11-19T16:50:48 | 2009-11-19T16:50:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,729 | h | /*
* This file is part of FBIde project
*
* FBIde is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FBIde is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Albert Varaksin <[email protected]>
* Copyright (C) The FBIde development team
*/
#ifndef TYPEMANAGER_H_INCLUDED
#define TYPEMANAGER_H_INCLUDED
namespace fb
{
/**
* Forward declarations...
*/
class CDocumentBase;
class CManager;
class CTypeManager;
/**
* Base class for type registrants
*/
class DLLIMPORT CTypeRegistrantBase
{
public:
virtual CDocumentBase * Create (const wxString & file = _T("")) = 0;
};
/**
* Template class for registering new document types
* siply use :
* new CTypeRegistrant<classNme>;
*/
template<class T> class CTypeRegistrant : public CTypeRegistrantBase
{
public : virtual CDocumentBase * Create (const wxString & file = _T("")) { return new T(file); }
};
/**
* Manager document types. register new types by name
* then associate file extensions and also generate
* file filter list for open / save dialogs
*
* later this class could also handle registering
* (optionally) said file types with the OS to be
* loaded by FBIde
*/
class DLLIMPORT CTypeManager
{
public :
void AddType (const wxString & name, const wxString & desc, CTypeRegistrantBase * type);
void BindExtensions (const wxString & type, const wxString & types);
void BindAlias (const wxString & alias, const wxString & type);
CDocumentBase * LoadFile (const wxString & file);
CDocumentBase * NewDocument (const wxString & type);
bool TypeExists (const wxString & type);
wxString GetFileFilters (bool allFiles = false);
private :
friend class CManager;
CTypeManager ();
~CTypeManager ();
// private data implementation
struct CData;
std::auto_ptr<CData> m_data;
};
}
#endif // TYPEMANAGER_H_INCLUDED
| [
"vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7"
] | [
[
[
1,
92
]
]
] |
08259715d1902c082a4e608e50a14de2a769d970 | a29ec259efa2c2f13e24be86a4c6ba174780857d | /include/ZakEngine/TextureManager.h | a2615af261b0b346e8bec389458989ba147ed98c | [] | no_license | nlelouche/programacion2 | 639ffb55d06af4f696031ec777bec898b6224774 | 5ec9b29014c13786230e834deb44679b110351b4 | refs/heads/master | 2016-09-06T15:40:38.888016 | 2007-11-09T01:03:51 | 2007-11-09T01:03:51 | 32,653,635 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | h | #ifndef _TextureManager_H_
#define _TextureManager_H_
#include "EntityList.h"
#include "Texture.h"
namespace zak {
class ZAKENGINE_API TextureManager {
private:
EntityList Map;
public:
Texture * Load(const char *szFilename, unsigned int uiColorKey, bool persist);
void Remove(const char *szFilename);
void Remove(Texture *pTexture);
void Clear();
int GetCount();
bool Reload();
TextureManager(int iSize);
~TextureManager();
};
extern ZAKENGINE_API TextureManager g_textureManager;
}
#endif // _TextureManager_H_ | [
"yoviacthulhu@70076bbf-733e-0410-a12a-85c366f55b74"
] | [
[
[
1,
29
]
]
] |
88d48e6107ecd094aa6651a6e1aa2407407a2419 | 989aa92c9dab9a90373c8f28aa996c7714a758eb | /HydraIRC/TextInputView.cpp | ed102f9ff630438ba8522a9b8f2e8661222113d1 | [] | no_license | john-peterson/hydrairc | 5139ce002e2537d4bd8fbdcebfec6853168f23bc | f04b7f4abf0de0d2536aef93bd32bea5c4764445 | refs/heads/master | 2021-01-16T20:14:03.793977 | 2010-04-03T02:10:39 | 2010-04-03T02:10:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,447 | cpp | /*
HydraIRC
Copyright (C) 2002-2006 Dominic Clifton aka Hydra
HydraIRC limited-use source license
1) You can:
1.1) Use the source to create improvements and bug-fixes to send to the
author to be incorporated in the main program.
1.2) Use it for review/educational purposes.
2) You can NOT:
2.1) Use the source to create derivative works. (That is, you can't release
your own version of HydraIRC with your changes in it)
2.2) Compile your own version and sell it.
2.3) Distribute unmodified, modified source or compiled versions of HydraIRC
without first obtaining permission from the author. (I want one place
for people to come to get HydraIRC from)
2.4) Use any of the code or other part of HydraIRC in anything other than
HydraIRC.
3) All code submitted to the project:
3.1) Must not be covered by any license that conflicts with this license
(e.g. GPL code)
3.2) Will become the property of the author.
*/
// TextInputView.cpp
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "HydraIRC.h"
BOOL CTextInputView::PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
LRESULT CTextInputView::OnChar(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
// Filter out some keyboard input
switch(wParam)
{
case VK_TAB:
bHandled = TRUE;
break;
}
return 0;
}
enum VirtKeyFlags
{
VKF_Control = (1<<0),
VKF_Alt = (1<<1),
VKF_Shift = (1<<2),
};
LRESULT CTextInputView::OnKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
int virtkeys = (GetKeyState(VK_CONTROL) & 0x10000 ? VKF_Control : 0) +
(GetKeyState(VK_MENU) & 0x10000 ? VKF_Alt : 0) +
(GetKeyState(VK_SHIFT) & 0x10000 ? VKF_Shift : 0);
#ifdef VERBOSE_DEBUG
sys_Printf(BIC_GUI,"key down message: '%c' 0x%02x 0x%08x\n",wParam,wParam,virtkeys);
#endif
// handle keys regardless of modifers
switch(wParam)
{
case VK_PRIOR:
case VK_NEXT:
{
bHandled = TRUE;
CChildFrame *pChildWnd = CHILDFRAMEPTR(FindChildWindow(m_MessageWindow));
if (pChildWnd->m_WindowType == CWTYPE_SERVER ||
pChildWnd->m_WindowType == CWTYPE_CHANNEL ||
pChildWnd->m_WindowType == CWTYPE_DCCCHAT ||
pChildWnd->m_WindowType == CWTYPE_QUERY)
{
// referencing pChildWnd->m_MsgView would be bad if
// the m_MessageWindow didn't point to one of the above types of windows.
WPARAM MessageParam;
if (wParam == VK_PRIOR)
MessageParam = (virtkeys == VKF_Control) ? SB_TOP : SB_PAGEUP;
else
MessageParam = (virtkeys == VKF_Control) ? SB_BOTTOM : SB_PAGEDOWN;
pChildWnd->m_MsgView.SendMessage(WM_VSCROLL, MessageParam, NULL);
}
bHandled = TRUE;
}
break;
}
// handle keys when control is pressed
if (virtkeys == VKF_Control)
{
// add a control character depending on what keys were pressed.
bHandled = TRUE;
switch(wParam)
{
case 'B': // Bold
ReplaceSel("\002");
break;
case 'I': // Ctrl+I or Ctrl+N for italics, but stop the tab appearing..
//case 'N': // Italics // depreciated, ctrl+i only now..
ReplaceSel("\035");
break;
case 'U': // Underline
ReplaceSel("\037");
break;
case 'K': // Color
ReplaceSel("\003");
break;
case 'M': // Hi-Color
ReplaceSel("\004");
break;
case 'R': // Reverse
ReplaceSel("\026");
break;
case 'O': // Normal
ReplaceSel("\017");
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
int Bookmark = (wParam - '0');
IRCChannel *pChannel = FindIRCChannelByName(STRINGPREF( PREF_sChannelBookmark1 + (Bookmark - 1) ));
if( pChannel && pChannel->m_pChildWnd)
{
pChannel->m_pChildWnd->ActivateWindow();
//g_pMainWnd->MDIActivate(pChannel->m_pChildWnd->m_hWnd);
}
}
break;
case VK_RETURN: // send text AS-IS.
{
int len = GetWindowTextLength();
char *buffer = (char *)malloc(len + 1);
GetWindowText(buffer,len+1);
SetWindowText(NULL);
m_History.Add(buffer);
m_History.ResetHistoryItemPointer();
::SendMessage(m_MessageWindow,WM_TEXTINPUT,(WPARAM)OTIF_None,(LPARAM)buffer);
bHandled = TRUE;
}
break;
default:
bHandled = FALSE;
}
}
else // handle other keys
{
switch(wParam)
{
case VK_RETURN:
{
int len = GetWindowTextLength();
char *buffer = (char *)malloc(len + 1);
GetWindowText(buffer,len+1);
SetWindowText(NULL);
m_History.Add(buffer);
m_History.ResetHistoryItemPointer();
::SendMessage(m_MessageWindow,WM_TEXTINPUT,(WPARAM)OTIF_StripWhitespace | OTIF_Parse,(LPARAM)buffer); // Note the TRUE for WPARAM
bHandled = TRUE;
}
break;
case VK_UP: // next history item
{
bHandled = TRUE;
BOOL WasFirst = m_History.IsFirst();
char *tempbuffer = NULL;
int len = GetWindowTextLength();
// don't store an empty buffer.
// this means we can handle no text, then up, down, some text, up, down
if (len>0)
{
tempbuffer = (char *)malloc(len + 1);
if (tempbuffer)
{
GetWindowText(tempbuffer,len+1);
}
}
char *currenthistory = m_History.GetCurrentHistoryItem();
char *buffer = m_History.GetNextHistoryItem();
if (buffer)
{
SetWindowText(buffer);
}
else
{
// don't erase the buffer, leave it at the first one
g_pNotificationManager->PlaySoundID(SID_DEFAULT);
}
SetSel(-1,-1);
if (tempbuffer)
{
// add to history if different
if (WasFirst || (currenthistory && stricmp(currenthistory,tempbuffer) != 0))
{
m_History.Add(tempbuffer);
//m_History.Next();
}
free(tempbuffer);
}
}
break;
case VK_DOWN: // previous history item
{
bHandled = TRUE;
BOOL WasLast = m_History.IsLast();
BOOL WasFirst = m_History.IsFirst();
char *tempbuffer = NULL;
int len = GetWindowTextLength();
// don't store an empty buffer.
// this means we can handle no text, then up, down, some text, up, down
if (len>0)
{
tempbuffer = (char *)malloc(len + 1);
if (tempbuffer)
{
GetWindowText(tempbuffer,len+1);
}
}
char *currenthistory = m_History.GetCurrentHistoryItem();
char *buffer = m_History.GetPreviousHistoryItem();
if (buffer)
{
SetWindowText(buffer);
}
else
{
SetWindowText(NULL);
g_pNotificationManager->PlaySoundID(SID_DEFAULT);
}
SetSel(-1,-1);
if (tempbuffer)
{
// add to history if different
if (!currenthistory || (currenthistory && stricmp(currenthistory,tempbuffer) != 0))
{
m_History.Add(tempbuffer);
if (WasFirst)
m_History.ResetHistoryItemPointer();
}
free(tempbuffer);
}
}
break;
case VK_TAB: // Nick completion
{
IRCServer *pServer;
// are we in a channel ?
IRCChannel *pChannel = FindIRCChannel(m_MessageWindow);
// or DCC Chat ?
pServer = FindDCCChat(m_MessageWindow);
// or Query ?
IRCQuery *pQuery = FindIRCQuery(m_MessageWindow);
// or Server ?
if (!pServer) // don't overwrite if we've already found a dcc server!
pServer = FindIRCServer(m_MessageWindow,FALSE,FALSE);
if (pChannel || pServer || pQuery)
{
bHandled = TRUE;
CHARRANGE cr;
char nick[1024]; // TODO: convert to char *
int len = GetWindowTextLength();
GetSel(cr);
*nick = 0; // null terminate it.
int startpos = cr.cpMax;
int endpos = cr.cpMax;
int curpos;
char *inputbuffer = NULL;
// don't store an empty buffer.
// this means we can handle no text, then up, down, some text, up, down
if (len>0)
{
inputbuffer = (char *)malloc(len + 1);
ATLASSERT(inputbuffer);
GetWindowText(inputbuffer,len+1);
// find the beginning of the word
while (startpos > 0 && inputbuffer[startpos-1] != ' ')
startpos--;
// find the end of the word
while (endpos < len && inputbuffer[endpos] != ' ')
endpos++;
// get the word
int chars = min(endpos - startpos,sizeof(nick)-1);
strncpy(nick,inputbuffer+startpos,chars);
nick[chars] = 0;
}
char *newnick = NULL; // shut the compiler up
// complete the nick, or get the next one if the nick is valid.
if (pChannel)
pChannel->CompleteNick(nick,&newnick,GetKeyState(VK_SHIFT) & 0x10000 ? FALSE : TRUE,TRUE);
else if (pServer && pServer->m_IsDirect)
newnick = strdup(pServer->m_OtherNick); // if we're in a dcc chat, then just get the other nick.
else if (pServer) // implies "&& !pServer->m_IsDirect"
newnick = strdup(pServer->GetNick()); // if we're in a server, then just get *our* nick.
else if (pQuery)
newnick = strdup(pQuery->m_OtherNick); // if we're in a query window, then just get the other nick.
if (newnick == NULL)
{
g_pNotificationManager->PlaySoundID(SID_DEFAULT);
}
else
{
CChildFrame *pChild = CHILDFRAMEPTR(FindChildWindow(m_MessageWindow));
if (pChild && pChild->IsUserListVisible())
{
// select nick!
sys_Printf(BIC_INFO,"Selecting nick %s\n", newnick);
IRCUser *pUser = NULL;
if (pChild->m_WindowType == CWTYPE_CHANNEL)
pUser = pChannel->m_Users.FindUser(newnick);
if (pUser)
pChild->m_UserListView.Select(pUser);
}
char *nickbuffer = newnick;
if( startpos == 0 )
{
nickbuffer = (char *) malloc( sizeof( char ) *
( strlen( newnick )
+ strlen( STRINGPREF( PREF_sNickCompletionSuffix ) )
+ 1
)
);
if (nickbuffer)
{
strcpy( nickbuffer, newnick );
strcat( nickbuffer, STRINGPREF( PREF_sNickCompletionSuffix ) );
// free the old buffer and swap the pointers over
free(newnick);
newnick = nickbuffer;
}
}
if (inputbuffer)
{
// allocate and build a new buffer
int newbufferlen = startpos + strlen(newnick) + (len - endpos) + 1;
char *newbuffer = (char *)malloc(newbufferlen);
strncpy(newbuffer,inputbuffer,startpos); // strncpy doesn't null terminate
strcpy(newbuffer+startpos,newnick); // so write to the end of the string and terminate
strcat(newbuffer,inputbuffer+endpos); // then add the rest of the input buffer
newbuffer[newbufferlen-1]=0; // null terminate, to make sure...
#ifdef DEBUG
// check that new buffer size is not more than allocated buffer size
int checklen = strlen(newbuffer)+1; // add space for null terminator.
ATLASSERT(checklen == newbufferlen); // This was the cause of the " | " crash in < v0.308, code above is now fixed.
#endif
// replace the buffer with the new one
SetWindowText(newbuffer);
// set the cursor to point to the character after the end of the nick
curpos = startpos + strlen(newnick);
SetSel(curpos,curpos);
free(newbuffer);
}
else
{
curpos = strlen(newnick);
SetWindowText(newnick);
SetSel(curpos,curpos);
}
free(newnick);
}
if (inputbuffer) free(inputbuffer);
}
}
break;
}
}
return 0;
}
LRESULT CTextInputView::OnFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
#ifdef VERBOSE_DEBUG
sys_Printf(BIC_GUI,"INPUT: Got Focus\n");
#endif
#ifndef MICROSOFTACKNOWLEDGESTHATWINDOWSISFUCKINGSHITSOMETIMES
// Doing this here is so fucking shit it's un-true, see this::OnCreate()
UpdateSettings();
#endif
bHandled = FALSE;
return 1;//TODO: Check
}
void CTextInputView::SetMessageWindow(HWND hWnd)
{
m_MessageWindow = hWnd;
}
LRESULT CTextInputView::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
#ifdef MICROSOFTACKNOWLEDGESTHATWINDOWSISFUCKINGSHITSOMETIMES
// aaaaaaaaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrrrrrrrrrrggggggggggggggggghhhhhhhhhhhhhhhhh
// why the *FUCK* doesn't this set the text colors ? It sets the background colors
// but not the text colors! Windows is SOOOO ghey sometimes.
// aaaaaaaaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrrrrrrrrrrggggggggggggggggghhhhhhhhhhhhhhhhh
// NOTE: problematic code moved to UpdateSettings()
#endif
UpdateSettings();
SetEventMask(ENM_MOUSEEVENTS);
LimitText(512);
bHandled = FALSE;
return 0;
}
LRESULT CTextInputView::OnPaste(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// TODO: if selection is not at the end then we need to cut the selection
// and then get the text to the right of the selection and add it onto the
// last line of the multi-line paste.
// access clipboard and check for clipboard contents with more that one line of text..
if (OpenClipboard())
{
bHandled = TRUE;
// Retrieve the Clipboard data (specifying that
// we want ANSI text (via the CF_TEXT value).
HANDLE hClipboardData = GetClipboardData(CF_TEXT);
if (hClipboardData)
{
// Call GlobalLock so that to retrieve a pointer
// to the data associated with the handle returned
// from GetClipboardData.
char *pData = (char*)GlobalLock(hClipboardData);
if (pData)
{
char *pLineStart = pData;
int LineCount = 0;
do
{
if (!*pData || *pData == '\r' || *pData == '\n' || pData - pLineStart > 400) // limit to 450 chars
{
int BufferLen = pData - pLineStart;
int LineLen = 0;
if (LineCount == 0)
LineLen = GetWindowTextLength();
char *buffer = (char *)malloc(LineLen + 1 + BufferLen);
if (LineCount == 0)
GetWindowText(buffer,LineLen+1);
strncpy(buffer + LineLen,pLineStart,BufferLen);
buffer[LineLen + BufferLen] = 0;
// skip the trailing \n and \r, also skip blank lines.
while (*pData && (*pData == '\r' || *pData == '\n'))
pData++;
pLineStart = pData;
LineCount++;
if (*pData)
{
SetWindowText(NULL);
m_History.Add(buffer); // TODO: make this a pref?
m_History.ResetHistoryItemPointer();
::SendMessage(m_MessageWindow,WM_TEXTINPUT,(WPARAM)OTIF_None,(LPARAM)buffer); // Note the TRUE for the WPARAM
}
else
{
// no more data!
if (LineCount > 1)
{
// if multi-line, send the last line too
SetWindowText(NULL);
m_History.Add(buffer); // TODO: make this a pref?
m_History.ResetHistoryItemPointer();
::SendMessage(m_MessageWindow,WM_TEXTINPUT,(WPARAM)OTIF_None,(LPARAM)buffer); // Note the TRUE for the WPARAM
}
else
{
// if not multi-line then insert the buffer
ReplaceSel(buffer+LineLen); // ignoring what we got from the buffer already..
free(buffer); // we must rember to free() in this instance.
// NOTE: NOT adding to history buffer...
}
break;
}
}
else
{
pData++;
}
} while (LineCount < INTPREF(PREF_nMaxClipboardPasteLines));
}
// Unlock the global memory.
GlobalUnlock(hClipboardData);
}
CloseClipboard();
}
return 0;
}
void CTextInputView::UpdateSettings( void )
{
CHARFORMAT2 fmt;
GetDefaultCharFormat(fmt);
fmt.dwMask = CFM_COLOR;
fmt.dwEffects = 0;
fmt.crTextColor = m_TextColor;
fmt.crBackColor = m_BackColor;
fmt.cbSize = sizeof(CHARFORMAT2);
SetDefaultCharFormat(fmt);
SetBackgroundColor(m_BackColor);
m_History.SetMaxLines(INTPREF(PREF_nMaxInputHistoryLines));
}
void CTextInputView::SetColors( COLORREF *pColors )
{
// extract just the colors we need from the array of colors.
m_TextColor = pColors[item_textinputnormaltext - PREF_COLOR_FIRST];
m_BackColor = pColors[item_textinputbackground - PREF_COLOR_FIRST];
}
short CTextInputView::GetRequiredHeight( int Windowtype )
{
int InputHeight;
HFONT hFont;
switch (Windowtype)
{
case CWTYPE_SERVER:
hFont = GetAppFont(PREF_fServerInputFont);
break;
case CWTYPE_DCCCHAT:
hFont = GetAppFont(PREF_fDCCChatInputFont);
break;
case CWTYPE_QUERY:
hFont = GetAppFont(PREF_fQueryInputFont);
break;
case CWTYPE_CHANNEL:
hFont = GetAppFont(PREF_fChannelInputFont);
break;
}
InputHeight = 6 + GetFontMaxHeight(hFont); // value (6) is dependant on window styles.
return InputHeight;
} | [
"hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0"
] | [
[
[
1,
602
]
]
] |
bb7a6664deeec212fd1b5fea5d1fab9a5c2768d3 | a0253037fb4d15a9f087c4415da58253998b453e | /lib/t_physics/physics.cpp | dd48e6c6f10f5020c4c396e33ca5619d7af9de29 | [] | no_license | thomas41546/Spario | a792746ca3e12c7c3fb2deb57ceb05196f5156a0 | 4aca33f9679515abce208eb1ee28d8bc6987cba0 | refs/heads/master | 2021-01-25T06:36:40.111835 | 2010-07-03T04:16:45 | 2010-07-03T04:16:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,551 | cpp | #include "physics.h"
#define PE PhysicsEngine
#define CO CollisionObj
CO::CollisionObj(){
}
CO::CollisionObj(Obj *reference){
CO::ref = reference;
CO::left = CO::right = CO::up = CO::down = NULL;
}
bool CO::CollisionTrue(){
if(CO::left == NULL && CO::right == NULL && CO::up == NULL && CO::down == NULL)return false;
return true;
}
bool CO::Vertical(){
if(CO::up != NULL && CO::down != NULL)return true;
return false;
}
bool CO::Horizontal(){
if(CO::left != NULL && CO::right != NULL)return true;
return false;
}
PE::PhysicsEngine(Display * p_disp,GameObjectController * p_goc,PlayerController * p_player,Timer * p_timer){
PE::pDisplay = p_disp;
PE::GameObjectControllerPtr = p_goc;
PE::pPlayer = p_player;
PE::pTimer = p_timer;
}
void PE::ApplyGravity(){
for(std::list<Obj>::iterator objIterator = (*GameObjectControllerPtr).ObjectIteratorBegin();
objIterator != (*GameObjectControllerPtr).ObjectIteratorEnd();
objIterator++){
if((objIterator->Type == PLAYER || objIterator->Type == MOB) && objIterator->Velocity.y < MAX_VELOCITY){
objIterator->Velocity.y += GRAVITY*MOVEMENT_MULTIPLIER;
}
// if(objIterator->Velocity.y > MAX_VELOCITY)objIterator->Velocity.y = MAX_VELOCITY;
// if(objIterator->Velocity.y < -MAX_VELOCITY)objIterator->Velocity.y = -MAX_VELOCITY;
}
}
void PE::ApplyAI(Obj * obby){
if(abs((int)(PE::pPlayer->PlayerPos().x - obby->Pos.x)) > 2 && obby->Id == MOB_GOOMPA){
if(PE::pPlayer->PlayerPos().x > obby->Pos.x){
obby->Velocity.x = 1*MOVEMENT_MULTIPLIER;
}
else{
obby->Velocity.x = -1*MOVEMENT_MULTIPLIER;
}
}
if(abs((int)(PE::pPlayer->PlayerPos().x - obby->Pos.x)) > 2 && obby->Id == MOB_MAR){
if(PE::pPlayer->PlayerPos().x > obby->Pos.x){
obby->Velocity.x = 2*MOVEMENT_MULTIPLIER;
}
else{
obby->Velocity.x = -2*MOVEMENT_MULTIPLIER;
}
}
}
void PE::ObjectSpriteIteration(Obj *objIterator){
if( (objIterator->Id == OBJECT_JUMPER ) && objIterator->VarA > 0){ //TODO Object sprite iteration is here, incorrect area
int currentSpriteIt = objIterator->SpriteIt;
PE::ChangeObjSprite(&(*objIterator),objIterator->Id);
if(currentSpriteIt != objIterator->SpriteIt)objIterator->VarA--;
}
else if( (objIterator->Id == OBJECT_QUESTION_MARK ) && objIterator->VarA > 1){
int currentSpriteIt = objIterator->SpriteIt;
PE::ChangeObjSprite(&(*objIterator),objIterator->Id);
if(currentSpriteIt != objIterator->SpriteIt)objIterator->VarA--;
}
}
void PE::ApplyVelocity(){
for(std::list<Obj>::iterator objIterator = (*GameObjectControllerPtr).ObjectIteratorBegin();
objIterator != (*GameObjectControllerPtr).ObjectIteratorEnd();
objIterator++){
if(objIterator->Type != STATIC){
if(objIterator->Type == PLAYER || objIterator->Type == MOB){
if(objIterator->Type == MOB)
PE::ApplyAI(&(*objIterator));
Collision_Handling(&(*objIterator));
}
else{ //Type: OBJECT
objIterator->Pos += objIterator->Velocity;
PE::ObjectSpriteIteration(&(*objIterator));
}
}
}
}
double PE::FrictionHandler(Obj *afflicted,Vector *idealVelocity,Obj *down){ //returns change
if(afflicted == NULL || down == NULL){
Debug("PE::FrictionHandler Null Object");
return 0.0;
}
double xbefore = (double)idealVelocity->x;
if((down->Type == STATIC || down->Type == OBJECT) && (afflicted->Type == MOB || afflicted->Type == PLAYER)){
idealVelocity->x *= STD_GROUND_FRICTION;
}
return (idealVelocity->x - xbefore);
}
void PE::ChangeObjSprite(Obj * obby, int spritecode){
int tmp=0;
if(pDisplay->GetAnimationSurface(spritecode,&tmp) != NULL){
if(obby->Sprite == spritecode){
pDisplay->IterateAnimation(obby->Sprite,&obby->SpriteIt,&obby->LastSpriteIt,pTimer->pollTimer()); //iterate if sprite is already used
}
else{
pDisplay->ResetAnimation(spritecode,&obby->SpriteIt,&obby->LastSpriteIt,pTimer->pollTimer());
obby->Sprite = spritecode;
}
Vector oldDim = obby->Dim;
Vector oldPos = obby->Pos;
Vector newDim = Vector(pDisplay->GetAnimationSurface(obby->Sprite,&obby->SpriteIt)->w,pDisplay->GetAnimationSurface(obby->Sprite,&obby->SpriteIt)->h);
obby->Dim = newDim;
if(obby->Velocity.x <= 0){
obby->Pos = oldPos - (newDim-oldDim);
}
else{
obby->Pos = oldPos + (newDim-oldDim);
}
}
else{
Debug("func ChangeObjSprite: Invalid Sprite Code");
}
}
void PE::Collision_HandlingVerticalCase(Obj *obby, CollisionObj * collb,CollisionObj * touchedcollb, Vector * idealPos, Vector * idealVec){
if(collb->up != NULL && collb->down == NULL){ //UP
if(idealVec->y < -MAX_VELOCITY)idealVec->y = -MAX_VELOCITY*3/4.0;
if((collb->up)->Id == OBJECT_QUESTION_MARK && (collb->up)->VarA == 0){
(collb->up)->VarA = 3;
}
idealPos->y = (collb->up)->Pos.y+(collb->up)->Dim.y;
idealVec->y = 2*MOVEMENT_MULTIPLIER;
touchedcollb->up = (Obj *)1;
}
else if(collb->down != NULL && collb->up == NULL){//DOWN
FrictionHandler(obby,&*idealVec,collb->down);
if(idealVec->y > MAX_VELOCITY)idealVec->y = MAX_VELOCITY*3/4.0;
/*
if(obby->Type == PLAYER && (collb->down)->Type == MOB && PE::pPlayer->pKeyboard->Down == true){
PE::GameObjectControllerPtr->RemoveObjectP((Obj *)collb->down);
}
fails make it work
*/
if((collb->down)->Id == OBJECT_JUMPER && (collb->down)->VarA == 0){
(collb->down)->VarA = 3;
idealVec->y = -MAX_VELOCITY*1.5;
}
else{
idealVec->y = 0;
}
idealPos->y = ((collb->down)->Pos.y)-(obby->Dim.y);
*collb = InvasiveCollisionCheck(obby, *idealPos);
touchedcollb->down = (Obj *)1;
}
}
void PE::Collision_HandlingHorizontalCase(Obj *obby, CollisionObj * collb,CollisionObj * touchedcollb, Vector * idealPos, Vector * idealVec){
if(collb->left != NULL && collb->right == NULL){ //LEFT
idealPos->x = (collb->left)->Pos.x+(collb->left)->Dim.x;
idealVec->x = 0;
touchedcollb->left = (Obj *)1;
}
else if(collb->right != NULL && collb->left == NULL){//RIGHT
idealPos->x = (collb->right)->Pos.x-(obby->Dim.x);
idealVec->x = 0;
touchedcollb->right = (Obj *)1;
}
}
void PE::Collision_Handling(Obj * obby){ //player,mob
CollisionObj collb;
CollisionObj touchedcollb; //Only used to record which sides have been touched
Vector idealPos = obby->Pos + obby->Velocity;
Vector idealVec = obby->Velocity;
touchedcollb.left = 0;
touchedcollb.right = 0;
touchedcollb.up = 0;
touchedcollb.down = 0;
collb = InvasiveCollisionCheck(obby, obby->Pos + obby->Velocity);
if(collb.CollisionTrue()){
if(obby->AirHeight == 0){
PE::Collision_HandlingVerticalCase(obby,&collb,&touchedcollb,&idealPos,&idealVec);
PE::Collision_HandlingHorizontalCase(obby,&collb,&touchedcollb,&idealPos,&idealVec);
}
else{
PE::Collision_HandlingHorizontalCase(obby,&collb,&touchedcollb,&idealPos,&idealVec);
collb = InvasiveCollisionCheck(obby, idealPos + idealVec);
PE::Collision_HandlingVerticalCase(obby,&collb,&touchedcollb,&idealPos,&idealVec);
}
if(( collb = InvasiveCollisionCheck(obby, idealPos)).CollisionTrue()){ //Bad Collision
/*if(collb.left != NULL && collb.right != NULL){
while(collb.CollisionTrue()){
if(obby->Velocity.x < 0)
idealPos.x+=MIN_INCREMENT;
else
idealPos.x-=MIN_INCREMENT;
collb = InvasiveCollisionCheck(obby,idealPos);
}
Debug("func Collision_Handling: Unwanted Collision Case VERTICAL");
}
if(collb.up != NULL && collb.down != NULL){
while(collb.CollisionTrue()){
if(obby->Velocity.y < 0)
idealPos.y+=MIN_INCREMENT;
else
idealPos.y-=MIN_INCREMENT;
collb = InvasiveCollisionCheck(obby,idealPos);
}
Debug("func Collision_Handling: Unwanted Collision Case HORIZONTAL");
}*/
if(collb.down != NULL){
while((collb = InvasiveCollisionCheck(obby,idealPos)).CollisionTrue())
--idealPos.y; //go up
}
idealVec *= 0;
touchedcollb.down = (Obj *)1;
touchedcollb.left = (Obj *)1;
}
}
else{
//adding velocity casues no problems
}
if(obby->Type == PLAYER || obby->Type == MOB){
int curheight = 0;
if(obby->Type == PLAYER)
curheight = PE::AirHeight(obby,idealPos);
else{
curheight = PE::DirtyAirHeight(obby,idealPos);
}
Vector diffPos = idealPos - obby->Pos;
Vector diffVec = idealVec - obby->Velocity;
obby->AirHeight = curheight;
//Sprite Handling
if(curheight > 0){
if(obby->Sprite == obby->SpriteMap->standLeft ||
obby->Sprite == obby->SpriteMap->skidLeft ||
obby->Sprite == obby->SpriteMap->jumpLeft ||
obby->Sprite == obby->SpriteMap->walkLeft){
ChangeObjSprite(obby,obby->SpriteMap->jumpLeft);
}
else{
ChangeObjSprite(obby,obby->SpriteMap->jumpRight);
}
}
if(curheight == 0){
if(idealVec.x > MINRUNVELOCITY){
ChangeObjSprite(obby,obby->SpriteMap->walkRight);
}
else if(idealVec.x < -MINRUNVELOCITY){
ChangeObjSprite(obby,obby->SpriteMap->walkLeft);
}
else if(idealVec.x > -MINRUNVELOCITY && idealVec.x < MINRUNVELOCITY){
if(diffVec.x < 0){
ChangeObjSprite(obby,obby->SpriteMap->standRight);
}
else if(diffVec.x > 0){
ChangeObjSprite(obby,obby->SpriteMap->standLeft);
}
else if(obby->Sprite == obby->SpriteMap->jumpLeft){
ChangeObjSprite(obby,obby->SpriteMap->standLeft);
}
else if(obby->Sprite == obby->SpriteMap->jumpRight){
ChangeObjSprite(obby,obby->SpriteMap->standRight);
}
}
}
}
obby->LastPos = obby->Pos;
obby->LastVelocity = obby->Velocity;
obby->Pos = idealPos;
obby->Velocity = idealVec;
}
CollisionObj PE::InvasiveCollisionCheck(Obj *obby, Vector TestPos){ /*todo, improve for platforms*/
CollisionObj collobj(obby);
for(std::list<Obj>::iterator objIterator = (*GameObjectControllerPtr).ObjectIteratorBegin();
objIterator != (*GameObjectControllerPtr).ObjectIteratorEnd();
objIterator++)
{
if(&(*objIterator) != obby &&
abs((int)(obby->Pos.x-objIterator->Pos.x)) < BLOCK_SIZE*2 && abs((int)(obby->Pos.y-objIterator->Pos.y)) < BLOCK_SIZE*2 &&
SDL_CollideRect( pDisplay->GetAnimationSurface(obby->Sprite,&obby->SpriteIt),(int)TestPos.x, (int)TestPos.y,
pDisplay->GetAnimationSurface(objIterator->Sprite,&objIterator->SpriteIt), (int)objIterator->Pos.x, (int)objIterator->Pos.y)){
int dx = (int)abs((int)(TestPos.x - objIterator->Pos.x));
int dy = (int)abs((int)(TestPos.y - objIterator->Pos.y));
if(dx > dy){ //HORIZONTAL COLLISION
if(dx > COLLISION_THRESHOLD ){
if(TestPos.x < objIterator->Pos.x){ //RIGHT
//if(collobj.right != NULL) PROBLEM? <-------Investigate
collobj.right = &(*objIterator);
continue;
}
else{//LEFT
collobj.left = &(*objIterator);
continue;
}
}
}
else { //VERTICAL COLLISION
if(TestPos.y < objIterator->Pos.y){ //DOWN
collobj.down = &(*objIterator);
continue;
}
else{//UP
collobj.up = &(*objIterator);
continue;
}
}
}
}
return collobj;
}
int PE::AirHeight(Obj *obby, Vector TestPos){ //16 passes
Vector HeightTestPos = TestPos;
while(!InvasiveCollisionCheck(obby, HeightTestPos).CollisionTrue() && (HeightTestPos.y - TestPos.y < BLOCK_SIZE*5)) //maximum 5 passes
HeightTestPos.y+=BLOCK_SIZE;
HeightTestPos.y-=BLOCK_SIZE;
while(!InvasiveCollisionCheck(obby, HeightTestPos).CollisionTrue() && (HeightTestPos.y - TestPos.y < BLOCK_SIZE*10)) //maximum 11 passes
HeightTestPos.y+=3;
HeightTestPos.y-=3;
return (int)(HeightTestPos.y - TestPos.y);
}
int PE::DirtyAirHeight(Obj *obby,Vector HeightTestPos){ //666 in air, 0 if not
HeightTestPos.y+=2;
if(InvasiveCollisionCheck(obby, HeightTestPos).CollisionTrue()){return 0;}
return 666;
}
| [
"[email protected]"
] | [
[
[
1,
368
]
]
] |
e7f4a0d803c3a458619cfebe72ebe7280709697a | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-19/pcbnew/class_pcb_text.cpp | dd12dc41292d93c0ff987a59d09fd23feb5eadde | [] | no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,431 | cpp | /************************************/
/* fonctions de la classe TEXTE_PCB */
/************************************/
#include "fctsys.h"
#include "wxstruct.h"
#include "gr_basic.h"
#include "common.h"
#include "pcbnew.h"
/*******************/
/* class TEXTE_PCB */
/*******************/
TEXTE_PCB::TEXTE_PCB(EDA_BaseStruct * parent):
EDA_BaseStruct(parent, TYPETEXTE), EDA_TextStruct()
{
}
/* Destructeur */
TEXTE_PCB:: ~TEXTE_PCB(void)
{
}
/* copie de stucture */
void TEXTE_PCB::Copy(TEXTE_PCB * source)
{
m_Parent = source->m_Parent;
Pback = Pnext = NULL;
m_Miroir = source->m_Miroir;
m_Size = source->m_Size;
m_Orient = source->m_Orient;
m_Pos = source->m_Pos;
m_Layer = source->m_Layer;
m_Width = source->m_Width;
m_Attributs = source->m_Attributs;
m_CharType = source->m_CharType;
m_HJustify = source->m_HJustify;
m_VJustify = source->m_VJustify;
m_Text = source->m_Text;
}
void TEXTE_PCB::UnLink( void )
{
/* Modification du chainage arriere */
if( Pback )
{
if( Pback->m_StructType != TYPEPCB)
{
Pback->Pnext = Pnext;
}
else /* Le chainage arriere pointe sur la structure "Pere" */
{
((BOARD*)Pback)->m_Drawings = Pnext;
}
}
/* Modification du chainage avant */
if( Pnext) Pnext->Pback = Pback;
Pnext = Pback = NULL;
}
/****************************************************************/
int TEXTE_PCB::ReadTextePcbDescr(FILE * File, int * LineNum)
/****************************************************************/
{
char text[1024], Line[1024];
int dummy;
while( GetLine(File, Line, LineNum ) != NULL )
{
if(strnicmp(Line,"$EndTEXTPCB",11) == 0) return 0;
if( strncmp(Line,"Te", 2) == 0 ) /* Texte */
{
ReadDelimitedText(text, Line+2, sizeof(text) );
m_Text = CONV_FROM_UTF8(text);
continue;
}
if( strncmp(Line,"Po", 2) == 0 )
{
sscanf( Line+2," %d %d %d %d %d %d",
&m_Pos.x, &m_Pos.y, &m_Size.x, &m_Size.y,
&m_Width, &m_Orient);
continue;
}
if( strncmp(Line,"De", 2) == 0 )
{
sscanf( Line+2," %d %d %lX %d\n",&m_Layer, &m_Miroir,
&m_TimeStamp, &dummy);
if ( m_Layer < LAYER_CUIVRE_N )
m_Layer = LAYER_CUIVRE_N;
if ( m_Layer > LAST_NO_COPPER_LAYER )
m_Layer = LAST_NO_COPPER_LAYER;
continue;
}
}
return(1);
}
/**************************************************/
int TEXTE_PCB::WriteTextePcbDescr(FILE * File)
/**************************************************/
{
if( GetState(DELETED) ) return(0);
if(m_Text.IsEmpty() ) return(0);
fprintf( File,"$TEXTPCB\n");
fprintf( File,"Te \"%s\"\n",CONV_TO_UTF8(m_Text));
fprintf( File,"Po %d %d %d %d %d %d\n",
m_Pos.x, m_Pos.y, m_Size.x, m_Size.y, m_Width, m_Orient );
fprintf( File,"De %d %d %lX %d\n", m_Layer, m_Miroir, m_TimeStamp, 0);
fprintf( File,"$EndTEXTPCB\n");
return(1);
}
/**********************************************************************/
void TEXTE_PCB::Draw(WinEDA_DrawPanel * panel, wxDC * DC,
const wxPoint & offset, int DrawMode)
/**********************************************************************/
/*
DrawMode = GR_OR, GR_XOR.., -1 si mode courant.
*/
{
EDA_TextStruct::Draw(panel, DC, offset, g_DesignSettings.m_LayerColor[m_Layer],
DrawMode, DisplayOpt.DisplayDrawItems,
(g_AnchorColor & ITEM_NOT_SHOW) ? -1 : (g_AnchorColor & MASKCOLOR));
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
] | [
[
[
1,
137
]
]
] |
0b5de7fd9b5cf08c5e44f7d80f32a0e7a50ab1b5 | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Autumn/WrapperDX/Device/State/BlendOperationSub.h | 83ebb8d586897be9168657dd5af72eb39e8f95c5 | [] | no_license | Ishoa/bizon | 4dbcbbe94d1b380f213115251e1caac5e3139f4d | d7820563ab6831d19e973a9ded259d9649e20e27 | refs/heads/master | 2016-09-05T11:44:00.831438 | 2010-03-10T23:14:22 | 2010-03-10T23:14:22 | 32,632,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | h | #ifndef _BLEND_OPERATION_SUB_
#define _BLEND_OPERATION_SUB_
#include <d3d11.h>
class BlendOperationSub
{
public:
BlendOperationSub();
~BlendOperationSub();
static D3D11_BLEND_OP GetBlendOperation();
static bool IsEnable();
};
#endif // _BLEND_OPERATION_SUB_ | [
"edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6"
] | [
[
[
1,
16
]
]
] |
ba7c62601ecd05c82f997705be421ee1f627f538 | 04fec4cbb69789d44717aace6c8c5490f2cdfa47 | /include/wx/richtext/richtextstyledlg.h | 1315c90311f0aabb2d76b8ed9e7234014b929ef5 | [] | no_license | aaryanapps/whiteTiger | 04f39b00946376c273bcbd323414f0a0b675d49d | 65ed8ffd530f20198280b8a9ea79cb22a6a47acd | refs/heads/master | 2021-01-17T12:07:15.264788 | 2010-10-11T20:20:26 | 2010-10-11T20:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,553 | h | /////////////////////////////////////////////////////////////////////////////
// Name: wx/richtext/richtextstyledlg.h
// Purpose:
// Author: Julian Smart
// Modified by:
// Created: 10/5/2006 12:05:31 PM
// RCS-ID: $Id: richtextstyledlg.h 49398 2007-10-24 14:20:43Z JS $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _RICHTEXTSTYLEDLG_H_
#define _RICHTEXTSTYLEDLG_H_
/*!
* Includes
*/
////@begin includes
////@end includes
#include "wx/richtext/richtextbuffer.h"
#include "wx/richtext/richtextstyles.h"
#include "wx/richtext/richtextctrl.h"
/*!
* Forward declarations
*/
////@begin forward declarations
class wxBoxSizer;
class wxRichTextStyleListCtrl;
class wxRichTextCtrl;
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
#define SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_STYLE wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER|wxSYSTEM_MENU|wxCLOSE_BOX
#define SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_TITLE _("Style Organiser")
#define SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_IDNAME ID_RICHTEXTSTYLEORGANISERDIALOG
#define SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_SIZE wxSize(400, 300)
#define SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_POSITION wxDefaultPosition
////@end control identifiers
/*!
* Flags for specifying permitted operations
*/
#define wxRICHTEXT_ORGANISER_DELETE_STYLES 0x0001
#define wxRICHTEXT_ORGANISER_CREATE_STYLES 0x0002
#define wxRICHTEXT_ORGANISER_APPLY_STYLES 0x0004
#define wxRICHTEXT_ORGANISER_EDIT_STYLES 0x0008
#define wxRICHTEXT_ORGANISER_RENAME_STYLES 0x0010
#define wxRICHTEXT_ORGANISER_OK_CANCEL 0x0020
#define wxRICHTEXT_ORGANISER_RENUMBER 0x0040
// The permitted style types to show
#define wxRICHTEXT_ORGANISER_SHOW_CHARACTER 0x0100
#define wxRICHTEXT_ORGANISER_SHOW_PARAGRAPH 0x0200
#define wxRICHTEXT_ORGANISER_SHOW_LIST 0x0400
#define wxRICHTEXT_ORGANISER_SHOW_ALL 0x0800
// Common combinations
#define wxRICHTEXT_ORGANISER_ORGANISE (wxRICHTEXT_ORGANISER_SHOW_ALL|wxRICHTEXT_ORGANISER_DELETE_STYLES|wxRICHTEXT_ORGANISER_CREATE_STYLES|wxRICHTEXT_ORGANISER_APPLY_STYLES|wxRICHTEXT_ORGANISER_EDIT_STYLES|wxRICHTEXT_ORGANISER_RENAME_STYLES)
#define wxRICHTEXT_ORGANISER_BROWSE (wxRICHTEXT_ORGANISER_SHOW_ALL|wxRICHTEXT_ORGANISER_OK_CANCEL)
#define wxRICHTEXT_ORGANISER_BROWSE_NUMBERING (wxRICHTEXT_ORGANISER_SHOW_LIST|wxRICHTEXT_ORGANISER_OK_CANCEL|wxRICHTEXT_ORGANISER_RENUMBER)
/*!
* wxRichTextStyleOrganiserDialog class declaration
*/
class WXDLLIMPEXP_RICHTEXT wxRichTextStyleOrganiserDialog: public wxDialog
{
DECLARE_DYNAMIC_CLASS( wxRichTextStyleOrganiserDialog )
DECLARE_EVENT_TABLE()
public:
/// Constructors
wxRichTextStyleOrganiserDialog( );
wxRichTextStyleOrganiserDialog( int flags, wxRichTextStyleSheet* sheet, wxRichTextCtrl* ctrl, wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& caption = SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_TITLE, const wxPoint& pos = SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_POSITION, const wxSize& size = SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_SIZE, long style = SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_STYLE );
/// Creation
bool Create( int flags, wxRichTextStyleSheet* sheet, wxRichTextCtrl* ctrl, wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& caption = SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_TITLE, const wxPoint& pos = SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_POSITION, const wxSize& size = SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_SIZE, long style = SYMBOL_WXRICHTEXTSTYLEORGANISERDIALOG_STYLE );
/// Creates the controls and sizers
void CreateControls();
/// Initialise member variables
void Init();
/// Transfer data from/to window
virtual bool TransferDataFromWindow();
virtual bool TransferDataToWindow();
/// Set/get style sheet
void SetStyleSheet(wxRichTextStyleSheet* sheet) { m_richTextStyleSheet = sheet; }
wxRichTextStyleSheet* GetStyleSheet() const { return m_richTextStyleSheet; }
/// Set/get control
void SetRichTextCtrl(wxRichTextCtrl* ctrl) { m_richTextCtrl = ctrl; }
wxRichTextCtrl* GetRichTextCtrl() const { return m_richTextCtrl; }
/// Set/get flags
void SetFlags(int flags) { m_flags = flags; }
int GetFlags() const { return m_flags; }
/// Show preview for given or selected preview
void ShowPreview(int sel = -1);
/// Clears the preview
void ClearPreview();
/// List selection
void OnListSelection(wxCommandEvent& event);
/// Get/set restart numbering boolean
bool GetRestartNumbering() const { return m_restartNumbering; }
void SetRestartNumbering(bool restartNumbering) { m_restartNumbering = restartNumbering; }
/// Get selected style name or definition
wxString GetSelectedStyle() const;
wxRichTextStyleDefinition* GetSelectedStyleDefinition() const;
/// Apply the style
bool ApplyStyle(wxRichTextCtrl* ctrl = NULL);
/// Should we show tooltips?
static bool ShowToolTips() { return sm_showToolTips; }
/// Determines whether tooltips will be shown
static void SetShowToolTips(bool show) { sm_showToolTips = show; }
////@begin wxRichTextStyleOrganiserDialog event handler declarations
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_CHAR
void OnNewCharClick( wxCommandEvent& event );
/// wxEVT_UPDATE_UI event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_CHAR
void OnNewCharUpdate( wxUpdateUIEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_PARA
void OnNewParaClick( wxCommandEvent& event );
/// wxEVT_UPDATE_UI event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_PARA
void OnNewParaUpdate( wxUpdateUIEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_LIST
void OnNewListClick( wxCommandEvent& event );
/// wxEVT_UPDATE_UI event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_LIST
void OnNewListUpdate( wxUpdateUIEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_APPLY
void OnApplyClick( wxCommandEvent& event );
/// wxEVT_UPDATE_UI event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_APPLY
void OnApplyUpdate( wxUpdateUIEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_RENAME
void OnRenameClick( wxCommandEvent& event );
/// wxEVT_UPDATE_UI event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_RENAME
void OnRenameUpdate( wxUpdateUIEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_EDIT
void OnEditClick( wxCommandEvent& event );
/// wxEVT_UPDATE_UI event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_EDIT
void OnEditUpdate( wxUpdateUIEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_DELETE
void OnDeleteClick( wxCommandEvent& event );
/// wxEVT_UPDATE_UI event handler for ID_RICHTEXTSTYLEORGANISERDIALOG_DELETE
void OnDeleteUpdate( wxUpdateUIEvent& event );
////@end wxRichTextStyleOrganiserDialog event handler declarations
////@begin wxRichTextStyleOrganiserDialog member function declarations
/// Retrieves bitmap resources
wxBitmap GetBitmapResource( const wxString& name );
/// Retrieves icon resources
wxIcon GetIconResource( const wxString& name );
////@end wxRichTextStyleOrganiserDialog member function declarations
////@begin wxRichTextStyleOrganiserDialog member variables
wxBoxSizer* m_innerSizer;
wxBoxSizer* m_buttonSizerParent;
wxRichTextStyleListCtrl* m_stylesListBox;
wxRichTextCtrl* m_previewCtrl;
wxBoxSizer* m_buttonSizer;
wxButton* m_newCharacter;
wxButton* m_newParagraph;
wxButton* m_newList;
wxButton* m_applyStyle;
wxButton* m_renameStyle;
wxButton* m_editStyle;
wxButton* m_deleteStyle;
wxButton* m_closeButton;
wxBoxSizer* m_bottomButtonSizer;
wxCheckBox* m_restartNumberingCtrl;
wxButton* m_okButton;
wxButton* m_cancelButton;
/// Control identifiers
enum {
ID_RICHTEXTSTYLEORGANISERDIALOG = 10500,
ID_RICHTEXTSTYLEORGANISERDIALOG_STYLES = 10501,
ID_RICHTEXTSTYLEORGANISERDIALOG_CURRENT_STYLE = 10510,
ID_RICHTEXTSTYLEORGANISERDIALOG_PREVIEW = 10509,
ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_CHAR = 10504,
ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_PARA = 10505,
ID_RICHTEXTSTYLEORGANISERDIALOG_NEW_LIST = 10508,
ID_RICHTEXTSTYLEORGANISERDIALOG_APPLY = 10503,
ID_RICHTEXTSTYLEORGANISERDIALOG_RENAME = 10502,
ID_RICHTEXTSTYLEORGANISERDIALOG_EDIT = 10506,
ID_RICHTEXTSTYLEORGANISERDIALOG_DELETE = 10507,
ID_RICHTEXTSTYLEORGANISERDIALOG_RESTART_NUMBERING = 10511
};
////@end wxRichTextStyleOrganiserDialog member variables
private:
wxRichTextCtrl* m_richTextCtrl;
wxRichTextStyleSheet* m_richTextStyleSheet;
bool m_dontUpdate;
int m_flags;
static bool sm_showToolTips;
bool m_restartNumbering;
};
#endif
// _RICHTEXTSTYLEDLG_H_
| [
"[email protected]"
] | [
[
[
1,
238
]
]
] |
22b121a4217b559c44e4151f8356da11f444c695 | c70941413b8f7bf90173533115c148411c868bad | /core/include/vtxThreadJobQueue.h | 3708577d7f4eac06edbb067b057c4512e7e7c1ad | [] | 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 | 2,537 | 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 __vtxThreadJobQueue_H__
#define __vtxThreadJobQueue_H__
#include "vtxPrerequisites.h"
#include "vtxInterLockedType.h"
#include "vtxSemaphore.h"
namespace vtx
{
//-----------------------------------------------------------------------
/** A class for queuing and processing thread jobs */
class vtxExport ThreadJobQueue
{
public:
typedef std::deque<ThreadJob*> JobQueue;
typedef std::vector<VTX_THREAD_TYPE*> ThreadPool;
ThreadJobQueue();
virtual ~ThreadJobQueue();
/** Set the number of threads that will be used to process the ThreadJob queue */
void setNumberOfThreads(const uint& num_threads);
/** Add the given job to the job queue */
void queueJob(ThreadJob* job);
protected:
InterLockedType<bool> mRunning;
VTX_MUTEX(mMutex);
Semaphore mSemaphore;
JobQueue mQueue;
ThreadPool mThreadPool;
/** The method that will be called by the processing threads */
void threadFunc();
/** Join and destroy all active threads */
void destroyThreads();
};
//-----------------------------------------------------------------------
}
#endif
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
] | [
[
[
1,
70
]
]
] |
aacda1dc01744bfe95754489d688db4e1393bfde | 3949d20551a203cf29801d888844d83d297d8118 | /Sources/LudoCore/InputMouse.h | efffd279665b35dc96a575bade49519577519656 | [] | no_license | Cuihuo/sorgamedev | 2197cf5f19a6e8b3b7bba51d46ebc1f8c1f5731e | fa6eb43a586b0e175ac291e8cd583343c0f7a337 | refs/heads/master | 2021-01-10T17:38:50.996616 | 2008-11-28T17:13:19 | 2008-11-28T17:13:19 | 49,120,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | h | #pragma once
class InputMouse
{
public:
enum MouseAction
{
MOUSE_LEFT,
MOUSE_UP,
MOUSE_RIGHT,
MOUSE_DOWN
};
InputMouse();
~InputMouse();
void AddInputEvent(int action, int eventNumber);
void SetMouseMouse(int x, int y);
void PostUpdate();
bool IsEventTriggered(int eventNumber);
private:
std::map<int,int> m_MouseActionEvent;
std::vector<int> m_CurrentAction;
int m_LastX;
int m_LastY;
}; | [
"sikhan.ariel.lee@a3e5f5c2-bd6c-11dd-94c0-21daf384169b"
] | [
[
[
1,
29
]
]
] |
a7df5197fd80dc57ba0bd89e8d2409a2a9d330d9 | 7a2144d11ce57a5286381d91d71b15592de3e7eb | /glm/test/core/core_type_mat3x3.cpp | 9c9e55acd18a3f25901f114075de0e0d13e821c6 | [
"MIT"
] | permissive | ryanschmitty/RDSTracer | 25449db75d2caf2bdbed317f9fa271bb8deda67c | 19fddc911c7d193e055ff697c15d76b83ce0b33a | refs/heads/master | 2021-01-10T20:38:23.050262 | 2011-09-20T23:19:46 | 2011-09-20T23:19:46 | 1,627,984 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,639 | cpp | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2008-08-31
// Updated : 2008-08-31
// Licence : This source is under MIT License
// File : test/core/type_mat3x3.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <glm/glm.hpp>
#include <cstdio>
void print(glm::dmat3 const & Mat0)
{
printf("mat3(\n");
printf("\tvec3(%2.3f, %2.3f, %2.3f)\n", Mat0[0][0], Mat0[0][1], Mat0[0][2]);
printf("\tvec3(%2.3f, %2.3f, %2.3f)\n", Mat0[1][0], Mat0[1][1], Mat0[1][2]);
printf("\tvec3(%2.3f, %2.3f, %2.3f))\n\n", Mat0[2][0], Mat0[2][1], Mat0[2][2]);
}
bool test_mat3x3()
{
glm::dmat3 Mat0(
glm::dvec3(0.6f, 0.2f, 0.3f),
glm::dvec3(0.2f, 0.7f, 0.5f),
glm::dvec3(0.3f, 0.5f, 0.7f));
glm::dmat3 Inv0 = glm::inverse(Mat0);
glm::dmat3 Res0 = Mat0 * Inv0;
print(Mat0);
print(Inv0);
print(Res0);
return true;
}
static bool test_operators()
{
glm::mat3x3 m(1.0f);
glm::vec3 u(1.0f);
glm::vec3 v(1.0f);
float x = 1.0f;
glm::vec3 a = m * u;
glm::vec3 b = v * m;
glm::mat3x3 n = x / m;
glm::mat3x3 o = m / x;
glm::mat3x3 p = x * m;
glm::mat3x3 q = m * x;
bool R = m != q;
bool S = m == m;
return true;
}
int main()
{
bool Result = true;
Result = Result && test_mat3x3();
Result = Result && test_operators();
assert(Result);
return Result;
}
| [
"[email protected]"
] | [
[
[
1,
65
]
]
] |
56d2f89d8603eef9baff22e933142cd89ffa2e82 | 4dd44d686f1b96f8e6edae3769369a89013f6bc1 | /ocass/liboch/ch_msgh.cpp | 5e326d26b9314a29977b74af82214919621bf16a | [] | no_license | bactq/ocass | e1975533a69adbd1b4d1f9fd1bd88647039fff82 | 116565ea7c554b11b0a696f185d3a6376e0161dc | refs/heads/master | 2021-01-10T14:04:02.179429 | 2007-07-14T16:03:23 | 2007-07-14T16:03:23 | 45,017,357 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,338 | cpp | /*
* OCASS - Microsoft Office Communicator Assistant
* (http://code.google.com/p/ocass/)
*
* Copyright (C) 2007 Le Xiongjia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Le Xiongjia ([email protected] [email protected])
*
*/
#include "ca_types.h"
#include "ch_inner.h"
LRESULT WINAPI CH_HookCBTProc(int nCode, WPARAM wParam, LPARAM lParam)
{
CHHDatum *pHDatum = CH_HDatumPtrGet();
LRESULT nResult;
if (NULL == pHDatum || NULL == pHDatum->hInjectWndHook)
{
return -1;
}
nResult = CallNextHookEx(pHDatum->hInjectWndHook, nCode, wParam, lParam);
CH_OnInject(pHDatum);
CH_OnInjectComplete(pHDatum);
return nResult;
}
| [
"lexiongjia@4b591cd5-a833-0410-8603-c1928dc92378"
] | [
[
[
1,
42
]
]
] |
783c937b37aedb3f78586b487983838ca49ba9cb | 1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50 | /shrimp_gui/shrimp_joystick.cpp | ea733474c9b77f1e28ae49f732667b06539631c4 | [] | no_license | llvllrbreeze/alcorapp | dfe2551f36d346d73d998f59d602c5de46ef60f7 | 3ad24edd52c19f0896228f55539aa8bbbb011aac | refs/heads/master | 2021-01-10T07:36:01.058011 | 2008-12-16T12:51:50 | 2008-12-16T12:51:50 | 47,865,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 920 | cpp | #include "shrimp_joystick.h"
shrimp_joystick::shrimp_joystick() {
yaxis_to_speed.set_range(axis_max, axis_min, shrimp_min_speed, shrimp_max_speed);
xaxis_to_steer.set_range(axis_min, axis_max, shrimp_min_steer, shrimp_max_steer);
m_mti.open("config/mti_driver.ini");
reset_mti();
}
all::math::angle shrimp_joystick::get_steer() {
wxPoint joyPos((*this).GetPosition());
int steer = xaxis_to_steer.x_to_y(joyPos.x);
return all::math::angle(steer, all::math::deg_tag);
}
int shrimp_joystick::get_speed() {
wxPoint joyPos((*this).GetPosition());
int speed = yaxis_to_speed.x_to_y(joyPos.y);
return speed;
}
void shrimp_joystick::reset_mti() {
m_mti.reset(all::sense::tags::align_reset);
}
void shrimp_joystick::get_pan_tilt(all::math::angle& pan, all::math::angle& tilt) {
all::math::rpy_angle_t rpy = m_mti.get_euler();
pan = -rpy.yaw;
tilt = rpy.pitch;
}
| [
"stefano.marra@1ffd000b-a628-0410-9a29-793f135cad17"
] | [
[
[
1,
39
]
]
] |
2d55bfd308468ba662bad5cdabe3f5b8c851f5f4 | 9340e21ef492eec9f19d1e4ef2ef33a19354ca6e | /cing/src/graphics/Style.h | a2bb5ee3d1f46c8e572bb9bbc33d37a2cfd482d9 | [] | no_license | jamessqr/Cing | e236c38fe729fd9d49ccd1584358eaad475f7686 | c46045d9d0c2b4d9e569466971bbff1662be4e7a | refs/heads/master | 2021-01-17T22:55:17.935520 | 2011-05-14T18:35:30 | 2011-05-14T18:35:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,103 | h | /*
This source file is part of the Cing project
For the latest info, see http://www.XXX.org
Copyright (c) 2006-2009 Julio Obelleiro and Jorge Cano
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _Style_H_
#define _Style_H_
// Precompiled headers
#include "Cing-Precompiled.h"
#include "GraphicsPrereqs.h"
#include "Graphics/Color.h"
namespace Cing
{
/**
* @internal
*
*/
class Style
{
public:
// Constructor / Destructor
Style();
Style( Color fillColor, Color strokeColor, int strokeWeight );
Style( bool isStroke, bool isFill, Color fillColor, Color strokeColor, int strokeWeight );
~Style();
void init(){};
void end(){};
// Query methods
bool isValid () const { return m_bIsValid; }
// Styling properties
Color m_fillColor; ///< Color used to fill shapes
Color m_strokeColor; ///< Color used to draw shapes
int m_strokeWeight; ///< Width of the stroke used for draw lines, points, and the border around shapes
bool m_fill; ///< Indicates if the shape is filled or not
bool m_stroke; ///< Indicates if the border of the shape is draw or not
private:
bool m_bIsValid; ///< Indicates whether the class is valid or not. If invalid none of its methods except init should be called.
};
} // namespace Cing
#endif // _Style_H_
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
3,
4
],
[
6,
24
],
[
28,
30
],
[
32,
63
],
[
65,
66
]
],
[
[
2,
2
],
[
5,
5
],
[
25,
27
],
[
31,
31
],
[
64,
64
]
]
] |
487cfabc07e8a4dea06fc240240eba8d0626d22e | 5eb582292aeef7c56b13bc05accf71592d15931f | /source/PhysicWorld.cpp | da221664bdf67b71be40decc6bc6e5041110e8fb | [] | no_license | goebish/WiiBlob | 9316a56f2a60a506ecbd856ab7c521f906b961a1 | bef78fc2fdbe2d52749ed3bc965632dd699c2fea | refs/heads/master | 2020-05-26T12:19:40.164479 | 2010-09-05T18:09:07 | 2010-09-05T18:09:07 | 188,229,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,565 | cpp | /*=============================================================================
Blobby Volley 2
Copyright (C) 2006 Jonathan Sieber ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
=============================================================================*/
#include "PhysicWorld.h"
#include "raknet/BitStream.h"
const int TIMESTEP = 5; // calculations per frame default = 5 // goebish
const float TIMEOUT_MAX = 2.5;
// Blobby Settings
const float BLOBBY_HEIGHT = 89;
const float BLOBBY_WIDTH = 75;
const float BLOBBY_UPPER_SPHERE = 19;
const float BLOBBY_UPPER_RADIUS = 25;
const float BLOBBY_LOWER_SPHERE = 13;
const float BLOBBY_LOWER_RADIUS = 33;
// Volley Ball Net
const float NET_POSITION_X = 400;
const float NET_POSITION_Y = 438;
const float NET_RADIUS = 7;
const float NET_SPHERE = 154;
const float NET_SPHERE_POSITION = 284;
// Ball Settings
const float BALL_RADIUS = 31.5;
const float GROUND_PLANE_HEIGHT_MAX = 500;
const float GROUND_PLANE_HEIGHT = GROUND_PLANE_HEIGHT_MAX - BLOBBY_HEIGHT / 2.0;
// Boarder Settings
const float LEFT_PLANE = 0;
const float RIGHT_PLANE = 800.0;
// These numbers should include the blobbys width, but in the original game
// the blobbys can go a bit into the walls too.
// Gamefeeling relevant constants:
const float BLOBBY_ANIMATION_SPEED = 0.5;
const float BLOBBY_JUMP_ACCELERATION = 15.1;
// This is exactly the half of the gravitation, i checked it in
// the original code
const float BLOBBY_JUMP_BUFFER = 0.44;
const float GRAVITATION = 0.88;
const float BALL_GRAVITATION = 0.28;
const float STANDARD_BALL_ANGULAR_VELOCITY = 0.1;
const float STANDARD_BALL_HEIGHT = 269 + BALL_RADIUS;
const float BALL_COLLISION_VELOCITY = 13.125;
PhysicWorld::PhysicWorld()
{
reset(LEFT_PLAYER);
mCurrentBlobbyAnimationSpeed[LEFT_PLAYER] = 0.0;
mCurrentBlobbyAnimationSpeed[RIGHT_PLAYER] = 0.0;
mTimeSinceBallout = 0.0;
}
PhysicWorld::~PhysicWorld()
{
}
bool PhysicWorld::resetAreaClear()
{
if (blobbyHitGround(LEFT_PLAYER) && blobbyHitGround(RIGHT_PLAYER))
return true;
return false;
}
void PhysicWorld::reset(PlayerSide player)
{
if (player == LEFT_PLAYER)
mBallPosition = Vector2(200, STANDARD_BALL_HEIGHT);
else if (player == RIGHT_PLAYER)
mBallPosition = Vector2(600, STANDARD_BALL_HEIGHT);
else
mBallPosition = Vector2(400, 450);
mBallVelocity.clear();
mBallRotation = 0.0;
mBallAngularVelocity = STANDARD_BALL_ANGULAR_VELOCITY;
mBlobState[LEFT_PLAYER] = 0.0;
mBlobState[RIGHT_PLAYER] = 0.0;
mIsGameRunning = false;
mIsBallValid = true;
mLastHitIntensity = 0.0;
}
void PhysicWorld::resetPlayer()
{
mBlobPosition[LEFT_PLAYER] = Vector2( 200,
GROUND_PLANE_HEIGHT + BLOBBY_HEIGHT / 2.0);
mBlobPosition[RIGHT_PLAYER] = Vector2(600,
GROUND_PLANE_HEIGHT + BLOBBY_HEIGHT / 2.0);
}
bool PhysicWorld::ballHitRightGround()
{
if (mIsBallValid)
if (mBallPosition.y > GROUND_PLANE_HEIGHT &&
mBallPosition.x > NET_POSITION_X)
return true;
return false;
}
bool PhysicWorld::ballHitLeftGround()
{
if (mIsBallValid)
if (mBallPosition.y > GROUND_PLANE_HEIGHT &&
mBallPosition.x < NET_POSITION_X)
return true;
return false;
}
bool PhysicWorld::blobbyHitGround(PlayerSide player)
{
if (player == 0)
{
if (getBlob(LEFT_PLAYER).y >= GROUND_PLANE_HEIGHT)
return true;
else
return false;
}
else if (player == 1)
{
if (getBlob(RIGHT_PLAYER).y >= GROUND_PLANE_HEIGHT)
return true;
else
return false;
}
else
return false;
}
void PhysicWorld::setBallValidity(bool validity)
{
mIsBallValid = validity;
}
bool PhysicWorld::roundFinished()
{
if (resetAreaClear())
{
if (!mIsBallValid)
if (mBallVelocity.y < 1.5 &&
mBallVelocity.y > -1.5 && mBallPosition.y > 430)
return true;
}
if (mTimeSinceBallout > TIMEOUT_MAX)
return true;
return false;
}
float PhysicWorld::lastHitIntensity()
{
float intensity = mLastHitIntensity / 25.0;
return intensity < 1.0 ? intensity : 1.0;
}
bool PhysicWorld::playerTopBallCollision(int player)
{
if (Vector2(mBallPosition,
Vector2(mBlobPosition[player].x,
mBlobPosition[player].y - BLOBBY_UPPER_SPHERE)
).length() <= BALL_RADIUS + BLOBBY_UPPER_RADIUS)
return true;
return false;
}
inline bool PhysicWorld::playerBottomBallCollision(int player)
{
if (Vector2(mBallPosition,
Vector2(mBlobPosition[player].x,
mBlobPosition[player].y + BLOBBY_LOWER_SPHERE)
).length() <= BALL_RADIUS + BLOBBY_LOWER_RADIUS)
return true;
return false;
}
bool PhysicWorld::ballHitLeftPlayer()
{
return mBallHitByBlob[LEFT_PLAYER];
}
bool PhysicWorld::ballHitRightPlayer()
{
return mBallHitByBlob[RIGHT_PLAYER];
}
Vector2 PhysicWorld::getBall()
{
return mBallPosition;
}
float PhysicWorld::getBallRotation()
{
return mBallRotation;
}
float PhysicWorld::getBallSpeed()
{
return mBallVelocity.length();
}
Vector2 PhysicWorld::getBlob(PlayerSide player)
{
return mBlobPosition[player];
}
float PhysicWorld::getBlobState(PlayerSide player)
{
return mBlobState[player];
}
void PhysicWorld::setLeftInput(const PlayerInput& input)
{
mPlayerInput[LEFT_PLAYER] = input;
}
void PhysicWorld::setRightInput(const PlayerInput& input)
{
mPlayerInput[RIGHT_PLAYER] = input;
}
// Blobby animation methods
void PhysicWorld::blobbyAnimationStep(PlayerSide player)
{
if (mBlobState[player] < 0.0)
{
mCurrentBlobbyAnimationSpeed[player] = 0;
mBlobState[player] = 0;
}
if (mBlobState[player] >= 4.5)
{
mCurrentBlobbyAnimationSpeed[player]
=- BLOBBY_ANIMATION_SPEED;
}
mBlobState[player] += mCurrentBlobbyAnimationSpeed[player];
if (mBlobState[player] >= 5)
{
mBlobState[player] = 4.99;
}
}
void PhysicWorld::blobbyStartAnimation(PlayerSide player)
{
if (mCurrentBlobbyAnimationSpeed[player] == 0)
mCurrentBlobbyAnimationSpeed[player] =
BLOBBY_ANIMATION_SPEED;
}
void PhysicWorld::handleBlob(PlayerSide player)
{
// Reset ball to blobby collision
mBallHitByBlob[player] = false;
if (mPlayerInput[player].up)
{
if (blobbyHitGround(player))
{
mBlobVelocity[player].y = -BLOBBY_JUMP_ACCELERATION;
blobbyStartAnimation(PlayerSide(player));
}
mBlobVelocity[player].y -= BLOBBY_JUMP_BUFFER;
}
if ((mPlayerInput[player].left || mPlayerInput[player].right)
&& blobbyHitGround(player))
{
blobbyStartAnimation(player);
}
mBlobVelocity[player].x =
(mPlayerInput[player].right ? BLOBBY_SPEED : 0) -
(mPlayerInput[player].left ? BLOBBY_SPEED : 0);
// Acceleration Integration
mBlobVelocity[player].y += GRAVITATION;
// Compute new position
mBlobPosition[player] += mBlobVelocity[player];
if (mBlobPosition[player].y > GROUND_PLANE_HEIGHT)
{
if(mBlobVelocity[player].y > 3.5)
{
blobbyStartAnimation(player);
}
mBlobPosition[player].y = GROUND_PLANE_HEIGHT;
mBlobVelocity[player].y = 0.0;
}
blobbyAnimationStep(player);
}
void PhysicWorld::checkBlobbyBallCollision(PlayerSide player)
{
// Check for bottom circles
if(playerBottomBallCollision(player))
{
mLastHitIntensity = Vector2(mBallVelocity, mBlobVelocity[player]).length();
const Vector2& blobpos = mBlobPosition[player];
const Vector2 circlepos = Vector2(blobpos.x, blobpos.y + BLOBBY_LOWER_SPHERE);
mBallVelocity = -Vector2(mBallPosition, circlepos);
mBallVelocity = mBallVelocity.normalise();
mBallVelocity = mBallVelocity.scale(BALL_COLLISION_VELOCITY);
mBallPosition += mBallVelocity;
mBallHitByBlob[player] = true;
}
else if(playerTopBallCollision(player))
{
mLastHitIntensity = Vector2(mBallVelocity, mBlobVelocity[player]).length();
const Vector2& blobpos = mBlobPosition[player];
const Vector2 circlepos = Vector2(blobpos.x, blobpos.y - BLOBBY_UPPER_SPHERE);
mBallVelocity = -Vector2(mBallPosition, circlepos);
mBallVelocity = mBallVelocity.normalise();
mBallVelocity = mBallVelocity.scale(BALL_COLLISION_VELOCITY);
mBallPosition += mBallVelocity;
mBallHitByBlob[player] = true;
}
}
void PhysicWorld::step()
{
// Determistic IEEE 754 floating point computations
set_fpu_single_precision();
// Compute independent actions
handleBlob(LEFT_PLAYER);
handleBlob(RIGHT_PLAYER);
// Ball Gravitation
if (mIsGameRunning)
mBallVelocity.y += BALL_GRAVITATION;
// move ball
mBallPosition += mBallVelocity;
// Collision detection
if(mIsBallValid)
{
checkBlobbyBallCollision(LEFT_PLAYER);
checkBlobbyBallCollision(RIGHT_PLAYER);
}
// Ball to ground Collision
else if (mBallPosition.y + BALL_RADIUS > 500.0)
{
mBallVelocity = mBallVelocity.reflectY().scaleY(0.5);
mBallVelocity = mBallVelocity.scaleX(0.55);
mBallPosition.y = 500 - BALL_RADIUS;
}
if (ballHitLeftPlayer() || ballHitRightPlayer())
mIsGameRunning = true;
// Border Collision
if (mBallPosition.x - BALL_RADIUS <= LEFT_PLANE && mBallVelocity.x < 0.0)
{
mBallVelocity = mBallVelocity.reflectX();
}
else if (mBallPosition.x + BALL_RADIUS >= RIGHT_PLANE && mBallVelocity.x > 0.0)
{
mBallVelocity = mBallVelocity.reflectX();
}
else if (mBallPosition.y > NET_SPHERE_POSITION &&
fabs(mBallPosition.x - NET_POSITION_X) < BALL_RADIUS + NET_RADIUS)
{
mBallVelocity = mBallVelocity.reflectX();
mBallPosition += mBallVelocity;
}
else
{
// Net Collisions
float ballNetDistance = Vector2(mBallPosition, Vector2(NET_POSITION_X, NET_SPHERE_POSITION)).length();
if (ballNetDistance < NET_RADIUS + BALL_RADIUS)
{
mBallVelocity = mBallVelocity.reflect(Vector2(mBallPosition,
Vector2(NET_POSITION_X, NET_SPHERE_POSITION))
.normalise()).scale(0.75);
while (ballNetDistance < NET_RADIUS + BALL_RADIUS)
{
mBallPosition += mBallVelocity;
ballNetDistance = Vector2(mBallPosition, Vector2(NET_POSITION_X, NET_SPHERE_POSITION)).length();
}
}
// mBallVelocity = mBallVelocity.reflect( Vector2( mBallPosition, Vector2 (NET_POSITION_X, temp) ).normalise()).scale(0.75);
}
// Collision between blobby and the net
if (mBlobPosition[LEFT_PLAYER].x+BLOBBY_LOWER_RADIUS>NET_POSITION_X-NET_RADIUS) // Collision with the net
mBlobPosition[LEFT_PLAYER].x=NET_POSITION_X-NET_RADIUS-BLOBBY_LOWER_RADIUS;
if (mBlobPosition[RIGHT_PLAYER].x-BLOBBY_LOWER_RADIUS<NET_POSITION_X+NET_RADIUS)
mBlobPosition[RIGHT_PLAYER].x=NET_POSITION_X+NET_RADIUS+BLOBBY_LOWER_RADIUS;
// Collision between blobby and the border
if (mBlobPosition[LEFT_PLAYER].x < LEFT_PLANE)
mBlobPosition[LEFT_PLAYER].x=LEFT_PLANE;
if (mBlobPosition[RIGHT_PLAYER].x > RIGHT_PLANE)
mBlobPosition[RIGHT_PLAYER].x=RIGHT_PLANE;
// Velocity Integration
if (mBallVelocity.x > 0.0)
mBallRotation += mBallAngularVelocity * (getBallSpeed() / 6);
else if (mBallVelocity.x < 0.0)
mBallRotation -= mBallAngularVelocity * (getBallSpeed() / 6);
else
mBallRotation -= mBallAngularVelocity;
// Overflow-Protection
if (mBallRotation <= 0)
mBallRotation = 6.25 + mBallRotation;
else if (mBallRotation >= 6.25)
mBallRotation = mBallRotation - 6.25;
mTimeSinceBallout = mIsBallValid ? 0.0 :
mTimeSinceBallout + 1.0 / 60;
}
void PhysicWorld::dampBall()
{
mBallVelocity = mBallVelocity.scale(0.6);
}
Vector2 PhysicWorld::getBallVelocity()
{
return mBallVelocity;
}
bool PhysicWorld::getBlobJump(PlayerSide player)
{
return !blobbyHitGround(player);
}
float PhysicWorld::estimateBallImpact()
{
float steps;
steps = (mBallVelocity.y - sqrt((mBallVelocity.y * mBallVelocity.y)-
(-2 * BALL_GRAVITATION * (-mBallPosition.y + GROUND_PLANE_HEIGHT_MAX + BALL_RADIUS)))) / (-BALL_GRAVITATION);
return (mBallVelocity.x * steps) + mBallPosition.x;
}
Vector2 PhysicWorld::estimateBallPosition(int steps)
{
Vector2 ret;
ret.x = mBallVelocity.x * float(steps);
ret.y = (mBallVelocity.y + 0.5 * (BALL_GRAVITATION * float(steps))) * float(steps);
return mBallPosition + ret;
}
bool PhysicWorld::getBallActive()
{
return mIsGameRunning;
}
void PhysicWorld::setState(RakNet::BitStream* stream)
{
stream->Read(mBlobPosition[LEFT_PLAYER].x);
stream->Read(mBlobPosition[LEFT_PLAYER].y);
stream->Read(mBlobPosition[RIGHT_PLAYER].x);
stream->Read(mBlobPosition[RIGHT_PLAYER].y);
stream->Read(mBallPosition.x);
stream->Read(mBallPosition.y);
stream->Read(mBlobVelocity[LEFT_PLAYER].x);
stream->Read(mBlobVelocity[LEFT_PLAYER].y);
stream->Read(mBlobVelocity[RIGHT_PLAYER].x);
stream->Read(mBlobVelocity[RIGHT_PLAYER].y);
stream->Read(mBallVelocity.x);
stream->Read(mBallVelocity.y);
stream->Read(mPlayerInput[LEFT_PLAYER].left);
stream->Read(mPlayerInput[LEFT_PLAYER].right);
stream->Read(mPlayerInput[LEFT_PLAYER].up);
stream->Read(mPlayerInput[RIGHT_PLAYER].left);
stream->Read(mPlayerInput[RIGHT_PLAYER].right);
stream->Read(mPlayerInput[RIGHT_PLAYER].up);
}
void PhysicWorld::getState(RakNet::BitStream* stream)
{
stream->Write(mBlobPosition[LEFT_PLAYER].x);
stream->Write(mBlobPosition[LEFT_PLAYER].y);
stream->Write(mBlobPosition[RIGHT_PLAYER].x);
stream->Write(mBlobPosition[RIGHT_PLAYER].y);
stream->Write(mBallPosition.x);
stream->Write(mBallPosition.y);
stream->Write(mBlobVelocity[LEFT_PLAYER].x);
stream->Write(mBlobVelocity[LEFT_PLAYER].y);
stream->Write(mBlobVelocity[RIGHT_PLAYER].x);
stream->Write(mBlobVelocity[RIGHT_PLAYER].y);
stream->Write(mBallVelocity.x);
stream->Write(mBallVelocity.y);
stream->Write(mPlayerInput[LEFT_PLAYER].left);
stream->Write(mPlayerInput[LEFT_PLAYER].right);
stream->Write(mPlayerInput[LEFT_PLAYER].up);
stream->Write(mPlayerInput[RIGHT_PLAYER].left);
stream->Write(mPlayerInput[RIGHT_PLAYER].right);
stream->Write(mPlayerInput[RIGHT_PLAYER].up);
}
void PhysicWorld::getSwappedState(RakNet::BitStream* stream)
{
stream->Write(800 - mBlobPosition[RIGHT_PLAYER].x);
stream->Write(mBlobPosition[RIGHT_PLAYER].y);
stream->Write(800 - mBlobPosition[LEFT_PLAYER].x);
stream->Write(mBlobPosition[LEFT_PLAYER].y);
stream->Write(800 - mBallPosition.x);
stream->Write(mBallPosition.y);
stream->Write(-mBlobVelocity[RIGHT_PLAYER].x);
stream->Write(mBlobVelocity[RIGHT_PLAYER].y);
stream->Write(-mBlobVelocity[LEFT_PLAYER].x);
stream->Write(mBlobVelocity[LEFT_PLAYER].y);
stream->Write(-mBallVelocity.x);
stream->Write(mBallVelocity.y);
stream->Write(mPlayerInput[RIGHT_PLAYER].right);
stream->Write(mPlayerInput[RIGHT_PLAYER].left);
stream->Write(mPlayerInput[RIGHT_PLAYER].up);
stream->Write(mPlayerInput[LEFT_PLAYER].right);
stream->Write(mPlayerInput[LEFT_PLAYER].left);
stream->Write(mPlayerInput[LEFT_PLAYER].up);
}
const PlayerInput* PhysicWorld::getPlayersInput()
{
return mPlayerInput;
}
| [
"[email protected]"
] | [
[
[
1,
565
]
]
] |
02ae1bd51ce84fdaf79dd257937dd606d4812fe4 | 7f4230cae41e0712d5942960674bfafe4cccd1f1 | /code/BlenderLoader.h | 001e4200f89362c67e708c77843a63a32630cb17 | [
"BSD-3-Clause"
] | permissive | tonttu/assimp | c6941538b3b3c3d66652423415dea098be21f37a | 320a7a7a7e0422e4d8d9c2a22b74cb48f74b14ce | refs/heads/master | 2021-01-16T19:56:09.309754 | 2011-06-07T20:00:41 | 2011-06-07T20:00:41 | 1,295,427 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,823 | h | /*
Open Asset Import Library (ASSIMP)
----------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file BlenderLoader.h
* @brief Declaration of the Blender 3D (*.blend) importer class.
*/
#ifndef INCLUDED_AI_BLEND_LOADER_H
#define INCLUDED_AI_BLEND_LOADER_H
#include "BaseImporter.h"
#include "LogAux.h"
namespace Assimp {
// TinyFormatter.h
namespace Formatter {
template <typename T,typename TR, typename A> class basic_formatter;
typedef class basic_formatter< char, std::char_traits<char>, std::allocator<char> > format;
}
// BlenderDNA.h
namespace Blender {
class FileDatabase;
struct ElemBase;
}
// BlenderScene.h
namespace Blender {
struct Scene;
struct Object;
struct Mesh;
struct Camera;
struct Lamp;
struct MTex;
struct Image;
struct Material;
}
// BlenderIntermediate.h
namespace Blender {
struct ConversionData;
template <template <typename,typename> class TCLASS, typename T> struct TempArray;
}
// BlenderModifier.h
namespace Blender {
class BlenderModifierShowcase;
class BlenderModifier;
}
enum aiLoaderFlags
{
aiLoaderFlags_SupportAsciiFlavour = 0x1,
aiLoaderFlags_SupportBinaryFlavour = 0x2,
aiLoaderFlags_SupportCompressedFlavour = 0x4,
aiLoaderFlags_LimitedSupport = 0x8,
aiLoaderFlags_Experimental = 0x10,
aiLoaderFlags_Testing = 0x20,
aiLoaderFlags_Production = 0x40,
};
struct aiLoaderDesc
{
const char* mName;
const char* mAuthor;
const char* mMaintainer;
const char* mComments;
unsigned int mFlags;
unsigned int mMinMajor;
unsigned int mMinMinor;
unsigned int mMaxMajor;
unsigned int mMaxMinor;
};
// -------------------------------------------------------------------------------------------
/** Load blenders official binary format. The actual file structure (the `DNA` how they
* call it is outsourced to BlenderDNA.cpp/BlenderDNA.h. This class only performs the
* conversion from intermediate format to aiScene. */
// -------------------------------------------------------------------------------------------
class BlenderImporter : public BaseImporter, public LogFunctions<BlenderImporter>
{
friend class Importer;
protected:
/** Constructor to be privately used by Importer */
BlenderImporter();
/** Destructor, private as well */
~BlenderImporter();
public:
// --------------------
bool CanRead( const std::string& pFile,
IOSystem* pIOHandler,
bool checkSig
) const;
protected:
// --------------------
const aiLoaderDesc& GetInfo () const;
// --------------------
void GetExtensionList(std::set<std::string>& app);
// --------------------
void SetupProperties(const Importer* pImp);
// --------------------
void InternReadFile( const std::string& pFile,
aiScene* pScene,
IOSystem* pIOHandler
);
// --------------------
void ParseBlendFile(Blender::FileDatabase& out,
boost::shared_ptr<IOStream> stream
);
// --------------------
void ExtractScene(Blender::Scene& out,
const Blender::FileDatabase& file
);
// --------------------
void ConvertBlendFile(aiScene* out,
const Blender::Scene& in,
const Blender::FileDatabase& file
);
private:
// --------------------
aiNode* ConvertNode(const Blender::Scene& in,
const Blender::Object* obj,
Blender::ConversionData& conv_info
);
// --------------------
void ConvertMesh(const Blender::Scene& in,
const Blender::Object* obj,
const Blender::Mesh* mesh,
Blender::ConversionData& conv_data,
Blender::TempArray<std::vector,aiMesh>& temp
);
// --------------------
aiLight* ConvertLight(const Blender::Scene& in,
const Blender::Object* obj,
const Blender::Lamp* mesh,
Blender::ConversionData& conv_data
);
// --------------------
aiCamera* ConvertCamera(const Blender::Scene& in,
const Blender::Object* obj,
const Blender::Camera* mesh,
Blender::ConversionData& conv_data
);
// --------------------
void BuildMaterials(
Blender::ConversionData& conv_data
) ;
// --------------------
void ResolveTexture(
MaterialHelper* out,
const Blender::Material* mat,
const Blender::MTex* tex,
Blender::ConversionData& conv_data
);
// --------------------
void ResolveImage(
MaterialHelper* out,
const Blender::Material* mat,
const Blender::MTex* tex,
const Blender::Image* img,
Blender::ConversionData& conv_data
);
void AddSentinelTexture(
MaterialHelper* out,
const Blender::Material* mat,
const Blender::MTex* tex,
Blender::ConversionData& conv_data
);
private: // static stuff, mostly logging and error reporting.
// --------------------
static void CheckActualType(const Blender::ElemBase* dt,
const char* check
);
// --------------------
static void NotSupportedObjectType(const Blender::Object* obj,
const char* type
);
private:
Blender::BlenderModifierShowcase* modifier_cache;
}; // !class BlenderImporter
} // end of namespace Assimp
#endif // AI_UNREALIMPORTER_H_INC
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
] | [
[
[
1,
253
]
]
] |
faba22f91c84ff95262562f68e55eb50b74a20a9 | 2a88336c57ecb9bd5a4d7a245205aef3209bc7d1 | /Lab1/Sources/lcd.inc | b1379e33ead2e6a82e41d9b61a6e67face02d838 | [] | no_license | zdraw/ee445l-labs | 53b0b75db48a31d79206171e97e69adf18312e55 | 89e7cce132cb35642e096c90234d02c9c12938c8 | refs/heads/master | 2020-06-02T04:30:58.864893 | 2011-03-12T05:04:37 | 2011-03-12T05:04:37 | 32,494,293 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | inc |
; ANSI-C/cC++ Compiler for HC12 V-5.0.35 Build 8093, Apr 3 2008
;
; Automatic generated include file for the assembler
; Generated using the following files :
; file :'D:\EE345L\9S12DP512\LCD_DP512\Sources\lcd.c'
; file :'C:\Program Files\Freescale\CodeWarrior for HCS12 V4.7\lib\HC12c\include\mc9s12dp512.h'
; file :'D:\EE345L\9S12DP512\LCD_DP512\Sources\LCD.H'
;
| [
"hall.c.stephen@0ddc7feb-e18c-b16c-be8a-5ee3ccc2ec1a"
] | [
[
[
1,
9
]
]
] |
b84bac6e104ae55a2764a5a9118ae76689e6d47f | a2ba072a87ab830f5343022ed11b4ac365f58ef0 | / urt-bumpy-q3map2 --username [email protected]/libs/script/scripttokenwriter.h | d49409a7bc4fb1d8a5686bf10138d7e9e33e2f27 | [] | no_license | Garey27/urt-bumpy-q3map2 | 7d0849fc8eb333d9007213b641138e8517aa092a | fcc567a04facada74f60306c01e68f410cb5a111 | refs/heads/master | 2021-01-10T17:24:51.991794 | 2010-06-22T13:19:24 | 2010-06-22T13:19:24 | 43,057,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,296 | h |
#if !defined(INCLUDED_SCRIPT_SCRIPTTOKENWRITER_H)
#define INCLUDED_SCRIPT_SCRIPTTOKENWRITER_H
#include "iscriplib.h"
class SimpleTokenWriter : public TokenWriter
{
public:
SimpleTokenWriter(TextOutputStream& ostream)
: m_ostream(ostream), m_separator('\n')
{
}
~SimpleTokenWriter()
{
writeSeparator();
}
void release()
{
delete this;
}
void nextLine()
{
m_separator = '\n';
}
void writeToken(const char* token)
{
ASSERT_MESSAGE(strchr(token, ' ') == 0, "token contains whitespace: ");
writeSeparator();
m_ostream << token;
}
void writeString(const char* string)
{
writeSeparator();
m_ostream << '"' << string << '"';
}
void writeInteger(int i)
{
writeSeparator();
m_ostream << i;
}
void writeUnsigned(std::size_t i)
{
writeSeparator();
m_ostream << Unsigned(i);
}
void writeFloat(double f)
{
writeSeparator();
m_ostream << Decimal(f);
}
private:
void writeSeparator()
{
m_ostream << m_separator;
m_separator = ' ';
}
TextOutputStream& m_ostream;
char m_separator;
};
inline TokenWriter& NewSimpleTokenWriter(TextOutputStream& ostream)
{
return *(new SimpleTokenWriter(ostream));
}
#endif
| [
"[email protected]"
] | [
[
[
1,
68
]
]
] |
0d40a8df9ac78e5aaadf6b7be3f7bf8ff1b276a0 | 102d8810abb4d1c8aecb454304ec564030bf2f64 | /TP3/Tanque/Tanque/Tanque/BattleCityEngine.cpp | d47a8e5a4bf2e0c02d04b42674ded98ae8b25f63 | [] | no_license | jfacorro/tp-taller-prog-1-fiuba | 2742d775b917cc6df28188ecc1f671d812017a0a | a1c95914c3be6b1de56d828ea9ff03e982560526 | refs/heads/master | 2016-09-14T04:32:49.047792 | 2008-07-15T20:17:27 | 2008-07-15T20:17:27 | 56,912,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,874 | cpp | #ifndef BattleCityEngine_cpp
#define BattleCityEngine_cpp
#include "BattleCityEngine.h"
#include "StringHelper.h"
BattleCityClientParameters GetBattleCityClientParameters(BattleCityParameters params)
{
BattleCityClientParameters clientParameters;
clientParameters.ArenaHeight = params.ArenaHeight;
clientParameters.ArenaWidth = params.ArenaWidth;
clientParameters.BombBlastDelay = params.BombBlastDelay;
clientParameters.BombBlastRadius = params.BombBlastRadius;
clientParameters.BombDelay = params.BombDelay;
clientParameters.BombRadius = params.BombRadius;
clientParameters.PixelsPerUM = params.PixelsPerUM;
StringHelper::Copy(params.BackGroundTextureId, clientParameters.BackGroundTextureId, strlen(params.BackGroundTextureId));
StringHelper::Copy(params.ExplosionTextureId, clientParameters.ExplosionTextureId, strlen(params.ExplosionTextureId));
clientParameters.BulletRadius = params.BulletRadius;
clientParameters.BulletScope = params.BulletScope;
clientParameters.BulletSpeed = params.BulletSpeed;
clientParameters.MaxBombs = params.MaxBombs;
clientParameters.MaxBullets = params.MaxBullets;
clientParameters.TankRadius = params.TankRadius;
return clientParameters;
}
BattleCityEngine::BattleCityEngine(BattleCityParameters parameters) : parameters(parameters)
{
if ( parameters.ArenaWidth == 0 || parameters.ArenaHeight == 0 )
throw exception("BattleCityEngine::BattleCityEngine Invalid parameters");
}
BattleCityEngine::~BattleCityEngine()
{
}
bool BattleCityEngine::GetDirty()
{
return dirty;
}
bool BattleCityEngine::GetFinished()
{
return finished;
}
BattleCityState BattleCityEngine::GetState()
{
BattleCityState retval;
retval.Tanks.assign(tanks.begin(),tanks.end());
retval.Bombs.assign(bombs.begin(),bombs.end());
retval.Bullets.assign(bullets.begin(),bullets.end());
retval.Walls.assign(walls.begin(),walls.end());
return retval;
}
void BattleCityEngine::Start()
{
for ( int i = 0 ; i < tanks.size() ; i++ )
parameters.Tanks[i].Points = tanks[i].Points;
tanks.assign(parameters.Tanks.begin(),parameters.Tanks.end());
walls.assign(parameters.Walls.begin(),parameters.Walls.end());
dirty = true;
finished = false;
#ifdef BATTLECITYENGINE_WALL_TEST
for ( unsigned int j = 0 ; j < parameters.Walls.size() ; j++ )
for ( unsigned int k = j + 1 ; k < parameters.Walls.size() ; k++ )
if ( parameters.Walls[j].Intersects(parameters.Walls[k]) )
throw exception ( "BattleCityEngine::BattleCityEngine Intersecting wall found" );
#endif
nextTick = GetTickCount();
UpdateNextTick();
}
void BattleCityEngine::UpdateBombs()
{
vector<BattleCityBomb> toDie;
for ( int i = 0 ; i < bombs.size() ; i++ )
{
bombs[i].TimeToDie -= (nextTick - lastTick);
if ( bombs[i].TimeToDie < - (int) parameters.BombBlastDelay )
{
toDie.push_back(bombs[i]);
dirty = true;
}
else if ( bombs[i].TimeToDie <= 0 && (bombs[i].TimeToDie + (int) nextTick - (int) lastTick) > 0)
{
dirty = true;
unsigned int j = 0;
for ( j = 0 ; j < tanks.size() ; j++ )
{
if (tanks[j].Intersects(bombs[i].GetExplodedRect()) && tanks[j].Life > 0)
{
HitTank(j, BATTLE_CITY_BOMB_HIT_ENERGY);
BattleCityTank hittedTank = tanks[j];
if((hittedTank.Life <= 0 || hittedTank.Life > parameters.Tanks[j].Life) && (j != bombs[i].Tank))
{
tanks[bombs[i].Tank].Points += BATTLE_CITY_POINTS_TANK;
}
}
}
for ( j = 0 ; j < walls.size() ; j++ )
{
if ( walls[j].Intersects(bombs[i].GetExplodedRect()))
{
if ( walls[j].Blast() <= 0 )
{
switch(walls[j].GetType())
{
case WOOD:
tanks[bombs[i].Tank].Points += BATTLE_CITY_POINTS_WOOD;
break;
case ROCK:
tanks[bombs[i].Tank].Points += BATTLE_CITY_POINTS_ROCK;
break;
}
walls.erase(walls.begin()+j);
j--;
}
}
}
}
}
if ( !toDie.empty() )
{
for ( int y = 0 ; y < toDie.size() ; y++ )
{
for ( int iterToDie = 0 ; iterToDie < bombs.size() ; iterToDie++ )
{
if ( bombs[y].Pos.X == toDie[y].Pos.X && bombs[iterToDie].Pos.Y == toDie[y].Pos.Y )
{
bombs.erase(bombs.begin() + iterToDie);
break;
}
}
}
}
}
void BattleCityEngine::UpdateNextTick()
{
lastTick = nextTick;
/*
double max = parameters.BulletSpeed;
for ( unsigned int i = 0 ; i < parameters.Tanks.size() ; i++ )
if ( parameters.Tanks[i].Speed > max )
max = parameters.Tanks[i].Speed;
nextTick += (int) (1000.0 / max);
*/
nextTick += (int) (1000.0 / FRAMES_PER_SECOND);
}
void BattleCityEngine::HitTank(unsigned int tank, int decrementedEnergy)
{
if ( tanks[tank].Life > 0 )
{
tanks[tank].Life -= decrementedEnergy;
}
else
{
}
if ( tanks[tank].Life > parameters.Tanks[tank].Life )
tanks[tank].Life = 0;
if ( tanks[tank].Life <= 0 || tanks[tank].Life > parameters.Tanks[tank].Life )
finished = true;
}
bool BattleCityEngine::FindTankCollition(unsigned int tank, int x, int y)
{
BattleCityTank nextPosTank(2 * this->parameters.TankRadius);
nextPosTank.Pos.X = x;
nextPosTank.Pos.Y = y;
for ( unsigned int i = 0 ; i < tanks.size() ; i++ )
if ( i != tank )
if ( nextPosTank.Intersects(tanks[i]) )
return true;
for ( unsigned int j = 0 ; j < walls.size() ; j++ )
if ( walls[j].Intersects(nextPosTank) )
return true;
if
(
nextPosTank.GetRect().X < 0 ||
nextPosTank.GetRect().Y < 0 ||
nextPosTank.GetRect().X > this->parameters.ArenaWidth - nextPosTank.GetRect().Width ||
nextPosTank.GetRect().Y > this->parameters.ArenaHeight - nextPosTank.GetRect().Height
)
{
return true;
}
return false;
}
void BattleCityEngine::UpdateTankPos(unsigned int tank,double nextX,double nextY)
{
if ( FindTankCollition(tank,(int)nextX,(int)nextY) )
tanks[tank].Speed = 0;
else
{
tanks[tank].Pos.X = nextX;
tanks[tank].Pos.Y = nextY;
dirty = true;
}
}
bool BattleCityEngine::UpdateBulletPos(unsigned int bullet,double currentX,double currentY,double nextX,double nextY,bool check)
{
bool hit = false;
BattleCityBullet currentBullet = bullets[bullet];
Rect currentRect = currentBullet.GetRect();
Rect nextRect = currentBullet.GetRect();
nextRect.X = nextX;
nextRect.Y = nextY;
if ( currentX < nextX )
{
nextRect.X = currentX;
nextRect.Width += (nextX - currentX);
}
else
{
nextRect.X = nextX;
nextRect.Width += (currentX - nextX);
}
if ( currentY < nextY )
{
nextRect.Y = currentY;
nextRect.Height += (nextY - currentY);
}
else
{
nextRect.Y = nextY;
nextRect.Height += (currentY - nextY);
}
for ( unsigned int i = 0 ; i < tanks.size() && !hit ; i++ )
{
if (tanks[i].Intersects(currentRect) && tanks[i].Intersects(nextRect) && tanks[i].Life > 0)
{
if ( !check && bullets[bullet].Tank == i )
{
}
else
{
HitTank(i, BATTLE_CITY_BULLET_HIT_ENERGY);
BattleCityTank hittedTank = tanks[i];
if((hittedTank.Life <= 0) && (i != bullets[bullet].Tank))
{
tanks[bullets[bullet].Tank].Points += BATTLE_CITY_POINTS_TANK;
}
hit = true;
}
}
}
/*
for ( unsigned int j = 0 ; j < walls.size() && !hit ; j++ )
{
if ( walls[j].GetType() == IRON )
{
switch(bullets[bullet].Direction)
{
case LEFT:
bullets[bullet].Direction = RIGHT;
break;
case RIGHT:
bullets[bullet].Direction = LEFT;
break;
case UP:
bullets[bullet].Direction = DOWN;
break;
case DOWN:
bullets[bullet].Direction = UP;
break;
}
}
else
{
if ( walls[j].Intersects(nextRect))
{
hit = true;
if ( walls[j].Shoot() <= 0 )
{
switch(walls[j].GetType())
{
case WOOD:
tanks[bullets[bullet].Tank].Points += BATTLE_CITY_POINTS_WOOD;
break;
case ROCK:
tanks[bullets[bullet].Tank].Points += BATTLE_CITY_POINTS_ROCK;
break;
}
walls.erase(walls.begin() + j);
j--;
}
}
}
}
*/
if ( !hit )
{
for ( unsigned int j = 0 ; j < walls.size() && !hit ; j++ )
{
if ( walls[j].Intersects(nextRect))
{
if ( walls[j].GetType() == IRON )
{
switch(bullets[bullet].Direction)
{
case LEFT:
bullets[bullet].Direction = RIGHT;
break;
case RIGHT:
bullets[bullet].Direction = LEFT;
break;
case UP:
bullets[bullet].Direction = DOWN;
break;
case DOWN:
bullets[bullet].Direction = UP;
break;
}
nextX = currentX;
nextY = currentY;
}
else
{
hit = true;
if ( walls[j].Shoot() <= 0 )
{
switch(walls[j].GetType())
{
case WOOD:
tanks[bullets[bullet].Tank].Points += BATTLE_CITY_POINTS_WOOD;
break;
case ROCK:
tanks[bullets[bullet].Tank].Points += BATTLE_CITY_POINTS_ROCK;
break;
}
walls.erase(walls.begin() + j);
j--;
}
}
}
}
}
if ( !hit )
{
bullets[bullet].Pos.X = nextX;
bullets[bullet].Pos.Y = nextY;
if ( bullets[bullet].Pos.X < 0 || bullets[bullet].Pos.Y < 0 ||
bullets[bullet].Pos.X >= parameters.ArenaWidth ||
bullets[bullet].Pos.Y >= parameters.ArenaHeight
)
hit = true;
if ( (int) currentX != (int) nextX || (int) currentY != (int) nextY )
{
bullets[bullet].DistanceToDie -= abs((nextX - currentX) + (nextY - currentY));
if ( bullets[bullet].DistanceToDie <= 0 )
hit = true;
}
}
return hit;
}
void BattleCityEngine::Tick()
{
unsigned int i;
dirty = false;
double dt = (double) (nextTick - lastTick) / 1000.0;
/*
double dt = (double) (nextTick - lastTick) / 1000.0;
for ( i = 0 ; i < tanks.size() ; i++ )
{
if(tanks[i].Life > 0)
{
if ( tanks[i].Direction == LEFT )
UpdateTankPos ( i , tanks[i].Pos.X - dt * tanks[i].Speed , tanks[i].Pos.Y );
else if ( tanks[i].Direction == RIGHT )
UpdateTankPos ( i , tanks[i].Pos.X + dt * tanks[i].Speed , tanks[i].Pos.Y );
else if ( tanks[i].Direction == UP )
UpdateTankPos ( i , tanks[i].Pos.X , tanks[i].Pos.Y - dt * tanks[i].Speed );
else if ( tanks[i].Direction == DOWN )
UpdateTankPos ( i , tanks[i].Pos.X , tanks[i].Pos.Y + dt * tanks[i].Speed );
}
}
*/
list<unsigned long> bulletsToDie;
for ( i = 0 ; i < bullets.size() ; i++ )
{
bool toDie = false;
if ( bullets[i].Direction == LEFT )
toDie = UpdateBulletPos ( i , bullets[i].Pos.X , bullets[i].Pos.Y , bullets[i].Pos.X - dt * parameters.BulletSpeed , bullets[i].Pos.Y );
else if ( bullets[i].Direction == RIGHT )
toDie = UpdateBulletPos ( i , bullets[i].Pos.X , bullets[i].Pos.Y , bullets[i].Pos.X + dt * parameters.BulletSpeed , bullets[i].Pos.Y );
else if ( bullets[i].Direction == UP )
toDie = UpdateBulletPos ( i , bullets[i].Pos.X , bullets[i].Pos.Y , bullets[i].Pos.X , bullets[i].Pos.Y - dt * parameters.BulletSpeed );
else if ( bullets[i].Direction == DOWN )
toDie = UpdateBulletPos ( i , bullets[i].Pos.X , bullets[i].Pos.Y , bullets[i].Pos.X , bullets[i].Pos.Y + dt * parameters.BulletSpeed );
if ( toDie )
bulletsToDie.push_back(i);
}
unsigned int bulletsToDieCount = 0;
list<unsigned long>::iterator iter;
for ( iter = bulletsToDie.begin() ; iter != bulletsToDie.end() ; ++iter, bulletsToDieCount++ )
bullets.erase(bullets.begin() + *iter - bulletsToDieCount);
for ( i = 0 ; i < tanks.size() ; i++ )
{
if(tanks[i].Life > 0)
{
if ( tanks[i].Direction == LEFT )
UpdateTankPos ( i , tanks[i].Pos.X - dt * tanks[i].Speed , tanks[i].Pos.Y );
else if ( tanks[i].Direction == RIGHT )
UpdateTankPos ( i , tanks[i].Pos.X + dt * tanks[i].Speed , tanks[i].Pos.Y );
else if ( tanks[i].Direction == UP )
UpdateTankPos ( i , tanks[i].Pos.X , tanks[i].Pos.Y - dt * tanks[i].Speed );
else if ( tanks[i].Direction == DOWN )
UpdateTankPos ( i , tanks[i].Pos.X , tanks[i].Pos.Y + dt * tanks[i].Speed );
}
}
UpdateNextTick();
UpdateBombs();
}
int BattleCityEngine::GetNextTickInterval()
{
DWORD tmp = GetTickCount();
if ( tmp >= nextTick )
return 0;
else
return nextTick - tmp;
}
void BattleCityEngine::TurnTank(unsigned int tank,Direction direction)
{
if ( tank >= tanks.size() )
throw exception ( "BattleCityEngine::TurnTank Invalid direction" );
else
{
tanks[tank].Direction = direction;
tanks[tank].Speed = parameters.Tanks[tank].Speed;
}
}
bool BattleCityEngine::DropBomb(unsigned int tank)
{
bool hasBomb = false;
unsigned int bombCount = 0;
for (int iter = 0; iter < bombs.size() ; iter ++)
{
if ( bombs[iter].Tank == tank )
bombCount++;
if ( bombs[iter].Pos.X == (int) tanks[tank].Pos.X && bombs[iter].Pos.Y == (int) tanks[tank].Pos.Y )
hasBomb = true;
}
if ( bombCount >= parameters.MaxBombs || hasBomb )
return false;
BattleCityBomb b(this->parameters.BombRadius * 2, this->parameters.BombBlastRadius * 2);
b.Tank = tank;
b.TimeToDie = parameters.BombDelay;
DoublePoint p = tanks[tank].Pos;
b.Pos.X = (int) p.X;
b.Pos.Y = (int) p.Y;
bombs.push_back(b);
return true;
}
bool BattleCityEngine::ShootBullet(unsigned int tank)
{
unsigned int bulletCount = 0;
for ( unsigned int i = 0 ; i < bullets.size() ; i++ )
if ( bullets[i].Tank == tank )
bulletCount++;
if ( bulletCount >= parameters.MaxBullets )
return false;
BattleCityBullet b(this->parameters.BulletRadius * 2);
b.Tank = tank;
b.Pos.X = (int) tanks[tank].Pos.X;
b.Pos.Y = (int) tanks[tank].Pos.Y;
b.DistanceToDie = parameters.BulletScope;
b.Direction = tanks[tank].Direction;
bullets.push_back(b);
double nextX = b.Pos.X;
double nextY = b.Pos.Y;
switch(b.Direction)
{
case LEFT:
nextX -= this->parameters.TankRadius + b.GetRect().Width / 2 + 1;
break;
case RIGHT:
nextX += this->parameters.TankRadius + b.GetRect().Width / 2 + 1;
break;
case UP:
nextY -= this->parameters.TankRadius + b.GetRect().Height / 2 + 1;
break;
case DOWN:
nextY += this->parameters.TankRadius + b.GetRect().Height / 2 + 1;
break;
}
if ( UpdateBulletPos ( bullets.size() - 1 , b.Pos.X , b.Pos.Y , nextX , nextY , false ) )
bullets.pop_back();
//bullets.push_back(b);
return true;
}
#endif | [
"juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb",
"nahuelgonzalez@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb"
] | [
[
[
1,
47
],
[
53,
64
],
[
80,
102
],
[
104,
104
],
[
106,
106
],
[
108,
108
],
[
110,
158
],
[
168,
180
],
[
187,
568
]
],
[
[
48,
52
],
[
65,
79
],
[
103,
103
],
[
105,
105
],
[
107,
107
],
[
109,
109
],
[
159,
167
],
[
181,
186
]
]
] |
fbf3b572d7050eaeff17fc47769553fcd2608226 | 1092bd6dc9b728f3789ba96e37e51cdfb9e19301 | /loci/video/d3d9/managed_vertex_buffer.h | 934c225d4005cc5c8059378d345e17168493da8f | [] | no_license | dtbinh/loci-extended | 772239e63b4e3e94746db82d0e23a56d860b6f0d | f4b5ad6c4412e75324d19b71559a66dd20f4f23f | refs/heads/master | 2021-01-10T12:23:52.467480 | 2011-03-15T22:03:06 | 2011-03-15T22:03:06 | 36,032,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | h | #ifndef LOCI_VIDEO_D3D9_MANAGED_VERTEX_BUFFER_H_
#define LOCI_VIDEO_D3D9_MANAGED_VERTEX_BUFFER_H_
/**
* Encapsulates a d3d9 vertex buffer, providing RAII.
* Sets up a vertex buffer, allows binding of that buffer to the pipeline and
* provides RAII support to automatically release that buffer.
*
* @file managed_vertex_buffer.h
* @author David Gill
* @date 05/11/2009
*/
#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>
#include <d3d9.h>
namespace loci {
namespace video {
namespace d3d9
{
// forward declaration
class device_services;
class managed_vertex_buffer : boost::noncopyable
{
public:
managed_vertex_buffer(const boost::shared_ptr<device_services> & device,
unsigned int bytes);
~managed_vertex_buffer();
void update(const void * vertices, unsigned int bytes);
void bind(unsigned int stride, DWORD fvf);
private:
void map(void *& destination);
void unmap();
private:
boost::shared_ptr<device_services> device;
LPDIRECT3DVERTEXBUFFER9 buffer;
};
} // namespace d3d9
} // namespace video
} // namespace loci
#endif // LOCI_VIDEO_D3D9_MANAGED_VERTEX_BUFFER_H_ | [
"[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132"
] | [
[
[
1,
49
]
]
] |
c56d4b841dea8973e75aef449c5a85c62550cc10 | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /source/OECore/OESkeleton_Impl.cpp | c65f627b9eeaffdc35b0debd85c1314d10c986b2 | [] | no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,436 | cpp | /*!
* \file OESkeleton_Impl.cpp
* \date 1-3-2010 19:20:56
*
*
* \author zjhlogo ([email protected])
*/
#include "OESkeleton_Impl.h"
#include "OEBone_Impl.h"
#include <OEBase/IOEFileMgr.h>
#include <OECore/OEFmtSkeleton.h>
COESkeleton_Impl::COESkeleton_Impl(const tstring& strFile)
{
Init();
m_bOK = CreateBones(strFile);
}
COESkeleton_Impl::~COESkeleton_Impl()
{
Destroy();
}
void COESkeleton_Impl::Init()
{
// TODO:
}
void COESkeleton_Impl::Destroy()
{
DestroyBones();
}
int COESkeleton_Impl::GetBonesCount()
{
return (int)m_vBones.size();
}
IOEBone* COESkeleton_Impl::GetBone(int nIndex)
{
if (nIndex < 0 || nIndex >= (int)m_vBones.size()) return NULL;
return m_vBones[nIndex];
}
bool COESkeleton_Impl::CreateBones(const tstring& strFile)
{
DestroyBones();
IOEFile* pFile = g_pOEFileMgr->OpenFile(strFile);
if (!pFile) return false;
COEFmtSkeleton::FILE_HEADER Header;
pFile->Read(&Header, sizeof(Header));
if (Header.nMagicNumber != COEFmtSkeleton::MAGIC_NUMBER
|| Header.nVersion != COEFmtSkeleton::CURRENT_VERSION)
{
SAFE_RELEASE(pFile);
return false;
}
// read bone info
std::vector<COEFmtSkeleton::BONE> vBones;
if (Header.nNumBones > 0)
{
vBones.resize(Header.nNumBones);
pFile->Read(&vBones[0], sizeof(COEFmtSkeleton::BONE)*Header.nNumBones);
}
// create bones
for (int i = 0; i < Header.nNumBones; ++i)
{
COEBone_Impl* pBone = new COEBone_Impl(vBones[i], i, pFile);
if (!pBone || !pBone->IsOK())
{
SAFE_RELEASE(pFile);
DestroyBones();
return false;
}
m_vBones.push_back(pBone);
}
SAFE_RELEASE(pFile);
// build bone matrix
for (int i = 0; i < Header.nNumBones; ++i)
{
int nParentID = m_vBones[i]->GetParentID();
if (nParentID != COEFmtSkeleton::INVALID_BONE_ID)
{
COEBone_Impl* pCurrBone = (COEBone_Impl*)m_vBones[i];
COEBone_Impl* pParentBone = (COEBone_Impl*)m_vBones[nParentID];
pCurrBone->SetWorldMatrix(pCurrBone->GetLocalMatrix() * pParentBone->GetWorldMatrix());
}
else
{
COEBone_Impl* pCurrBone = (COEBone_Impl*)m_vBones[i];
pCurrBone->SetWorldMatrix(pCurrBone->GetLocalMatrix());
}
}
return true;
}
void COESkeleton_Impl::DestroyBones()
{
for (TV_BONE::iterator it = m_vBones.begin(); it != m_vBones.end(); ++it)
{
IOEBone* pBone = (*it);
SAFE_DELETE(pBone);
}
m_vBones.clear();
}
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
] | [
[
[
1,
115
]
]
] |
19db9916c990f801c6146e89709412db9d0597d2 | cc2c5b6d66f95d87bbf211c75e11bcd3c32153b2 | /src/CNC Map Renderer/CCRC.cpp | 37cd5d721796eef6967f2d46ec2bfa7b7f77cdda | [] | no_license | JuGGerNaunT/ccmaps | 88b290e13a920bba889033c32e305e2e36e420e2 | e81cf80b00157870542e5cd6aebbb5b4d667e16c | refs/heads/master | 2016-09-06T06:13:36.682009 | 2011-05-19T23:58:00 | 2011-05-19T23:58:00 | 38,542,028 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,634 | cpp | #include "CCRC.h"
#include <boost/cstdint.hpp>
using boost::int8_t;
// The following is all code to decode mix headers
int crc_table[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
const static int8_t char2num[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
void Ccrc::do_block(const void* data, int size)
{
const unsigned char* r = reinterpret_cast<const unsigned char*>(data);
m_crc = ~m_crc;
while (size--)
m_crc = (m_crc >> 8) ^ crc_table[*r++ ^ (m_crc & 0xff)];
m_crc = ~m_crc;
}
| [
"zzattack@3f6db025-b88a-a86c-ecf4-85930648a86d"
] | [
[
[
1,
70
]
]
] |
369bab26e5aac6264c075e2f0d7d299f3f8abca0 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/nemesis/nodenode_cmds.cc | c2caadc754ceb3c9f6fc5d7147a8f55c328616f7 | [] | no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,402 | cc | #define N_IMPLEMENTS nOdeNode
//==============================================================================
// subdir/nOdeNode_init.cc
// author: Your Name
// (C) 2000 Radon Labs GmbH
//------------------------------------------------------------------------------
// includes
#include "kernel/npersistserver.h"
#include "nemesis/nodenode.h"
#include "nemesis/node_physics.h"
#include "nemesis/node_collideobject.h"
// global declarations
static void n_getrelpointvel(void *, nCmd*);
static void n_getrelpointpos(void *, nCmd*);
static void n_gettorque(void *, nCmd*);
static void n_getforce(void *, nCmd*);
// Setters
static void n_addforce(void *, nCmd *);
static void n_addtorque(void *, nCmd *);
static void n_addforceatrelpos(void *, nCmd*);
static void n_addforceatpos(void *, nCmd*);
static void n_addrelforceatpos(void *, nCmd*);
static void n_setfiniterotationmode(void *, nCmd*);
static void n_setfiniterotationaxis(void *, nCmd*);
// Getters
static void n_getforce(void *, nCmd*);
static void n_gettorque(void *, nCmd*);
static void n_getrelpointpos(void *, nCmd*);
static void n_getrelpointvel(void *, nCmd*);
static void n_getfiniterotationmode(void *, nCmd*);
static void n_getfiniterotationaxis(void *, nCmd*);
static void n_getnumjoints(void *, nCmd*);
static void n_getjoint(void *, nCmd*);
static void n_setvisualize(void*, nCmd*);
static void n_setcollisionclass(void*, nCmd*);
static void n_connectwithball(void*, nCmd*);
static void n_connectfixed(void*, nCmd*);
static void n_connectwithhinge(void*, nCmd*);
static void n_connectwithhinge2(void*, nCmd*);
static void n_connectwithslider(void*, nCmd*);
static void n_setshapestyle(void *, nCmd *);
static void n_setradius(void *, nCmd *);
static void n_setheight(void *, nCmd *);
static void n_setbox(void *, nCmd *);
static void n_makesphere(void *, nCmd *);
static void n_makecylinder(void *, nCmd *);
static void n_makebox(void *, nCmd *);
static void n_makeplane(void *, nCmd *);
static void n_usecollision(void *, nCmd *);
static void n_usephysics(void *, nCmd *);
static void n_setcontactparam(void *, nCmd *);
static void n_getcontactparam(void *, nCmd *);
static void n_setcollisionlink(void *, nCmd *);
static void n_setcollisionfile(void *, nCmd *);
static void n_maketrilist(void *, nCmd *);
struct str2param {
const char *str;
nOdePhysics::nOdeTypes param;
};
static struct str2param str2param_table[] =
{
{ "sphere", nOdePhysics::ODE_SPHERE },
{ "cylinder", nOdePhysics::ODE_CYLINDER },
{ "plane", nOdePhysics::ODE_PLANE },
{ "box", nOdePhysics::ODE_BOX },
{ "trilist", nOdePhysics::ODE_TRILIST },
{ NULL, nOdePhysics::ODE_UNKNOWN }
};
static nOdePhysics::nOdeTypes str2param( const char *str )
{
int i=0;
struct str2param *p = NULL;
while ( p = &(str2param_table[i++]), p->str )
{
if ( strcmp( p->str, str ) == 0 )
return p->param;
}
return nOdePhysics::ODE_UNKNOWN;
};
static const char *param2str( nOdePhysics::nOdeTypes type )
{
int i=0;
struct str2param *p = NULL;
while ( p = &(str2param_table[i++]), p->str )
{
if (type == p->param)
return p->str;
}
return NULL;
};
struct str2param2 {
const char *str;
int param;
};
static struct str2param2 str2param_table2[] =
{
{ "mu", dCParamMu },
{ "mu2", dCParamMu2 },
{ "bounce", dCParamBounce },
{ "bouncevel", dCParamBounceVel },
{ "softerp", dCParamSoftErp },
{ "softcfm", dCParamSoftCfm },
{ "motion1", dCParamMotion1 },
{ "motion2", dCParamMotion2 },
{ "slip1", dCParamSlip1 },
{ "slip2", dCParamSlip2 },
{ NULL, -1 }
};
static int str2param2( const char *str )
{
int i=0;
struct str2param *p = NULL;
while ( p = &(str2param_table[i++]), p->str )
{
if ( strcmp( p->str, str ) == 0 )
return p->param;
}
return -1;
}
struct str2param3 {
const char *str;
int param;
};
static struct str2param3 str2param3_table[] =
{
{ "lowstop", dParamLoStop },
{ "highstop", dParamHiStop },
{ "velocity", dParamVel },
{ "maxforce", dParamFMax },
{ "fudgefactor", dParamFudgeFactor },
{ "bounce", dParamBounce },
{ "stoperp", dParamStopERP },
{ "stopcfm", dParamStopCFM },
{ "suspensionerp", dParamSuspensionERP },
{ "suspensioncfm", dParamSuspensionCFM },
{ "lowstop2", dParamLoStop2 },
{ "highstop2", dParamHiStop2 },
{ "velocity2", dParamVel2 },
{ "maxforce2", dParamFMax2 },
{ "fudgefactor2", dParamFudgeFactor2 },
{ "bounce2", dParamBounce2 },
{ "stoperp2", dParamStopERP2 },
{ "stopcfm2", dParamStopCFM2 },
{ "suspensionerp2", dParamSuspensionERP2 },
{ "suspensioncfm2", dParamSuspensionCFM2 },
{ NULL, -1 }
};
static int str2param3( const char *str )
{
int i=0;
struct str2param *p = NULL;
while ( p = &(str2param_table[i++]), p->str )
{
if ( strcmp( p->str, str ) == 0 )
return p->param;
}
return -1;
}
//==============================================================================
// CLASS
// nOdeNode
// SUPERCLASS
// nsuperclassname
// INCLUDE
// subdir/nOdeNode.h
// INFO
// Yeah right.. Where's the better documentation? (see methods below)
//------------------------------------------------------------------------------
void
n_initcmds(nClass *cl)
{
cl->BeginCmds();
cl->AddCmd("v_setvisualize_b", 'SMNO', n_setvisualize);
cl->AddCmd("v_setcollisionclass_s", 'SCOC', n_setcollisionclass);
// Hand-build a collision shape
cl->AddCmd("v_setshapetyle_s", 'SCOA', n_setshapestyle);
cl->AddCmd("v_setradius_f", 'SCOB', n_setradius);
cl->AddCmd("v_setheight_f", 'SCOD', n_setheight);
cl->AddCmd("v_setbox_ffffff", 'SCOE', n_setbox);
cl->AddCmd("v_setcollisionlink_ss", 'SCLK', n_setcollisionlink);
cl->AddCmd("v_setcollisionfile_ss", 'SCLF', n_setcollisionfile);
// Use built-in shapes
cl->AddCmd("v_makesphere_f", 'SCOG', n_makesphere);
cl->AddCmd("v_makecylinder_ff", 'SCOH', n_makecylinder);
cl->AddCmd("v_makebox_ffffff", 'SCOI', n_makebox);
cl->AddCmd("v_makeplane_ffff", 'SCOJ', n_makeplane);
cl->AddCmd("v_maketrilist_s", 'SCTL', n_maketrilist);
// To collide or not to collide
cl->AddCmd("v_usecollision_b", 'SCOK', n_usecollision);
// To physics or not to physics
cl->AddCmd("v_usephysics_b", 'SCOL', n_usephysics);
// Set this object's surface params (See ODE docs)
cl->AddCmd("v_setcontactparam_sf", 'SCPR', n_setcontactparam);
cl->AddCmd("f_getcontactparam_s", 'GCPR', n_getcontactparam);
// Add some forces and axes to the system
cl->AddCmd("v_addforce_fff", 'ADDF', n_addforce);
cl->AddCmd("v_addtorque_fff", 'ADDT', n_addtorque);
cl->AddCmd("v_addforceatpos_ffffff", 'AFAP', n_addforceatpos);
cl->AddCmd("v_addforceatrelpos_ffffff", 'AFRP', n_addforceatrelpos);
cl->AddCmd("v_addrelforceatpos_ffffff", 'ARFP', n_addrelforceatpos);
cl->AddCmd("v_setfiniterotationmode_i",'SFRM', n_setfiniterotationmode);
cl->AddCmd("v_setfiniterotationaxis_fff",'SFRA', n_setfiniterotationaxis);
// Get the data back out of the system
cl->AddCmd("fff_getforce_v", 'GETF', n_getforce);
cl->AddCmd("fff_gettorque_v", 'GTOQ', n_gettorque);
cl->AddCmd("fff_getrelpointpos_v", 'GRPP', n_getrelpointpos);
cl->AddCmd("fff_getrelpointvel_v", 'GRPV', n_getrelpointvel);
cl->AddCmd("i_getfiniterotationmode_v",'GFRM', n_getfiniterotationmode);
cl->AddCmd("fff_getfiniterotationaxis_v",'GFRA', n_getfiniterotationaxis);
cl->AddCmd("i_getnumjoints_v",'GNJO', n_getnumjoints);
cl->AddCmd("i_getjoints_i",'GJOI', n_getjoint);
// cl->AddCmd("v_connectwithmotor_ssfff", 'CHIN', n_connectwithslider );
cl->AddCmd("s_connectwithslider_sfff", 'CSLI', n_connectwithslider );
cl->AddCmd("s_connectwithhinge2_sfffffffff", 'CHIN', n_connectwithhinge2 );
cl->AddCmd("s_connectwithhinge_sffffff", 'CHGE', n_connectwithhinge );
cl->AddCmd("s_connectwithball_sfff", 'CBAL', n_connectwithball );
cl->AddCmd("s_connectfixed_s", 'CFIX', n_connectfixed );
cl->EndCmds();
}
//------------------------------------------------------------------------------
/**
@cmd
connectwithhinge
@input
s ( other nodenode ),
f ( anchor x value )
f ( anchor y value )
f ( anchor z value )
f ( axis x value )
f ( axis y value )
f ( axis z value )
@output
s The name of the joint created (use this to set parameters)
@info
Connect this odenode with another odenode via a ODE
HINGE joint. See ODE docs for more details
*/
static void n_connectwithhinge(void* vpObj, nCmd* pCmd)
{
nOdeNode* pSelf = static_cast<nOdeNode*>(vpObj);
const char* other = pCmd->In()->GetS();
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
float x2 = pCmd->In()->GetF();
float y2 = pCmd->In()->GetF();
float z2 = pCmd->In()->GetF();
pCmd->Out()->SetS(pSelf->connectWithHingeJoint( other, &vector3(x,y,z), &vector3(x2,y2,z2)));
}
//------------------------------------------------------------------------------
/**
@cmd
connectwithhinge2
@input
s ( other nodenode ),
f ( anchor x value )
f ( anchor y value )
f ( anchor z value )
f ( axis x value )
f ( axis y value )
f ( axis z value )
f ( axis2 x value )
f ( axis2 y value )
f ( axis2 z value )
@output
s The name of the joint created
@info
Connect this odenode with another odenode via a ODE
HINGE joint. See ODE docs for more details
*/
static void n_connectwithhinge2(void* vpObj, nCmd* pCmd)
{
nOdeNode* pSelf = static_cast<nOdeNode*>(vpObj);
const char* other = pCmd->In()->GetS();
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
float ax = pCmd->In()->GetF();
float ay = pCmd->In()->GetF();
float az = pCmd->In()->GetF();
float ax2 = pCmd->In()->GetF();
float ay2 = pCmd->In()->GetF();
float az2 = pCmd->In()->GetF();
pCmd->Out()->SetS(pSelf->connectWithHinge2Joint( other, &vector3(x,y,z), &vector3(ax,ay,az), &vector3(ax2,ay2,az2)));
}
//------------------------------------------------------------------------------
/**
@cmd
connectwithball
@input
s ( other nodenode ),
f ( anchor x value )
f ( anchor y value )
f ( anchor z value )
@output
s name of the joint created
@info
Connect this odenode with another odenode via a ODE
BALL joint. See ODE docs for more details
*/
static void n_connectwithball(void* vpObj, nCmd* pCmd)
{
nOdeNode* pSelf = static_cast<nOdeNode*>(vpObj);
const char* other = pCmd->In()->GetS();
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
pCmd->Out()->SetS(pSelf->connectWithBallJoint( other, &vector3(x,y,z)));
}
//------------------------------------------------------------------------------
/**
@cmd
connectwithslider
@input
s ( other nodenode ),
f ( axis x value )
f ( axis y value )
f ( axis z value )
@output
s Name of the joint
@info
Connect this odenode with another odenode via a ODE
SLIDER joint. See ODE docs for more details
*/
static void n_connectwithslider(void* vpObj, nCmd* pCmd)
{
nOdeNode* pSelf = static_cast<nOdeNode*>(vpObj);
const char* other = pCmd->In()->GetS();
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
pCmd->Out()->SetS(pSelf->connectWithSliderJoint( other,&vector3(x,y,z)));
}
//------------------------------------------------------------------------------
/**
@cmd
connectfixed
@input
s ( other nodenode ),
f ( anchor x value )
f ( anchor y value )
f ( anchor z value )
f ( axis x value )
f ( axis y value )
f ( axis z value )
@output
s The name of the joint created
@info
Connect this odenode with another odenode via a ODE
FIXED (immovable) joint. See ODE docs for more details
*/
static void n_connectfixed(void* vpObj, nCmd* pCmd)
{
nOdeNode* pSelf = static_cast<nOdeNode*>(vpObj);
pCmd->Out()->SetS(pSelf->connectWithFixedJoint( pCmd->In()->GetS()));
}
//------------------------------------------------------------------------------
/**
@cmd
setcontactparam
@input
s ( parameter ), f ( value )
@output
v
@info
set optional surface parameters for contacts resulting
from collisions in the space.
see ODE documentation for complete descriptions.
valid parameters are:
mu
mu2
bounce
bouncevel
softerp
softcfm
motion1
motion2
slip1
slip2
*/
static
void
n_setcontactparam(void* slf, nCmd* cmd)
{
nOdeNode* self = static_cast<nOdeNode*>(slf);
const char* strParam = cmd->In()->GetS();
float value = cmd->In()->GetF();
((nOdeCollideObject *)self->getCollideObject())->SetContactParam( str2param2( strParam ), value );
}
//------------------------------------------------------------------------------
/**
@cmd
getcontactparam
@input
s ( parameter )
@output
f ( value )
@info
get value of an optional parameter for contacts
resulting from collisions in the space.
see setcontactparam for valid parameters.
*/
static
void
n_getcontactparam(void* slf, nCmd* cmd)
{
nOdeNode* self = static_cast<nOdeNode*>(slf);
const char* strParam = cmd->In()->GetS();
float value = 0.0;
value = ((nOdeCollideObject *)self->getCollideObject())->GetContactParam(str2param2( strParam ) );
cmd->Out()->SetF( value );
}
//==============================================================================
// CMD
// setmeshnode
// INPUT
// s
// OUTPUT
// v
// INFO
// Sets the visual nMeshNode to use for this object at render time
//------------------------------------------------------------------------------
static
void
n_setvisualize(void* vpObj, nCmd* pCmd)
{
nOdeNode* pSelf = static_cast<nOdeNode*>(vpObj);
pSelf->setVisualize( pCmd->In()->GetB() );
}
//==============================================================================
// CMD
// setcollisionclass
// INPUT
// s
// OUTPUT
// v
// INFO
// Sets the class of collisions -- see Startup for list
//------------------------------------------------------------------------------
static
void
n_setcollisionclass(void* vpObj, nCmd* pCmd)
{
nOdeNode* pSelf = static_cast<nOdeNode*>(vpObj);
pSelf->setCollisionClass( pCmd->In()->GetS() );
}
//------------------------------------------------------------------------------
// 2000.mm.dd your name created
//------------------------------------------------------------------------------
bool
nOdeNode::SaveCmds(nPersistServer* ps)
{
if (nVisNode::SaveCmds(ps))
{
nCmd* pCmd = 0;
if ((pCmd = ps->GetCmd(this, 'SMNO')))
{
ps->PutCmd(pCmd);
}
if ((pCmd = ps->GetCmd(this, 'SCOC')))
{
ps->PutCmd(pCmd);
}
if ((pCmd = ps->GetCmd(this, 'CVAL')))
{
ps->PutCmd(pCmd);
}
if ((pCmd = ps->GetCmd(this, 'CFIX')))
{
ps->PutCmd(pCmd);
}
return true;
}
else
{
return false;
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Manually set the shape of this collision object. This
// shape will then need to have it's radius and possibly
// its height and other parameters tweaked
//
// This must be called before Attach() / Compute() is reached.
// so be sure to fully initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_setshapestyle( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
nOdePhysics::nOdeTypes shape = (nOdePhysics::nOdeTypes) str2param(pCmd->In()->GetS());
pSelf->setBoundingShapeStyle( shape );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Manually set the radius of this collision object.
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized o be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_setradius( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float radius = pCmd->In()->GetF();
pSelf->setRadius( radius );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Manually set the height of this collision object. (Cylinders only)
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized o be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_setheight( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float height = pCmd->In()->GetF();
pSelf->setHeight( height );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Manually set the min/max bounding box of this collision object.
//
// INPUT:
// fff - The min x/y/z of the bounding box
// fff - The max x/y/z of the bounding box
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized o be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_setbox( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float minx = pCmd->In()->GetF();
float miny = pCmd->In()->GetF();
float minz = pCmd->In()->GetF();
float maxx = pCmd->In()->GetF();
float maxy = pCmd->In()->GetF();
float maxz = pCmd->In()->GetF();
bbox3 box;
box.vmin.set( minx, miny, minz );
box.vmax.set( maxx, maxy, maxz );
pSelf->setBoundingBox( &box );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Automatically sense the values this collision object will need,
// given the nVisNode pointer, and the shape style passed in.
//
// INPUT:
// s - The name of the nVisNode to link to
// s - The shape to syle after (sphere, box, cylinder, plane)
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized o be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_setcollisionlink( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
const char* linkTo = pCmd->In()->GetS();
nOdePhysics::nOdeTypes shape = str2param( pCmd->In()->GetS() );
nClass *visClass = pSelf->pKernelServer->FindClass("nvisnode");
nRoot *test = pSelf->pKernelServer->Lookup( linkTo );
if (test->IsA( visClass ))
pSelf->setCollisionLink( (nVisNode*)test, shape );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Automatically sense the values this collision object will need,
// given the .N3D filename pointer, and the shape style passed in.
//
// INPUT:
// s - The name of the .N3D file to link to
// s - The shape to style after (sphere, box, cylinder, plane)
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized o be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_setcollisionfile( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
const char* linkTo = pCmd->In()->GetS();
nOdePhysics::nOdeTypes shape = str2param( pCmd->In()->GetS() );
pSelf->setCollisionFile( linkTo, shape );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Automatically create a sphere with the given radius.
// No other methods need to be called once this is called.
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized o be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_makesphere( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float radius = pCmd->In()->GetF();
pSelf->MakeSphere( radius );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Automatically create a cylinder with the given radius/height.
// No other methods need to be called once this is called.
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized so be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_makecylinder( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float radius = pCmd->In()->GetF();
float height = pCmd->In()->GetF();
pSelf->MakeCylinder( radius, height );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Automatically create a box with the given min/max values.
// No other methods need to be called once this is called.
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized so be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_makebox( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float minx = pCmd->In()->GetF();
float miny = pCmd->In()->GetF();
float minz = pCmd->In()->GetF();
float maxx = pCmd->In()->GetF();
float maxy = pCmd->In()->GetF();
float maxz = pCmd->In()->GetF();
pSelf->MakeBox( minx, miny, minz, maxx, maxy, maxz );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Automatically create a plane with the given radius on the given axis.
// No other methods need to be called once this is called.
//
// INPUT:
// f - the 'a' vector of the plane equation
// f - the 'b' vector of the plane equation
// f - the 'c' vector of the plane equation
// f - the 'd' vector of the plane equation
//
// From ODE docs:
// Create a plane geometry object of the given parameters The plane equation is
// a*x+b*y+c*z = d
//
// The plane's normal vector is (a,b,c), and it must have length 1. Unlike other
// geometry objects, planes disregard their assigned position and rotation, i.e.
// the parameters are always in global coordinates. In other words it is assumed
// that the plane is always part of the static environment and not tied to any
// movable object.
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized so be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_makeplane( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float a = pCmd->In()->GetF();
float b = pCmd->In()->GetF();
float c = pCmd->In()->GetF();
float d = pCmd->In()->GetF();
pSelf->MakePlane( a, b, c, d);
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Automatically create a plane with the given radius on the given axis.
// No other methods need to be called once this is called.
//
// INPUT:
// f - the 'a' vector of the plane equation
// f - the 'b' vector of the plane equation
// f - the 'c' vector of the plane equation
// f - the 'd' vector of the plane equation
//
// From ODE docs:
// Create a plane geometry object of the given parameters The plane equation is
// a*x+b*y+c*z = d
//
// The plane's normal vector is (a,b,c), and it must have length 1. Unlike other
// geometry objects, planes disregard their assigned position and rotation, i.e.
// the parameters are always in global coordinates. In other words it is assumed
// that the plane is always part of the static environment and not tied to any
// movable object.
//
// This must be called before Attach() / Compute() is reached,
// as this is where the shape is fully realized so be sure to fully
// initialize the object in one pass.
//------------------------------------------------------------------------------
static void n_maketrilist( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
const char *a = pCmd->In()->GetS();
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Add a force to this object represented by a vector3
//
// INPUT:
// f - the 'x' vector of the force
// f - the 'y' vector of the force
// f - the 'z' vector of the force
//
// From ODE docs:
// 3.4. Force accumulators
//
// Between each integrator step the user can call functions to apply
// forces to the rigid body. These forces are added to "force accumulators"
// in the rigid body object. When the next integrator step happens, the sum
// of all the applied forces will be used to push the body around. The forces
// accumulators are set to zero after each integrator step.
//
//------------------------------------------------------------------------------
static void n_addforce( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
pSelf->addForce( &vector3(x,y,z) );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Add a torque to this object represented by a vector3
//
// INPUT:
// f - the 'x' vector of the torque
// f - the 'y' vector of the torque
// f - the 'z' vector of the torque
//
// From ODE docs:
// 3.4. Force accumulators
//
// Between each integrator step the user can call functions to apply
// forces to the rigid body. These forces are added to "force accumulators"
// in the rigid body object. When the next integrator step happens, the sum
// of all the applied forces will be used to push the body around. The forces
// accumulators are set to zero after each integrator step.
//
//------------------------------------------------------------------------------
static void n_addtorque( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
pSelf->addTorque( &vector3(x,y,z) );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Toggle this object's collidability. If false, It will still be effected by
// gravity, just not as a collide target anymore.
//
// // TODO: Implement this
//
//------------------------------------------------------------------------------
static void n_usecollision( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Toggle this object's phyiscs. If false, It will still be effected by
// collisions, just not modified by gravity anymore.
//
//------------------------------------------------------------------------------
static void n_usephysics( void* pObj, nCmd* pCmd )
{
nOdeNode *pSelf = static_cast<nOdeNode*>(pObj);
pSelf->SetPhysicsable( !pCmd->In()->GetB() );
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Add a force to this object represented by a vector3
//
// INPUT:
// f - the 'x' vector of the force
// f - the 'y' vector of the force
// f - the 'z' vector of the force
//
// f - the 'x' vector of the position
// f - the 'y' vector of the position
// f - the 'z' vector of the position
//
// From ODE docs:
// 3.4. Force accumulators
//
// Between each integrator step the user can call functions to apply
// forces to the rigid body. These forces are added to "force accumulators"
// in the rigid body object. When the next integrator step happens, the sum
// of all the applied forces will be used to push the body around. The forces
// accumulators are set to zero after each integrator step.
//
//------------------------------------------------------------------------------
static void n_addforceatpos(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
float px = pCmd->In()->GetF();
float py = pCmd->In()->GetF();
float pz = pCmd->In()->GetF();
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
co->addForceAtPos( &vector3( x, y, z), &vector3(px, py, pz)) ;
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Add a force to this object represented by a vector3
//
// INPUT:
// f - the 'x' vector of the force
// f - the 'y' vector of the force
// f - the 'z' vector of the force
//
// f - the 'x' vector of the position
// f - the 'y' vector of the position
// f - the 'z' vector of the position
//
// From ODE docs:
// 3.4. Force accumulators
//
// Between each integrator step the user can call functions to apply
// forces to the rigid body. These forces are added to "force accumulators"
// in the rigid body object. When the next integrator step happens, the sum
// of all the applied forces will be used to push the body around. The forces
// accumulators are set to zero after each integrator step.
//
//------------------------------------------------------------------------------
static void n_addforceatrelpos(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
float px = pCmd->In()->GetF();
float py = pCmd->In()->GetF();
float pz = pCmd->In()->GetF();
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
co->addForceAtRelPos( &vector3( x, y, z), &vector3(px, py, pz)) ;
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Add a force to this object represented by a vector3
//
// INPUT:
// f - the 'x' vector of the relative force
// f - the 'y' vector of the relative force
// f - the 'z' vector of the relative force
//
// f - the 'x' vector of the position
// f - the 'y' vector of the position
// f - the 'z' vector of the position
//
// From ODE docs:
// 3.4. Force accumulators
//
// Between each integrator step the user can call functions to apply
// forces to the rigid body. These forces are added to "force accumulators"
// in the rigid body object. When the next integrator step happens, the sum
// of all the applied forces will be used to push the body around. The forces
// accumulators are set to zero after each integrator step.
//
//------------------------------------------------------------------------------
static void n_addrelforceatpos(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
float px = pCmd->In()->GetF();
float py = pCmd->In()->GetF();
float pz = pCmd->In()->GetF();
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
co->addRelForceAtPos( &vector3( x, y, z), &vector3(px, py, pz)) ;
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Set the finite rotation mode for this object
//
// INPUT:
//
// i - the mode of rotation
//
// From ODE docs:
// This function controls the way a body's orientation is
// updated at each time step. The mode argument can be:
// 0: An ``infitesimal'' orientation update is used.
// This is fast to compute, but it can occasionally cause
// inaccuracies for bodies that are rotating at high speed,
// especially when those bodies are joined to other bodies.
// This is the default for every new body that is created.
// 1: A ``finite'' orientation update is used. This is more costly
// to compute, but will be more accurate for high speed rotations.
// Note however that high speed rotations can result in many types
// of error in a simulation, and this mode will only fix one of
// those sources of error.
//
//------------------------------------------------------------------------------
static void n_setfiniterotationmode(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
int mode = pCmd->In()->GetI();
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
co->setFiniteRotationMode( mode );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// Set the finite rotation mode for this object
//
// INPUT:
//
// i - the mode of rotation
//
// From ODE docs:
// This sets the finite rotation axis for a body.
// This is axis only has meaning when the finite rotation mode is set
// (see setFiniteRotationMode()).
//
// If this axis is zero (0,0,0), full finite rotations are performed on
// the body.
//
// If this axis is nonzero, the body is rotated by performing a partial
// finite rotation along the axis direction followed by an infitesimal
// rotation along an orthogonal direction.
//
// This can be useful to alleviate certain sources of error caused by
// quickly spinning bodies. For example, if a car wheel is rotating at
// high speed you can call this function with the wheel's hinge axis as
// the argument to try and improve its behavior.
//
//------------------------------------------------------------------------------
static void n_setfiniterotationaxis(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
co->setFiniteRotationAxis( &vector3(x, y, z) );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
//------------------------------------------------------------------------------
static void n_getforce(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
vector3 force(co->getForce());
pCmd->Out()->SetF( force.x );
pCmd->Out()->SetF( force.y );
pCmd->Out()->SetF( force.z );
} else {
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
//------------------------------------------------------------------------------
static void n_gettorque(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
vector3 torque(co->getTorque());
pCmd->Out()->SetF( torque.x );
pCmd->Out()->SetF( torque.y );
pCmd->Out()->SetF( torque.z );
} else {
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
//------------------------------------------------------------------------------
static void n_getrelpointpos(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
nOdeCollideObject *co = pSelf->getCollideObject();
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
if (co)
{
vector3 pos(co->getRelPointPos( &vector3( x, y, z) ));
pCmd->Out()->SetF( pos.x );
pCmd->Out()->SetF( pos.y );
pCmd->Out()->SetF( pos.z );
} else {
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
//------------------------------------------------------------------------------
static void n_getrelpointvel(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
nOdeCollideObject *co = pSelf->getCollideObject();
float x = pCmd->In()->GetF();
float y = pCmd->In()->GetF();
float z = pCmd->In()->GetF();
if (co)
{
vector3 vel(co->getRelPointVel( &vector3( x, y, z) ));
pCmd->Out()->SetF( vel.x );
pCmd->Out()->SetF( vel.y );
pCmd->Out()->SetF( vel.z );
} else {
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
//------------------------------------------------------------------------------
static void n_getfiniterotationmode(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
int mode = co->getFiniteRotationMode();
pCmd->Out()->SetI( mode );
} else {
pCmd->Out()->SetI( -1 );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
//------------------------------------------------------------------------------
static void n_getfiniterotationaxis(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
vector3 axis( co->getFiniteRotationAxis() );
pCmd->Out()->SetF( axis.x );
pCmd->Out()->SetF( axis.y );
pCmd->Out()->SetF( axis.z );
} else {
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
pCmd->Out()->SetF( 0.0f );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
//------------------------------------------------------------------------------
static void n_getnumjoints(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
nOdeCollideObject *co = pSelf->getCollideObject();
if (co)
{
int num = co->getNumJoints();
pCmd->Out()->SetI( num );
} else {
pCmd->Out()->SetI( 0 );
}
}
//------------------------------------------------------------------------------
// 2002.02.06 whitegold created
//
// TODO: Passing a struct?
//------------------------------------------------------------------------------
static void n_getjoint(void * pObj, nCmd* pCmd)
{
nOdeNode *pSelf = static_cast<nOdeNode *>(pObj);
nOdeCollideObject *co = pSelf->getCollideObject();
int index = pCmd->In()->GetI();
if (0)
{
//co->getJoint( index );
//pCmd->Out()->SetI( num );
} else {
pCmd->Out()->SetI( -1 );
}
}
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
] | [
[
[
1,
1303
]
]
] |
131875c68c2cf0ebca9c538fc17dfe6efe2ac2f7 | d37a1d5e50105d82427e8bf3642ba6f3e56e06b8 | /DVR/HaohanITPlayer/public/Common/SysUtils/RandomSequence.h | 07bc9aee9ec681e834aad572b7dce7ab6994a5ea | [] | no_license | 080278/dvrmd-filter | 176f4406dbb437fb5e67159b6cdce8c0f48fe0ca | b9461f3bf4a07b4c16e337e9c1d5683193498227 | refs/heads/master | 2016-09-10T21:14:44.669128 | 2011-10-17T09:18:09 | 2011-10-17T09:18:09 | 32,274,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | h | //-----------------------------------------------------------------------------
// RandomSequence.h
// Copyright (c) 2002 - 2004, Haohanit. All rights reserved.
//-----------------------------------------------------------------------------
//SR FS: Reviewed [JAW 20040912]
//SR FS: Reviewed [wwt 20040914]
#ifndef __RandomSequence__
#define __RandomSequence__
#include "CommonTypes.h"
class RandomSequence
{
public:
// **CodeWizzard** - Informational: More Effective C++ item 5 - Be wary of user-defined conversion function
RandomSequence(UInt32 length);
~RandomSequence();
UInt32 GetFirst();
UInt32 GetNext(UInt32 n);
UInt32 GetLength()
{ return(mLength); }
protected:
UInt32 FindMask(UInt32 length);
protected:
UInt32 mLength;
UInt32 mMask;
};
#endif
| [
"[email protected]@27769579-7047-b306-4d6f-d36f87483bb3"
] | [
[
[
1,
35
]
]
] |
f5b8e46de4c3743240f4a5c257b83b5dff81037d | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/Platforms/Tru64/Tru64PlatformUtils.cpp | bfa996400178a47651409146c5e41fa66c1d9f4e | [] | 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 | 18,285 | cpp | /*
* Copyright 1999-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: Tru64PlatformUtils.cpp 180016 2005-06-04 19:49:30Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#if !defined (APP_NO_THREADS)
#include <pthread.h>
#endif // APP_NO_THREADS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/util/Mutexes.hpp>
#include <xercesc/util/XMLHolder.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/PanicHandler.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
//
// These control which transcoding service is used by the Tru64 version.
// They allow this to be controlled from the build process by just defining
// one of these values.
//
#if defined (XML_USE_ICU_TRANSCODER)
#include <xercesc/util/Transcoders/ICU/ICUTransService.hpp>
#else // use native transcoder
#include <xercesc/util/Transcoders/Iconv/IconvTransService.hpp>
#endif
//
// These control which message loading service is used by the Tru64 version.
// They allow this to be controlled from the build process by just defining
// one of these values.
//
#if defined (XML_USE_ICU_MESSAGELOADER)
#include <xercesc/util/MsgLoaders/ICU/ICUMsgLoader.hpp>
#elif defined (XML_USE_ICONV_MESSAGELOADER)
#include <xercesc/util/MsgLoaders/MsgCatalog/MsgCatalogLoader.hpp>
#else // use In-memory message loader
#include <xercesc/util/MsgLoaders/InMemory/InMemMsgLoader.hpp>
#endif
#if defined (XML_USE_NETACCESSOR_LIBWWW)
#include <xercesc/util/NetAccessors/libWWW/LibWWWNetAccessor.hpp>
#elif defined (XML_USE_NETACCESSOR_SOCKET)
#include <xercesc/util/NetAccessors/Socket/SocketNetAccessor.hpp>
#endif
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Private Static Methods
// ---------------------------------------------------------------------------
XMLNetAccessor* XMLPlatformUtils::makeNetAccessor()
#if defined (XML_USE_NETACCESSOR_LIBWWW)
{
return new (fgMemoryManager) LibWWWNetAccessor();
}
#elif defined (XML_USE_NETACCESSOR_SOCKET)
{
return new (fgMemoryManager) SocketNetAccessor();
}
#else
{
return 0;
}
#endif
//
// This method is called by the platform independent part of this class
// when client code asks to have one of the supported message sets loaded.
// In our case, we use the ICU based message loader mechanism.
//
XMLMsgLoader* XMLPlatformUtils::loadAMsgSet(const XMLCh* const msgDomain)
{
XMLMsgLoader* retVal;
try
{
#if defined (XML_USE_ICU_MESSAGELOADER)
retVal = new (fgMemoryManager) ICUMsgLoader(msgDomain);
#elif defined (XML_USE_ICONV_MESSAGELOADER)
retVal = new (fgMemoryManager) MsgCatalogLoader(msgDomain);
#else
retVal = new (fgMemoryManager) InMemMsgLoader(msgDomain);
#endif
}
catch(const OutOfMemoryException&)
{
throw;
}
catch(...)
{
panic(PanicHandler::Panic_CantLoadMsgDomain);
}
return retVal;
}
//
// This method is called very early in the bootstrapping process. This guy
// must create a transcoding service and return it. It cannot use any string
// methods, any transcoding services, throw any exceptions, etc... It just
// makes a transcoding service and returns it, or returns zero on failure.
//
XMLTransService* XMLPlatformUtils::makeTransService()
#if defined (XML_USE_ICU_TRANSCODER)
{
return new (fgMemoryManager) ICUTransService;
}
#elif defined (XML_USE_ICONV_TRANSCODER)
{
return new (fgMemoryManager) IconvTransService;
}
#else // Use Native transcoding service
{
return new (fgMemoryManager) IconvTransService;
}
#endif
// ---------------------------------------------------------------------------
// XMLPlatformUtils: The panic method
// ---------------------------------------------------------------------------
void XMLPlatformUtils::panic(const PanicHandler::PanicReasons reason)
{
fgUserPanicHandler? fgUserPanicHandler->panic(reason) : fgDefaultPanicHandler->panic(reason);
}
// ---------------------------------------------------------------------------
// XMLPlatformUtils: File Methods
// ---------------------------------------------------------------------------
unsigned int XMLPlatformUtils::curFilePos(FileHandle theFile
, MemoryManager* const manager)
{
// Get the current position
int curPos = ftell( (FILE*)theFile);
if (curPos == -1)
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotGetSize, manager);
return (unsigned int)curPos;
}
void XMLPlatformUtils::closeFile(FileHandle theFile
, MemoryManager* const manager)
{
if (fclose((FILE*) theFile))
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotCloseFile, manager);
}
unsigned int XMLPlatformUtils::fileSize(FileHandle theFile
, MemoryManager* const manager)
{
// Get the current position
long int curPos = ftell((FILE*) theFile);
if (curPos == -1)
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotGetCurPos, manager);
// Seek to the end and save that value for return
if (fseek( (FILE*) theFile, 0, SEEK_END) )
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotSeekToEnd, manager);
long int retVal = ftell((FILE*) theFile);
if (retVal == -1)
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotSeekToEnd, manager);
// And put the pointer back
if (fseek((FILE*) theFile, curPos, SEEK_SET))
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotSeekToPos, manager);
return (unsigned int)retVal;
}
FileHandle XMLPlatformUtils::openFile(const char* const fileName
, MemoryManager* const manager)
{
FileHandle retVal = (FILE*)fopen( fileName , "rb" );
if (retVal == NULL)
return 0;
return retVal;
}
FileHandle XMLPlatformUtils::openFile(const XMLCh* const fileName
, MemoryManager* const manager)
{
const char* tmpFileName = XMLString::transcode(fileName, manager);
ArrayJanitor<char> janText((char*)tmpFileName, manager);
FileHandle retVal = (FILE*)fopen( tmpFileName , "rb" );
if (retVal == NULL)
return 0;
return retVal;
}
FileHandle XMLPlatformUtils::openFileToWrite(const XMLCh* const fileName
, MemoryManager* const manager)
{
const char* tmpFileName = XMLString::transcode(fileName, manager);
ArrayJanitor<char> janText((char*)tmpFileName, manager);
return fopen( tmpFileName , "wb" );
}
FileHandle XMLPlatformUtils::openFileToWrite(const char* const fileName
, MemoryManager* const manager)
{
return fopen( fileName , "wb" );
}
unsigned int XMLPlatformUtils::readFileBuffer(FileHandle theFile,
const unsigned int toRead,
XMLByte* const toFill
, MemoryManager* const manager)
{
size_t noOfItemsRead =
fread((void*) toFill, 1, toRead, (FILE*) theFile);
if(ferror((FILE*) theFile))
{
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotReadFromFile, manager);
}
return (unsigned int) noOfItemsRead;
}
void
XMLPlatformUtils::writeBufferToFile( FileHandle const theFile
, long toWrite
, const XMLByte* const toFlush
, MemoryManager* const manager)
{
if (!theFile ||
(toWrite <= 0 ) ||
!toFlush )
return;
const XMLByte* tmpFlush = (const XMLByte*) toFlush;
size_t bytesWritten = 0;
while (true)
{
bytesWritten=fwrite(tmpFlush, sizeof(XMLByte), toWrite, (FILE*)theFile);
if(ferror((FILE*)theFile))
{
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotWriteToFile, manager);
}
if (bytesWritten < toWrite) //incomplete write
{
tmpFlush+=bytesWritten;
toWrite-=bytesWritten;
bytesWritten=0;
}
else
return;
}
return;
}
void XMLPlatformUtils::resetFile(FileHandle theFile
, MemoryManager* const manager)
{
// Seek to the start of the file
if (fseek((FILE*) theFile, 0, SEEK_SET))
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotResetFile, manager);
}
// ---------------------------------------------------------------------------
// XMLPlatformUtils: File system methods
// ---------------------------------------------------------------------------
XMLCh* XMLPlatformUtils::getFullPath(const XMLCh* const srcPath,
MemoryManager* const manager)
{
//
// NOTE: THe path provided has always already been opened successfully,
// so we know that its not some pathological freaky path. It comes in
// in native format, and goes out as Unicode always
//
char* newSrc = XMLString::transcode(srcPath, manager);
ArrayJanitor<char> janText(newSrc, manager);
// Use a local buffer that is big enough for the largest legal path
char absPath[PATH_MAX + 1];
//get the absolute path
char* retPath = realpath(newSrc, &absPath[0]);
if (!retPath)
{
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotGetBasePathName, manager);
}
return XMLString::transcode(absPath, manager);
}
bool XMLPlatformUtils::isRelative(const XMLCh* const toCheck
, MemoryManager* const manager)
{
// Check for pathological case of empty path
if (!toCheck[0])
return false;
//
// If it starts with a slash, then it cannot be relative. This covers
// both something like "\Test\File.xml" and an NT Lan type remote path
// that starts with a node like "\\MyNode\Test\File.xml".
//
if (toCheck[0] == XMLCh('/'))
return false;
// Else assume its a relative path
return true;
}
XMLCh* XMLPlatformUtils::getCurrentDirectory(MemoryManager* const manager)
{
char dirBuf[PATH_MAX + 2];
char *curDir = getcwd(&dirBuf[0], PATH_MAX + 1);
if (!curDir)
{
ThrowXMLwithMemMgr(XMLPlatformUtilsException,
XMLExcepts::File_CouldNotGetBasePathName, manager);
}
return XMLString::transcode(curDir, manager);
}
inline bool XMLPlatformUtils::isAnySlash(XMLCh c)
{
return ( chBackSlash == c || chForwardSlash == c);
}
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Timing Methods
// ---------------------------------------------------------------------------
unsigned long XMLPlatformUtils::getCurrentMillis()
{
timespec ts;
clock_gettime (CLOCK_REALTIME, &ts);
return (unsigned long) ((ts.tv_sec * 1000) + (ts.tv_nsec / 1000000));
}
#if !defined (APP_NO_THREADS)
// ---------------------------------------------------------------------------
// XMLPlatformUtils: Platform init method
// ---------------------------------------------------------------------------
typedef XMLHolder<pthread_mutex_t> MutexHolderType;
static MutexHolderType* gAtomicOpMutex = 0;
void XMLPlatformUtils::platformInit()
{
//
// The gAtomicOpMutex mutex needs to be created
// because compareAndSwap and incrementlocation and decrementlocation
// does not have the atomic system calls for usage
// Normally, mutexes are created on first use, but there is a
// circular dependency between compareAndExchange() and
// mutex creation that must be broken.
gAtomicOpMutex = new (fgMemoryManager) MutexHolderType;
if (pthread_mutex_init(&gAtomicOpMutex->fInstance, NULL)) {
delete gAtomicOpMutex;
gAtomicOpMutex = 0;
panic( PanicHandler::Panic_SystemInit );
}
}
// -----------------------------------------------------------------------
// Mutex methods
// -----------------------------------------------------------------------
class RecursiveMutex
{
public:
pthread_mutex_t mutex;
int recursionCount;
pthread_t tid;
MemoryManager* const fMemoryManager;
RecursiveMutex(MemoryManager* manager) :
mutex(),
recursionCount(0),
tid(0),
fMemoryManager(manager)
{
if (pthread_mutex_init(&mutex, NULL))
XMLPlatformUtils::panic(PanicHandler::Panic_MutexErr);
}
~RecursiveMutex()
{
if (pthread_mutex_destroy(&mutex))
ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::Mutex_CouldNotDestroy, fMemoryManager);
}
void lock()
{
if (pthread_equal(tid, pthread_self()))
{
recursionCount++;
return;
}
if (pthread_mutex_lock(&mutex) != 0)
XMLPlatformUtils::panic(PanicHandler::Panic_MutexErr);
tid = pthread_self();
recursionCount = 1;
}
void unlock()
{
if (--recursionCount > 0)
return;
if (pthread_mutex_unlock(&mutex) != 0)
XMLPlatformUtils::panic(PanicHandler::Panic_MutexErr);
tid = 0;
}
};
void* XMLPlatformUtils::makeMutex(MemoryManager* manager)
{
return new (manager) RecursiveMutex(manager);
}
void XMLPlatformUtils::closeMutex(void* const mtxHandle)
{
if (mtxHandle == NULL)
return;
RecursiveMutex *rm = (RecursiveMutex *)mtxHandle;
delete rm;
}
void XMLPlatformUtils::lockMutex(void* const mtxHandle)
{
if (mtxHandle == NULL)
return;
RecursiveMutex *rm = (RecursiveMutex *)mtxHandle;
rm->lock();
}
void XMLPlatformUtils::unlockMutex(void* const mtxHandle)
{
if (mtxHandle == NULL)
return;
RecursiveMutex *rm = (RecursiveMutex *)mtxHandle;
rm->unlock();
}
// -----------------------------------------------------------------------
// Miscellaneous synchronization methods
// -----------------------------------------------------------------------
//atomic system calls in Solaris is only restricted to kernel libraries
//So, to make operations thread safe we implement static mutex and lock
//the atomic operations. It makes the process slow but what's the alternative!
void* XMLPlatformUtils::compareAndSwap (void** toFill,
const void* const newValue,
const void* const toCompare)
{
//return ((void*)cas32( (uint32_t*)toFill, (uint32_t)toCompare, (uint32_t)newValue) );
// the below calls are temporarily made till the above functions are part of user library
// Currently its supported only in the kernel mode
if (pthread_mutex_lock( &gAtomicOpMutex->fInstance))
panic(PanicHandler::Panic_SynchronizationErr);
void *retVal = *toFill;
if (*toFill == toCompare)
*toFill = (void *)newValue;
if (pthread_mutex_unlock( &gAtomicOpMutex->fInstance))
panic(PanicHandler::Panic_SynchronizationErr);
return retVal;
}
int XMLPlatformUtils::atomicIncrement(int &location)
{
//return (int)atomic_add_32_nv( (uint32_t*)&location, 1);
if (pthread_mutex_lock( &gAtomicOpMutex->fInstance))
panic(PanicHandler::Panic_SynchronizationErr);
int tmp = ++location;
if (pthread_mutex_unlock( &gAtomicOpMutex->fInstance))
panic(PanicHandler::Panic_SynchronizationErr);
return tmp;
}
int XMLPlatformUtils::atomicDecrement(int &location)
{
//return (int)atomic_add_32_nv( (uint32_t*)&location, -1);
if (pthread_mutex_lock( &gAtomicOpMutex->fInstance))
panic(PanicHandler::Panic_SynchronizationErr);
int tmp = --location;
if (pthread_mutex_unlock( &gAtomicOpMutex->fInstance))
panic(PanicHandler::Panic_SynchronizationErr);
return tmp;
}
#else // #if !defined (APP_NO_THREADS)
void XMLPlatformUtils::platformInit()
{
// do nothing
}
void XMLPlatformUtils::closeMutex(void* const)
{
}
void XMLPlatformUtils::lockMutex(void* const)
{
}
void* XMLPlatformUtils::makeMutex(MemoryManager*)
{
return 0;
}
void XMLPlatformUtils::unlockMutex(void* const)
{
}
void* XMLPlatformUtils::compareAndSwap ( void** toFill,
const void* const newValue,
const void* const toCompare)
{
void *retVal = *toFill;
if (*toFill == toCompare)
*toFill = (void *)newValue;
return retVal;
}
int XMLPlatformUtils::atomicIncrement(int &location)
{
return ++location;
}
int XMLPlatformUtils::atomicDecrement(int &location)
{
return --location;
}
#endif // APP_NO_THREADS
FileHandle XMLPlatformUtils::openStdInHandle(MemoryManager* const manager)
{
return (FileHandle)fdopen(dup(0), "rb");
}
void XMLPlatformUtils::platformTerm()
{
#if !defined (APP_NO_THREADS)
pthread_mutex_destroy(&gAtomicOpMutex->fInstance);
delete gAtomicOpMutex;
gAtomicOpMutex = 0;
#endif
}
#include <xercesc/util/LogicalPath.c>
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
622
]
]
] |
ebdc8a226138d7228deb02099a31d27e09f111d5 | 2e8adfe9e0e8e6bceb7f7b20c73a66ddddc2b60e | /ThorConfigDialog.h | d33884fee6c73479a41561a043e51d7c78959079 | [] | no_license | j3LLostyL3Z/thor-v2 | ee898f9e11023b40e0100f16150fe026dd863f24 | c4555a347a7f833780bc0b65f039397f3787a4c2 | refs/heads/master | 2021-01-10T10:25:51.677372 | 2009-02-06T12:32:34 | 2009-02-06T12:32:34 | 49,520,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 817 | h | // ThorConfigDialog.h: interface for the ThorConfigDialog class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_THORCONFIGDIALOG_H__E11F5A37_C876_4D14_B59D_1B28022DA4B9__INCLUDED_)
#define AFX_THORCONFIGDIALOG_H__E11F5A37_C876_4D14_B59D_1B28022DA4B9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <juce.h>
#include "ThorConfigComponent.h"
#include "ThorConfig.h"
class ThorConfigDialog : public DialogWindow
{
public:
ThorConfigDialog(ThorConfig *_config, Component *content=0);
virtual ~ThorConfigDialog();
void closeButtonPressed();
private:
ThorConfig *config;
ThorConfigComponent *configComponent;
};
#endif // !defined(AFX_THORCONFIGDIALOG_H__E11F5A37_C876_4D14_B59D_1B28022DA4B9__INCLUDED_)
| [
"kubiak.roman@f386313e-e04c-0410-8915-733321d37a57"
] | [
[
[
1,
26
]
]
] |
5d079f67a44ca01d6add5c46c706f60365c66f9e | 6131815bf1b62accfc529c2bc9db21194c7ba545 | /FrameworkApp/App Framework/Shader Interface/Non Animated/SpotLightingInterface.h | a03c41c82a003a6d10f661bf1fd465c25f19a2ee | [] | no_license | dconefourseven/honoursproject | b2ee664ccfc880c008f29d89aad03d9458480fc8 | f26b967fda8eb6937f574fd6f3eb76c8fecf072a | refs/heads/master | 2021-05-29T07:14:35.261586 | 2011-05-15T18:27:49 | 2011-05-15T18:27:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,368 | h | #ifndef _SPOTLIGHTINGINTERFACE_H
#define _SPOTLIGHTINGINTERFACE_H
#include <d3dx9.h>
#include "..\..\Utilities\d3dUtil.h"
typedef struct SpotLighting
{
//The objects needed to be set for the basic lighting shader
D3DXMATRIXA16 m_World, m_WVP, m_LightWVP, m_LightViewProj;
Mtrl m_Material;
SpotLight m_Light;
D3DXVECTOR3 m_EyePosW;
IDirect3DTexture9* m_ShadowMap;
}SpotLighting;
class SpotLightingInterface
{
public:
SpotLightingInterface(IDirect3DDevice9* device);
~SpotLightingInterface();
bool LoadShader();
void SetupHandles();
void UpdateHandles(SpotLighting* input);
void UpdateShadowHandles(D3DXMATRIX* matLightWVP);
void Release();
ID3DXEffect* GetEffect() { return mFX; }
D3DXHANDLE GetTextureHandle() { return mhTex; }
D3DXHANDLE GetTechnique() { return mhTech; }
D3DXHANDLE GetShadowTechnique() { return mhBuildShadowMapTech; }
private:
D3DXHANDLE mhBuildShadowMapTech;
D3DXHANDLE mhLightWVP;
D3DXHANDLE mhTech;
D3DXHANDLE mhWVP;
D3DXHANDLE mhWorldInvTrans;
D3DXHANDLE mhEyePosW;
D3DXHANDLE mhWorld;
D3DXHANDLE mhTex;
D3DXHANDLE mhShadowMap;
D3DXHANDLE mhMtrl;
D3DXHANDLE mhLight;
SpotLight mSpotLight;
D3DXMATRIXA16 m_LightViewProj;
//The effect
ID3DXEffect *mFX;
ID3DXBuffer *m_Error;
IDirect3DDevice9* pDevice;
};
#endif | [
"davidclarke1990@fa56ba20-0011-6cdf-49b4-5b20436119f6"
] | [
[
[
1,
62
]
]
] |
2f198f32436c8b909e5799aa68d80cb28145c478 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/chromium/src/WebViewImpl.cpp | 7343a78f4d69ce931cf3ba752ab8758eef8e852c | [
"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 | 85,639 | cpp | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebViewImpl.h"
#include "AutoFillPopupMenuClient.h"
#include "AXObjectCache.h"
#include "Chrome.h"
#include "ColorSpace.h"
#include "CompositionUnderlineVectorBuilder.h"
#include "ContextMenu.h"
#include "ContextMenuController.h"
#include "ContextMenuItem.h"
#include "CSSStyleSelector.h"
#include "CSSValueKeywords.h"
#include "Cursor.h"
#include "DeviceOrientationClientProxy.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "DOMUtilitiesPrivate.h"
#include "DragController.h"
#include "DragScrollTimer.h"
#include "DragData.h"
#include "Editor.h"
#include "EventHandler.h"
#include "FocusController.h"
#include "FontDescription.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "GLES2Context.h"
#include "GLES2ContextInternal.h"
#include "GraphicsContext.h"
#include "GraphicsContext3D.h"
#include "HTMLInputElement.h"
#include "HTMLMediaElement.h"
#include "HitTestResult.h"
#include "HTMLNames.h"
#include "Image.h"
#include "ImageBuffer.h"
#include "ImageData.h"
#include "InspectorController.h"
#include "KeyboardCodes.h"
#include "KeyboardEvent.h"
#include "MIMETypeRegistry.h"
#include "NodeRenderStyle.h"
#include "Page.h"
#include "PageGroup.h"
#include "PageGroupLoadDeferrer.h"
#include "Pasteboard.h"
#include "PlatformContextSkia.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformMouseEvent.h"
#include "PlatformThemeChromiumGtk.h"
#include "PlatformWheelEvent.h"
#include "PopupMenuChromium.h"
#include "PopupMenuClient.h"
#include "ProgressTracker.h"
#include "RenderView.h"
#include "ResourceHandle.h"
#include "SecurityOrigin.h"
#include "SelectionController.h"
#include "Settings.h"
#include "SharedGraphicsContext3D.h"
#include "Timer.h"
#include "TypingCommand.h"
#include "UserGestureIndicator.h"
#include "Vector.h"
#include "WebAccessibilityObject.h"
#include "WebDevToolsAgentPrivate.h"
#include "WebDevToolsAgentImpl.h"
#include "WebDragData.h"
#include "WebFrameImpl.h"
#include "WebImage.h"
#include "WebInputElement.h"
#include "WebInputEvent.h"
#include "WebInputEventConversion.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebMediaPlayerAction.h"
#include "WebNode.h"
#include "WebPlugin.h"
#include "WebPluginContainerImpl.h"
#include "WebPoint.h"
#include "WebPopupMenuImpl.h"
#include "WebRect.h"
#include "WebRuntimeFeatures.h"
#include "WebSettingsImpl.h"
#include "WebString.h"
#include "WebVector.h"
#include "WebViewClient.h"
#include <wtf/RefPtr.h>
#if PLATFORM(CG)
#include <CoreGraphics/CGContext.h>
#endif
#if OS(WINDOWS)
#include "RenderThemeChromiumWin.h"
#else
#if OS(LINUX)
#include "RenderThemeChromiumLinux.h"
#endif
#include "RenderTheme.h"
#endif
// Get rid of WTF's pow define so we can use std::pow.
#undef pow
#include <cmath> // for std::pow
using namespace WebCore;
namespace WebKit {
// Change the text zoom level by kTextSizeMultiplierRatio each time the user
// zooms text in or out (ie., change by 20%). The min and max values limit
// text zoom to half and 3x the original text size. These three values match
// those in Apple's port in WebKit/WebKit/WebView/WebView.mm
static const double textSizeMultiplierRatio = 1.2;
static const double minTextSizeMultiplier = 0.5;
static const double maxTextSizeMultiplier = 3.0;
// The group name identifies a namespace of pages. Page group is used on OSX
// for some programs that use HTML views to display things that don't seem like
// web pages to the user (so shouldn't have visited link coloring). We only use
// one page group.
const char* pageGroupName = "default";
// Used to defer all page activity in cases where the embedder wishes to run
// a nested event loop. Using a stack enables nesting of message loop invocations.
static Vector<PageGroupLoadDeferrer*> pageGroupLoadDeferrerStack;
// Ensure that the WebDragOperation enum values stay in sync with the original
// DragOperation constants.
#define COMPILE_ASSERT_MATCHING_ENUM(coreName) \
COMPILE_ASSERT(int(coreName) == int(Web##coreName), dummy##coreName)
COMPILE_ASSERT_MATCHING_ENUM(DragOperationNone);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationCopy);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationLink);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationGeneric);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationPrivate);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationMove);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationDelete);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationEvery);
static const PopupContainerSettings autoFillPopupSettings = {
false, // setTextOnIndexChange
false, // acceptOnAbandon
true, // loopSelectionNavigation
false, // restrictWidthOfListBox (For security reasons show the entire entry
// so the user doesn't enter information it did not intend to.)
// For suggestions, we use the direction of the input field as the direction
// of the popup items. The main reason is to keep the display of items in
// drop-down the same as the items in the input field.
PopupContainerSettings::DOMElementDirection,
};
// WebView ----------------------------------------------------------------
WebView* WebView::create(WebViewClient* client, WebDevToolsAgentClient* devToolsClient)
{
// Keep runtime flag for device motion turned off until it's implemented.
WebRuntimeFeatures::enableDeviceMotion(false);
// Pass the WebViewImpl's self-reference to the caller.
return adoptRef(new WebViewImpl(client, devToolsClient)).leakRef();
}
void WebView::updateVisitedLinkState(unsigned long long linkHash)
{
Page::visitedStateChanged(PageGroup::pageGroup(pageGroupName), linkHash);
}
void WebView::resetVisitedLinkState()
{
Page::allVisitedStateChanged(PageGroup::pageGroup(pageGroupName));
}
void WebView::willEnterModalLoop()
{
PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
ASSERT(pageGroup);
if (pageGroup->pages().isEmpty())
pageGroupLoadDeferrerStack.append(static_cast<PageGroupLoadDeferrer*>(0));
else {
// Pick any page in the page group since we are deferring all pages.
pageGroupLoadDeferrerStack.append(new PageGroupLoadDeferrer(*pageGroup->pages().begin(), true));
}
}
void WebView::didExitModalLoop()
{
ASSERT(pageGroupLoadDeferrerStack.size());
delete pageGroupLoadDeferrerStack.last();
pageGroupLoadDeferrerStack.removeLast();
}
void WebViewImpl::initializeMainFrame(WebFrameClient* frameClient)
{
// NOTE: The WebFrameImpl takes a reference to itself within InitMainFrame
// and releases that reference once the corresponding Frame is destroyed.
RefPtr<WebFrameImpl> frame = WebFrameImpl::create(frameClient);
frame->initializeAsMainFrame(this);
// Restrict the access to the local file system
// (see WebView.mm WebView::_commonInitializationWithFrameName).
SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForLocalOnly);
}
WebViewImpl::WebViewImpl(WebViewClient* client, WebDevToolsAgentClient* devToolsClient)
: m_client(client)
, m_backForwardListClientImpl(this)
, m_chromeClientImpl(this)
, m_contextMenuClientImpl(this)
, m_dragClientImpl(this)
, m_editorClientImpl(this)
, m_inspectorClientImpl(this)
, m_observedNewNavigation(false)
#ifndef NDEBUG
, m_newNavigationLoader(0)
#endif
, m_zoomLevel(0)
, m_zoomTextOnly(false)
, m_contextMenuAllowed(false)
, m_doingDragAndDrop(false)
, m_ignoreInputEvents(false)
, m_suppressNextKeypressEvent(false)
, m_initialNavigationPolicy(WebNavigationPolicyIgnore)
, m_imeAcceptEvents(true)
, m_dragTargetDispatch(false)
, m_dragIdentity(0)
, m_dropEffect(DropEffectDefault)
, m_operationsAllowed(WebDragOperationNone)
, m_dragOperation(WebDragOperationNone)
, m_autoFillPopupShowing(false)
, m_autoFillPopupClient(0)
, m_autoFillPopup(0)
, m_isTransparent(false)
, m_tabsToLinks(false)
, m_dragScrollTimer(new DragScrollTimer())
#if USE(ACCELERATED_COMPOSITING)
, m_layerRenderer(0)
, m_isAcceleratedCompositingActive(false)
, m_compositorCreationFailed(false)
#endif
#if ENABLE(INPUT_SPEECH)
, m_speechInputClient(client)
#endif
, m_gles2Context(0)
, m_deviceOrientationClientProxy(new DeviceOrientationClientProxy(client ? client->deviceOrientationClient() : 0))
{
// WebKit/win/WebView.cpp does the same thing, except they call the
// KJS specific wrapper around this method. We need to have threading
// initialized because CollatorICU requires it.
WTF::initializeThreading();
WTF::initializeMainThread();
// set to impossible point so we always get the first mouse pos
m_lastMousePosition = WebPoint(-1, -1);
if (devToolsClient)
m_devToolsAgent = new WebDevToolsAgentImpl(this, devToolsClient);
Page::PageClients pageClients;
pageClients.chromeClient = &m_chromeClientImpl;
pageClients.contextMenuClient = &m_contextMenuClientImpl;
pageClients.editorClient = &m_editorClientImpl;
pageClients.dragClient = &m_dragClientImpl;
pageClients.inspectorClient = &m_inspectorClientImpl;
#if ENABLE(INPUT_SPEECH)
pageClients.speechInputClient = &m_speechInputClient;
#endif
pageClients.deviceOrientationClient = m_deviceOrientationClientProxy.get();
m_page.set(new Page(pageClients));
m_page->backForwardList()->setClient(&m_backForwardListClientImpl);
m_page->setGroupName(pageGroupName);
m_inspectorSettingsMap.set(new SettingsMap);
}
WebViewImpl::~WebViewImpl()
{
ASSERT(!m_page);
}
RenderTheme* WebViewImpl::theme() const
{
return m_page.get() ? m_page->theme() : RenderTheme::defaultTheme().get();
}
WebFrameImpl* WebViewImpl::mainFrameImpl()
{
return m_page.get() ? WebFrameImpl::fromFrame(m_page->mainFrame()) : 0;
}
bool WebViewImpl::tabKeyCyclesThroughElements() const
{
ASSERT(m_page.get());
return m_page->tabKeyCyclesThroughElements();
}
void WebViewImpl::setTabKeyCyclesThroughElements(bool value)
{
if (m_page)
m_page->setTabKeyCyclesThroughElements(value);
}
void WebViewImpl::mouseMove(const WebMouseEvent& event)
{
if (!mainFrameImpl() || !mainFrameImpl()->frameView())
return;
m_lastMousePosition = WebPoint(event.x, event.y);
// We call mouseMoved here instead of handleMouseMovedEvent because we need
// our ChromeClientImpl to receive changes to the mouse position and
// tooltip text, and mouseMoved handles all of that.
mainFrameImpl()->frame()->eventHandler()->mouseMoved(
PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
}
void WebViewImpl::mouseLeave(const WebMouseEvent& event)
{
// This event gets sent as the main frame is closing. In that case, just
// ignore it.
if (!mainFrameImpl() || !mainFrameImpl()->frameView())
return;
m_client->setMouseOverURL(WebURL());
mainFrameImpl()->frame()->eventHandler()->handleMouseMoveEvent(
PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
}
void WebViewImpl::mouseDown(const WebMouseEvent& event)
{
if (!mainFrameImpl() || !mainFrameImpl()->frameView())
return;
// If there is a select popup open, close it as the user is clicking on
// the page (outside of the popup). We also save it so we can prevent a
// click on the select element from immediately reopening the popup.
RefPtr<WebCore::PopupContainer> selectPopup;
if (event.button == WebMouseEvent::ButtonLeft) {
selectPopup = m_selectPopup;
hideSelectPopup();
ASSERT(!m_selectPopup);
}
m_lastMouseDownPoint = WebPoint(event.x, event.y);
RefPtr<Node> clickedNode;
if (event.button == WebMouseEvent::ButtonLeft) {
IntPoint point(event.x, event.y);
point = m_page->mainFrame()->view()->windowToContents(point);
HitTestResult result(m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false));
Node* hitNode = result.innerNonSharedNode();
// Take capture on a mouse down on a plugin so we can send it mouse events.
if (hitNode && hitNode->renderer() && hitNode->renderer()->isEmbeddedObject())
m_mouseCaptureNode = hitNode;
// If a text field that has focus is clicked again, we should display the
// AutoFill popup.
RefPtr<Node> focusedNode = focusedWebCoreNode();
if (focusedNode.get() && toHTMLInputElement(focusedNode.get())) {
if (hitNode == focusedNode) {
// Already focused text field was clicked, let's remember this. If
// focus has not changed after the mouse event is processed, we'll
// trigger the autocomplete.
clickedNode = focusedNode;
}
}
}
mainFrameImpl()->frame()->loader()->resetMultipleFormSubmissionProtection();
mainFrameImpl()->frame()->eventHandler()->handleMousePressEvent(
PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
if (clickedNode.get() && clickedNode == focusedWebCoreNode()) {
// Focus has not changed, show the AutoFill popup.
static_cast<EditorClientImpl*>(m_page->editorClient())->
showFormAutofillForNode(clickedNode.get());
}
if (m_selectPopup && m_selectPopup == selectPopup) {
// That click triggered a select popup which is the same as the one that
// was showing before the click. It means the user clicked the select
// while the popup was showing, and as a result we first closed then
// immediately reopened the select popup. It needs to be closed.
hideSelectPopup();
}
// Dispatch the contextmenu event regardless of if the click was swallowed.
// On Windows, we handle it on mouse up, not down.
#if OS(DARWIN)
if (event.button == WebMouseEvent::ButtonRight
|| (event.button == WebMouseEvent::ButtonLeft
&& event.modifiers & WebMouseEvent::ControlKey))
mouseContextMenu(event);
#elif OS(LINUX)
if (event.button == WebMouseEvent::ButtonRight)
mouseContextMenu(event);
#endif
}
void WebViewImpl::mouseContextMenu(const WebMouseEvent& event)
{
if (!mainFrameImpl() || !mainFrameImpl()->frameView())
return;
m_page->contextMenuController()->clearContextMenu();
PlatformMouseEventBuilder pme(mainFrameImpl()->frameView(), event);
// Find the right target frame. See issue 1186900.
HitTestResult result = hitTestResultForWindowPos(pme.pos());
Frame* targetFrame;
if (result.innerNonSharedNode())
targetFrame = result.innerNonSharedNode()->document()->frame();
else
targetFrame = m_page->focusController()->focusedOrMainFrame();
#if OS(WINDOWS)
targetFrame->view()->setCursor(pointerCursor());
#endif
m_contextMenuAllowed = true;
targetFrame->eventHandler()->sendContextMenuEvent(pme);
m_contextMenuAllowed = false;
// Actually showing the context menu is handled by the ContextMenuClient
// implementation...
}
void WebViewImpl::mouseUp(const WebMouseEvent& event)
{
if (!mainFrameImpl() || !mainFrameImpl()->frameView())
return;
#if OS(LINUX)
// If the event was a middle click, attempt to copy text into the focused
// frame. We execute this before we let the page have a go at the event
// because the page may change what is focused during in its event handler.
//
// This code is in the mouse up handler. There is some debate about putting
// this here, as opposed to the mouse down handler.
// xterm: pastes on up.
// GTK: pastes on down.
// Firefox: pastes on up.
// Midori: couldn't paste at all with 0.1.2
//
// There is something of a webcompat angle to this well, as highlighted by
// crbug.com/14608. Pages can clear text boxes 'onclick' and, if we paste on
// down then the text is pasted just before the onclick handler runs and
// clears the text box. So it's important this happens after the
// handleMouseReleaseEvent() earlier in this function
if (event.button == WebMouseEvent::ButtonMiddle) {
Frame* focused = focusedWebCoreFrame();
FrameView* view = m_page->mainFrame()->view();
IntPoint clickPoint(m_lastMouseDownPoint.x, m_lastMouseDownPoint.y);
IntPoint contentPoint = view->windowToContents(clickPoint);
HitTestResult hitTestResult = focused->eventHandler()->hitTestResultAtPoint(contentPoint, false, false, ShouldHitTestScrollbars);
// We don't want to send a paste when middle clicking a scroll bar or a
// link (which will navigate later in the code). The main scrollbars
// have to be handled separately.
if (!hitTestResult.scrollbar() && !hitTestResult.isLiveLink() && focused && !view->scrollbarAtPoint(clickPoint)) {
Editor* editor = focused->editor();
Pasteboard* pasteboard = Pasteboard::generalPasteboard();
bool oldSelectionMode = pasteboard->isSelectionMode();
pasteboard->setSelectionMode(true);
editor->command(AtomicString("Paste")).execute();
pasteboard->setSelectionMode(oldSelectionMode);
}
}
#endif
mainFrameImpl()->frame()->eventHandler()->handleMouseReleaseEvent(
PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
#if OS(WINDOWS)
// Dispatch the contextmenu event regardless of if the click was swallowed.
// On Mac/Linux, we handle it on mouse down, not up.
if (event.button == WebMouseEvent::ButtonRight)
mouseContextMenu(event);
#endif
}
bool WebViewImpl::mouseWheel(const WebMouseWheelEvent& event)
{
PlatformWheelEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
return mainFrameImpl()->frame()->eventHandler()->handleWheelEvent(platformEvent);
}
bool WebViewImpl::keyEvent(const WebKeyboardEvent& event)
{
ASSERT((event.type == WebInputEvent::RawKeyDown)
|| (event.type == WebInputEvent::KeyDown)
|| (event.type == WebInputEvent::KeyUp));
// Please refer to the comments explaining the m_suppressNextKeypressEvent
// member.
// The m_suppressNextKeypressEvent is set if the KeyDown is handled by
// Webkit. A keyDown event is typically associated with a keyPress(char)
// event and a keyUp event. We reset this flag here as this is a new keyDown
// event.
m_suppressNextKeypressEvent = false;
// Give any select popup a chance at consuming the key event.
if (selectPopupHandleKeyEvent(event))
return true;
// Give Autocomplete a chance to consume the key events it is interested in.
if (autocompleteHandleKeyEvent(event))
return true;
Frame* frame = focusedWebCoreFrame();
if (!frame)
return false;
EventHandler* handler = frame->eventHandler();
if (!handler)
return keyEventDefault(event);
#if OS(WINDOWS) || OS(LINUX)
const WebInputEvent::Type contextMenuTriggeringEventType =
#if OS(WINDOWS)
WebInputEvent::KeyUp;
#elif OS(LINUX)
WebInputEvent::RawKeyDown;
#endif
if (((!event.modifiers && (event.windowsKeyCode == VKEY_APPS))
|| ((event.modifiers == WebInputEvent::ShiftKey) && (event.windowsKeyCode == VKEY_F10)))
&& event.type == contextMenuTriggeringEventType) {
sendContextMenuEvent(event);
return true;
}
#endif
// It's not clear if we should continue after detecting a capslock keypress.
// I'll err on the side of continuing, which is the pre-existing behaviour.
if (event.windowsKeyCode == VKEY_CAPITAL)
handler->capsLockStateMayHaveChanged();
PlatformKeyboardEventBuilder evt(event);
if (handler->keyEvent(evt)) {
if (WebInputEvent::RawKeyDown == event.type) {
// Suppress the next keypress event unless the focused node is a plug-in node.
// (Flash needs these keypress events to handle non-US keyboards.)
Node* node = frame->document()->focusedNode();
if (!node || !node->renderer() || !node->renderer()->isEmbeddedObject())
m_suppressNextKeypressEvent = true;
}
return true;
}
return keyEventDefault(event);
}
bool WebViewImpl::selectPopupHandleKeyEvent(const WebKeyboardEvent& event)
{
if (!m_selectPopup)
return false;
return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
}
bool WebViewImpl::autocompleteHandleKeyEvent(const WebKeyboardEvent& event)
{
if (!m_autoFillPopupShowing
// Home and End should be left to the text field to process.
|| event.windowsKeyCode == VKEY_HOME
|| event.windowsKeyCode == VKEY_END)
return false;
// Pressing delete triggers the removal of the selected suggestion from the DB.
if (event.windowsKeyCode == VKEY_DELETE
&& m_autoFillPopup->selectedIndex() != -1) {
Node* node = focusedWebCoreNode();
if (!node || (node->nodeType() != Node::ELEMENT_NODE)) {
ASSERT_NOT_REACHED();
return false;
}
Element* element = static_cast<Element*>(node);
if (!element->hasLocalName(HTMLNames::inputTag)) {
ASSERT_NOT_REACHED();
return false;
}
int selectedIndex = m_autoFillPopup->selectedIndex();
if (!m_autoFillPopupClient->canRemoveSuggestionAtIndex(selectedIndex))
return false;
WebString name = WebInputElement(static_cast<HTMLInputElement*>(element)).nameForAutofill();
WebString value = m_autoFillPopupClient->itemText(selectedIndex);
m_client->removeAutofillSuggestions(name, value);
// Update the entries in the currently showing popup to reflect the
// deletion.
m_autoFillPopupClient->removeSuggestionAtIndex(selectedIndex);
refreshAutoFillPopup();
return false;
}
if (!m_autoFillPopup->isInterestedInEventForKey(event.windowsKeyCode))
return false;
if (m_autoFillPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event))) {
// We need to ignore the next Char event after this otherwise pressing
// enter when selecting an item in the menu will go to the page.
if (WebInputEvent::RawKeyDown == event.type)
m_suppressNextKeypressEvent = true;
return true;
}
return false;
}
bool WebViewImpl::charEvent(const WebKeyboardEvent& event)
{
ASSERT(event.type == WebInputEvent::Char);
// Please refer to the comments explaining the m_suppressNextKeypressEvent
// member. The m_suppressNextKeypressEvent is set if the KeyDown is
// handled by Webkit. A keyDown event is typically associated with a
// keyPress(char) event and a keyUp event. We reset this flag here as it
// only applies to the current keyPress event.
bool suppress = m_suppressNextKeypressEvent;
m_suppressNextKeypressEvent = false;
Frame* frame = focusedWebCoreFrame();
if (!frame)
return suppress;
EventHandler* handler = frame->eventHandler();
if (!handler)
return suppress || keyEventDefault(event);
PlatformKeyboardEventBuilder evt(event);
if (!evt.isCharacterKey())
return true;
// Accesskeys are triggered by char events and can't be suppressed.
if (handler->handleAccessKey(evt))
return true;
// Safari 3.1 does not pass off windows system key messages (WM_SYSCHAR) to
// the eventHandler::keyEvent. We mimic this behavior on all platforms since
// for now we are converting other platform's key events to windows key
// events.
if (evt.isSystemKey())
return false;
if (!suppress && !handler->keyEvent(evt))
return keyEventDefault(event);
return true;
}
#if ENABLE(TOUCH_EVENTS)
bool WebViewImpl::touchEvent(const WebTouchEvent& event)
{
if (!mainFrameImpl() || !mainFrameImpl()->frameView())
return false;
PlatformTouchEventBuilder touchEventBuilder(mainFrameImpl()->frameView(), event);
return mainFrameImpl()->frame()->eventHandler()->handleTouchEvent(touchEventBuilder);
}
#endif
#if OS(WINDOWS) || OS(LINUX)
// Mac has no way to open a context menu based on a keyboard event.
bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event)
{
// The contextMenuController() holds onto the last context menu that was
// popped up on the page until a new one is created. We need to clear
// this menu before propagating the event through the DOM so that we can
// detect if we create a new menu for this event, since we won't create
// a new menu if the DOM swallows the event and the defaultEventHandler does
// not run.
page()->contextMenuController()->clearContextMenu();
m_contextMenuAllowed = true;
Frame* focusedFrame = page()->focusController()->focusedOrMainFrame();
bool handled = focusedFrame->eventHandler()->sendContextMenuEventForKey();
m_contextMenuAllowed = false;
return handled;
}
#endif
bool WebViewImpl::keyEventDefault(const WebKeyboardEvent& event)
{
Frame* frame = focusedWebCoreFrame();
if (!frame)
return false;
switch (event.type) {
case WebInputEvent::Char:
if (event.windowsKeyCode == VKEY_SPACE) {
int keyCode = ((event.modifiers & WebInputEvent::ShiftKey) ? VKEY_PRIOR : VKEY_NEXT);
return scrollViewWithKeyboard(keyCode, event.modifiers);
}
break;
case WebInputEvent::RawKeyDown:
if (event.modifiers == WebInputEvent::ControlKey) {
switch (event.windowsKeyCode) {
#if !OS(DARWIN)
case 'A':
focusedFrame()->executeCommand(WebString::fromUTF8("SelectAll"));
return true;
case VKEY_INSERT:
case 'C':
focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
return true;
#endif
// Match FF behavior in the sense that Ctrl+home/end are the only Ctrl
// key combinations which affect scrolling. Safari is buggy in the
// sense that it scrolls the page for all Ctrl+scrolling key
// combinations. For e.g. Ctrl+pgup/pgdn/up/down, etc.
case VKEY_HOME:
case VKEY_END:
break;
default:
return false;
}
}
if (!event.isSystemKey && !(event.modifiers & WebInputEvent::ShiftKey))
return scrollViewWithKeyboard(event.windowsKeyCode, event.modifiers);
break;
default:
break;
}
return false;
}
bool WebViewImpl::scrollViewWithKeyboard(int keyCode, int modifiers)
{
ScrollDirection scrollDirection;
ScrollGranularity scrollGranularity;
if (!mapKeyCodeForScroll(keyCode, &scrollDirection, &scrollGranularity))
return false;
return propagateScroll(scrollDirection, scrollGranularity);
}
bool WebViewImpl::mapKeyCodeForScroll(int keyCode,
WebCore::ScrollDirection* scrollDirection,
WebCore::ScrollGranularity* scrollGranularity)
{
switch (keyCode) {
case VKEY_LEFT:
*scrollDirection = ScrollLeft;
*scrollGranularity = ScrollByLine;
break;
case VKEY_RIGHT:
*scrollDirection = ScrollRight;
*scrollGranularity = ScrollByLine;
break;
case VKEY_UP:
*scrollDirection = ScrollUp;
*scrollGranularity = ScrollByLine;
break;
case VKEY_DOWN:
*scrollDirection = ScrollDown;
*scrollGranularity = ScrollByLine;
break;
case VKEY_HOME:
*scrollDirection = ScrollUp;
*scrollGranularity = ScrollByDocument;
break;
case VKEY_END:
*scrollDirection = ScrollDown;
*scrollGranularity = ScrollByDocument;
break;
case VKEY_PRIOR: // page up
*scrollDirection = ScrollUp;
*scrollGranularity = ScrollByPage;
break;
case VKEY_NEXT: // page down
*scrollDirection = ScrollDown;
*scrollGranularity = ScrollByPage;
break;
default:
return false;
}
return true;
}
void WebViewImpl::hideSelectPopup()
{
if (m_selectPopup.get())
m_selectPopup->hidePopup();
}
bool WebViewImpl::propagateScroll(ScrollDirection scrollDirection,
ScrollGranularity scrollGranularity)
{
Frame* frame = focusedWebCoreFrame();
if (!frame)
return false;
bool scrollHandled = frame->eventHandler()->scrollOverflow(scrollDirection, scrollGranularity);
Frame* currentFrame = frame;
while (!scrollHandled && currentFrame) {
scrollHandled = currentFrame->view()->scroll(scrollDirection, scrollGranularity);
currentFrame = currentFrame->tree()->parent();
}
return scrollHandled;
}
void WebViewImpl::popupOpened(WebCore::PopupContainer* popupContainer)
{
if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
ASSERT(!m_selectPopup);
m_selectPopup = popupContainer;
}
}
void WebViewImpl::popupClosed(WebCore::PopupContainer* popupContainer)
{
if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
ASSERT(m_selectPopup.get());
m_selectPopup = 0;
}
}
void WebViewImpl::hideAutoFillPopup()
{
if (m_autoFillPopupShowing) {
m_autoFillPopup->hidePopup();
m_autoFillPopupShowing = false;
}
}
Frame* WebViewImpl::focusedWebCoreFrame()
{
return m_page.get() ? m_page->focusController()->focusedOrMainFrame() : 0;
}
WebViewImpl* WebViewImpl::fromPage(Page* page)
{
if (!page)
return 0;
return static_cast<ChromeClientImpl*>(page->chrome()->client())->webView();
}
// WebWidget ------------------------------------------------------------------
void WebViewImpl::close()
{
RefPtr<WebFrameImpl> mainFrameImpl;
if (m_page.get()) {
// Initiate shutdown for the entire frameset. This will cause a lot of
// notifications to be sent.
if (m_page->mainFrame()) {
mainFrameImpl = WebFrameImpl::fromFrame(m_page->mainFrame());
m_page->mainFrame()->loader()->frameDetached();
}
m_page.clear();
}
// Should happen after m_page.clear().
if (m_devToolsAgent.get())
m_devToolsAgent.clear();
// Reset the delegate to prevent notifications being sent as we're being
// deleted.
m_client = 0;
deref(); // Balances ref() acquired in WebView::create
}
void WebViewImpl::resize(const WebSize& newSize)
{
if (m_size == newSize)
return;
m_size = newSize;
if (mainFrameImpl()->frameView()) {
mainFrameImpl()->frameView()->resize(m_size.width, m_size.height);
mainFrameImpl()->frame()->eventHandler()->sendResizeEvent();
}
if (m_client) {
WebRect damagedRect(0, 0, m_size.width, m_size.height);
if (isAcceleratedCompositingActive()) {
#if USE(ACCELERATED_COMPOSITING)
invalidateRootLayerRect(damagedRect);
#endif
} else
m_client->didInvalidateRect(damagedRect);
}
#if OS(DARWIN)
if (m_gles2Context) {
m_gles2Context->resizeOnscreenContent(WebSize(std::max(1, m_size.width),
std::max(1, m_size.height)));
}
#endif
}
void WebViewImpl::layout()
{
WebFrameImpl* webframe = mainFrameImpl();
if (webframe) {
// In order for our child HWNDs (NativeWindowWidgets) to update properly,
// they need to be told that we are updating the screen. The problem is
// that the native widgets need to recalculate their clip region and not
// overlap any of our non-native widgets. To force the resizing, call
// setFrameRect(). This will be a quick operation for most frames, but
// the NativeWindowWidgets will update a proper clipping region.
FrameView* view = webframe->frameView();
if (view)
view->setFrameRect(view->frameRect());
// setFrameRect may have the side-effect of causing existing page
// layout to be invalidated, so layout needs to be called last.
webframe->layout();
}
}
#if USE(ACCELERATED_COMPOSITING)
void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
{
ASSERT(rect.right() <= m_layerRenderer->rootLayerTextureSize().width()
&& rect.bottom() <= m_layerRenderer->rootLayerTextureSize().height());
#if PLATFORM(SKIA)
PlatformContextSkia context(canvas);
// PlatformGraphicsContext is actually a pointer to PlatformContextSkia
GraphicsContext gc(reinterpret_cast<PlatformGraphicsContext*>(&context));
int bitmapHeight = canvas->getDevice()->accessBitmap(false).height();
#elif PLATFORM(CG)
GraphicsContext gc(canvas);
int bitmapHeight = CGBitmapContextGetHeight(reinterpret_cast<CGContextRef>(canvas));
#else
notImplemented();
#endif
// Compute rect to sample from inverted GPU buffer.
IntRect invertRect(rect.x(), bitmapHeight - rect.bottom(), rect.width(), rect.height());
OwnPtr<ImageBuffer> imageBuffer(ImageBuffer::create(rect.size()));
RefPtr<ImageData> imageData(ImageData::create(rect.width(), rect.height()));
if (imageBuffer.get() && imageData.get()) {
m_layerRenderer->getFramebufferPixels(imageData->data()->data()->data(), invertRect);
imageBuffer->putPremultipliedImageData(imageData.get(), IntRect(IntPoint(), rect.size()), IntPoint());
gc.save();
gc.translate(FloatSize(0.0f, bitmapHeight));
gc.scale(FloatSize(1.0f, -1.0f));
// Use invertRect in next line, so that transform above inverts it back to
// desired destination rect.
gc.drawImageBuffer(imageBuffer.get(), DeviceColorSpace, invertRect.location());
gc.restore();
}
}
#endif
void WebViewImpl::paint(WebCanvas* canvas, const WebRect& rect)
{
if (isAcceleratedCompositingActive()) {
#if USE(ACCELERATED_COMPOSITING)
doComposite();
// If a canvas was passed in, we use it to grab a copy of the
// freshly-rendered pixels.
if (canvas) {
// Clip rect to the confines of the rootLayerTexture.
IntRect resizeRect(rect);
resizeRect.intersect(IntRect(IntPoint(), m_layerRenderer->rootLayerTextureSize()));
doPixelReadbackToCanvas(canvas, resizeRect);
}
// Temporarily present so the downstream Chromium renderwidget still renders.
// FIXME: remove this call once the changes to Chromium's renderwidget have landed.
m_layerRenderer->present();
#endif
} else {
WebFrameImpl* webframe = mainFrameImpl();
if (webframe)
webframe->paint(canvas, rect);
}
}
void WebViewImpl::themeChanged()
{
if (!page())
return;
FrameView* view = page()->mainFrame()->view();
WebRect damagedRect(0, 0, m_size.width, m_size.height);
view->invalidateRect(damagedRect);
}
void WebViewImpl::composite(bool finish)
{
#if USE(ACCELERATED_COMPOSITING)
doComposite();
// Finish if requested.
// FIXME: handle finish flag.
// Put result onscreen.
m_layerRenderer->present();
#endif
}
// FIXME: m_currentInputEvent should be removed once ChromeClient::show() can
// get the current-event information from WebCore.
const WebInputEvent* WebViewImpl::m_currentInputEvent = 0;
bool WebViewImpl::handleInputEvent(const WebInputEvent& inputEvent)
{
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
// If we've started a drag and drop operation, ignore input events until
// we're done.
if (m_doingDragAndDrop)
return true;
if (m_ignoreInputEvents)
return true;
if (m_mouseCaptureNode.get() && WebInputEvent::isMouseEventType(inputEvent.type)) {
// Save m_mouseCaptureNode since mouseCaptureLost() will clear it.
RefPtr<Node> node = m_mouseCaptureNode;
// Not all platforms call mouseCaptureLost() directly.
if (inputEvent.type == WebInputEvent::MouseUp)
mouseCaptureLost();
AtomicString eventType;
switch (inputEvent.type) {
case WebInputEvent::MouseMove:
eventType = eventNames().mousemoveEvent;
break;
case WebInputEvent::MouseLeave:
eventType = eventNames().mouseoutEvent;
break;
case WebInputEvent::MouseDown:
eventType = eventNames().mousedownEvent;
break;
case WebInputEvent::MouseUp:
eventType = eventNames().mouseupEvent;
break;
default:
ASSERT_NOT_REACHED();
}
node->dispatchMouseEvent(
PlatformMouseEventBuilder(mainFrameImpl()->frameView(), *static_cast<const WebMouseEvent*>(&inputEvent)),
eventType);
return true;
}
// FIXME: Remove m_currentInputEvent.
// This only exists to allow ChromeClient::show() to know which mouse button
// triggered a window.open event.
// Safari must perform a similar hack, ours is in our WebKit glue layer
// theirs is in the application. This should go when WebCore can be fixed
// to pass more event information to ChromeClient::show()
m_currentInputEvent = &inputEvent;
bool handled = true;
// FIXME: WebKit seems to always return false on mouse events processing
// methods. For now we'll assume it has processed them (as we are only
// interested in whether keyboard events are processed).
switch (inputEvent.type) {
case WebInputEvent::MouseMove:
mouseMove(*static_cast<const WebMouseEvent*>(&inputEvent));
break;
case WebInputEvent::MouseLeave:
mouseLeave(*static_cast<const WebMouseEvent*>(&inputEvent));
break;
case WebInputEvent::MouseWheel:
handled = mouseWheel(*static_cast<const WebMouseWheelEvent*>(&inputEvent));
break;
case WebInputEvent::MouseDown:
mouseDown(*static_cast<const WebMouseEvent*>(&inputEvent));
break;
case WebInputEvent::MouseUp:
mouseUp(*static_cast<const WebMouseEvent*>(&inputEvent));
break;
case WebInputEvent::RawKeyDown:
case WebInputEvent::KeyDown:
case WebInputEvent::KeyUp:
handled = keyEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
break;
case WebInputEvent::Char:
handled = charEvent(*static_cast<const WebKeyboardEvent*>(&inputEvent));
break;
#if ENABLE(TOUCH_EVENTS)
case WebInputEvent::TouchStart:
case WebInputEvent::TouchMove:
case WebInputEvent::TouchEnd:
case WebInputEvent::TouchCancel:
handled = touchEvent(*static_cast<const WebTouchEvent*>(&inputEvent));
break;
#endif
default:
handled = false;
}
m_currentInputEvent = 0;
return handled;
}
void WebViewImpl::mouseCaptureLost()
{
m_mouseCaptureNode = 0;
}
void WebViewImpl::setFocus(bool enable)
{
m_page->focusController()->setFocused(enable);
if (enable) {
// Note that we don't call setActive() when disabled as this cause extra
// focus/blur events to be dispatched.
m_page->focusController()->setActive(true);
RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
if (focusedFrame) {
Node* focusedNode = focusedFrame->document()->focusedNode();
if (focusedNode && focusedNode->isElementNode()
&& focusedFrame->selection()->selection().isNone()) {
// If the selection was cleared while the WebView was not
// focused, then the focus element shows with a focus ring but
// no caret and does respond to keyboard inputs.
Element* element = static_cast<Element*>(focusedNode);
if (element->isTextFormControl())
element->updateFocusAppearance(true);
else if (focusedNode->isContentEditable()) {
// updateFocusAppearance() selects all the text of
// contentseditable DIVs. So we set the selection explicitly
// instead. Note that this has the side effect of moving the
// caret back to the beginning of the text.
Position position(focusedNode, 0,
Position::PositionIsOffsetInAnchor);
focusedFrame->selection()->setSelection(
VisibleSelection(position, SEL_DEFAULT_AFFINITY));
}
}
}
m_imeAcceptEvents = true;
} else {
hideAutoFillPopup();
hideSelectPopup();
// Clear focus on the currently focused frame if any.
if (!m_page.get())
return;
Frame* frame = m_page->mainFrame();
if (!frame)
return;
RefPtr<Frame> focusedFrame = m_page->focusController()->focusedFrame();
if (focusedFrame.get()) {
// Finish an ongoing composition to delete the composition node.
Editor* editor = focusedFrame->editor();
if (editor && editor->hasComposition())
editor->confirmComposition();
m_imeAcceptEvents = false;
}
}
}
bool WebViewImpl::setComposition(
const WebString& text,
const WebVector<WebCompositionUnderline>& underlines,
int selectionStart,
int selectionEnd)
{
Frame* focused = focusedWebCoreFrame();
if (!focused || !m_imeAcceptEvents)
return false;
Editor* editor = focused->editor();
if (!editor)
return false;
// The input focus has been moved to another WebWidget object.
// We should use this |editor| object only to complete the ongoing
// composition.
if (!editor->canEdit() && !editor->hasComposition())
return false;
// We should verify the parent node of this IME composition node are
// editable because JavaScript may delete a parent node of the composition
// node. In this case, WebKit crashes while deleting texts from the parent
// node, which doesn't exist any longer.
PassRefPtr<Range> range = editor->compositionRange();
if (range) {
const Node* node = range->startPosition().node();
if (!node || !node->isContentEditable())
return false;
}
// If we're not going to fire a keypress event, then the keydown event was
// canceled. In that case, cancel any existing composition.
if (text.isEmpty() || m_suppressNextKeypressEvent) {
// A browser process sent an IPC message which does not contain a valid
// string, which means an ongoing composition has been canceled.
// If the ongoing composition has been canceled, replace the ongoing
// composition string with an empty string and complete it.
String emptyString;
Vector<CompositionUnderline> emptyUnderlines;
editor->setComposition(emptyString, emptyUnderlines, 0, 0);
return text.isEmpty();
}
// When the range of composition underlines overlap with the range between
// selectionStart and selectionEnd, WebKit somehow won't paint the selection
// at all (see InlineTextBox::paint() function in InlineTextBox.cpp).
// But the selection range actually takes effect.
editor->setComposition(String(text),
CompositionUnderlineVectorBuilder(underlines),
selectionStart, selectionEnd);
return editor->hasComposition();
}
bool WebViewImpl::confirmComposition()
{
Frame* focused = focusedWebCoreFrame();
if (!focused || !m_imeAcceptEvents)
return false;
Editor* editor = focused->editor();
if (!editor || !editor->hasComposition())
return false;
// We should verify the parent node of this IME composition node are
// editable because JavaScript may delete a parent node of the composition
// node. In this case, WebKit crashes while deleting texts from the parent
// node, which doesn't exist any longer.
PassRefPtr<Range> range = editor->compositionRange();
if (range) {
const Node* node = range->startPosition().node();
if (!node || !node->isContentEditable())
return false;
}
editor->confirmComposition();
return true;
}
WebTextInputType WebViewImpl::textInputType()
{
WebTextInputType type = WebTextInputTypeNone;
const Frame* focused = focusedWebCoreFrame();
if (!focused)
return type;
const Editor* editor = focused->editor();
if (!editor || !editor->canEdit())
return type;
SelectionController* controller = focused->selection();
if (!controller)
return type;
const Node* node = controller->start().node();
if (!node)
return type;
// FIXME: Support more text input types when necessary, eg. Number,
// Date, Email, URL, etc.
if (controller->isInPasswordField())
type = WebTextInputTypePassword;
else if (node->shouldUseInputMethod())
type = WebTextInputTypeText;
return type;
}
WebRect WebViewImpl::caretOrSelectionBounds()
{
WebRect rect;
const Frame* focused = focusedWebCoreFrame();
if (!focused)
return rect;
SelectionController* controller = focused->selection();
if (!controller)
return rect;
const FrameView* view = focused->view();
if (!view)
return rect;
const Node* node = controller->start().node();
if (!node || !node->renderer())
return rect;
if (controller->isCaret())
rect = view->contentsToWindow(controller->absoluteCaretBounds());
else if (controller->isRange()) {
node = controller->end().node();
if (!node || !node->renderer())
return rect;
RefPtr<Range> range = controller->toNormalizedRange();
rect = view->contentsToWindow(focused->editor()->firstRectForRange(range.get()));
}
return rect;
}
void WebViewImpl::setTextDirection(WebTextDirection direction)
{
// The Editor::setBaseWritingDirection() function checks if we can change
// the text direction of the selected node and updates its DOM "dir"
// attribute and its CSS "direction" property.
// So, we just call the function as Safari does.
const Frame* focused = focusedWebCoreFrame();
if (!focused)
return;
Editor* editor = focused->editor();
if (!editor || !editor->canEdit())
return;
switch (direction) {
case WebTextDirectionDefault:
editor->setBaseWritingDirection(NaturalWritingDirection);
break;
case WebTextDirectionLeftToRight:
editor->setBaseWritingDirection(LeftToRightWritingDirection);
break;
case WebTextDirectionRightToLeft:
editor->setBaseWritingDirection(RightToLeftWritingDirection);
break;
default:
notImplemented();
break;
}
}
bool WebViewImpl::isAcceleratedCompositingActive() const
{
#if USE(ACCELERATED_COMPOSITING)
return m_isAcceleratedCompositingActive;
#else
return false;
#endif
}
// WebView --------------------------------------------------------------------
WebSettings* WebViewImpl::settings()
{
if (!m_webSettings.get())
m_webSettings.set(new WebSettingsImpl(m_page->settings()));
ASSERT(m_webSettings.get());
return m_webSettings.get();
}
WebString WebViewImpl::pageEncoding() const
{
if (!m_page.get())
return WebString();
return m_page->mainFrame()->loader()->writer()->encoding();
}
void WebViewImpl::setPageEncoding(const WebString& encodingName)
{
if (!m_page.get())
return;
// Only change override encoding, don't change default encoding.
// Note that the new encoding must be 0 if it isn't supposed to be set.
String newEncodingName;
if (!encodingName.isEmpty())
newEncodingName = encodingName;
m_page->mainFrame()->loader()->reloadWithOverrideEncoding(newEncodingName);
}
bool WebViewImpl::dispatchBeforeUnloadEvent()
{
// FIXME: This should really cause a recursive depth-first walk of all
// frames in the tree, calling each frame's onbeforeunload. At the moment,
// we're consistent with Safari 3.1, not IE/FF.
Frame* frame = m_page->mainFrame();
if (!frame)
return true;
return frame->loader()->shouldClose();
}
void WebViewImpl::dispatchUnloadEvent()
{
// Run unload handlers.
m_page->mainFrame()->loader()->closeURL();
}
WebFrame* WebViewImpl::mainFrame()
{
return mainFrameImpl();
}
WebFrame* WebViewImpl::findFrameByName(
const WebString& name, WebFrame* relativeToFrame)
{
if (!relativeToFrame)
relativeToFrame = mainFrame();
Frame* frame = static_cast<WebFrameImpl*>(relativeToFrame)->frame();
frame = frame->tree()->find(name);
return WebFrameImpl::fromFrame(frame);
}
WebFrame* WebViewImpl::focusedFrame()
{
return WebFrameImpl::fromFrame(focusedWebCoreFrame());
}
void WebViewImpl::setFocusedFrame(WebFrame* frame)
{
if (!frame) {
// Clears the focused frame if any.
Frame* frame = focusedWebCoreFrame();
if (frame)
frame->selection()->setFocused(false);
return;
}
WebFrameImpl* frameImpl = static_cast<WebFrameImpl*>(frame);
Frame* webcoreFrame = frameImpl->frame();
webcoreFrame->page()->focusController()->setFocusedFrame(webcoreFrame);
}
void WebViewImpl::setInitialFocus(bool reverse)
{
if (!m_page.get())
return;
// Since we don't have a keyboard event, we'll create one.
WebKeyboardEvent keyboardEvent;
keyboardEvent.type = WebInputEvent::RawKeyDown;
if (reverse)
keyboardEvent.modifiers = WebInputEvent::ShiftKey;
// VK_TAB which is only defined on Windows.
keyboardEvent.windowsKeyCode = 0x09;
PlatformKeyboardEventBuilder platformEvent(keyboardEvent);
RefPtr<KeyboardEvent> webkitEvent = KeyboardEvent::create(platformEvent, 0);
page()->focusController()->setInitialFocus(
reverse ? FocusDirectionBackward : FocusDirectionForward,
webkitEvent.get());
}
void WebViewImpl::clearFocusedNode()
{
if (!m_page.get())
return;
RefPtr<Frame> frame = m_page->mainFrame();
if (!frame.get())
return;
RefPtr<Document> document = frame->document();
if (!document.get())
return;
RefPtr<Node> oldFocusedNode = document->focusedNode();
// Clear the focused node.
document->setFocusedNode(0);
if (!oldFocusedNode.get())
return;
// If a text field has focus, we need to make sure the selection controller
// knows to remove selection from it. Otherwise, the text field is still
// processing keyboard events even though focus has been moved to the page and
// keystrokes get eaten as a result.
if (oldFocusedNode->hasTagName(HTMLNames::textareaTag)
|| (oldFocusedNode->hasTagName(HTMLNames::inputTag)
&& static_cast<HTMLInputElement*>(oldFocusedNode.get())->isTextField())) {
// Clear the selection.
SelectionController* selection = frame->selection();
selection->clear();
}
}
int WebViewImpl::zoomLevel()
{
return m_zoomLevel;
}
int WebViewImpl::setZoomLevel(bool textOnly, int zoomLevel)
{
float zoomFactor = static_cast<float>(
std::max(std::min(std::pow(textSizeMultiplierRatio, zoomLevel),
maxTextSizeMultiplier),
minTextSizeMultiplier));
Frame* frame = mainFrameImpl()->frame();
FrameView* view = frame->view();
if (!view)
return m_zoomLevel;
float oldZoomFactor = m_zoomTextOnly ? view->textZoomFactor() : view->pageZoomFactor();
if (textOnly)
view->setPageAndTextZoomFactors(1, zoomFactor);
else
view->setPageAndTextZoomFactors(zoomFactor, 1);
if (oldZoomFactor != zoomFactor || textOnly != m_zoomTextOnly) {
WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
if (pluginContainer)
pluginContainer->plugin()->setZoomFactor(zoomFactor, textOnly);
}
m_zoomLevel = zoomLevel;
m_zoomTextOnly = textOnly;
return m_zoomLevel;
}
void WebViewImpl::performMediaPlayerAction(const WebMediaPlayerAction& action,
const WebPoint& location)
{
HitTestResult result =
hitTestResultForWindowPos(location);
RefPtr<Node> node = result.innerNonSharedNode();
if (!node->hasTagName(HTMLNames::videoTag) && !node->hasTagName(HTMLNames::audioTag))
return;
RefPtr<HTMLMediaElement> mediaElement =
static_pointer_cast<HTMLMediaElement>(node);
switch (action.type) {
case WebMediaPlayerAction::Play:
if (action.enable)
mediaElement->play(mediaElement->processingUserGesture());
else
mediaElement->pause(mediaElement->processingUserGesture());
break;
case WebMediaPlayerAction::Mute:
mediaElement->setMuted(action.enable);
break;
case WebMediaPlayerAction::Loop:
mediaElement->setLoop(action.enable);
break;
case WebMediaPlayerAction::Controls:
mediaElement->setControls(action.enable);
break;
default:
ASSERT_NOT_REACHED();
}
}
void WebViewImpl::copyImageAt(const WebPoint& point)
{
if (!m_page.get())
return;
HitTestResult result = hitTestResultForWindowPos(point);
if (result.absoluteImageURL().isEmpty()) {
// There isn't actually an image at these coordinates. Might be because
// the window scrolled while the context menu was open or because the page
// changed itself between when we thought there was an image here and when
// we actually tried to retreive the image.
//
// FIXME: implement a cache of the most recent HitTestResult to avoid having
// to do two hit tests.
return;
}
m_page->mainFrame()->editor()->copyImage(result);
}
void WebViewImpl::dragSourceEndedAt(
const WebPoint& clientPoint,
const WebPoint& screenPoint,
WebDragOperation operation)
{
PlatformMouseEvent pme(clientPoint,
screenPoint,
LeftButton, MouseEventMoved, 0, false, false, false,
false, 0);
m_page->mainFrame()->eventHandler()->dragSourceEndedAt(pme,
static_cast<DragOperation>(operation));
m_dragScrollTimer->stop();
}
void WebViewImpl::dragSourceMovedTo(
const WebPoint& clientPoint,
const WebPoint& screenPoint,
WebDragOperation operation)
{
m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
}
void WebViewImpl::dragSourceSystemDragEnded()
{
// It's possible for us to get this callback while not doing a drag if
// it's from a previous page that got unloaded.
if (m_doingDragAndDrop) {
m_page->dragController()->dragEnded();
m_doingDragAndDrop = false;
}
}
WebDragOperation WebViewImpl::dragTargetDragEnter(
const WebDragData& webDragData, int identity,
const WebPoint& clientPoint,
const WebPoint& screenPoint,
WebDragOperationsMask operationsAllowed)
{
ASSERT(!m_currentDragData.get());
m_currentDragData = webDragData;
m_dragIdentity = identity;
m_operationsAllowed = operationsAllowed;
return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragEnter);
}
WebDragOperation WebViewImpl::dragTargetDragOver(
const WebPoint& clientPoint,
const WebPoint& screenPoint,
WebDragOperationsMask operationsAllowed)
{
m_operationsAllowed = operationsAllowed;
return dragTargetDragEnterOrOver(clientPoint, screenPoint, DragOver);
}
void WebViewImpl::dragTargetDragLeave()
{
ASSERT(m_currentDragData.get());
DragData dragData(
m_currentDragData.get(),
IntPoint(),
IntPoint(),
static_cast<DragOperation>(m_operationsAllowed));
m_dragTargetDispatch = true;
m_page->dragController()->dragExited(&dragData);
m_dragTargetDispatch = false;
m_currentDragData = 0;
m_dropEffect = DropEffectDefault;
m_dragOperation = WebDragOperationNone;
m_dragIdentity = 0;
}
void WebViewImpl::dragTargetDrop(const WebPoint& clientPoint,
const WebPoint& screenPoint)
{
ASSERT(m_currentDragData.get());
// If this webview transitions from the "drop accepting" state to the "not
// accepting" state, then our IPC message reply indicating that may be in-
// flight, or else delayed by javascript processing in this webview. If a
// drop happens before our IPC reply has reached the browser process, then
// the browser forwards the drop to this webview. So only allow a drop to
// proceed if our webview m_dragOperation state is not DragOperationNone.
if (m_dragOperation == WebDragOperationNone) { // IPC RACE CONDITION: do not allow this drop.
dragTargetDragLeave();
return;
}
DragData dragData(
m_currentDragData.get(),
clientPoint,
screenPoint,
static_cast<DragOperation>(m_operationsAllowed));
m_dragTargetDispatch = true;
m_page->dragController()->performDrag(&dragData);
m_dragTargetDispatch = false;
m_currentDragData = 0;
m_dropEffect = DropEffectDefault;
m_dragOperation = WebDragOperationNone;
m_dragIdentity = 0;
m_dragScrollTimer->stop();
}
int WebViewImpl::dragIdentity()
{
if (m_dragTargetDispatch)
return m_dragIdentity;
return 0;
}
WebDragOperation WebViewImpl::dragTargetDragEnterOrOver(const WebPoint& clientPoint, const WebPoint& screenPoint, DragAction dragAction)
{
ASSERT(m_currentDragData.get());
DragData dragData(
m_currentDragData.get(),
clientPoint,
screenPoint,
static_cast<DragOperation>(m_operationsAllowed));
m_dropEffect = DropEffectDefault;
m_dragTargetDispatch = true;
DragOperation effect = dragAction == DragEnter ? m_page->dragController()->dragEntered(&dragData)
: m_page->dragController()->dragUpdated(&dragData);
// Mask the operation against the drag source's allowed operations.
if (!(effect & dragData.draggingSourceOperationMask()))
effect = DragOperationNone;
m_dragTargetDispatch = false;
if (m_dropEffect != DropEffectDefault) {
m_dragOperation = (m_dropEffect != DropEffectNone) ? WebDragOperationCopy
: WebDragOperationNone;
} else
m_dragOperation = static_cast<WebDragOperation>(effect);
if (dragAction == DragOver)
m_dragScrollTimer->triggerScroll(mainFrameImpl()->frameView(), clientPoint);
else
m_dragScrollTimer->stop();
return m_dragOperation;
}
unsigned long WebViewImpl::createUniqueIdentifierForRequest()
{
if (m_page)
return m_page->progress()->createUniqueIdentifier();
return 0;
}
void WebViewImpl::inspectElementAt(const WebPoint& point)
{
if (!m_page.get())
return;
if (point.x == -1 || point.y == -1)
m_page->inspectorController()->inspect(0);
else {
HitTestResult result = hitTestResultForWindowPos(point);
if (!result.innerNonSharedNode())
return;
m_page->inspectorController()->inspect(result.innerNonSharedNode());
}
}
WebString WebViewImpl::inspectorSettings() const
{
return m_inspectorSettings;
}
void WebViewImpl::setInspectorSettings(const WebString& settings)
{
m_inspectorSettings = settings;
}
bool WebViewImpl::inspectorSetting(const WebString& key, WebString* value) const
{
if (!m_inspectorSettingsMap->contains(key))
return false;
*value = m_inspectorSettingsMap->get(key);
return true;
}
void WebViewImpl::setInspectorSetting(const WebString& key,
const WebString& value)
{
m_inspectorSettingsMap->set(key, value);
client()->didUpdateInspectorSetting(key, value);
}
WebDevToolsAgent* WebViewImpl::devToolsAgent()
{
return m_devToolsAgent.get();
}
WebAccessibilityObject WebViewImpl::accessibilityObject()
{
if (!mainFrameImpl())
return WebAccessibilityObject();
Document* document = mainFrameImpl()->frame()->document();
return WebAccessibilityObject(
document->axObjectCache()->getOrCreate(document->renderer()));
}
void WebViewImpl::applyAutoFillSuggestions(
const WebNode& node,
const WebVector<WebString>& names,
const WebVector<WebString>& labels,
const WebVector<int>& uniqueIDs,
int separatorIndex)
{
WebVector<WebString> icons(names.size());
applyAutoFillSuggestions(node, names, labels, icons, uniqueIDs, separatorIndex);
}
void WebViewImpl::applyAutoFillSuggestions(
const WebNode& node,
const WebVector<WebString>& names,
const WebVector<WebString>& labels,
const WebVector<WebString>& icons,
const WebVector<int>& uniqueIDs,
int separatorIndex)
{
ASSERT(names.size() == labels.size());
ASSERT(names.size() == uniqueIDs.size());
ASSERT(separatorIndex < static_cast<int>(names.size()));
if (names.isEmpty()) {
hideAutoFillPopup();
return;
}
RefPtr<Node> focusedNode = focusedWebCoreNode();
// If the node for which we queried the AutoFill suggestions is not the
// focused node, then we have nothing to do. FIXME: also check the
// caret is at the end and that the text has not changed.
if (!focusedNode || focusedNode != PassRefPtr<Node>(node)) {
hideAutoFillPopup();
return;
}
HTMLInputElement* inputElem =
static_cast<HTMLInputElement*>(focusedNode.get());
// The first time the AutoFill popup is shown we'll create the client and
// the popup.
if (!m_autoFillPopupClient.get())
m_autoFillPopupClient.set(new AutoFillPopupMenuClient);
m_autoFillPopupClient->initialize(
inputElem, names, labels, icons, uniqueIDs, separatorIndex);
if (!m_autoFillPopup.get()) {
m_autoFillPopup = PopupContainer::create(m_autoFillPopupClient.get(),
PopupContainer::Suggestion,
autoFillPopupSettings);
}
if (m_autoFillPopupShowing) {
m_autoFillPopupClient->setSuggestions(
names, labels, icons, uniqueIDs, separatorIndex);
refreshAutoFillPopup();
} else {
m_autoFillPopup->show(focusedNode->getRect(),
focusedNode->ownerDocument()->view(), 0);
m_autoFillPopupShowing = true;
}
// DEPRECATED: This special mode will go away once AutoFill and Autocomplete
// merge is complete.
if (m_autoFillPopupClient)
m_autoFillPopupClient->setAutocompleteMode(false);
}
// DEPRECATED: replacing with applyAutoFillSuggestions.
void WebViewImpl::applyAutocompleteSuggestions(
const WebNode& node,
const WebVector<WebString>& suggestions,
int defaultSuggestionIndex)
{
WebVector<WebString> names(suggestions.size());
WebVector<WebString> labels(suggestions.size());
WebVector<WebString> icons(suggestions.size());
WebVector<int> uniqueIDs(suggestions.size());
for (size_t i = 0; i < suggestions.size(); ++i)
names[i] = suggestions[i];
applyAutoFillSuggestions(node, names, labels, icons, uniqueIDs, -1);
if (m_autoFillPopupClient)
m_autoFillPopupClient->setAutocompleteMode(true);
}
void WebViewImpl::hidePopups()
{
hideSelectPopup();
hideAutoFillPopup();
}
void WebViewImpl::performCustomContextMenuAction(unsigned action)
{
if (!m_page)
return;
ContextMenu* menu = m_page->contextMenuController()->contextMenu();
if (!menu)
return;
ContextMenuItem* item = menu->itemWithAction(static_cast<ContextMenuAction>(ContextMenuItemBaseCustomTag + action));
if (item)
m_page->contextMenuController()->contextMenuItemSelected(item);
m_page->contextMenuController()->clearContextMenu();
}
// WebView --------------------------------------------------------------------
bool WebViewImpl::setDropEffect(bool accept)
{
if (m_dragTargetDispatch) {
m_dropEffect = accept ? DropEffectCopy : DropEffectNone;
return true;
}
return false;
}
void WebViewImpl::setIsTransparent(bool isTransparent)
{
// Set any existing frames to be transparent.
Frame* frame = m_page->mainFrame();
while (frame) {
frame->view()->setTransparent(isTransparent);
frame = frame->tree()->traverseNext();
}
// Future frames check this to know whether to be transparent.
m_isTransparent = isTransparent;
}
bool WebViewImpl::isTransparent() const
{
return m_isTransparent;
}
void WebViewImpl::setIsActive(bool active)
{
if (page() && page()->focusController())
page()->focusController()->setActive(active);
}
bool WebViewImpl::isActive() const
{
return (page() && page()->focusController()) ? page()->focusController()->isActive() : false;
}
void WebViewImpl::setDomainRelaxationForbidden(bool forbidden, const WebString& scheme)
{
SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme));
}
void WebViewImpl::setScrollbarColors(unsigned inactiveColor,
unsigned activeColor,
unsigned trackColor) {
#if OS(LINUX)
PlatformThemeChromiumGtk::setScrollbarColors(inactiveColor,
activeColor,
trackColor);
#endif
}
void WebViewImpl::setSelectionColors(unsigned activeBackgroundColor,
unsigned activeForegroundColor,
unsigned inactiveBackgroundColor,
unsigned inactiveForegroundColor) {
#if OS(LINUX)
RenderThemeChromiumLinux::setSelectionColors(activeBackgroundColor,
activeForegroundColor,
inactiveBackgroundColor,
inactiveForegroundColor);
theme()->platformColorsDidChange();
#endif
}
void WebView::addUserScript(const WebString& sourceCode,
const WebVector<WebString>& patternsIn,
WebView::UserScriptInjectAt injectAt,
WebView::UserContentInjectIn injectIn)
{
OwnPtr<Vector<String> > patterns(new Vector<String>);
for (size_t i = 0; i < patternsIn.size(); ++i)
patterns->append(patternsIn[i]);
PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
pageGroup->addUserScriptToWorld(world.get(), sourceCode, WebURL(), patterns.release(), 0,
static_cast<UserScriptInjectionTime>(injectAt),
static_cast<UserContentInjectedFrames>(injectIn));
}
void WebView::addUserStyleSheet(const WebString& sourceCode,
const WebVector<WebString>& patternsIn,
WebView::UserContentInjectIn injectIn)
{
OwnPtr<Vector<String> > patterns(new Vector<String>);
for (size_t i = 0; i < patternsIn.size(); ++i)
patterns->append(patternsIn[i]);
PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
RefPtr<DOMWrapperWorld> world(DOMWrapperWorld::create());
// FIXME: Current callers always want the level to be "author". It probably makes sense to let
// callers specify this though, since in other cases the caller will probably want "user" level.
//
// FIXME: It would be nice to populate the URL correctly, instead of passing an empty URL.
pageGroup->addUserStyleSheetToWorld(world.get(), sourceCode, WebURL(), patterns.release(), 0,
static_cast<UserContentInjectedFrames>(injectIn),
UserStyleSheet::AuthorLevel);
}
void WebView::removeAllUserContent()
{
PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
pageGroup->removeAllUserContent();
}
void WebViewImpl::didCommitLoad(bool* isNewNavigation)
{
if (isNewNavigation)
*isNewNavigation = m_observedNewNavigation;
#ifndef NDEBUG
ASSERT(!m_observedNewNavigation
|| m_page->mainFrame()->loader()->documentLoader() == m_newNavigationLoader);
m_newNavigationLoader = 0;
#endif
m_observedNewNavigation = false;
}
bool WebViewImpl::navigationPolicyFromMouseEvent(unsigned short button,
bool ctrl, bool shift,
bool alt, bool meta,
WebNavigationPolicy* policy)
{
#if OS(WINDOWS) || OS(LINUX) || OS(FREEBSD) || OS(SOLARIS)
const bool newTabModifier = (button == 1) || ctrl;
#elif OS(DARWIN)
const bool newTabModifier = (button == 1) || meta;
#endif
if (!newTabModifier && !shift && !alt)
return false;
ASSERT(policy);
if (newTabModifier) {
if (shift)
*policy = WebNavigationPolicyNewForegroundTab;
else
*policy = WebNavigationPolicyNewBackgroundTab;
} else {
if (shift)
*policy = WebNavigationPolicyNewWindow;
else
*policy = WebNavigationPolicyDownload;
}
return true;
}
void WebViewImpl::startDragging(const WebDragData& dragData,
WebDragOperationsMask mask,
const WebImage& dragImage,
const WebPoint& dragImageOffset)
{
if (!m_client)
return;
ASSERT(!m_doingDragAndDrop);
m_doingDragAndDrop = true;
m_client->startDragging(dragData, mask, dragImage, dragImageOffset);
}
void WebViewImpl::setCurrentHistoryItem(HistoryItem* item)
{
m_backForwardListClientImpl.setCurrentHistoryItem(item);
}
HistoryItem* WebViewImpl::previousHistoryItem()
{
return m_backForwardListClientImpl.previousHistoryItem();
}
void WebViewImpl::observeNewNavigation()
{
m_observedNewNavigation = true;
#ifndef NDEBUG
m_newNavigationLoader = m_page->mainFrame()->loader()->documentLoader();
#endif
}
void WebViewImpl::setIgnoreInputEvents(bool newValue)
{
ASSERT(m_ignoreInputEvents != newValue);
m_ignoreInputEvents = newValue;
}
#if ENABLE(NOTIFICATIONS)
NotificationPresenterImpl* WebViewImpl::notificationPresenterImpl()
{
if (!m_notificationPresenter.isInitialized() && m_client)
m_notificationPresenter.initialize(m_client->notificationPresenter());
return &m_notificationPresenter;
}
#endif
void WebViewImpl::refreshAutoFillPopup()
{
ASSERT(m_autoFillPopupShowing);
// Hide the popup if it has become empty.
if (!m_autoFillPopupClient->listSize()) {
hideAutoFillPopup();
return;
}
IntRect oldBounds = m_autoFillPopup->boundsRect();
m_autoFillPopup->refresh();
IntRect newBounds = m_autoFillPopup->boundsRect();
// Let's resize the backing window if necessary.
if (oldBounds != newBounds) {
WebPopupMenuImpl* popupMenu =
static_cast<WebPopupMenuImpl*>(m_autoFillPopup->client());
if (popupMenu)
popupMenu->client()->setWindowRect(newBounds);
}
}
Node* WebViewImpl::focusedWebCoreNode()
{
Frame* frame = m_page->focusController()->focusedFrame();
if (!frame)
return 0;
Document* document = frame->document();
if (!document)
return 0;
return document->focusedNode();
}
HitTestResult WebViewImpl::hitTestResultForWindowPos(const IntPoint& pos)
{
IntPoint docPoint(m_page->mainFrame()->view()->windowToContents(pos));
return m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(docPoint, false);
}
void WebViewImpl::setTabsToLinks(bool enable)
{
m_tabsToLinks = enable;
}
bool WebViewImpl::tabsToLinks() const
{
return m_tabsToLinks;
}
#if USE(ACCELERATED_COMPOSITING)
bool WebViewImpl::allowsAcceleratedCompositing()
{
return !m_compositorCreationFailed;
}
void WebViewImpl::setRootGraphicsLayer(WebCore::PlatformLayer* layer)
{
bool wasActive = m_isAcceleratedCompositingActive;
setIsAcceleratedCompositingActive(layer ? true : false);
if (m_layerRenderer)
m_layerRenderer->setRootLayer(layer);
if (wasActive != m_isAcceleratedCompositingActive) {
IntRect damagedRect(0, 0, m_size.width, m_size.height);
if (m_isAcceleratedCompositingActive)
invalidateRootLayerRect(damagedRect);
else
m_client->didInvalidateRect(damagedRect);
}
}
void WebViewImpl::setRootLayerNeedsDisplay()
{
if (m_layerRenderer)
m_layerRenderer->setNeedsDisplay();
m_client->scheduleComposite();
// FIXME: To avoid breaking the downstream Chrome render_widget while downstream
// changes land, we also have to pass a 1x1 invalidate up to the client
{
WebRect damageRect(0, 0, 1, 1);
m_client->didInvalidateRect(damageRect);
}
}
void WebViewImpl::scrollRootLayerRect(const IntSize& scrollDelta, const IntRect& clipRect)
{
// FIXME: To avoid breaking the Chrome render_widget when the new compositor render
// path is not checked in, we must still pass scroll damage up to the client. This
// code will be backed out in a followup CL once the Chromium changes have landed.
m_client->didScrollRect(scrollDelta.width(), scrollDelta.height(), clipRect);
ASSERT(m_layerRenderer);
// Compute the damage rect in viewport space.
WebFrameImpl* webframe = mainFrameImpl();
if (!webframe)
return;
FrameView* view = webframe->frameView();
if (!view)
return;
IntRect contentRect = view->visibleContentRect(false);
// We support fast scrolling in one direction at a time.
if (scrollDelta.width() && scrollDelta.height()) {
invalidateRootLayerRect(WebRect(contentRect));
return;
}
// Compute the region we will expose by scrolling. We use the
// content rect for invalidation. Using this space for damage
// rects allows us to intermix invalidates with scrolls.
IntRect damagedContentsRect;
if (scrollDelta.width()) {
float dx = static_cast<float>(scrollDelta.width());
damagedContentsRect.setY(contentRect.y());
damagedContentsRect.setHeight(contentRect.height());
if (dx > 0) {
damagedContentsRect.setX(contentRect.x());
damagedContentsRect.setWidth(dx);
} else {
damagedContentsRect.setX(contentRect.right() + dx);
damagedContentsRect.setWidth(-dx);
}
} else {
float dy = static_cast<float>(scrollDelta.height());
damagedContentsRect.setX(contentRect.x());
damagedContentsRect.setWidth(contentRect.width());
if (dy > 0) {
damagedContentsRect.setY(contentRect.y());
damagedContentsRect.setHeight(dy);
} else {
damagedContentsRect.setY(contentRect.bottom() + dy);
damagedContentsRect.setHeight(-dy);
}
}
m_scrollDamage.unite(damagedContentsRect);
setRootLayerNeedsDisplay();
}
void WebViewImpl::invalidateRootLayerRect(const IntRect& rect)
{
// FIXME: To avoid breaking the Chrome render_widget when the new compositor render
// path is not checked in, we must still pass damage up to the client. This
// code will be backed out in a followup CL once the Chromium changes have landed.
m_client->didInvalidateRect(rect);
ASSERT(m_layerRenderer);
if (!page())
return;
FrameView* view = page()->mainFrame()->view();
// rect is in viewport space. Convert to content space
// so that invalidations and scroll invalidations play well with one-another.
FloatRect contentRect = view->windowToContents(rect);
// FIXME: add a smarter damage aggregation logic? Right now, LayerChromium does simple union-ing.
m_layerRenderer->rootLayer()->setNeedsDisplay(contentRect);
}
void WebViewImpl::setIsAcceleratedCompositingActive(bool active)
{
if (m_isAcceleratedCompositingActive == active)
return;
if (active) {
m_layerRenderer = LayerRendererChromium::create(getOnscreenGLES2Context());
if (m_layerRenderer) {
m_isAcceleratedCompositingActive = true;
} else {
m_isAcceleratedCompositingActive = false;
m_compositorCreationFailed = true;
}
} else {
m_layerRenderer = 0;
m_isAcceleratedCompositingActive = false;
}
}
void WebViewImpl::updateRootLayerContents(const IntRect& rect)
{
if (!isAcceleratedCompositingActive())
return;
WebFrameImpl* webframe = mainFrameImpl();
if (!webframe)
return;
FrameView* view = webframe->frameView();
if (!view)
return;
LayerChromium* rootLayer = m_layerRenderer->rootLayer();
if (rootLayer) {
IntRect visibleRect = view->visibleContentRect(true);
m_layerRenderer->setRootLayerCanvasSize(IntSize(rect.width(), rect.height()));
GraphicsContext* rootLayerContext = m_layerRenderer->rootLayerGraphicsContext();
#if PLATFORM(SKIA)
PlatformContextSkia* skiaContext = rootLayerContext->platformContext();
skia::PlatformCanvas* platformCanvas = skiaContext->canvas();
platformCanvas->save();
// Bring the canvas into the coordinate system of the paint rect.
platformCanvas->translate(static_cast<SkScalar>(-rect.x()), static_cast<SkScalar>(-rect.y()));
rootLayerContext->save();
webframe->paintWithContext(*rootLayerContext, rect);
rootLayerContext->restore();
platformCanvas->restore();
#elif PLATFORM(CG)
CGContextRef cgContext = rootLayerContext->platformContext();
CGContextSaveGState(cgContext);
// Bring the CoreGraphics context into the coordinate system of the paint rect.
CGContextTranslateCTM(cgContext, -rect.x(), -rect.y());
rootLayerContext->save();
webframe->paintWithContext(*rootLayerContext, rect);
rootLayerContext->restore();
CGContextRestoreGState(cgContext);
#else
#error Must port to your platform
#endif
}
}
void WebViewImpl::doComposite()
{
ASSERT(isAcceleratedCompositingActive());
if (!page())
return;
FrameView* view = page()->mainFrame()->view();
// The visibleRect includes scrollbars whereas the contentRect doesn't.
IntRect visibleRect = view->visibleContentRect(true);
IntRect contentRect = view->visibleContentRect(false);
IntRect viewPort = IntRect(0, 0, m_size.width, m_size.height);
// Give the compositor a chance to setup/resize the root texture handle and perform scrolling.
m_layerRenderer->prepareToDrawLayers(visibleRect, contentRect, IntPoint(view->scrollX(), view->scrollY()));
// Draw the contents of the root layer.
Vector<FloatRect> damageRects;
damageRects.append(m_scrollDamage);
damageRects.append(m_layerRenderer->rootLayer()->dirtyRect());
for (size_t i = 0; i < damageRects.size(); ++i) {
// The damage rect for the root layer is in content space [e.g. unscrolled].
// Convert from content space to viewPort space.
const FloatRect damagedContentRect = damageRects[i];
IntRect damagedRect = view->contentsToWindow(IntRect(damagedContentRect));
// Intersect this rectangle with the viewPort.
damagedRect.intersect(viewPort);
// Now render it.
if (damagedRect.width() && damagedRect.height()) {
updateRootLayerContents(damagedRect);
m_layerRenderer->updateRootLayerTextureRect(damagedRect);
}
}
m_layerRenderer->rootLayer()->resetNeedsDisplay();
m_scrollDamage = WebRect();
// Draw the actual layers...
m_layerRenderer->drawLayers(visibleRect, contentRect);
}
#endif
PassOwnPtr<GLES2Context> WebViewImpl::getOnscreenGLES2Context()
{
WebGLES2Context* context = gles2Context();
if (!context)
return 0;
return GLES2Context::create(GLES2ContextInternal::create(context, false));
}
SharedGraphicsContext3D* WebViewImpl::getSharedGraphicsContext3D()
{
if (!m_sharedContext3D) {
GraphicsContext3D::Attributes attr;
OwnPtr<GraphicsContext3D> context = GraphicsContext3D::create(attr, m_page->chrome());
if (!context)
return 0;
m_sharedContext3D = SharedGraphicsContext3D::create(context.release());
}
return m_sharedContext3D.get();
}
// Returns the GLES2 context associated with this View. If one doesn't exist
// it will get created first.
WebGLES2Context* WebViewImpl::gles2Context()
{
if (!m_gles2Context) {
m_gles2Context = webKitClient()->createGLES2Context();
if (!m_gles2Context)
return 0;
if (!m_gles2Context->initialize(this, 0)) {
m_gles2Context.clear();
return 0;
}
#if OS(DARWIN)
m_gles2Context->resizeOnscreenContent(WebSize(std::max(1, m_size.width),
std::max(1, m_size.height)));
#endif
}
return m_gles2Context.get();
}
} // namespace WebKit
| [
"[email protected]"
] | [
[
[
1,
2462
]
]
] |
103c3ce9874fc62b0e86af6ea7df5e2979aa1b26 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/arcemu-shared/PacketLog.h | 25de21e040a7e62610d6722b6f3ed08cec751c77 | [] | no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | h | #ifndef WOWSERVER_PACKETLOG_H
#define WOWSERVER_PACKETLOG_H
#include "Common.h"
#include "Singleton.h"
#include "RealmPacket.h"
#include "WorldPacket.h"
class PacketLog : public Singleton< PacketLog > {
public:
PacketLog();
~PacketLog();
//utility functions
int hextoint(char c);
char makehexchar(int i);
//general log functions
void HexDump(const unsigned char* data, size_t length, const char* file);
void HexDump(const char *data, size_t length, const char* file);
void HexDumpStr(const char *msg, const char *data, size_t len, const char* file);
//realm packet log
void RealmHexDump(RealmPacket * data, uint32 socket, bool direction);
//world packet log
void WorldHexDump(WorldPacket * data, uint32 socket, bool direction);
};
#define sPacketLog PacketLog::getSingleton()
#endif | [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
] | [
[
[
1,
28
]
]
] |
493e1343ac756d6af62bdd5da564ffa421b1320a | 2fd4a846571728820b84b059f3b4dfc4d2f8f140 | /vclient/client.h | 1d036d356eca4820f92b2d92e910812b9b86ebdc | [] | no_license | jbreslin33/breslinlistenserver | 876ff770a2e8503df449ce2da190d5c4e8e18c41 | 31002739334106e05ea8330485daa746331f173d | refs/heads/master | 2020-06-02T07:55:29.508192 | 2011-03-15T02:23:18 | 2011-03-15T02:23:18 | 37,391,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,685 | h | #ifndef CLIENT_H
#define CLIENT_H
#include "BaseApplication.h"
#include "common.h"
//#include "Tutorial4.h"
extern bool keys[256];
typedef struct
{
float x;
float y;
} VECTOR2D;
typedef struct
{
int key;
VECTOR2D vel;
VECTOR2D origin;
VECTOR2D predictedOrigin;
int msec;
} command_t;
typedef struct clientData
{
command_t frame[64]; // frame history
command_t serverFrame; // the latest frame from server
command_t command; // current frame's commands
int index;
VECTOR2D startPos;
bool team;
char nickname[30];
char password[30];
Ogre::SceneNode *myNode;
clientData *next;
} clientData;
// The main application class interface
class CArmyWar : public BaseApplication
{
private:
// Methods
// Client.cpp
void DrawMap(void);
void CheckPredictionError(int a);
void CalculateVelocity(command_t *command, float frametime);
void PredictMovement(int prevFrame, int curFrame);
void MoveObjects(void);
void MovePlayer(void);
void AddClient(int local, int index, char *name);
void RemoveClient(int index);
void RemoveClients(void);
// Network.cpp
void ReadPackets(void);
void SendCommand(void);
void SendRequestNonDeltaFrame(void);
void ReadMoveCommand(dreamMessage *mes, clientData *client);
void ReadDeltaMoveCommand(dreamMessage *mes, clientData *client);
void BuildDeltaMoveCommand(dreamMessage *mes, clientData *theClient);
bool processUnbufferedInput(const Ogre::FrameEvent& evt);
// Variables
// Network variables
dreamClient *networkClient;
clientData *clientList; // Client list
clientData *localClient; // Pointer to the local client in the client list
int clients;
clientData inputClient; // Handles all keyboard input
float frametime;
float rendertime;
char gamename[32];
bool init;
//bool mapdata[100][100];
int gameIndex;
public:
CArmyWar();
~CArmyWar();
void createPlayer(int index);
virtual void createScene(void);
virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt);
// Client.cpp
void Shutdown(void);
void CheckKeys(void);
void Frame(void);
void RunNetwork(int msec);
// Network.cpp
void StartConnection();
void Connect(void);
void Disconnect(void);
void SendStartGame(void);
void SetName(char *n) { strcpy(gamename, n); }
char *GetName(void) { return gamename; }
void SetGameIndex(int index) { gameIndex = index; }
int GetGameIndex(void) { return gameIndex; }
clientData *GetClientList(void) { return clientList; }
clientData *GetClientPointer(int index);
CArmyWar *next;
};
#endif | [
"jbreslin33@localhost"
] | [
[
[
1,
132
]
]
] |
0a59ee3b4c832f8bc5461de3d446cdd823b70dcd | 4e563b9a2cd25d59b320aad84b7641755d498f34 | /swarm/mainwindow.h | b46e9476bd4cebe9ee3314f3c7dc4a05a199521d | [] | no_license | 607011/ct-swarm | 47483cf391e4cffb0f096a26a66f05f1c5f9be4e | 08b8f85e949224951800f58413b1e7dfbf54c8dc | refs/heads/master | 2023-03-03T10:52:53.628037 | 2011-07-19T11:37:15 | 2011-07-19T11:37:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | h | // Copyright (c) 2005-2011 Oliver Lau <[email protected]>
// Heise Zeitschriften Verlag, Hannover, Germany
#ifndef __MAINWINDOW_H_
#define __MAINWINDOW_H_
#include <QObject>
#include <QMainWindow>
#include <QWidget>
#include <QAction>
#include <QCloseEvent>
#include <QStatusBar>
#include <QMenuBar>
#include <QToolBar>
#include <QButtonGroup>
#include <QMenu>
#include <QSettings>
#include "populatedialog.h"
class PSO;
class ThreeDWidget;
class MainWindow : public QMainWindow
{
Q_OBJECT
private: // variables
QToolBar* drawingTools;
QAction* newAct;
QAction* populateAct;
QAction* exitAct;
QAction* view3DAct;
QAction* aboutAct;
QAction* helpAct;
QAction* bearModeAct;
QAction* buildModeAct;
QAction* destructModeAct;
QButtonGroup* toolButtons;
QMenu* fileMenu;
QMenu* editMenu;
QMenu* viewMenu;
QMenu* helpMenu;
ThreeDWidget* gl;
PSO* pso;
QSettings* settings;
PopulateDialog* populateDialog;
bool swarmChanged;
bool graphChanged;
private: // methods
bool maybeSave(void);
void writeSettings(void);
private slots:
void newFile(void);
void about(void);
void help(void);
void populate(void);
void view3D(bool checked);
void fitnessChanged(void);
void enterBearMode(bool);
void enterBuildMode(bool);
void enterDestructMode(bool);
void threeDWidgetClosed(void);
public: // methods
MainWindow(QWidget* parent = NULL);
protected: // methods
void closeEvent(QCloseEvent*);
void showEvent(QShowEvent*);
signals:
void numberOfParticlesChanged(int);
};
#endif // __MAINWINDOW_H_
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
25,
25
],
[
28,
48
],
[
51,
52
],
[
55,
64
],
[
70,
71
],
[
74,
74
]
],
[
[
2,
24
],
[
26,
27
],
[
49,
50
],
[
53,
54
],
[
65,
69
],
[
72,
73
],
[
75,
78
]
]
] |
12943f31ec0a74fb18a535717681274b2f188fd4 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/26042005/include/mesh/Overlay.h | b55d55f51211ab37fbaba4c67814712e3ee1ca6a | [] | no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,502 | h | #ifndef _OVERLAY_H_
#define _OVERLAY_H_
#include <mesh/Mesh.h>
class Rect;
// Overlay stretch types
#define STRETCH_TOP 2 // stretches an overlay upwards
#define STRETCH_BOTTOM 4 // stretches an overlay downwards
#define STRETCH_LEFT 8 // stretches an overlay to the left
#define STRETCH_RIGHT 16 // stretches an overlay to the right
#define STRETCH_CENTRE 32 // stretches an overlay in all directions
/** @ingroup Mesh_Graphics_Group
* @brief Derived Mesh class which serves as a base class for all Overlay objects
*/
class Overlay: public Mesh{
protected:
/** @var std::vector<Vector2f *> m_texcoords
* @brief An array of Texture coordinate arrays
*
* To allow the overlay to have animations you hold
* multiple sets of texture coordinates, to update
* the animation of the overlay, set the mesh's
* texture coordinate pointer to another set of coordinates
*
* Think of animation frames contained within one image, each
* animation frame == one set of texture coordinates(one rectangle in the image).
* To change animation frame, simply set the mesh's texture coordinates to
* the frame of animation requested
*/
std::vector<Vertex2f *> m_texcoords;
public:
Overlay ();
virtual ~Overlay ();
virtual void AddFrame (Rect *tr=NULL);
virtual void SetFrame (unsigned int frameid);
virtual void SetTexture (ITexture *texture);
virtual void Stretch (int Direction, float amt);
};
#endif // #ifndef _OVERLAY_H_
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] | [
[
[
1,
43
]
]
] |
d0a01f1e280c561e165d1147590514b1e343bb05 | 45229380094a0c2b603616e7505cbdc4d89dfaee | /CLROpenCV/Stdafx.cpp | de47c2f543834ad0ebb5ce64d6205b4a9f163e55 | [] | no_license | xcud/msrds | a71000cc096723272e5ada7229426dee5100406c | 04764859c88f5c36a757dbffc105309a27cd9c4d | refs/heads/master | 2021-01-10T01:19:35.834296 | 2011-11-04T09:26:01 | 2011-11-04T09:26:01 | 45,697,313 | 1 | 2 | null | null | null | null | UHC | C++ | false | false | 239 | cpp | // stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다.
// CLROpenCV.pch는 미리 컴파일된 헤더가 됩니다.
// stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다.
#include "stdafx.h"
| [
"perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671"
] | [
[
[
1,
5
]
]
] |
7eb431cfcbccd52cf6d8c9694ea554816bde03e2 | 27167a5a0340fdc9544752bd724db27d3699a9a2 | /include/dockwins/WndFrmPkg.h | 94a94b0538276446edea97aadc10663221c42ba4 | [] | no_license | eaglexmw-gmail/wtl-dockwins | 2b464be3958e1683cd668a10abafb528f43ac695 | ae307a1978b73bfd2823945068224bb6c01ae350 | refs/heads/master | 2020-06-30T21:03:26.075864 | 2011-10-23T12:50:14 | 2011-10-23T12:50:14 | 200,951,487 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 45,013 | h | // Copyright (c) 2002
// Sergey Klimov ([email protected])
// WTL Docking windows
//
// This code is provided "as is", with absolutely no warranty expressed
// or implied. Any use is at your own risk.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included. If
// the source code in this file is used in any commercial application
// then a simple email would be nice.
#ifndef WTL_DW_WNDFRMPKG_H_INCLUDED_
#define WTL_DW_WNDFRMPKG_H_INCLUDED_
#pragma once
#ifndef __ATLMISC_H__
#error WndFrmPkg.h requires atlmisc.h to be included first
#endif
#include <memory>
#ifdef USE_BOOST
#include <boost/smart_ptr.hpp>
#endif
#include "ssec.h"
#include "DDTracker.h"
namespace dockwins
{
class CWndFrame
{
public:
typedef long position;
typedef long distance;
class CCmp
{
public:
CCmp(HWND hWnd) : m_hWnd(hWnd)
{
}
bool operator()(const CWndFrame& frame) const
{
return (frame.hwnd() == m_hWnd);
}
protected:
HWND m_hWnd;
};
CWndFrame(position pos = 0, HWND hWnd = NULL)
: m_hWnd(hWnd), m_pos(pos)
{
}
HWND hwnd() const
{
return m_hWnd;
}
operator position() const
{
return m_pos;
}
CWndFrame& operator += (position val)
{
m_pos += val;
return *this;
}
CWndFrame& operator -= (position val)
{
m_pos -= val;
return *this;
}
CWndFrame& operator = (position pos)
{
m_pos = pos;
return *this;
}
HDWP DeferFramePos(HDWP hdwp, long x1, long y1, long x2, long y2) const
{
return ::DeferWindowPos(hdwp, hwnd(),
NULL,
x1, y1,
x2 - x1, y2 - y1,
SWP_NOZORDER | SWP_NOACTIVATE);
}
void GetMinMaxInfo(LPMINMAXINFO pMinMaxInfo) const
{
::SendMessage(m_hWnd, WM_GETMINMAXINFO, NULL, reinterpret_cast<LPARAM>(pMinMaxInfo));
}
distance MinDistance() const
{
DFMHDR dockHdr;
dockHdr.code = DC_GETMINDIST;
dockHdr.hWnd = m_hWnd;
dockHdr.hBar =::GetParent(m_hWnd);
ATLASSERT(::IsWindow(dockHdr.hBar));
return static_cast<distance>
(::SendMessage(dockHdr.hBar, WMDF_DOCK, NULL, reinterpret_cast<LPARAM>(&dockHdr)));
}
protected:
position m_pos;
mutable HWND m_hWnd;
};
//template<class T,const T::distance TMinDist=0>
//struct CWndFrameTraits : ssec::spraits<T, T::position, T::distance/*,TMinDist*/>
//{
// typedef ssec::spraits<T,position,position/*,TMinDist*/> baseClass;
// static distance min_distance(const T& x)
// {
// const distance dist=TMinDist;
// return dist+x.MinDistance();
// }
//
//};
template< class TFrame = CWndFrame , class TTraits = CDockingFrameTraits>
class CWndFramesPackageBase
{
typedef TFrame CFrame;
typedef TTraits CTraits;
typedef typename CTraits::CSplitterBar CSplitterBar;
typedef CWndFramesPackageBase<CFrame, TTraits> thisClass;
protected:
typedef typename CFrame::position position;
template < class T,
#if _MSC_VER<1300
const T::distance TMinDist = 0 >
#else
class TTraits = CSimpleSplitterBarTraits>
#endif
struct CWndFrameTraits
: ssec::spraits < T, typename T::position, typename T::distance/*,TMinDist*/ >
{
typedef ssec::spraits < T, position, position/*,TMinDist*/ > baseClass;
static distance min_distance(const T& x)
{
const distance dist = TTraits::GetWidth();
return dist + x.MinDistance();
}
};
typedef CWndFrameTraits<CFrame, typename CSplitterBar::Traits> CFrameTraits;
typedef ssec::ssection<CFrame, CFrameTraits> CFrames;
typedef typename CFrames::iterator iterator;
typedef typename CFrames::reverse_iterator reverse_iterator;
typedef typename CFrames::const_iterator const_iterator;
typedef typename CFrames::const_reverse_iterator const_reverse_iterator;
typedef ssec::bounds_type<position> CBounds;
protected:
struct CEmbeddedSplitterBar : public CSplitterBar
{
CEmbeddedSplitterBar(bool bHorizontal, position vertex, const CRect& rcClient)
: CSplitterBar(bHorizontal)
{
if (IsHorizontal())
{
top = vertex;
bottom = top + GetThickness();
left = rcClient.left;
right = rcClient.right;
}
else
{
left = vertex;
right = left + GetThickness();
top = rcClient.top;
bottom = rcClient.bottom;
}
}
};
class CEmbeddedSplitterBarPainter
{
public:
CEmbeddedSplitterBarPainter(CDC& dc, bool bHorizontal, const CRect& rc)
: m_dc(dc), m_rc(rc), m_bHorizontal(bHorizontal)
{
}
void operator()(const CFrame& ref) const
{
CEmbeddedSplitterBar splitter(m_bHorizontal, ref, m_rc);
splitter.Draw(m_dc);
}
protected:
const CRect& m_rc;
bool m_bHorizontal;
CDC& m_dc;
};
class CSplitterMoveTrackerBase : public IDDTracker//CDDTrackerBaseT<CSizeTrackerBase>
{
protected:
void SetPosition()
{
ATLASSERT(m_bounds.bind(m_pos) == m_pos);
m_frames.set_position(m_i, m_pos);
m_owner.Arrange(m_rc);
m_wnd.RedrawWindow(&m_rc, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
}
public:
CSplitterMoveTrackerBase(HWND hWnd, thisClass& owner, const CPoint& pt, const CRect& rc)
: m_wnd(hWnd), m_owner(owner), m_frames(owner.m_frames), m_rc(rc)
{
position pos = owner.IsHorizontal() ? pt.x : pt.y;
m_i = m_frames.locate(pos);
if (m_i != m_frames.end())
{
m_pos = (*m_i);
m_offset = pos - m_pos;
m_frames.get_effective_bounds(m_i, m_bounds);
}
}
operator iterator() const
{
return m_i;
}
void OnMove(long x, long y)
{
position pos = m_owner.IsHorizontal() ? x : y;
pos = m_bounds.bind(pos - m_offset);
if (pos != m_pos)
{
m_pos = pos;
Move();
}
}
virtual void Move() = 0;
protected:
thisClass& m_owner;
CFrames& m_frames;
iterator m_i;
CBounds m_bounds;
position m_pos;
position m_offset;
const CRect& m_rc;
CWindow m_wnd;
};
friend class CSplitterMoveTrackerBase;
class CSplitterMoveTrackerFull : public CSplitterMoveTrackerBase
{
public:
CSplitterMoveTrackerFull(HWND hWnd, thisClass& owner, const CPoint& pt, const CRect& rc)
: CSplitterMoveTrackerBase(hWnd, owner, pt, rc)
{
}
void Move()
{
SetPosition();
}
};
class CSplitterMoveTrackerGhost : public CSplitterMoveTrackerBase
{
typedef CEmbeddedSplitterBar CSplitterBar;
typedef CSimpleSplitterBarSlider<CSplitterBar> CSlider;
public:
CSplitterMoveTrackerGhost(HWND hWnd, thisClass& owner,
const CPoint& pt, const CRect& rc)
: CSplitterMoveTrackerBase(hWnd, owner, pt, rc),
m_dc(::GetWindowDC(NULL)), m_splitter(!owner.IsHorizontal(), m_pos, rc), m_slider(m_splitter)
{
CPoint point(rc.TopLeft());
::ClientToScreen(hWnd, &point);
CSize offset(point.x - rc.left, point.y - rc.top);
m_splitter += offset;
m_ghOffset = owner.IsHorizontal()
? offset.cx
: offset.cy;
}
void BeginDrag()
{
m_splitter.DrawGhostBar(m_dc);
}
void EndDrag(bool bCanceled)
{
m_splitter.CleanGhostBar(m_dc);
if (!bCanceled)
SetPosition();
}
void Move()
{
m_splitter.CleanGhostBar(m_dc);
m_slider = m_pos + m_ghOffset;
m_splitter.DrawGhostBar(m_dc);
}
protected:
position m_ghOffset;
CSplitterBar m_splitter;
CSlider m_slider;
CDC m_dc;
};
template<class TTraits>
class CMinMaxInfoAccumulator
{
typedef LPMINMAXINFO(*CFunPtr)(MINMAXINFO& mmInfo, LPMINMAXINFO pMinMaxInfo);
public:
CMinMaxInfoAccumulator(bool bHorizontal)
{
m_pFun = bHorizontal ? &MinMaxInfoH : &MinMaxInfoV;
}
LPMINMAXINFO operator()(LPMINMAXINFO pMinMaxInfo, const CFrame& x) const
{
MINMAXINFO mmInfo;
ZeroMemory(&mmInfo, sizeof(MINMAXINFO));
x.GetMinMaxInfo(&mmInfo);
return (*m_pFun)(mmInfo, pMinMaxInfo);
}
protected:
static LPMINMAXINFO MinMaxInfoH(MINMAXINFO& mmInfo, LPMINMAXINFO pMinMaxInfo)
{
if (pMinMaxInfo->ptMinTrackSize.y < mmInfo.ptMinTrackSize.y)
pMinMaxInfo->ptMinTrackSize.y = mmInfo.ptMinTrackSize.y;
pMinMaxInfo->ptMinTrackSize.x += mmInfo.ptMinTrackSize.x +
TTraits::GetHeight();
return pMinMaxInfo;
}
static LPMINMAXINFO MinMaxInfoV(MINMAXINFO& mmInfo, LPMINMAXINFO pMinMaxInfo)
{
if (pMinMaxInfo->ptMinTrackSize.x < mmInfo.ptMinTrackSize.x)
pMinMaxInfo->ptMinTrackSize.x = mmInfo.ptMinTrackSize.x;
pMinMaxInfo->ptMinTrackSize.y += mmInfo.ptMinTrackSize.y + TTraits::GetWidth();
return pMinMaxInfo;
}
protected:
CFunPtr m_pFun;
};
protected:
bool ArrangeH(const CRect& rc)
{
HDWP hdwp = reinterpret_cast<HDWP>(TRUE);
const_iterator begin = m_frames.begin();
const_iterator end = m_frames.end();
if (begin != end)
{
hdwp = BeginDeferWindowPos(static_cast<int>(m_frames.size()));
const_iterator next = begin;
while ((hdwp != NULL) && (++next != end))
{
long x = (*begin) + typename CSplitterBar::Traits::GetSize(!IsHorizontal());
hdwp = begin->DeferFramePos(hdwp,
x,
rc.top,
(*next),
rc.bottom);
begin = next;
}
if (hdwp != NULL)
{
long x = (*begin) + typename CSplitterBar::Traits::GetSize(!IsHorizontal());
hdwp = begin->DeferFramePos(hdwp,
x,
rc.top,
rc.right,
rc.bottom);
if (hdwp)
hdwp = reinterpret_cast<HDWP>(EndDeferWindowPos(hdwp));
}
}
return hdwp != NULL;
}
bool ArrangeV(const CRect& rc)
{
HDWP hdwp = reinterpret_cast<HDWP>(TRUE);
const_iterator begin = m_frames.begin();
const_iterator end = m_frames.end();
if (begin != end)
{
hdwp = BeginDeferWindowPos(static_cast<int>(m_frames.size()));
const_iterator next = begin;
while ((hdwp != NULL) && (++next != end))
{
long y = (*begin) + typename CSplitterBar::Traits::GetSize(!IsHorizontal());
hdwp = begin->DeferFramePos(hdwp,
rc.left,
y,
rc.right,
(*next));
begin = next;
}
if (hdwp != NULL)
{
long y = (*begin) + typename CSplitterBar::Traits::GetSize(!IsHorizontal());
hdwp = begin->DeferFramePos(hdwp,
rc.left,
y,
rc.right,
rc.bottom);
if (hdwp)
hdwp = reinterpret_cast<HDWP>(EndDeferWindowPos(hdwp));
}
}
return hdwp != NULL;
}
bool Arrange(const CRect& rcClient)
{
bool bRes;
if (IsHorizontal())
bRes = ArrangeH(rcClient);
else
bRes = ArrangeV(rcClient);
return bRes;
}
CWndFramesPackageBase(bool bHorizontal)
: m_bHorizontal(bHorizontal), m_frames(0, 0)
{
}
public:
bool IsHorizontal() const
{
return m_bHorizontal;
}
void SetOrientation(bool bHorizontal)
{
m_bHorizontal = bHorizontal;
}
HCURSOR GetCursor(const CPoint& pt, const CRect& rc) const
{
HCURSOR hCursor = NULL;
position pos = IsHorizontal() ? pt.x : pt.y;
const_iterator i = m_frames.locate(pos);
if (i != m_frames.end())
{
CEmbeddedSplitterBar splitter(!IsHorizontal(), (*i), rc);
hCursor = splitter.GetCursor(pt);
}
return hCursor;
}
/*
bool StartSliding(HWND hWnd,const CPoint& pt,const CRect& rc,bool bGhostMove)
{
std::auto_ptr<CSplitterMoveTrackerBase> pTracker;
if(bGhostMove)
pTracker=std::auto_ptr<CSplitterMoveTrackerBase>(
new CSplitterMoveTrackerGhost(hWnd,*this,pt,rc));
else
pTracker=std::auto_ptr<CSplitterMoveTrackerBase>(
new CSplitterMoveTrackerFull(*this,pt,rc));
bool bRes=false;
if(const_iterator(*pTracker)!=m_frames.end())
bRes=TrackDragAndDrop(*pTracker,hWnd);
return bRes;
}
*/
bool StartSliding(HWND hWnd, const CPoint& pt, const CRect& rc, bool bGhostMove)
{
bool bRes = false;
position pos = IsHorizontal() ? pt.x : pt.y;
const_iterator i = m_frames.locate(pos);
if (i != m_frames.end())
{
CEmbeddedSplitterBar splitter(!IsHorizontal(), (*i), rc);
if (splitter.IsPtIn(pt))
{
std::auto_ptr<CSplitterMoveTrackerBase> pTracker;
if (bGhostMove)
pTracker = std::auto_ptr<CSplitterMoveTrackerBase>(
new CSplitterMoveTrackerGhost(hWnd, *this, pt, rc));
else
pTracker = std::auto_ptr<CSplitterMoveTrackerBase>(
new CSplitterMoveTrackerFull(hWnd, *this, pt, rc));
if (const_iterator(*pTracker) != m_frames.end())
bRes = TrackDragAndDrop(*pTracker, hWnd);
}
}
return bRes;
}
bool UpdateLayout(const CRect& rc)
{
CBounds bounds;
if (IsHorizontal())
{
bounds.low = rc.left;
bounds.hi = rc.right;
}
else
{
bounds.low = rc.top;
bounds.hi = rc.bottom;
}
bounds.low -= typename CSplitterBar::Traits::GetSize(!IsHorizontal());
CBounds::distance_t limit = m_frames.distance_limit();
if (bounds.distance() < limit)
bounds.hi = bounds.low + limit;
m_frames.set_bounds(bounds);
return Arrange(rc);
}
void GetMinFrameSize(const DFMHDR* pHdr, CSize& sz) const
{
MINMAXINFO mmInfo;
ZeroMemory(&mmInfo, sizeof(MINMAXINFO));
::SendMessage(pHdr->hWnd, WM_GETMINMAXINFO, NULL, reinterpret_cast<LPARAM>(&mmInfo));
sz.cx = mmInfo.ptMinTrackSize.x;
sz.cy = mmInfo.ptMinTrackSize.y;
}
LRESULT GetMinFrameDist(const DFMHDR* pHdr) const
{
CSize sz;
GetMinFrameSize(pHdr, sz);
return (IsHorizontal()) ? sz.cx : sz.cy;
}
void GetMinMaxInfo(LPMINMAXINFO pMinMaxInfo) const
{
if (m_frames.size() != 0)
{
pMinMaxInfo = std::accumulate(m_frames.begin(), m_frames.end(),
pMinMaxInfo, CMinMaxInfoAccumulator<typename CSplitterBar::Traits>(IsHorizontal()));
if (IsHorizontal())
pMinMaxInfo->ptMinTrackSize.x -= typename CSplitterBar::Traits::GetSize(!IsHorizontal());
else
pMinMaxInfo->ptMinTrackSize.y -= typename CSplitterBar::Traits::GetSize(!IsHorizontal());
}
}
void Draw(CDC& dc, const CRect& rc) const
{
if (m_frames.begin() != m_frames.end())
std::for_each(++m_frames.begin(), m_frames.end(), CEmbeddedSplitterBarPainter(dc, !IsHorizontal(), rc));
}
bool AcceptDock(DFDOCKRECT* pHdr, const CRect& rc)
{
bool bRes = false;
CSize sz;
GetMinFrameSize(&(pHdr->hdr), sz);
if (rc.PtInRect(CPoint(pHdr->rect.left, pHdr->rect.top))
&& (sz.cx <= rc.Width())
&& (sz.cy <= rc.Height())
&& ((((IsHorizontal()) ? sz.cx : sz.cy) + m_frames.distance_limit()) < (m_frames.hi() - m_frames.low())))
{
if (IsHorizontal())
{
pHdr->rect.top = rc.top;
pHdr->rect.bottom = rc.bottom;
}
else
{
pHdr->rect.left = rc.left;
pHdr->rect.right = rc.right;
}
bRes = true;
}
return bRes;
}
bool Dock(CFrame& frame, const DFDOCKRECT* pHdr, const CRect& rc)
{
position pos;
CFrames::distance len;
if (IsHorizontal())
{
pos = pHdr->rect.left;
len = pHdr->rect.right - pHdr->rect.left;
}
else
{
pos = pHdr->rect.top;
len = pHdr->rect.bottom - pHdr->rect.top;
}
iterator i = m_frames.locate(pos);
if (i != m_frames.end())
{
iterator inext = i;
++inext;
CBounds fbounds((*i), (inext != m_frames.end()) ? (*inext) : m_frames.hi());
if ((fbounds.low + (fbounds.hi - fbounds.low) / 3) < pos)
i = inext;
}
frame = pos;
m_frames.insert(i, frame, len);
return Arrange(rc);
}
bool Undock(const DFMHDR* pHdr, const CRect& rc)
{
iterator i = std::find_if(m_frames.begin(), m_frames.end(), CFrame::CCmp(pHdr->hWnd));
ATLASSERT(i != m_frames.end());
m_frames.erase(i);
return Arrange(rc);
}
bool Replace(const DFDOCKREPLACE* pHdr, const CRect& rc)
{
iterator i = std::find_if(m_frames.begin(), m_frames.end(), CFrame::CCmp(pHdr->hdr.hWnd));
ATLASSERT(i != m_frames.end());
m_frames.replace(i, CFrame(0, pHdr->hWnd));
return Arrange(rc);
}
protected:
bool m_bHorizontal;
CFrames m_frames;
};
template< class TTraits = CDockingFrameTraits >
class CWndFramesPackage : public CWndFramesPackageBase<CWndFrame, TTraits >
{
typedef CWndFrame CFrame;
typedef TTraits CTraits;
typedef typename CTraits::CSplitterBar CSplitterBar;
typedef CWndFramesPackage<TTraits> thisClass;
typedef CWndFramesPackageBase<CFrame, TTraits > baseClass;
public:
CWndFramesPackage(bool bHorizontal): baseClass(bHorizontal)
{
}
void PrepareForDocking(CWindow wnd, HDOCKBAR bar)
{
wnd.ShowWindow(SW_HIDE);
DWORD style = wnd.GetWindowLong(GWL_STYLE);
DWORD newStyle = style & (~WS_POPUP) | WS_CHILD;
wnd.SetWindowLong(GWL_STYLE, newStyle);
wnd.SetParent(bar);
wnd.SendMessage(WM_NCACTIVATE, TRUE);
wnd.SendMessage(WMDF_NDOCKSTATECHANGED,
MAKEWPARAM(TRUE, IsHorizontal()),
reinterpret_cast<LPARAM>(bar));
}
void PrepareForUndocking(CWindow wnd, HDOCKBAR bar)
{
wnd.ShowWindow(SW_HIDE);
DWORD style = wnd.GetWindowLong(GWL_STYLE);
DWORD newStyle = style & (~WS_CHILD) | WS_POPUP;
wnd.SetWindowLong(GWL_STYLE, newStyle);
wnd.SetParent(NULL);
wnd.SendMessage(WMDF_NDOCKSTATECHANGED,
FALSE,
reinterpret_cast<LPARAM>(bar));
}
bool SetDockingPosition(const DFDOCKPOS* pHdr, const CRect& rc)
{
ATLASSERT(::IsWindow(pHdr->hdr.hWnd));
CWindow wnd(pHdr->hdr.hWnd);
PrepareForDocking(wnd, pHdr->hdr.hBar);
position pos = m_frames.low() + position((m_frames.hi() - m_frames.low()) * pHdr->fPctPos);
m_frames.insert(CFrame(pos, pHdr->hdr.hWnd), pHdr->nHeight);
// wnd.ShowWindow(SW_SHOWNA);
bool bRes = Arrange(rc);
wnd.SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW);
return bRes;
}
bool GetDockingPosition(DFDOCKPOS* pHdr, const CRect& /*rc*/) const
{
ATLASSERT(::IsWindow(pHdr->hdr.hWnd));
const_iterator i = std::find_if(m_frames.begin(), m_frames.end(), CFrame::CCmp(pHdr->hdr.hWnd));
bool bRes = (i != m_frames.end());
if (bRes)
{
position pos = *i - m_frames.low();
pHdr->fPctPos = float(pos) / (m_frames.hi() - m_frames.low());
pHdr->nHeight = m_frames.get_frame_size(i) - typename CSplitterBar::Traits::GetSize(!IsHorizontal());
// pHdr->nWidth=IsHorizontal() ? rc.Height() : rc.Width();
// pHdr->nWidth-=CSplitterBar::GetThickness();
if (m_frames.size() == 1)
pHdr->dwDockSide |= CDockingSide::sSingle;
}
return bRes;
}
bool AcceptDock(DFDOCKRECT* pHdr, const CRect& rc)
{
return (!((m_frames.size() == 1)
&& (m_frames.begin()->hwnd() == pHdr->hdr.hWnd)))
&& baseClass::AcceptDock(pHdr, rc);
}
bool Dock(DFDOCKRECT* pHdr, const CRect& rc)
{
ATLASSERT(::IsWindow(pHdr->hdr.hWnd));
CWindow wnd(pHdr->hdr.hWnd);
PrepareForDocking(wnd, pHdr->hdr.hBar);
CFrame frame(0, pHdr->hdr.hWnd);
bool bRes = baseClass::Dock(frame, pHdr, rc);
wnd.SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE |
SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOACTIVATE);
wnd.GetTopLevelParent().SetActiveWindow();
return bRes;
}
bool Undock(DFMHDR* pHdr, const CRect& rc)
{
bool bRes = baseClass::Undock(pHdr, rc);
ATLASSERT(bRes);
PrepareForUndocking(pHdr->hWnd, pHdr->hBar);
if (m_frames.size() == 0)
{
DFMHDR dockHdr;
dockHdr.hWnd = pHdr->hBar;
dockHdr.hBar = ::GetParent(pHdr->hBar);
ATLASSERT(::IsWindow(dockHdr.hBar));
dockHdr.code = DC_UNDOCK;
::SendMessage(dockHdr.hBar, WMDF_DOCK, NULL, reinterpret_cast<LPARAM>(&dockHdr));
::PostMessage(dockHdr.hWnd, WM_CLOSE, NULL, NULL);
}
return bRes;
}
bool Replace(const DFDOCKREPLACE* pHdr, const CRect& rc)
{
PrepareForUndocking(pHdr->hdr.hWnd, pHdr->hdr.hBar);
PrepareForDocking(pHdr->hWnd, pHdr->hdr.hBar);
bool bRes = baseClass::Replace(pHdr, rc);
ATLASSERT(bRes);
::SetWindowPos(pHdr->hWnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW);
// ::ShowWindow(pHdr->hWnd,SW_SHOWNA);
return bRes;
}
};
template<class T>
class CPtrFrame
{
typedef CPtrFrame<T> thisClass;
public:
typedef typename T::position position;
typedef typename T::distance distance;
class CCmp
{
public:
CCmp(HWND hWnd) : m_hWnd(hWnd)
{
}
bool operator()(const thisClass& frame) const
{
return (frame.hwnd() == m_hWnd);
}
protected:
HWND m_hWnd;
};
CPtrFrame(position pos, T* ptr)
: m_pos(pos), m_ptr(ptr)
{
}
HWND hwnd() const
{
return m_ptr->operator HWND();
}
operator position() const
{
return m_pos;
}
thisClass& operator += (position val)
{
m_pos += val;
return *this;
}
thisClass& operator -= (position val)
{
m_pos -= val;
return *this;
}
thisClass& operator = (position pos)
{
m_pos = pos;
return *this;
}
HDWP DeferFramePos(HDWP hdwp, long x1, long y1, long x2, long y2) const
{
return m_ptr->DeferFramePos(hdwp, x1, y1, x2, y2);
}
T* operator ->() const
{
return m_ptr.get();
}
void GetMinMaxInfo(LPMINMAXINFO pMinMaxInfo) const
{
m_ptr->GetMinMaxInfo(pMinMaxInfo);
}
distance MinDistance() const
{
return m_ptr->MinDistance();
}
protected:
position m_pos;
mutable std::tr1::shared_ptr<T> m_ptr;
};
struct IFrame
{
typedef long position;
typedef long distance;
virtual ~IFrame() {};
virtual HWND hwnd() const = 0;
operator HWND() const
{
return hwnd();
}
virtual bool AcceptDock(DFDOCKRECT* pHdr) const = 0;
virtual distance MinDistance() const = 0;
virtual void GetMinMaxInfo(LPMINMAXINFO pMinMaxInfo) const = 0;
virtual HDWP DeferFramePos(HDWP hdwp, long x1, long y1, long x2, long y2) const
{
return ::DeferWindowPos(hdwp, hwnd(),
NULL,
x1, y1,
x2 - x1, y2 - y1,
SWP_NOZORDER | SWP_NOACTIVATE);
}
};
class CWindowPtrWrapper : public IFrame
{
public:
CWindowPtrWrapper(HWND* phWnd): m_phWnd(phWnd)
{
}
virtual HWND hwnd() const
{
return (*m_phWnd);
}
virtual bool AcceptDock(DFDOCKRECT* /*pHdr*/) const
{
return false;
}
virtual HDWP DeferFramePos(HDWP hdwp, long x1, long y1, long x2, long y2) const
{
if (*m_phWnd != NULL)
hdwp =::DeferWindowPos(hdwp, hwnd(),
NULL,
x1, y1,
x2 - x1, y2 - y1,
SWP_NOZORDER | SWP_NOACTIVATE);
return hdwp;
}
void GetMinMaxInfo(LPMINMAXINFO pMinMaxInfo) const
{
if (*m_phWnd != NULL)
::SendMessage(hwnd(), WM_GETMINMAXINFO, NULL, reinterpret_cast<LPARAM>(pMinMaxInfo));
}
virtual distance MinDistance() const
{
MINMAXINFO mmInfo;
ZeroMemory(&mmInfo, sizeof(MINMAXINFO));
GetMinMaxInfo(&mmInfo);
return mmInfo.ptMinTrackSize.x;;
}
protected:
HWND* m_phWnd;
};
//TImbeddedPackegeWnd
template<class TPackageFrame, class TTraits = CDockingWindowTraits >
class CSubWndFramesPackage :
public CRect,
public CWndFramesPackageBase<CPtrFrame<IFrame>, TTraits >
{
typedef CPtrFrame<IFrame> CFrame;
typedef TTraits CTraits;
typedef typename CTraits::CSplitterBar CSplitterBar;
typedef CSubWndFramesPackage<TPackageFrame, TTraits> thisClass;
typedef CWndFramesPackageBase<CFrame, TTraits > baseClass;
typedef TPackageFrame CPackageFrame;
struct CDockOrientationFlag
{
enum {low = 0, high = 1};
static void SetHigh(DWORD& flag)
{
flag = high;
}
static void SetLow(DWORD& flag)
{
flag = low;
}
static bool IsLow(DWORD flag)
{
return (flag & high) == 0;
}
};
protected:
class CFrameWrapper : public IFrame
{
public:
CFrameWrapper(thisClass* ptr): m_ptr(ptr)
{
}
virtual ~CFrameWrapper()
{
}
virtual HWND hwnd() const
{
return NULL;
}
/*
virtual bool AcceptDock(DFDOCKRECT* pHdr) const
{
return m_ptr->AcceptDock(pHdr);
}
*/
virtual bool AcceptDock(DFDOCKRECT* /*pHdr*/) const
{
ATLASSERT(false);
return true;
}
virtual HDWP DeferFramePos(HDWP hdwp, long x1, long y1, long x2, long y2) const
{
m_ptr->UpdateLayout(CRect(x1, y1, x2, y2));
return hdwp;
}
virtual void GetMinMaxInfo(LPMINMAXINFO pMinMaxInfo) const
{
m_ptr->GetMinMaxInfo(pMinMaxInfo);
}
virtual distance MinDistance() const
{
MINMAXINFO mmInfo;
ZeroMemory(&mmInfo, sizeof(MINMAXINFO));
GetMinMaxInfo(&mmInfo);
return m_ptr->IsHorizontal() ? mmInfo.ptMinTrackSize.y : mmInfo.ptMinTrackSize.x;
}
protected:
thisClass* m_ptr;
};
public:
CSubWndFramesPackage(bool bHorizontal)
: baseClass(bHorizontal), m_pDecl(0)
{
}
HCURSOR GetCursor(const CPoint& pt) const
{
return baseClass::GetCursor(pt, *this);
}
bool StartSliding(HWND hWnd, const CPoint& pt, bool bGhostMove)
{
return baseClass::StartSliding(hWnd, pt, *this, bGhostMove);
}
#ifndef DW_PROPORTIONAL_RESIZE
bool UpdateLayout(const CRect& rc)
{
bool bRes = EqualRect(&rc) != FALSE;
if (!bRes)
{
CopyRect(rc);
CBounds bounds;
if (IsHorizontal())
{
bounds.low = rc.left;
bounds.hi = rc.right;
}
else
{
bounds.low = rc.top;
bounds.hi = rc.bottom;
}
bounds.low -= typename CSplitterBar::Traits::GetSize(!IsHorizontal());
CBounds::distance_t limit = m_frames.distance_limit();
if (bounds.distance() < limit)
bounds.hi = bounds.low + limit;
if (m_pDecl != 0)
m_frames.set_bounds(bounds, CFrame::CCmp(m_pDecl->hwnd()));
else
m_frames.set_bounds(bounds);
bRes = Arrange(rc);
}
return bRes;
}
#else
bool UpdateLayout(const CRect& rc)
{
bool bRes = EqualRect(&rc) != FALSE;
if (!bRes)
{
CopyRect(rc);
bRes = baseClass::UpdateLayout(*this);
}
return bRes;
}
#endif //DW_PROPORTIONAL_RESIZE
void Draw(CDC& dc)
{
baseClass::Draw(dc, *this);
}
int GetControlledLen()
{
return 15 + typename CSplitterBar::Traits::GetSize(!IsHorizontal());
}
bool AcceptDock(DFDOCKRECT* pHdr)
{
CPoint pt(pHdr->rect.left, pHdr->rect.top);
CSize sz(0, 0);
position pos;
if (IsHorizontal())
{
pos = pt.x;
sz.cx = GetControlledLen();
}
else
{
pos = pt.y;
sz.cy = GetControlledLen();
}
bool bRes = PtInRect(pt) == TRUE;
if (bRes)
{
// position pos=IsHorizontal() ? pHdr->rect.left :pHdr->rect.top;
const_iterator i = m_frames.locate(pos);
if (m_frames.get_frame_low(i) + GetControlledLen() > pos)
bRes = AcceptDock(i, pHdr, *this);
else
{
if (m_frames.get_frame_hi(i) - GetControlledLen() < pos)
bRes = AcceptDock(++i, pHdr, *this);
else
{
bRes = i->hwnd() != m_pDecl->hwnd();
if (bRes)
bRes = (*i)->AcceptDock(pHdr);
}
}
}
else
{
CRect rc(this);
rc.InflateRect(sz);
bRes = rc.PtInRect(pt) == TRUE;
if (bRes)
{
if (pos < m_frames.hi())
bRes = AcceptDock(m_frames.begin(), pHdr, rc);
else
bRes = AcceptDock(m_frames.end(), pHdr, rc);
}
}
return bRes;
}
bool AcceptDock(const_iterator i, DFDOCKRECT* pHdr, const CRect& rc)
{
ATLASSERT(std::find_if(m_frames.begin(), m_frames.end(), CFrame::CCmp(m_pDecl->hwnd())) != m_frames.end());
const_iterator begin = m_frames.begin();
if (std::find_if(begin, i, CFrame::CCmp(m_pDecl->hwnd())) == i)
CDockOrientationFlag::SetLow(pHdr->flag);
else
CDockOrientationFlag::SetHigh(pHdr->flag);
bool bRes = baseClass::AcceptDock(pHdr, rc);
if (bRes)
{
if (IsHorizontal())
{
long len = (pHdr->rect.right - pHdr->rect.left);
if (CDockOrientationFlag::IsLow(pHdr->flag))
{
ATLASSERT(i != m_frames.end());
pHdr->rect.left = (*i) + typename CSplitterBar::Traits::GetSize(!IsHorizontal());
pHdr->rect.right = pHdr->rect.left + len;
}
else
{
pHdr->rect.right = (i == m_frames.end()) ? m_frames.hi() : (*i);
pHdr->rect.left = pHdr->rect.right - len;
}
}
else
{
long len = (pHdr->rect.bottom - pHdr->rect.top);
if (CDockOrientationFlag::IsLow(pHdr->flag))
{
ATLASSERT(i != m_frames.end());
pHdr->rect.top = (*i) + typename CSplitterBar::Traits::GetSize(!IsHorizontal());
pHdr->rect.bottom = pHdr->rect.top + len;
}
else
{
pHdr->rect.bottom = (i == m_frames.end()) ? m_frames.hi() : (*i);
pHdr->rect.top = pHdr->rect.bottom - len;
}
}
}
return bRes;
}
bool Dock(CFrame& frame, const DFDOCKRECT* pHdr, const CRect& rc)
{
position pos;
CFrames::distance len;
if (IsHorizontal())
{
pos = pHdr->rect.left;
len = pHdr->rect.right - pHdr->rect.left;
}
else
{
pos = pHdr->rect.top;
len = pHdr->rect.bottom - pHdr->rect.top;
}
frame = pos;
if (!CDockOrientationFlag::IsLow(pHdr->flag))
pos += len;
iterator i;
if (pos != m_frames.hi())
i = m_frames.locate(pos);
else
i = m_frames.end();
m_frames.insert(i, CFrame::CCmp(m_pDecl->hwnd()), frame, len);
return Arrange(rc);
}
bool Dock(DFDOCKRECT* pHdr)
{
CPackageFrame* ptr = CPackageFrame::CreateInstance(pHdr->hdr.hBar, !IsHorizontal());
bool bRes = (ptr != 0);
if (bRes)
{
HWND hDockWnd = pHdr->hdr.hWnd;
pHdr->hdr.hWnd = ptr->hwnd();
CFrame frame(0, ptr);
bRes = Dock(frame, pHdr, *this);
ATLASSERT(bRes);
if (bRes)
{
pHdr->hdr.hWnd = hDockWnd;
pHdr->hdr.hBar = ptr->hwnd();
CWindow bar(pHdr->hdr.hBar);
bar.GetWindowRect(&(pHdr->rect));
bRes =::SendMessage(ptr->hwnd(), WMDF_DOCK, NULL, reinterpret_cast<LPARAM>(pHdr)) != FALSE;
}
}
return bRes;
}
bool Undock(const DFMHDR* pHdr)
{
iterator i = std::find_if(m_frames.begin(), m_frames.end(), CFrame::CCmp(pHdr->hWnd));
bool bRes = (i != m_frames.end());
if (bRes)
{
m_frames.erase(i, CFrame::CCmp(m_pDecl->hwnd()));
bRes = Arrange(*this);
}
return bRes;
}
bool GetDockingPosition(DFDOCKPOS* pHdr) const
{
const_iterator i = std::find_if(m_frames.begin(), m_frames.end(), CFrame::CCmp(pHdr->hdr.hBar));
bool bRes = (i != m_frames.end());
if (bRes)
{
pHdr->nWidth = m_frames.get_frame_size(i) -
typename CSplitterBar::Traits::GetSize(!IsHorizontal());
CFrames::size_type dWnd = std::distance(m_frames.begin(), i);
i = std::find_if(m_frames.begin(), m_frames.end(), CFrame::CCmp(m_pDecl->hwnd()));
ATLASSERT(i != m_frames.end());
CFrames::size_type dBWnd = std::distance(m_frames.begin(), i);
if (dBWnd > dWnd)
{
pHdr->nBar = dWnd;
pHdr->dwDockSide |= CDockingSide::sTop;
}
else
{
pHdr->nBar = m_frames.size() - dWnd - 1;
// pHdr->dwDockSide|=0;
}
bRes = (::SendMessage(pHdr->hdr.hBar, WMDF_DOCK, NULL, reinterpret_cast<LPARAM>(pHdr)) != FALSE);
}
return bRes;
}
// bool SetDockingPosition(DFDOCKPOS* pHdr)
// {
// bool bRes=true;
// UINT limit=GetMinFrameDist(&(pHdr->hdr));
// if(pHdr->nWidth<limit)
// pHdr->nWidth=limit;
// CDockingSide side(pHdr->dwDockSide);
// if(side.IsTop())
// {
// iterator i=ssec::search_n(m_frames.begin(),m_frames.end(),CFrame::CCmp(m_pDecl->hwnd()),pHdr->nBar);
// ATLASSERT(i!=m_frames.end());
// if(i->hwnd()==m_pDecl->hwnd() || side.IsSingle())
// {
// CPackageFrame* ptr=CPackageFrame::CreateInstance(pHdr->hdr.hBar,!IsHorizontal());
// bRes=(ptr!=0);
// if(bRes)
// {
//// i=m_frames.insert(i,CFrame(*i,ptr),pHdr->nWidth);
// i=m_frames.insert(i,CFrame::CCmp(m_pDecl->hwnd()),CFrame(*i,ptr),pHdr->nWidth+splitterSize);
// }
// }
// else
// m_frames.set_frame_size(i,pHdr->nWidth+splitterSize);
// pHdr->hdr.hBar=i->hwnd();
// }
// else
// {
// reverse_iterator ri=ssec::search_n(m_frames.rbegin(),m_frames.rend(),CFrame::CCmp(m_pDecl->hwnd()),pHdr->nBar);
// ATLASSERT(ri!=m_frames.rend());
// iterator i=ri.base();
// if(/*ri->hwnd()*/(*ri).hwnd()==m_pDecl->hwnd() || side.IsSingle())
// {
// CPackageFrame* ptr=CPackageFrame::CreateInstance(pHdr->hdr.hBar,!IsHorizontal());
// bRes=(ptr!=0);
// if(bRes)
// {
// position pos=(i==m_frames.end())? m_frames.hi():*i;
// pos-=pHdr->nWidth+CSplitterBar::GetThickness();
// if(pos<m_frames.low())
// pos=m_frames.low();
//// i=m_frames.insert(i,CFrame(pos,ptr),pHdr->nWidth);
// i=m_frames.insert(i,CFrame::CCmp(m_pDecl->hwnd()),CFrame(pos,ptr),pHdr->nWidth+splitterSize);
// }
// }
// else
// {
// ATLASSERT(i!=m_frames.begin());
// m_frames.set_frame_size(--i,pHdr->nWidth+splitterSize);
// }
// pHdr->hdr.hBar=i->hwnd();
// }
// bRes=Arrange(*this);
// ATLASSERT(bRes);
// if(bRes)
// {
// bRes=(::SendMessage(pHdr->hdr.hBar,WMDF_DOCK,NULL,reinterpret_cast<LPARAM>(pHdr))!=FALSE);
// ATLASSERT(bRes);
// }
// return bRes;
// }
bool SetDockingPosition(DFDOCKPOS* pHdr)
{
bool bRes = true;
LRESULT limit = GetMinFrameDist(&(pHdr->hdr));
if (static_cast<LRESULT>(pHdr->nWidth) < limit)
pHdr->nWidth = static_cast<UINT>(limit);
CDockingSide side(pHdr->dwDockSide);
if (side.IsTop())
{
iterator i = ssec::search_n(m_frames.begin(), m_frames.end(), CFrame::CCmp(m_pDecl->hwnd()), pHdr->nBar);
ATLASSERT(i != m_frames.end());
if (i->hwnd() == m_pDecl->hwnd() || side.IsSingle())
{
CPackageFrame* ptr = CPackageFrame::CreateInstance(pHdr->hdr.hBar, !IsHorizontal());
bRes = (ptr != 0);
if (bRes)
{
// i=m_frames.insert(i,CFrame(*i,ptr),pHdr->nWidth);
i = m_frames.insert(i, CFrame::CCmp(m_pDecl->hwnd()), CFrame(*i, ptr), pHdr->nWidth +
typename CSplitterBar::Traits::GetSize(!IsHorizontal()));
bRes = Arrange(*this);
ATLASSERT(bRes);
}
}
pHdr->hdr.hBar = i->hwnd();
}
else
{
reverse_iterator ri = ssec::search_n(m_frames.rbegin(), m_frames.rend(), CFrame::CCmp(m_pDecl->hwnd()), pHdr->nBar);
ATLASSERT(ri != m_frames.rend());
iterator i = ri.base();
if (/*ri->hwnd()*/(*ri).hwnd() == m_pDecl->hwnd() || side.IsSingle())
{
CPackageFrame* ptr = CPackageFrame::CreateInstance(pHdr->hdr.hBar, !IsHorizontal());
bRes = (ptr != 0);
if (bRes)
{
position pos = (i == m_frames.end()) ? m_frames.hi() : *i;
pos -= pHdr->nWidth + typename CSplitterBar::Traits::GetSize(!IsHorizontal());
if (pos < m_frames.low())
pos = m_frames.low();
// i=m_frames.insert(i,CFrame(pos,ptr),pHdr->nWidth);
i = m_frames.insert(i, CFrame::CCmp(m_pDecl->hwnd()), CFrame(pos, ptr), pHdr->nWidth + typename CSplitterBar::Traits::GetSize(!IsHorizontal()));
bRes = Arrange(*this);
ATLASSERT(bRes);
pHdr->hdr.hBar = i->hwnd();
}
}
else
pHdr->hdr.hBar =/*ri->hwnd()*/(*ri).hwnd();
}
if (bRes)
{
bRes = (::SendMessage(pHdr->hdr.hBar, WMDF_DOCK, NULL, reinterpret_cast<LPARAM>(pHdr)) != FALSE);
ATLASSERT(bRes);
}
return bRes;
}
bool Insert(HWND* ptr, const CRect& rc)
{
DFDOCKRECT dockHdr;
::CopyRect(&dockHdr.rect, &rc);
ATLASSERT(m_pDecl == 0);
m_pDecl = new CWindowPtrWrapper(ptr);
CFrame frame(0, m_pDecl);
return baseClass::Dock(frame, &dockHdr, *this);
}
bool Insert(thisClass* ptr, const CRect& rc)
{
DFDOCKRECT dockHdr;
::CopyRect(&dockHdr.rect, &rc);
ATLASSERT(m_pDecl == 0);
m_pDecl = new CFrameWrapper(ptr);
CFrame frame(0, m_pDecl);
return baseClass::Dock(frame, &dockHdr, *this);
}
protected:
IFrame* m_pDecl;
};
}//namespace dockwins
#endif // WTL_DW_WNDFRMPKG_H_INCLUDED_
| [
"[email protected]"
] | [
[
[
1,
1432
]
]
] |
053a03f2158aea21331422b3ef13fdab35b14262 | 8d2ef01bfa0b7ed29cf840da33e8fa10f2a69076 | /code/Kernel/fxConsole.h | 48a200c390adc10673a7951fd780d3bb89c28dc8 | [] | no_license | BackupTheBerlios/insane | fb4c5c6a933164630352295692bcb3e5163fc4bc | 7dc07a4eb873d39917da61e0a21e6c4c843b2105 | refs/heads/master | 2016-09-05T11:28:43.517158 | 2001-01-31T20:46:38 | 2001-01-31T20:46:38 | 40,043,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | h | //---------------------------------------------------------------------------
#ifndef fxConsoleH
#define fxConsoleH
//---------------------------------------------------------------------------
#include "../insanefx.h"
#include "../kernel/fxClass.h"
#include "../shared/fxList.h"
#include "../shared/fxConst.h"
//#include "kernel/fxConsoleWindow.h"
class INSANEFX_API fxConsole : public fxClass
{
protected:
static fxList StringList;
// very ugly hack, use a borland vcl window for output
// TfxConsoleForm * Form;
public:
fxConsole()
{
ClassName = "fxConsole";
RegisterObject(this, ClassName);
// Form = new TfxConsoleForm(NULL);
DisplayString(IFX_VERSION_STRING);
DisplayString("");
}
~fxConsole(void)
{
UnregisterObject(ClassName);
}
virtual void DisplayString(char * s);
virtual void DisplayError(char * s);
};
#endif
| [
"josef"
] | [
[
[
1,
47
]
]
] |
24440909ff5b5bd796e844223a158494b2c70c63 | 0b22b8ba6217ecf49669a81342c1f226fa5b851d | /BBOSD.h | c657f7e6c3242bfd8da266e78cfe7a6e1383e2c3 | [] | no_license | BB4Win/bbosd | c96d1402263ef0d54ca4ef182c4a755946ad7e89 | 17d4c7cc1d486d66aac1cf67dfcf6f12e5eca715 | refs/heads/master | 2016-09-16T05:17:03.872563 | 2007-10-31T21:41:34 | 2007-10-31T21:41:34 | 32,025,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,185 | h | /*
BBOSD.h
Header file for BBOSD class
Copyright (c) 2007, Brian Hartvigsen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the BBSOD nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "BBPlugin.h"
#define POSITION_TOP 0x0001
#define POSITION_MIDDLE 0x0002
#define POSITION_BOTTOM 0x0004
#define POSITION_LEFT 0x0010
#define POSITION_CENTER 0x0020
#define POSITION_RIGHT 0x0040
class CBBOSD : public CBBPlugin {
public:
CBBOSD(HINSTANCE h) : CBBPlugin(h)
{
m_hInstance = h;
m_hMemDC = NULL;
m_hMemBitmap = NULL;
m_hFont = NULL;
m_szOsdText = NULL;
}
~CBBOSD()
{
DeleteObject(SelectObject(m_hMemDC, m_hFont));
DeleteObject(SelectObject(m_hMemDC, m_hMemBitmap));
ReleaseDC(m_hWindow,m_hMemDC);
delete[] m_szOsdText;
}
void Destroy()
{
KillTimer(m_hWindow, 1);
_DestroyWindow();
}
int Initialize()
{
_RegisterClass();
_CreateWindow(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
BOOL (WINAPI*pSetLayeredWindowAttributes)(HWND, COLORREF, BYTE, DWORD) = NULL;
HMODULE hUser32 = LoadLibraryA("user32.dll");
if (hUser32) {
pSetLayeredWindowAttributes=(BOOL(WINAPI*)(HWND, COLORREF, BYTE, DWORD))GetProcAddress(hUser32, "SetLayeredWindowAttributes");
if (!pSetLayeredWindowAttributes) {
FreeLibrary(hUser32);
hUser32=NULL;
}
}
if(!pSetLayeredWindowAttributes){
MessageBox(NULL, "OS version not supported (Windows2000+ required)", "BBOSD", MB_OK|MB_TOPMOST|MB_SETFOREGROUND);
return TRUE;
}
if (pSetLayeredWindowAttributes)
pSetLayeredWindowAttributes(m_hWindow, 0, 0, LWA_COLORKEY);
if (ReadSettings())
return FALSE;
return TRUE;
}
bool ReadSettings()
{
char rcpath[MAX_PATH]; int i;
GetModuleFileName(m_hInstance, rcpath, sizeof(rcpath));
for (i=0;;)
{
int nLen = lstrlen(rcpath);
while (nLen && rcpath[nLen-1] != '\\') nLen--;
strcpy(rcpath+nLen, "bbosdrc"); if (FileExists(rcpath)) break;
strcpy(rcpath+nLen, "bbosd.rc"); if (FileExists(rcpath)) break;
if (2 == ++i)
{
strncpy(rcpath, extensionsrcPath(), MAX_PATH);
}
GetBlackboxPath(rcpath, sizeof(rcpath));
}
char setting[MAX_LINE_LENGTH];
ZeroMemory(setting, MAX_LINE_LENGTH);
m_bShowToolbarLabel = ReadBool(rcpath, "bbOSD.ShowLabel:", true);
bool bVoodooMath = ReadBool(rcpath, "bbOSD.VoodooMath:", false);
m_nEdgePadding = ReadInt(rcpath, "bbOSD.EdgePadding:", 10);
m_nTimeout = ReadInt(rcpath, "bbOSD.Timeout:", 30000);
m_cFontColor = ReadColor(rcpath, "bbosd.ClrOSD:", "#FFFFFF");
m_cBorderColor = ReadColor(rcpath, "bbOSD.ClrOutline:", "#010101");
strncpy(setting, ReadString(rcpath, "bbOSD.Position:", ""), MAX_LINE_LENGTH);
if (IsInString(setting, "Middle"))
m_dPosition = POSITION_MIDDLE;
else if(IsInString(setting, "Bottom"))
m_dPosition = POSITION_BOTTOM;
else
m_dPosition = POSITION_TOP;
if (IsInString(setting, "Center"))
m_dPosition |= POSITION_CENTER;
else if (IsInString(setting, "Right"))
m_dPosition |= POSITION_RIGHT;
else
m_dPosition |= POSITION_LEFT;
InitializeImages();
strncpy(setting, ReadString(rcpath, "bbOSD.FontFace:", "Verdana"), MAX_LINE_LENGTH);
int size = ReadInt(rcpath, "bbOSD.FontHeight:", 75);
size = (bVoodooMath ? 1 : -1) * MulDiv(size, GetDeviceCaps(GetDC(NULL), LOGPIXELSY), bVoodooMath ? 100 : 72);
HFONT temp = CreateFont(size, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, NONANTIALIASED_QUALITY, DEFAULT_PITCH, setting);
if (!temp && !m_hFont)
return false;
else
{
if (temp)
{
if (m_hFont)
// Put the old font back and delete the new one
DeleteObject(SelectObject(m_hMemDC, m_hFont));
m_hFont = temp;
}
}
m_hFont = (HFONT)SelectObject(m_hMemDC, m_hFont);
return true;
}
void InitializeImages()
{
m_hMemDC = CreateCompatibleDC(NULL);
m_hMemBitmap = CreateBitmap(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), 1, 32, NULL);
m_hMemBitmap = (HBITMAP)SelectObject(m_hMemDC, m_hMemBitmap);
}
void OnDraw()
{
int height = GetSystemMetrics(SM_CYSCREEN);
int width = GetSystemMetrics(SM_CXSCREEN);
RECT rc = {0, 0, width, height};
HBRUSH black = CreateSolidBrush(RGB(0,0,0));
HBRUSH old = (HBRUSH)SelectObject(m_hMemDC, black);
FillRect(m_hMemDC, &rc, black);
SelectObject(m_hMemDC, old);
DeleteObject(black);
DrawText(m_hMemDC, m_szOsdText, -1, &rc, DT_CALCRECT);
int yOffset = m_nEdgePadding, xOffset = m_nEdgePadding;
if (m_dPosition & POSITION_MIDDLE)
yOffset = (height / 2) - (rc.bottom / 2);
else if (m_dPosition & POSITION_BOTTOM)
yOffset = height - rc.bottom - m_nEdgePadding;
if (m_dPosition & POSITION_CENTER)
xOffset = (width / 2) - (rc.right / 2);
else if (m_dPosition & POSITION_RIGHT)
xOffset = width - rc.right - m_nEdgePadding;
SetWindowPos(m_hWindow, NULL, xOffset, yOffset, rc.right, rc.bottom, SWP_NOSENDCHANGING | SWP_NOACTIVATE | SWP_NOZORDER);
SetBkMode(m_hMemDC, TRANSPARENT);
rc.left -= 1;
rc.top -= 1;
SetTextColor(m_hMemDC, m_cBorderColor);
DrawText(m_hMemDC, m_szOsdText, -1, &rc, DT_LEFT);
rc.left += 2;
rc.top += 2;
DrawText(m_hMemDC, m_szOsdText, -1, &rc, DT_LEFT);
rc.left -= 2;
DrawText(m_hMemDC, m_szOsdText, -1, &rc, DT_LEFT);
rc.left += 2;
rc.top -= 2;
DrawText(m_hMemDC, m_szOsdText, -1, &rc, DT_LEFT);
rc.left -= 1;
rc.top += 1;
SetTextColor(m_hMemDC, m_cFontColor);
DrawText(m_hMemDC, m_szOsdText, -1, &rc, DT_LEFT);
}
void OnPaint()
{
PAINTSTRUCT ps;
BeginPaint(m_hWindow, &ps);
BitBlt(ps.hdc, ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom, m_hMemDC, 0, 0, SRCCOPY);
EndPaint(m_hWindow, &ps);
}
void OnBroam(LPCSTR broam)
{
char *b = new char[strlen(broam) + 1];
strcpy(b,broam);
if (!_strnicmp(b, "@BBOSD ", 7))
{
size_t len = lstrlen(b) + 1;
char *drop = new char[len];
char *osd = new char[len];
char *timeout = new char[len];
char *tokens[2] = { drop, osd };
drop[0] = osd[0] = timeout[0] = 0;
int toks = BBTokenize(b, tokens, 2, timeout);
ShowOSD(osd, atoi(timeout));
delete[] drop;
delete[] osd;
delete[] timeout;
}
delete[] b;
}
void ShowOSD(LPCSTR message, int timeout)
{
if (!m_szOsdText || _stricmp(message, m_szOsdText))
{
if (m_szOsdText)
delete[] m_szOsdText;
m_szOsdText = new char[lstrlen(message) + 1];
strcpy(m_szOsdText, message);
OnDraw();
}
InvalidateRect(m_hWindow, NULL, TRUE);
ShowWindow(m_hWindow, SW_SHOW);
SetTimer(m_hWindow, 1, timeout ? timeout : m_nTimeout, NULL);
}
virtual LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch(uMessage)
{
case WM_CLOSE: break;
case WM_PAINT:
OnPaint();
break;
case WM_TIMER:
if(wParam == 1)
{
ShowWindow(m_hWindow, SW_HIDE);
KillTimer(m_hWindow, 1);
}
break;
case BB_SETTOOLBARLABEL:
if (m_bShowToolbarLabel)
ShowOSD((char*)lParam, 0);
break;
case BB_BROADCAST:
OnBroam((char *)lParam);
break;
case BB_RECONFIGURE:
ReadSettings();
break;
default:
return DefWindowProc(hWnd, uMessage, wParam, lParam);
}
return FALSE;
}
private:
// Windows
HINSTANCE m_hInstance;
// Gdi
HDC m_hMemDC;
HBITMAP m_hMemBitmap;
HFONT m_hFont;
// RC Settings
bool m_bShowToolbarLabel;
int m_nEdgePadding;
int m_nTimeout;
DWORD m_dPosition;
COLORREF m_cFontColor;
COLORREF m_cBorderColor;
// Other
LPSTR m_szOsdText;
}; | [
"[email protected]"
] | [
[
[
1,
332
]
]
] |
809fd5607bc4f6745f8533e892e4fcbcaa249099 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/Registrations/MultiResolutionRegistration/elxMultiResolutionRegistration.cxx | 3be37fec9225a3fffdeacd98cf5afcc4bad6c4b8 | [] | no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cxx | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#include "elxMultiResolutionRegistration.h"
elxInstallMacro( MultiResolutionRegistration );
| [
"[email protected]"
] | [
[
[
1,
18
]
]
] |
9e207ee430290b74ba9f3d44e0f2a8954d8c7959 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/serialization/test/test_inclusion.cpp | ebb3dac4f78b2f18ec80e49ef7658ccbcb4340ba | [
"BSL-1.0"
] | permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | cpp | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_const.cpp
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/level_enum.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/tracking_enum.hpp>
#include <boost/serialization/traits.hpp>
#include <boost/serialization/type_info_implementation.hpp>
#include <boost/serialization/version.hpp>
struct foo
{
int x;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
// In compilers implementing 2-phase lookup, the call to
// make_nvp is resolved even if foo::serialize() is never
// instantiated.
ar & boost::serialization::make_nvp("x",x);
}
};
int
main(int argc, char * argv[]){
return 0;
}
| [
"metrix@Blended.(none)"
] | [
[
[
1,
42
]
]
] |
b8d3d791baee73b4275e283189daa94f69d81cf9 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/Code/Tools/Viewer/Viewer.cpp | 023c637d27bd8be3b82f60fab9635e34d06f6a51 | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,880 | cpp | #include "__PCH_Viewer.h"
#include <windows.h>
//---Engine Includes---------
#include "Core/FlostiEngine.h"
#include "Base/Exceptions/Exception.h"
//----------------------------
#include "ViewerProcess.h"
//---Always the last:
#include "Memory/MemLeaks.h"
#define APPLICATION_NAME "VIEWER"
// ----------------------------------------
// -- Windows Message Handlers
// ----------------------------------------
#define WM_SERVER (WM_USER + 1)
#define WM_CLIENT (WM_USER + 2)
//Globals
CFlostiEngine * g_FlostEngine = new CFlostiEngine();
//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY:
{
PostQuitMessage( 0 );
return 0;
}
break;
case WM_KEYDOWN:
{
switch( wParam )
{
case VK_ESCAPE:
//Cleanup();
PostQuitMessage( 0 );
return 0;
break;
}
}
break;
case WM_SERVER: case WM_CLIENT:
{
g_FlostEngine->MsgProc(wParam, lParam);
}
break;
}//end switch( msg )
return DefWindowProc( hWnd, msg, wParam, lParam );
}
void ShowErrorMessage (const std::string& message)
{
bool logSaved = false;
logSaved = LOGGER->SaveLogsInFile();
std::string end_message = "";
if (logSaved)
{
end_message += "Sorry, Application failed. Logs saved\n";
}
else
{
end_message += "Sorry, Application failed. Logs could not be saved\n";
}
end_message += message;
MessageBox(0, end_message.c_str(), "FlostiProject Report", MB_OK | MB_ICONERROR);
}
//-----------------------------------------------------------------------
// WinMain
//-----------------------------------------------------------------------
int APIENTRY WinMain(HINSTANCE _hInstance, HINSTANCE _hPrevInstance, LPSTR _lpCmdLine, int _nCmdShow)
{
#if defined( _DEBUG )
MemLeaks::MemoryBegin();
#endif //defined(_DEBUG)
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL),
NULL, NULL, NULL, NULL, APPLICATION_NAME, NULL };
// Register the window class
RegisterClassEx( &wc );
try
{
CViewerProcess* viewerProcess = new CViewerProcess("ViewerProcess");
std::vector<CProcess*> l_ProcessVector;
l_ProcessVector.push_back(viewerProcess);
g_FlostEngine->LoadInitParams("Data/Config/init_viewer.xml");
uint32 width = g_FlostEngine->GetInitParams().m_ScreenResolution.x;
uint32 height = g_FlostEngine->GetInitParams().m_ScreenResolution.y;
uint32 posX = g_FlostEngine->GetInitParams().m_WindowsPosition.x;
uint32 posY = g_FlostEngine->GetInitParams().m_WindowsPosition.y;
// Create the application's window
HWND hWnd = CreateWindow( APPLICATION_NAME, APPLICATION_NAME, WS_OVERLAPPEDWINDOW,
posX, posY, width, height,
NULL, NULL, wc.hInstance, NULL );
g_FlostEngine->Init(l_ProcessVector, hWnd);
ShowWindow( hWnd, SW_SHOWDEFAULT );
UpdateWindow( hWnd );
MSG msg;
ZeroMemory( &msg, sizeof(msg) );
while( msg.message!=WM_QUIT && !g_FlostEngine->Exit())
{
if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
// main loop
g_FlostEngine->Update();
g_FlostEngine->Render();
}
}
}
catch(CException& e)
{
ShowErrorMessage(e.GetDescription());
}
catch (...)
{
ShowErrorMessage("Exception Occured");
}
UnregisterClass( APPLICATION_NAME, wc.hInstance );
CHECKED_DELETE(g_FlostEngine);
#if defined( _DEBUG )
MemLeaks::MemoryEnd();
#endif //defined(_DEBUG)
return 0;
} | [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
159
]
]
] |
1e5b6548093b444cb36b1d37bc6a898257200696 | 016c54cb102ac6b792ee9756614d43b5687950b7 | /UiCommon/UiImage.cpp | 40682d6cd7b253811ba6c09f0851ba2519367042 | [] | no_license | jemyzhang/MzCommonDll | 3103fc4f5214a069c473b5aaca90aaf09d355517 | 82cbfa7eaa872809fa0bdea4531d5df73e23ca47 | refs/heads/master | 2021-01-19T14:53:26.687575 | 2010-05-20T03:18:16 | 2010-05-20T03:18:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | cpp | #include "UiImage.h"
#include <MzCommon.h>
using namespace MzCommon;
void UiImage::PaintWin(HDC hdcDst, RECT* prcWin, RECT* prcUpdate){
UiWin::PaintWin(hdcDst,prcWin,prcUpdate);
if(pimg){
pimg->Draw(hdcDst,prcWin,true,false);
}
if(pimgPath){
ImagingHelper::DrawImage(hdcDst,prcWin,pimgPath,true,false);
}
}
void UiImage::setupImagePath(LPWSTR path){
if(path){
C::newstrcpy(&pimgPath,path);
if(pimg){
delete pimg;
pimg = 0;
}
}
} | [
"jemyzhang@96341596-6814-2f4c-99ee-b9cf7f28d869"
] | [
[
[
1,
23
]
]
] |
3d7900cfae4193d7866c9338c01ce553b2762fd3 | f283c74ea3824717278ed21798134cfb058d7c6e | /jni/Box2D/Collision/Shapes/b2EdgeShape.h | 8e41bf7c3c135fce91210a2b3feec885833bafbd | [] | no_license | mnem/Box2D_AndroidNDK | 16c3de8be7866b7ac287cefc65b9477ae2c41c45 | 7205fb2a78ff4b533beb417d28cef7d3a7d86c3e | refs/heads/master | 2021-01-23T13:55:47.884624 | 2010-08-19T19:53:54 | 2010-08-19T19:53:54 | 682,429 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,066 | h | /*
* Copyright (c) 2006-2010 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_EDGE_SHAPE_H
#define B2_EDGE_SHAPE_H
#include <Box2D/Collision/Shapes/b2Shape.h>
/// A line segment (edge) shape. These can be connected in chains or loops
/// to other edge shapes. The connectivity information is used to ensure
/// correct contact normals.
class b2EdgeShape : public b2Shape
{
public:
b2EdgeShape();
/// Implement b2Shape.
b2Shape* Clone(b2BlockAllocator* allocator) const;
/// @see b2Shape::TestPoint
bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
/// Implement b2Shape.
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform) const;
/// @see b2Shape::ComputeAABB
void ComputeAABB(b2AABB* aabb, const b2Transform& transform) const;
/// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData, float32 density) const;
b2Vec2 m_vertex1, m_vertex2;
int32 m_index1, m_index2;
b2EdgeShape* m_side1;
b2EdgeShape* m_side2;
};
inline b2EdgeShape::b2EdgeShape()
{
m_type = e_edge;
m_radius = b2_polygonRadius;
m_index1 = 0;
m_index2 = 1;
m_side1 = NULL;
m_side2 = NULL;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
63
]
]
] |
a65960ea7f6ba06a8b2d3759f8e3ba61da6a5b0f | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/UIVisual.h | bf522819d023549d6679393b7831bcf781171fd5 | [] | 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 | 5,064 | h | #pragma once
#ifndef __HALAK_UIVISUAL_H__
#define __HALAK_UIVISUAL_H__
# include <Halak/FWD.h>
# include <Halak/UIElement.h>
# include <Halak/Vector2.h>
namespace Halak
{
class UIVisual : public UIElement
{
public:
static const Property<float> OpacityProperty;
static const Property<bool> ShownProperty;
public:
UIVisual();
virtual ~UIVisual();
inline void Show();
inline void Hide();
void BringToFront();
void SendToBack();
RectangleF ComputeBounds(UIVisualVisitor& visitor);
inline float GetOpacity() const;
void SetOpacity(float value);
inline bool GetShown() const;
inline void SetShown(bool value);
inline UIFrame* GetFrame() const;
void SetFrame(UIFrame* value);
inline UITransform* GetTransform() const;
void SetTransform(UITransform* value);
inline UIEventMap* GetEventMap() const;
void SetEventMap(UIEventMap* value);
inline virtual Vector2 GetDesiredSize();
inline UIPanel* GetParent() const;
inline bool IsVisible() const;
virtual bool IsPanel() const;
protected:
virtual void OnDraw(UIDrawingContext& context);
virtual void OnPick(UIPickingContext& context);
virtual void OnParentChanged(UIPanel* old);
virtual bool OnKeyDown(const UIKeyboardEventArgs& args);
virtual bool OnKeyUp(const UIKeyboardEventArgs& args);
virtual bool OnKeyPressing(const UIKeyboardEventArgs& args);
virtual void OnMouseEnter(const UIMouseEventArgs& args);
virtual void OnMouseLeave(const UIMouseEventArgs& args);
virtual bool OnMouseMove(const UIMouseEventArgs& args);
virtual bool OnMouseClick(const UIMouseEventArgs& args);
virtual bool OnMouseButtonDown(const UIMouseButtonEventArgs& args);
virtual bool OnMouseButtonUp(const UIMouseButtonEventArgs& args);
virtual bool OnMouseButtonPressing(const UIMouseButtonEventArgs& args);
virtual bool OnMouseWheel(const UIMouseWheelEventArgs& args);
virtual bool OnGamePadButtonDown(const UIGamePadEventArgs& args);
virtual bool OnGamePadButtonUp(const UIGamePadEventArgs& args);
virtual bool OnGamePadButtonPressing(const UIGamePadEventArgs& args);
virtual bool OnGamePadTrigger(const UIGamePadEventArgs& args);
virtual bool OnGamePadThumbstick(const UIGamePadEventArgs& args);
private:
void SetParent(UIPanel* value);
void RaiseKeyDownEvent(const UIKeyboardEventArgs& args);
void RaiseKeyUpEvent(const UIKeyboardEventArgs& args);
void RaiseKeyPressingEvent(const UIKeyboardEventArgs& args);
void RaiseMouseEnterEvent(const UIMouseEventArgs& args);
void RaiseMouseLeaveEvent(const UIMouseEventArgs& args);
void RaiseMouseMoveEvent(const UIMouseEventArgs& args);
void RaiseMouseClickEvent(const UIMouseEventArgs& args);
void RaiseMouseButtonDownEvent(const UIMouseButtonEventArgs& args);
void RaiseMouseButtonUpEvent(const UIMouseButtonEventArgs& args);
void RaiseMouseButtonPressingEvent(const UIMouseButtonEventArgs& args);
void RaiseMouseWheelEvent(const UIMouseWheelEventArgs& args);
void RaiseGamePadButtonDownEvent(const UIGamePadEventArgs& args);
void RaiseGamePadButtonUpEvent(const UIGamePadEventArgs& args);
void RaiseGamePadButtonPressingEvent(const UIGamePadEventArgs& args);
void RaiseGamePadTriggerEvent(const UIGamePadEventArgs& args);
void RaiseGamePadThumbstickEvent(const UIGamePadEventArgs& args);
private:
float opacity;
Vector2 size;
bool shown;
UIFramePtr frame;
UITransformPtr transform;
UIEventMapPtr eventMap;
UIPanel* parent;
friend class UIDrawingContext;
friend class UIPickingContext;
friend class UIKeyboardEventDispatcher;
friend class UIMouseEventDispatcher;
friend class UIGamdPadEventDispatcher;
friend class UITouchEventDispatcher;
friend class UIPanel;
friend void __Startup__();
static void __Startup__();
};
}
# include <Halak/UIVisual.inl>
#endif | [
"[email protected]"
] | [
[
[
1,
118
]
]
] |
bb2d61478a030382cf5d016e0ce7fa29a6253981 | 8270eedb9660f6257229db97f767b91d7054b568 | /usaco_oct09/sinavcan/heatwv.cpp | b91b01c2b5c8c8dd9746a55b17dba3f30b75cf48 | [] | no_license | kuzux/olimpcan | 979201e982e15741248b5d0574a7f4ffdb14c7f2 | 947cb5f5dab6c78cbee2d6fa12b081817b684d37 | refs/heads/master | 2016-09-05T13:19:25.681613 | 2009-12-19T12:51:10 | 2009-12-19T12:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,237 | cpp | /*
PROG: heatwv
LANG: C++
ID: kuzux921
*/
#include <fstream>
#include <climits>
using namespace std;
int N, C;
int **mat;
int dist[2500];
bool visited[2500];
void shortest(int start, int dest){
for(int i=0;i<N;i++) dist[i] = INT_MAX;
dist[start] = 0;
for(int i=0;i<N;i++){
int selected, mindist = INT_MAX;
for(int j=0;j<N;j++){
if(visited[j]) continue;
if(dist[j]<mindist){
mindist = dist[j];
selected = j;
}
}
if(selected==dest) return;
visited[selected] = true;
for(int j=0;j<N;j++){
if(mat[selected][j]){
if(dist[selected]+mat[selected][j]<dist[j])
dist[j] = dist[selected]+mat[selected][j];
}
}
}
}
int main(){
ifstream in("heatwv.in");
ofstream out("heatwv.out");
int start, end;
in >> N >> C >> start >> end;
mat = new int*[N];
for(int i=0;i<N;i++) mat[i] = new int[N];
start--; end--;
for(int i=0;i<C;i++){
int b, e, l; in >> b >> e >> l;
b--;e--;
if(mat[b][e]){
if(l<mat[b][e]) mat[b][e] = mat[e][b] = l;
}
else mat[b][e] = mat[e][b] = l;
}
shortest(start, end);
out << dist[end] << endl;
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
63
]
]
] |
1a12aa13f0abf045404eeb2049ca402765e34a6b | 555ce7f1e44349316e240485dca6f7cd4496ea9c | /DirectShowFilters/StreamingServer/Source/CriticalSection.h | 66443f87925731c3f7f8f491cead08bed4655e8d | [] | no_license | Yura80/MediaPortal-1 | c71ce5abf68c70852d261bed300302718ae2e0f3 | 5aae402f5aa19c9c3091c6d4442b457916a89053 | refs/heads/master | 2021-04-15T09:01:37.267793 | 2011-11-25T20:02:53 | 2011-11-25T20:11:02 | 2,851,405 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,068 | h | // CriticalSection.h: interface for the CCriticalSection class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CRITICALSECTION_H__3B3A15BD_92D5_4044_8D69_5E1B8F15F369__INCLUDED_)
#define AFX_CRITICALSECTION_H__3B3A15BD_92D5_4044_8D69_5E1B8F15F369__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef _WINDOWS_
#include <Windows.h>
#endif /* _WINDOWS_ */
namespace Mediaportal
{
// Wrapper for critical section struct
class CCriticalSection
{
public:
// Constructor
// Initializes the critical section struct
CCriticalSection();
// Destructor
virtual ~CCriticalSection();
// Conversion operator
operator LPCRITICAL_SECTION();
private:
// Copy constructor is disabled
CCriticalSection(const CCriticalSection& src);
// operator= is disabled
CCriticalSection& operator=(const CCriticalSection& src);
CRITICAL_SECTION m_cs;
};
}
#endif // !defined(AFX_CRITICALSECTION_H__3B3A15BD_92D5_4044_8D69_5E1B8F15F369__INCLUDED_)
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
18
],
[
40,
42
]
],
[
[
19,
39
]
]
] |
7f2d07e6762e69cfa9a9836fbbadd0b4bf47096e | bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed | /kguithread.h | ccefdf79bf604af8fff9f57ad6a97f6ba1dc3809 | [] | no_license | cnsuhao/kgui-1 | d0a7d1e11cc5c15d098114051fabf6218f26fb96 | ea304953c7f5579487769258b55f34a1c680e3ed | refs/heads/master | 2021-05-28T22:52:18.733717 | 2011-03-10T03:10:47 | 2011-03-10T03:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,573 | h | #ifndef __KGUITHREAD__
#define __KGUITHREAD__
#if defined(LINUX) || defined(MACINTOSH)
#include <pthread.h>
#include <signal.h>
#elif defined(MINGW)
#include <Wincon.h>
#elif defined(WIN32)
#else
#error
#endif
class kGUIThread
{
public:
kGUIThread() {m_active=false;}
void Start(void *codeobj,void (*code)(void *));
void Close(bool now);
volatile bool GetActive(void) {return m_active;}
private:
volatile bool m_active;
#if defined(LINUX) || defined(MACINTOSH)
pthread_t m_thread;
#elif defined(WIN32) || defined(MINGW)
HANDLE m_thread; /* only used for async */
#else
#error
#endif
};
/* call a program and send input or grab it's output */
enum
{
CALLTHREAD_READ,
CALLTHREAD_WRITE
};
#define CALLTHREADUSEFORK 1
class kGUICallThread
{
public:
kGUICallThread();
~kGUICallThread();
void SetUpdateCallback(void *codeobj,void (*code)(void *)) {m_updatecallback.Set(codeobj,code);}
bool Start(const char *line,int mode);
void Stop(void);
void SetString(kGUIString *s) {m_string.SetString(s);}
kGUIString *GetString(void) {return &m_string;}
volatile bool GetActive(void) {return m_active;}
private:
kGUICallBack m_updatecallback;
kGUIString m_string;
#if defined(LINUX) || defined(MACINTOSH)
FILE *m_handle;
#if CALLTHREADUSEFORK
long m_tid;
int m_p[2];
kGUIString m_sl;
kGUIStringSplit m_ss;
char **m_args;
#endif
#elif defined(WIN32) || defined(MINGW)
PROCESS_INFORMATION m_pi;
#else
#error
#endif
volatile bool m_active:1;
volatile bool m_closing:1;
};
#endif
| [
"[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d"
] | [
[
[
1,
76
]
]
] |
e2a3cc4bd82a635063b465ef1dfb6c735d597f9e | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /TEST_MyGUI_Source/MyGUIEngine/include/MyGUI_EditFactory.h | fad8b8896b9b7d9709d4a363d278d93b7dc22905 | [] | no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23T16:40:19.477150 | 2008-03-06T22:19:12 | 2008-03-06T22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,326 | h | /*!
@file
@author Albert Semenov
@date 11/2007
@module
*/
#ifndef __MYGUI_EDIT_FACTORY_H__
#define __MYGUI_EDIT_FACTORY_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_WidgetFactoryInterface.h"
#include "MyGUI_WidgetDefines.h"
namespace MyGUI
{
namespace factory
{
class _MyGUIExport EditFactory : public WidgetFactoryInterface
{
public:
EditFactory();
~EditFactory();
// реализация интерфейса фабрики
const Ogre::String& getType();
WidgetPtr createWidget(const Ogre::String& _skin, const IntCoord& _coord, Align _align, CroppedRectanglePtr _parent, WidgetCreator * _creator, const Ogre::String& _name);
// методы для парсинга
void Edit_CursorPosition(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value);
void Edit_TextSelect(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value);
void Edit_ReadOnly(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value);
void Edit_Password(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value);
void Edit_MultiLine(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value);
};
} // namespace factory
} // namespace MyGUI
#endif // __MYGUI_EDIT_FACTORY_H__
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
c19c22ece8492df88ea12d7bf13c0c2b7c712507 | 7476d2c710c9a48373ce77f8e0113cb6fcc4c93b | /vaultmp.cpp | 758f75c1d954ff6bd01cd9cab44a01ba0f8acf09 | [] | no_license | CmaThomas/Vault-Tec-Multiplayer-Mod | af23777ef39237df28545ee82aa852d687c75bc9 | 5c1294dad16edd00f796635edaf5348227c33933 | refs/heads/master | 2021-01-16T21:13:29.029937 | 2011-10-30T21:58:41 | 2011-10-30T22:00:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,169 | cpp | #include <windows.h>
#include <shlwapi.h>
#include <shlobj.h>
#include <commctrl.h>
#include <map>
#include "vaultmp.h"
#include "Bethesda.h"
#include "ServerEntry.h"
#include "Data.h"
#include "VaultException.h"
#include "ufmod.h"
#include "iniparser/dictionary.c"
#include "iniparser/iniparser.c"
#include "RakNet/RakPeerInterface.h"
#include "RakNet/PacketizedTCP.h"
#include "RakNet/MessageIdentifiers.h"
#include "RakNet/FileListTransfer.h"
#include "RakNet/FileListTransferCBInterface.h"
#include "RakNet/BitStream.h"
#include "RakNet/RakString.h"
#include "RakNet/RakSleep.h"
#include "RakNet/GetTime.h"
#define MSG_MINTRAYICON (WM_USER + 1)
#define WND_CLASS_NAME "vaultmp"
#define RAKNET_CONNECTIONS 2
#define RAKNET_MASTER_ADDRESS "127.0.0.1"
#define RAKNET_MASTER_PORT 1660
#define IDC_GROUP0 2000
#define IDC_GROUP1 2001
#define IDC_GROUP2 2002
#define IDC_STATIC0 2003
#define IDC_STATIC1 2004
#define IDC_STATIC2 2005
#define IDC_STATIC3 2006
#define IDC_STATIC4 2007
#define IDC_GRID0 2008
#define IDC_GRID1 2009
#define IDC_CHECK0 2010
#define IDC_BUTTON0 2011
#define IDC_BUTTON1 2012
#define IDC_BUTTON2 2013
#define IDC_BUTTON3 2014
#define IDC_BUTTON4 2015
#define IDC_EDIT0 2016
#define IDC_EDIT1 2017
#define IDC_EDIT3 2018
#define IDC_PROGRESS0 2019
#define CHIPTUNE 3000
#define ICON_MAIN 4000
#define POWERED 5000
using namespace RakNet;
using namespace Data;
using namespace std;
HINSTANCE instance;
HANDLE mutex;
HFONT hFont;
HWND wndmain;
HWND wndsortcur;
HWND wndchiptune;
HWND wndlistview;
HWND wndlistview2;
HWND wndprogressbar;
HWND wndsync;
HDC hdc, hdcMem;
HBITMAP hBitmap;
BITMAP bitmap;
PAINTSTRUCT ps;
BOOL sort_flag;
RakPeerInterface* peer;
SocketDescriptor* sockdescr;
typedef map<SystemAddress, ServerEntry> ServerMap;
ServerMap serverList;
SystemAddress* selectedServer = NULL;
dictionary* config = NULL;
char* player_name;
char* server_name;
unsigned char games;
HWND CreateMainWindow();
int RegisterClasses();
int MessageLoop();
void InitRakNet();
void CreateWindowContent( HWND parent );
void CleanUp();
LRESULT CALLBACK WindowProcedure( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam );
FileListTransfer* flt;
PacketizedTCP* tcp;
ServerEntry* buf;
void seDebugPrivilege()
{
TOKEN_PRIVILEGES priv;
HANDLE hThis, hToken;
LUID luid;
hThis = GetCurrentProcess();
OpenProcessToken( hThis, TOKEN_ADJUST_PRIVILEGES, &hToken );
LookupPrivilegeValue( 0, "seDebugPrivilege", &luid );
priv.PrivilegeCount = 1;
priv.Privileges[0].Luid = luid;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges( hToken, false, &priv, 0, 0, 0 );
CloseHandle( hToken );
CloseHandle( hThis );
}
void MinimizeToTray( HWND hwnd )
{
NOTIFYICONDATA nid = {0};
ZeroMemory( &nid, sizeof( NOTIFYICONDATA ) );
nid.cbSize = sizeof( NOTIFYICONDATA );
nid.hWnd = hwnd;
nid.uID = ICON_MAIN;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uCallbackMessage = MSG_MINTRAYICON;
nid.hIcon = ( HICON ) LoadImage( GetModuleHandle( NULL ), MAKEINTRESOURCE( ICON_MAIN ), IMAGE_ICON, 16, 16, 0 );
strcpy( nid.szTip, "Vault-Tec Multiplayer Mod" );
Shell_NotifyIcon( NIM_ADD, &nid );
ShowWindow( hwnd, SW_HIDE );
}
void Maximize( HWND hwnd )
{
NOTIFYICONDATA nid = {0};
ZeroMemory( &nid, sizeof( NOTIFYICONDATA ) );
nid.cbSize = sizeof( NOTIFYICONDATA );
nid.hWnd = hwnd;
nid.uID = ICON_MAIN;
Shell_NotifyIcon( NIM_DELETE, &nid );
ShowWindow( hwnd, SW_RESTORE );
SetForegroundWindow( hwnd );
}
class FileServer : public FileListTransferCBInterface
{
public:
bool OnFile( OnFileStruct* onFileStruct )
{
char wndtitle[256];
snprintf( wndtitle, sizeof( wndtitle ), "(100%%) %i/%i %s %i bytes / %i bytes\n",
onFileStruct->fileIndex + 1,
onFileStruct->numberOfFilesInThisSet,
onFileStruct->fileName,
onFileStruct->byteLengthOfThisFile,
onFileStruct->byteLengthOfThisSet );
SetWindowText( wndmain, wndtitle );
TCHAR file[MAX_PATH];
ZeroMemory( file, sizeof( file ) );
switch ( onFileStruct->context.op )
{
case FILE_SAVEGAME:
{
ZeroMemory( file, sizeof( file ) );
SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, 0, file ); // SHGFP_TYPE_CURRENT
switch ( buf->GetGame() )
{
case FALLOUT3:
strcat( file, "\\My Games\\Fallout3\\Saves\\" );
break;
case NEWVEGAS:
strcat( file, "\\My Games\\FalloutNV\\Saves\\" );
break;
case OBLIVION:
strcat( file, "\\My Games\\Oblivion\\Saves\\" );
break;
}
strcat( file, Utils::FileOnly( onFileStruct->fileName ) );
break;
}
case FILE_MODFILE:
{
GetModuleFileName( GetModuleHandle( NULL ), ( LPTSTR ) file, MAX_PATH );
PathRemoveFileSpec( file );
strcat( file, "\\Data\\" );
strcat( file, Utils::FileOnly( onFileStruct->fileName ) );
break;
}
}
FILE* fp = fopen( file, "rb" );
if ( fp != NULL )
{
fclose( fp );
char msg[256];
snprintf( msg, sizeof( msg ), "%s\n\nalready exists. Do you want to overwrite it?", file );
int result = MessageBox( NULL, msg, "Attention", MB_YESNO | MB_ICONWARNING | MB_TOPMOST | MB_TASKMODAL );
if ( result == IDNO )
{
return true;
}
}
fp = fopen( file, "wb" );
fwrite( onFileStruct->fileData, onFileStruct->byteLengthOfThisFile, 1, fp );
fclose( fp );
return true;
}
virtual void OnFileProgress( FileProgressStruct *fps )
{
char wndtitle[256];
snprintf( wndtitle, sizeof( wndtitle ), "(%i%%) %i/%i %s %i bytes / %i bytes\n",
( int ) ( 100.0 * ( double ) fps->partCount / ( double ) fps->partTotal ),
fps->onFileStruct->fileIndex + 1,
fps->onFileStruct->numberOfFilesInThisSet,
fps->onFileStruct->fileName,
fps->onFileStruct->byteLengthOfThisFile,
fps->onFileStruct->byteLengthOfThisSet,
fps->firstDataChunk );
SetWindowText( wndmain, wndtitle );
}
virtual bool OnDownloadComplete( DownloadCompleteStruct* dcs )
{
char wndtitle[sizeof( CLIENT_VERSION ) + 64];
snprintf( wndtitle, sizeof( wndtitle ), "Vault-Tec Multiplayer Mod %s (FOR TESTING PURPOSES ONLY)", CLIENT_VERSION );
SetWindowText( wndmain, wndtitle );
buf = NULL;
return false;
}
} transferCallback;
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdline, int show )
{
#ifdef VAULTMP_DEBUG
if ( LoadLibrary( "exchndl.dll" ) == NULL )
return MessageBox( NULL, "Could not find exchndl.dll!", "Error", MB_OK | MB_ICONERROR );
#endif
mutex = CreateMutex( NULL, TRUE, "vaultmp" );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
return MessageBox( NULL, "Vault-Tec Multiplayer Mod is already running!", "Error", MB_OK | MB_ICONERROR );
FILE* filecheck = NULL;
DWORD checksum, checksum_real;
filecheck = fopen( "Fallout3.exe", "rb" );
if ( filecheck != NULL )
{
fclose( filecheck );
Utils::GenerateChecksum( "Fallout3.exe", checksum, checksum_real );
if ( checksum == FALLOUT3_EN_VER17 /*|| checksum == FALLOUT3_EN_VER17_STEAM*/ )
{
filecheck = fopen( "fose_1_7.dll", "rb" );
if ( filecheck != NULL )
{
fclose( filecheck );
Utils::GenerateChecksum( "fose_1_7.dll", checksum, checksum_real );
if ( checksum_real == FOSE_VER0122 )
{
filecheck = fopen( "xlive.dll", "rb" );
if ( filecheck != NULL )
{
fclose( filecheck );
Utils::GenerateChecksum( "xlive.dll", checksum, checksum_real );
if ( checksum_real == XLIVE_PATCH )
{
games |= FALLOUT3;
}
else
return MessageBox( NULL, "xlive.dll is unpatched!", "Error", MB_OK | MB_ICONERROR );
}
else
return MessageBox( NULL, "xlive.dll is missing!", "Error", MB_OK | MB_ICONERROR );
}
else
return MessageBox( NULL, "Your FOSE version is probably outdated!\nhttp://fose.silverlock.org/", "Error", MB_OK | MB_ICONERROR );
}
else
return MessageBox( NULL, "Could not find FOSE!\nhttp://fose.silverlock.org/", "Error", MB_OK | MB_ICONERROR );
}
else
return MessageBox( NULL, "Your version of Fallout 3 is not supported!", "Error", MB_OK | MB_ICONERROR );
}
filecheck = fopen( "FalloutNV.exe", "rb" );
if ( filecheck != NULL )
{
fclose( filecheck );
Utils::GenerateChecksum( "FalloutNV.exe", checksum, checksum_real );
if ( checksum == NEWVEGAS_EN_VER14_STEAM )
{
filecheck = fopen( "nvse_1_1.dll", "rb" );
if ( filecheck != NULL )
{
fclose( filecheck );
Utils::GenerateChecksum( "nvse_1_1.dll", checksum, checksum_real );
if ( checksum_real == NVSE_VER0209 )
{
games |= NEWVEGAS;
}
else
return MessageBox( NULL, "Your NVSE version is probably outdated!\nhttp://nvse.silverlock.org/", "Error", MB_OK | MB_ICONERROR );
}
else
return MessageBox( NULL, "Could not find NVSE!\nhttp://nvse.silverlock.org/", "Error", MB_OK | MB_ICONERROR );
}
else
return MessageBox( NULL, "Your version of Fallout: New Vegas is not supported!", "Error", MB_OK | MB_ICONERROR );
}
filecheck = fopen( "Oblivion.exe", "rb" );
if ( filecheck != NULL )
{
fclose( filecheck );
Utils::GenerateChecksum( "Oblivion.exe", checksum, checksum_real );
if ( checksum == OBLIVION_EN_VER120416 || checksum == OBLIVION_EN_VER120416_STEAM )
{
filecheck = fopen( "obse_1_2_416.dll", "rb" );
if ( filecheck != NULL )
{
fclose( filecheck );
Utils::GenerateChecksum( "obse_1_2_416.dll", checksum, checksum_real );
if ( checksum_real == OBSE_VER0020 )
{
games |= OBLIVION;
}
else
return MessageBox( NULL, "Your OBSE version is probably outdated!\nhttp://obse.silverlock.org/", "Error", MB_OK | MB_ICONERROR );
}
else
return MessageBox( NULL, "Could not find OBSE!\nhttp://obse.silverlock.org/", "Error", MB_OK | MB_ICONERROR );
}
else
return MessageBox( NULL, "Your version of TES: Oblivion is not supported!", "Error", MB_OK | MB_ICONERROR );
}
if ( !games )
return MessageBox( NULL, "Could not find either Fallout 3, Fallout: New Vegas or TES: Oblivion!", "Error", MB_OK | MB_ICONERROR );
filecheck = fopen( "vaultmp.dll", "rb" );
if ( filecheck != NULL )
{
fclose( filecheck );
Utils::GenerateChecksum( "vaultmp.dll", checksum, checksum_real );
/*if (checksum_real != VAULTMP_DLL)
return MessageBox(NULL, "vaultmp.dll is not up to date!", "Error", MB_OK | MB_ICONERROR);*/
}
else
return MessageBox( NULL, "Could not find vaultmp.dll!", "Error", MB_OK | MB_ICONERROR );
instance = hInstance;
seDebugPrivilege();
InitCommonControls();
RegisterClasses();
InitRakNet();
config = iniparser_load( ( char* ) "vaultmp.ini" );
player_name = iniparser_getstring( config, ( char* ) "general:name", ( char* ) "" );
server_name = iniparser_getstring( config, ( char* ) "general:master", ( char* ) "" );
char* servers = iniparser_getstring( config, ( char* ) "general:servers", ( char* ) "" );
char* token;
token = strtok( servers, "," );
while ( token != NULL )
{
SystemAddress addr;
char* port;
if ( port = strchr( token, ':' ) )
{
*port = '\0';
addr.SetPort( atoi( port + 1 ) );
}
addr.SetBinaryAddress( token );
ServerEntry entry( addr.ToString( true ), "", pair<int, int>( 0, 0 ), USHRT_MAX, 0 );
serverList.insert( pair<SystemAddress, ServerEntry>( addr, entry ) );
token = strtok( NULL, "," );
}
hFont = CreateFont( -11, 0, 0, 0, FW_NORMAL, 0, 0, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Verdana" );
wndmain = CreateMainWindow();
return MessageLoop();
}
HWND CreateMainWindow()
{
HWND wnd;
char wndtitle[sizeof( CLIENT_VERSION ) + 64];
snprintf( wndtitle, sizeof( wndtitle ), "Vault-Tec Multiplayer Mod %s (FOR TESTING PURPOSES ONLY)", CLIENT_VERSION );
wnd = CreateWindowEx( 0, WND_CLASS_NAME, wndtitle, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, ( GetSystemMetrics( SM_CXSCREEN ) / 2 ) - 392, ( GetSystemMetrics( SM_CYSCREEN ) / 2 ) - 221, 785, 442, HWND_DESKTOP, NULL, instance, NULL );
ShowWindow( wnd, SW_SHOWNORMAL );
UpdateWindow( wnd );
return wnd;
}
void InitRakNet()
{
tcp = PacketizedTCP::GetInstance();
flt = FileListTransfer::GetInstance();
sockdescr = new SocketDescriptor();
tcp->Start( RAKNET_FILE_SERVER, 1 );
tcp->AttachPlugin( flt );
peer = RakPeerInterface::GetInstance();
peer->Startup( RAKNET_CONNECTIONS, sockdescr, 1, THREAD_PRIORITY_NORMAL );
}
void CreateWindowContent( HWND parent )
{
HWND wnd;
LV_COLUMN col;
sort_flag = true;
col.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
col.fmt = LVCFMT_LEFT;
wnd = CreateWindowEx( 0x00000000, "Button", "Server details", 0x50020007, 543, 0, 229, 214, parent, ( HMENU ) IDC_GROUP0, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Button", "Vault-Tec Multiplayer Controls", 0x50020007, 543, 218, 229, 190, parent, ( HMENU ) IDC_GROUP1, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000200, "SysListView32", "", 0x50010005 | LVS_SINGLESEL | LVS_SHOWSELALWAYS, 6, 6, 531, 285, parent, ( HMENU ) IDC_GRID0, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
SendMessage( wnd, ( LVM_FIRST + 54 ), 0, 64 | 32 );
wndlistview = wnd;
col.cx = 299;
col.pszText = ( char* ) "Name";
col.iSubItem = 0;
SendMessage( wnd, LVM_INSERTCOLUMN, 0, ( LPARAM ) &col );
col.cx = 62;
col.pszText = ( char* ) "Players";
col.iSubItem = 1;
SendMessage( wnd, LVM_INSERTCOLUMN, 1, ( LPARAM ) &col );
col.cx = 50;
col.pszText = ( char* ) "Ping";
col.iSubItem = 2;
SendMessage( wnd, LVM_INSERTCOLUMN, 2, ( LPARAM ) &col );
col.cx = 116;
col.pszText = ( char* ) "Map";
col.iSubItem = 3;
SendMessage( wnd, LVM_INSERTCOLUMN, 3, ( LPARAM ) &col );
wnd = CreateWindowEx( 0x00000200, "SysListView32", "", 0x50010001, 553, 19, 210, 157, parent, ( HMENU ) IDC_GRID1, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wndlistview2 = wnd;
col.cx = 103;
col.pszText = ( char* ) "Key";
col.iSubItem = 0;
SendMessage( wnd, LVM_INSERTCOLUMN, 0, ( LPARAM ) &col );
col.cx = 103;
col.pszText = ( char* ) "Value";
col.iSubItem = 1;
SendMessage( wnd, LVM_INSERTCOLUMN, 1, ( LPARAM ) &col );
wnd = CreateWindowEx( 0x00000000, "msctls_progress32", "", 0x50000000, 553, 184, 210, 16, parent, ( HMENU ) IDC_PROGRESS0, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wndprogressbar = wnd;
wnd = CreateWindowEx( 0x00000000, "Static", "Fallout / TES: Oblivion are trademarks of Bethesda Softworks LLC in the U.S. and/or", 0x5000030C, 12, 374, 531, 18, parent, ( HMENU ) IDC_STATIC0, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Static", "other countries. Vault-Tec Multiplayer Mod is not affliated with Bethesda Softworks LLC.", 0x50000300, 12, 392, 531, 18, parent, ( HMENU ) IDC_STATIC1, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Button", "Powered by", 0x50020007, 6, 294, 531, 78, parent, ( HMENU ) IDC_GROUP2, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Button", "mantronix - the wasteland", 0x50010003, 555, 374, 174, 32, parent, ( HMENU ) IDC_CHECK0, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wndchiptune = wnd;
wnd = CreateWindowEx( 0x00000000, "Button", "", WS_BORDER | WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_ICON, 730, 380, 34, 20, parent, ( HMENU ) IDC_BUTTON4, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
SendMessage( wnd, BM_SETIMAGE, IMAGE_ICON, ( LPARAM ) LoadIcon( instance, MAKEINTRESOURCE( ICON_MAIN ) ) );
wnd = CreateWindowEx( 0x00000000, "Button", "Join Server", WS_BORDER | WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 555, 239, 100, 25, parent, ( HMENU ) IDC_BUTTON0, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Button", "Update Server", WS_BORDER | WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 660, 239, 100, 25, parent, ( HMENU ) IDC_BUTTON1, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Button", "Master Query", WS_BORDER | WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 555, 272, 100, 25, parent, ( HMENU ) IDC_BUTTON2, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Button", "Synchronize", WS_BORDER | WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 660, 272, 100, 25, parent, ( HMENU ) IDC_BUTTON3, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wndsync = wnd;
wnd = CreateWindowEx( 0x00000200, "Edit", "vaultmp.com", 0x50010080, 611, 305, 146, 20, parent, ( HMENU ) IDC_EDIT3, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
SendMessage( wnd, EM_SETLIMITTEXT, ( WPARAM ) MAX_MASTER_SERVER, 0 );
wnd = CreateWindowEx( 0x00000200, "Edit", "", 0x50010080, 611, 331, 146, 20, parent, ( HMENU ) IDC_EDIT0, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
SendMessage( wnd, EM_SETLIMITTEXT, ( WPARAM ) MAX_PLAYER_NAME, 0 );
wnd = CreateWindowEx( 0x00000200, "Edit", "", 0x500100A0, 611, 357, 146, 20, parent, ( HMENU ) IDC_EDIT1, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
SendMessage( wnd, EM_SETLIMITTEXT, ( WPARAM ) MAX_PASSWORD_SIZE, 0 );
wnd = CreateWindowEx( 0x00000000, "Static", "Master", 0x50000300, 570, 302, 38, 24, parent, ( HMENU ) IDC_STATIC4, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Static", "Name", 0x50000300, 575, 328, 35, 24, parent, ( HMENU ) IDC_STATIC2, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
wnd = CreateWindowEx( 0x00000000, "Static", "Password", 0x50000300, 554, 354, 57, 24, parent, ( HMENU ) IDC_STATIC3, instance, NULL );
SendMessage( wnd, WM_SETFONT, ( WPARAM ) hFont, TRUE );
}
int RegisterClasses()
{
WNDCLASSEX wc;
wc.hInstance = instance;
wc.lpszClassName = WND_CLASS_NAME;
wc.lpfnWndProc = WindowProcedure;
wc.style = CS_DBLCLKS;
wc.cbSize = sizeof( WNDCLASSEX );
wc.hIcon = LoadIcon( instance, MAKEINTRESOURCE( ICON_MAIN ) );
wc.hIconSm = LoadIcon( instance, MAKEINTRESOURCE( ICON_MAIN ) );
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.lpszMenuName = NULL;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = ( HBRUSH )( COLOR_3DFACE + 1 );
return RegisterClassEx( &wc );
}
int MessageLoop()
{
MSG msg;
while ( GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
CleanUp();
return msg.wParam;
}
void CleanUp()
{
DeleteObject( hFont );
DeleteObject( hBitmap );
tcp->DetachPlugin( flt );
FileListTransfer::DestroyInstance( flt );
PacketizedTCP::DestroyInstance( tcp );
peer->Shutdown( 300 );
RakPeerInterface::DestroyInstance( peer );
iniparser_freedict( config );
CloseHandle( mutex );
}
int Create2ColItem( HWND hwndList, char* text1, char* text2 )
{
LVITEM lvi = {0};
int ret;
lvi.mask = LVIF_TEXT;
lvi.pszText = text1;
ret = ListView_InsertItem( hwndList, &lvi );
if ( ret >= 0 )
ListView_SetItemText( hwndList, ret, 1, text2 );
return ret;
}
int Create4ColItem( HWND hwndList, const SystemAddress* addr, char* text1, char* text2, char* text3, char* text4 )
{
LVITEM lvi = {0};
int ret;
lvi.mask = LVIF_TEXT | LVIF_PARAM;
lvi.pszText = text1;
lvi.lParam = ( LPARAM ) addr;
ret = ListView_InsertItem( hwndList, &lvi );
if ( ret >= 0 )
{
ListView_SetItemText( hwndList, ret, 1, text2 );
ListView_SetItemText( hwndList, ret, 2, text3 );
ListView_SetItemText( hwndList, ret, 3, text4 );
}
return ret;
}
void RefreshServerList()
{
SendMessage( wndlistview, LVM_DELETEALLITEMS, 0, 0 );
SendMessage( wndlistview2, LVM_DELETEALLITEMS, 0, 0 );
selectedServer = NULL;
for ( map<SystemAddress, ServerEntry>::iterator i = serverList.begin(); i != serverList.end(); ++i )
{
const SystemAddress* addr = &i->first;
ServerEntry entry = i->second;
char players[16];
char ping[16];
snprintf( players, sizeof( players ), "%d / %d", entry.GetServerPlayers().first, entry.GetServerPlayers().second );
snprintf( ping, sizeof( ping ), "%d", entry.GetServerPing() );
Create4ColItem( wndlistview, addr, ( char* ) entry.GetServerName().c_str(), players, ping, ( char* ) entry.GetServerMap().c_str() );
}
}
int CALLBACK CompareProc( LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort )
{
static char buf[64], buf2[64];
ListView_GetItemText( wndsortcur, lParam1, lParamSort, buf, sizeof( buf ) );
ListView_GetItemText( wndsortcur, lParam2, lParamSort, buf2, sizeof( buf2 ) );
if ( sort_flag )
return ( stricmp( buf, buf2 ) );
else
return ( stricmp( buf, buf2 ) * -1 );
}
LRESULT CALLBACK WindowProcedure( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam )
{
bool update = false;
switch ( message )
{
case WM_CREATE:
CreateWindowContent( hwnd );
RefreshServerList();
hBitmap = LoadBitmap( GetModuleHandle( NULL ), MAKEINTRESOURCE( POWERED ) );
GetObject( hBitmap, sizeof( BITMAP ), &bitmap );
if ( strlen( player_name ) > 0 ) SetDlgItemText( hwnd, IDC_EDIT0, player_name );
if ( strlen( server_name ) > 0 ) SetDlgItemText( hwnd, IDC_EDIT3, server_name );
break;
case WM_PAINT:
hdc = BeginPaint( hwnd, &ps );
hdcMem = CreateCompatibleDC( hdc );
SelectObject( hdcMem, hBitmap );
BitBlt( hdc, 13, 310, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY );
DeleteDC( hdcMem );
EndPaint( hwnd, &ps );
break;
case WM_SIZE:
if ( wParam == SIZE_MINIMIZED )
MinimizeToTray( hwnd );
break;
case WM_COMMAND:
switch ( wParam )
{
case IDC_BUTTON0:
if ( peer->NumberOfConnections() == 0 )
{
if ( selectedServer != NULL )
{
SystemAddress addr = *selectedServer;
char name[MAX_PLAYER_NAME], pwd[MAX_PASSWORD_SIZE];
GetDlgItemText( hwnd, IDC_EDIT0, name, sizeof( name ) );
GetDlgItemText( hwnd, IDC_EDIT1, pwd, sizeof( pwd ) );
if ( strlen( name ) < 3 )
{
MessageBox( NULL, "Please sepcify a player name of at least 3 characters.", "Error", MB_OK | MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL );
break;
}
map<SystemAddress, ServerEntry>::iterator i;
i = serverList.find( *selectedServer );
unsigned char game = ( &i->second )->GetGame();
if ( ( games & game ) != game || !game )
{
switch ( game )
{
case FALLOUT3:
MessageBox( NULL, "Could not find Fallout3.exe!", "Error", MB_OK | MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL );
break;
case NEWVEGAS:
MessageBox( NULL, "Could not find FalloutNV.exe!", "Error", MB_OK | MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL );
break;
case OBLIVION:
MessageBox( NULL, "Could not find Oblivion.exe!", "Error", MB_OK | MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL );
break;
default:
break;
}
break;
}
MinimizeToTray( hwnd );
try
{
Bethesda::InitializeVaultMP( peer, addr, string( name ), string( pwd ), game );
}
catch ( std::exception& e )
{
try
{
VaultException& vaulterror = dynamic_cast<VaultException&>( e );
vaulterror.Message();
}
catch ( std::bad_cast& no_vaulterror )
{
VaultException vaulterror( e.what() );
vaulterror.Message();
}
}
#ifdef VAULTMP_DEBUG
VaultException::FinalizeDebug();
#endif
Maximize( hwnd );
selectedServer = NULL;
}
}
break;
case IDC_BUTTON1:
if ( selectedServer != NULL )
update = true;
else break;
case IDC_BUTTON2:
/* RakNet Master Query */
if ( peer->NumberOfConnections() == 0 )
{
if ( !update ) serverList.clear();
SystemAddress master;
char maddr[32];
GetDlgItemText( hwnd, IDC_EDIT3, maddr, sizeof( maddr ) );
if ( strcmp( maddr, "" ) == 0 )
{
SetDlgItemText( hwnd, IDC_EDIT3, ( char* ) RAKNET_MASTER_ADDRESS );
master.SetBinaryAddress( ( char* ) RAKNET_MASTER_ADDRESS );
master.SetPort( RAKNET_MASTER_PORT );
}
else
{
master.SetBinaryAddress( strtok( maddr, ":" ) );
char* cport = strtok( NULL, ":" );
master.SetPort( cport != NULL ? atoi( cport ) : RAKNET_MASTER_PORT );
}
if ( peer->Connect( master.ToString( false ), master.GetPort(), MASTER_VERSION, sizeof( MASTER_VERSION ), 0, 0, 3, 100, 0 ) == CONNECTION_ATTEMPT_STARTED )
{
bool query = true;
bool lock = false;
Packet* packet;
while ( query )
{
for ( packet = peer->Receive(); packet; peer->DeallocatePacket( packet ), packet = peer->Receive() )
{
switch ( packet->data[0] )
{
case ID_CONNECTION_REQUEST_ACCEPTED:
{
BitStream query;
if ( update )
{
query.Write( ( MessageID ) ID_MASTER_UPDATE );
SystemAddress addr = *selectedServer;
SystemAddress self = peer->GetExternalID( packet->systemAddress );
if ( strcmp( addr.ToString( false ), packet->systemAddress.ToString( false ) ) == 0 )
addr.SetBinaryAddress( "127.0.0.1" );
else if ( strcmp( addr.ToString( false ), "127.0.0.1" ) == 0 )
addr.SetBinaryAddress( self.ToString( false ) );
query.Write( addr );
}
else
query.Write( ( MessageID ) ID_MASTER_QUERY );
peer->Send( &query, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, false, 0 );
break;
}
case ID_MASTER_QUERY:
{
BitStream query( packet->data, packet->length, false );
query.IgnoreBytes( sizeof( MessageID ) );
unsigned int size;
query.Read( size );
SendMessage( wndprogressbar, PBM_SETPOS, 0, 0 );
SendMessage( wndprogressbar, PBM_SETRANGE, 0, MAKELONG( 0, size ) );
SendMessage( wndprogressbar, PBM_SETSTEP, 1, 0 );
for ( int i = 0; i < size; i++ )
{
SystemAddress addr;
RakString name, map;
int players, playersMax, rsize;
unsigned char game;
std::map<string, string> rules;
query.Read( addr );
query.Read( name );
query.Read( map );
query.Read( players );
query.Read( playersMax );
query.Read( game );
query.Read( rsize );
ServerEntry entry( name.C_String(), map.C_String(), pair<int, int>( players, playersMax ), USHRT_MAX, game );
for ( int j = 0; j < rsize; j++ )
{
RakString key, value;
query.Read( key );
query.Read( value );
entry.SetServerRule( key.C_String(), value.C_String() );
}
SystemAddress self = peer->GetExternalID( packet->systemAddress );
if ( strcmp( addr.ToString( false ), "127.0.0.1" ) == 0 )
addr.SetBinaryAddress( packet->systemAddress.ToString( false ) );
else if ( strcmp( addr.ToString( false ), self.ToString( false ) ) == 0 )
addr.SetBinaryAddress( "127.0.0.1" );
serverList.insert( pair<SystemAddress, ServerEntry>( addr, entry ) );
peer->Ping( addr.ToString( false ), addr.GetPort(), false );
SendMessage( wndprogressbar, PBM_STEPIT, 0, 0 );
}
peer->CloseConnection( packet->systemAddress, true, 0, LOW_PRIORITY );
query = false;
break;
}
case ID_MASTER_UPDATE:
{
BitStream query( packet->data, packet->length, false );
query.IgnoreBytes( sizeof( MessageID ) );
SystemAddress addr;
query.Read( addr );
SystemAddress self = peer->GetExternalID( packet->systemAddress );
if ( strcmp( addr.ToString( false ), "127.0.0.1" ) == 0 )
addr.SetBinaryAddress( packet->systemAddress.ToString( false ) );
else if ( strcmp( addr.ToString( false ), self.ToString( false ) ) == 0 )
addr.SetBinaryAddress( "127.0.0.1" );
std::map<SystemAddress, ServerEntry>::iterator i;
i = serverList.find( addr );
if ( query.GetNumberOfUnreadBits() > 0 )
{
RakString name, map;
int players, playersMax, rsize;
unsigned char game;
query.Read( name );
query.Read( map );
query.Read( players );
query.Read( playersMax );
query.Read( game );
query.Read( rsize );
ServerEntry* entry;
if ( i != serverList.end() )
{
entry = &i->second;
entry->SetServerName( name.C_String() );
entry->SetServerMap( map.C_String() );
entry->SetServerPlayers( pair<int, int>( players, playersMax ) );
entry->SetGame( game );
}
else
{
std::pair<std::map<SystemAddress, ServerEntry>::iterator, bool> k;
k = serverList.insert( pair<SystemAddress, ServerEntry>( addr, ServerEntry( name.C_String(), map.C_String(), pair<int, int>( players, playersMax ), USHRT_MAX, game ) ) );
entry = &( k.first )->second;
}
for ( int j = 0; j < rsize; j++ )
{
RakString key, value;
query.Read( key );
query.Read( value );
entry->SetServerRule( key.C_String(), value.C_String() );
}
peer->Ping( addr.ToString( false ), addr.GetPort(), false );
}
else if ( i != serverList.end() )
serverList.erase( i );
peer->CloseConnection( packet->systemAddress, true, 0, LOW_PRIORITY );
query = false;
break;
}
case ID_UNCONNECTED_PONG:
{
BitStream query( packet->data, packet->length, false );
query.IgnoreBytes( sizeof( MessageID ) );
TimeMS ping;
query.Read( ping );
map<SystemAddress, ServerEntry>::iterator i;
i = serverList.find( packet->systemAddress );
if ( i != serverList.end() )
{
ServerEntry* entry = &i->second;
entry->SetServerPing( GetTimeMS() - ping );
}
break;
}
case ID_NO_FREE_INCOMING_CONNECTIONS:
case ID_CONNECTION_ATTEMPT_FAILED:
{
if ( update && !lock )
{
peer->Connect( selectedServer->ToString( false ), selectedServer->GetPort(), DEDICATED_VERSION, sizeof( DEDICATED_VERSION ), 0, 0, 3, 500, 0 );
lock = true;
}
else
{
if ( update )
{
map<SystemAddress, ServerEntry>::iterator i;
i = serverList.find( *selectedServer );
if ( i != serverList.end() )
serverList.erase( *selectedServer );
}
query = false;
}
break;
}
case ID_INVALID_PASSWORD:
if ( update ) MessageBox( NULL, "MasterServer version mismatch.\nPlease download the most recent binaries from www.vaultmp.com", "Error", MB_OK | MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL );
else MessageBox( NULL, "Dedicated server version mismatch.\nPlease download the most recent binaries from www.vaultmp.com", "Error", MB_OK | MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL );
case ID_DISCONNECTION_NOTIFICATION:
case ID_CONNECTION_BANNED:
case ID_CONNECTION_LOST:
query = false;
break;
}
}
RakSleep( 2 );
}
}
}
update = false;
RefreshServerList();
break;
case IDC_BUTTON4:
MessageBox( NULL, CREDITS, "vaultmp credits", MB_OK | MB_ICONINFORMATION | MB_TOPMOST | MB_TASKMODAL );
break;
case IDC_BUTTON3:
{
/* RakNet File Transfer */
if ( selectedServer != NULL && serverList.find( *selectedServer )->second.GetGame() )
{
EnableWindow( wndsync, 0 );
int result = MessageBox( NULL, "This function downloads files (savegames, mods etc.) from the server. vaultmp has no control of which files get downloaded; this is up to the server configuration. Files will be placed in the \"Saves\" or \"Data\" folder of the appropiate game. Do NOT continue if you do not trust the server!", "Attention", MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST | MB_TASKMODAL );
if ( result == IDCANCEL )
{
EnableWindow( wndsync, 1 );
break;
}
SystemAddress server = *selectedServer;
buf = &serverList.find( *selectedServer )->second;
tcp->Connect( server.ToString( false ), server.GetPort(), false );
RakSleep( 500 );
server = tcp->HasCompletedConnectionAttempt();
if ( server == UNASSIGNED_SYSTEM_ADDRESS )
{
MessageBox( NULL, "Could not establish a connection to the fileserver. The server probably has file downloading disabled or its number of maximum parallel connections reached.", "Error", MB_OK | MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL );
EnableWindow( wndsync, 1 );
break;
}
char rdy[3];
rdy[0] = RAKNET_FILE_RDY;
*( ( unsigned short* ) ( rdy + 1 ) ) = flt->SetupReceive( &transferCallback, false, server );
tcp->Send( rdy, sizeof( rdy ), server, false );
Packet* packet;
while ( buf )
{
packet = tcp->Receive();
tcp->DeallocatePacket( packet );
RakSleep( 5 );
}
tcp->CloseConnection( server );
EnableWindow( wndsync, 1 );
MessageBox( NULL, "Successfully synchronized with the server!", "Success", MB_OK | MB_ICONINFORMATION | MB_TOPMOST | MB_TASKMODAL );
}
break;
}
case IDC_CHECK0:
if ( SendMessage( wndchiptune, BM_GETCHECK, 0, 0 ) )
uFMOD_PlaySong( MAKEINTRESOURCE( CHIPTUNE ), GetModuleHandle( NULL ), XM_RESOURCE );
else
uFMOD_StopSong();
break;
}
break;
case MSG_MINTRAYICON:
if ( wParam == ICON_MAIN && lParam == WM_LBUTTONUP )
Maximize( hwnd );
break;
case WM_NOTIFY:
switch ( ( ( LPNMHDR ) lParam )->code )
{
case ( LVN_FIRST - 14 ): // LVN_ITEMACTIVATE
{
HWND hwndFrom = ( HWND )( ( LPNMHDR ) lParam )->hwndFrom;
if ( hwndFrom == wndlistview )
{
LVITEM item;
item.mask = LVIF_PARAM;
item.iItem = ListView_GetNextItem( hwndFrom, -1, LVNI_SELECTED );
item.iSubItem = 0;
ListView_GetItem( hwndFrom, &item );
selectedServer = ( SystemAddress* ) item.lParam;
SendMessage( wndlistview2, LVM_DELETEALLITEMS, 0, 0 );
map<SystemAddress, ServerEntry>::iterator i;
i = serverList.find( *selectedServer );
if ( i != serverList.end() )
{
ServerEntry* entry = &i->second;
std::map<string, string> rules = entry->GetServerRules();
for ( map<string, string>::iterator k = rules.begin(); k != rules.end(); ++k )
{
string key = k->first;
string value = k->second;
char c_key[key.length()];
char c_value[value.length()];
strcpy( c_key, key.c_str() );
strcpy( c_value, value.c_str() );
Create2ColItem( wndlistview2, c_key, c_value );
}
}
}
break;
}
case LVN_COLUMNCLICK:
{
NMLISTVIEW* nmlv = ( NMLISTVIEW* ) lParam;
wndsortcur = ( HWND )( ( LPNMHDR ) lParam )->hwndFrom;
ListView_SortItemsEx( wndsortcur, CompareProc, nmlv->iSubItem );
sort_flag = !sort_flag;
break;
}
}
break;
case WM_DESTROY:
PostQuitMessage( 0 );
break;
default:
return DefWindowProc( hwnd, message, wParam, lParam );
}
return 0;
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
94
],
[
96,
96
],
[
98,
104
],
[
117,
118
],
[
120,
120
],
[
122,
122
],
[
131,
131
],
[
133,
133
],
[
135,
136
],
[
138,
138
],
[
148,
151
],
[
251,
253
],
[
255,
256
],
[
261,
262
],
[
443,
446
],
[
454,
457
],
[
465,
466
],
[
468,
468
],
[
472,
472
],
[
475,
475
],
[
478,
478
],
[
481,
481
],
[
486,
486
],
[
491,
491
],
[
496,
496
],
[
501,
501
],
[
506,
506
],
[
510,
510
],
[
515,
515
],
[
520,
520
],
[
524,
524
],
[
527,
527
],
[
530,
530
],
[
533,
533
],
[
537,
537
],
[
541,
541
],
[
544,
544
],
[
547,
547
],
[
550,
550
],
[
554,
554
],
[
558,
558
],
[
562,
562
],
[
566,
566
],
[
569,
569
],
[
572,
572
],
[
575,
578
],
[
596,
599
],
[
601,
601
],
[
607,
607
],
[
609,
609
],
[
611,
614
],
[
624,
625
],
[
627,
627
],
[
633,
633
],
[
636,
636
],
[
638,
639
],
[
641,
641
],
[
657,
660
],
[
677,
678
],
[
680,
680
],
[
685,
685
],
[
688,
688
],
[
691,
692
],
[
694,
694
],
[
795,
796
],
[
798,
799
],
[
1218,
1218
]
],
[
[
95,
95
],
[
97,
97
],
[
105,
116
],
[
119,
119
],
[
121,
121
],
[
123,
130
],
[
132,
132
],
[
134,
134
],
[
137,
137
],
[
139,
147
],
[
152,
250
],
[
254,
254
],
[
257,
260
],
[
263,
442
],
[
447,
453
],
[
458,
464
],
[
467,
467
],
[
469,
471
],
[
473,
474
],
[
476,
477
],
[
479,
480
],
[
482,
485
],
[
487,
490
],
[
492,
495
],
[
497,
500
],
[
502,
505
],
[
507,
509
],
[
511,
514
],
[
516,
519
],
[
521,
523
],
[
525,
526
],
[
528,
529
],
[
531,
532
],
[
534,
536
],
[
538,
540
],
[
542,
543
],
[
545,
546
],
[
548,
549
],
[
551,
553
],
[
555,
557
],
[
559,
561
],
[
563,
565
],
[
567,
568
],
[
570,
571
],
[
573,
574
],
[
579,
595
],
[
600,
600
],
[
602,
606
],
[
608,
608
],
[
610,
610
],
[
615,
623
],
[
626,
626
],
[
628,
632
],
[
634,
635
],
[
637,
637
],
[
640,
640
],
[
642,
656
],
[
661,
676
],
[
679,
679
],
[
681,
684
],
[
686,
687
],
[
689,
690
],
[
693,
693
],
[
695,
794
],
[
797,
797
],
[
800,
1217
]
]
] |
de20c01f58751a2325abe818c46dcafa961861ec | 6630a81baef8700f48314901e2d39141334a10b7 | /1.4/Testing/Cxx/swFrameworkDependent/GUI/swToolGuiObjectManager.h | fa670d2b142cdf2b2497bbbe548a997652f29c2d | [] | no_license | jralls/wxGuiTesting | a1c0bed0b0f5f541cc600a3821def561386e461e | 6b6e59e42cfe5b1ac9bca02fbc996148053c5699 | refs/heads/master | 2021-01-10T19:50:36.388929 | 2009-03-24T20:22:11 | 2009-03-26T18:51:24 | 623,722 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,457 | h | ///////////////////////////////////////////////////////////////////////////////
// Name: swFrameworkDependent/GUI/swToolGuiObjectManager.h
// Author: Reinhold Füreder
// Created: 2005
// Copyright: (c) 2005 Reinhold Füreder
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef SWTOOLGUIOBJECTMANAGER_H
#define SWTOOLGUIOBJECTMANAGER_H
#ifdef __GNUG__
#pragma interface "swToolGuiObjectManager.h"
#endif
#include "Common.h"
#include "swGuiObjectManager.h"
namespace sw {
class ToolGuiObject;
class ToolBar;
/*! \class ToolGuiObjectManager
\brief Extend standard GuiObjectManager with support for toolbars.
*/
class ToolGuiObjectManager : public GuiObjectManager
{
public:
/*! \fn ToolGuiObjectManager ()
\brief Constructor
*/
ToolGuiObjectManager ();
/*! \fn virtual ~ToolGuiObjectManager ()
\brief Destructor
*/
virtual ~ToolGuiObjectManager ();
/*! \fn GuiObject * UnregisterGuiObject (GuiObject *guiObject)
\brief Extends unregistering by removing tool if it is a ToolGuiObject.
\param guiObject GUI object to unregister
*/
GuiObject * UnregisterGuiObject (GuiObject *guiObject);
/*! \fn virtual void AddTool (ToolGuiObject &toolGuiObject, ToolBar &toolBar)
\brief Add GUI object to toolbar.
\param toolGuiObject GUI object to add to toolbar
\param toolBar toolBar where GUI object should be added
*/
virtual void AddTool (ToolGuiObject &toolGuiObject, ToolBar &toolBar);
/*! \fn virtual void UpdateStatus (GuiObject *guiObject)
\brief Update status of GUI objects GUI appearance WRT toggle state of tools.
\param guiObject whose status is changed
*/
virtual void UpdateStatus (GuiObject *guiObject);
protected:
/*! \fn virtual void UpdateGuiEnableStatus (GuiObject *guiObject, const bool enable)
\brief Enable/disable GUI status appearance of GUI object (toolbar).
\param guiObject GUI object to update status for
\param enable enable/disable status
*/
virtual void UpdateGuiEnableStatus (GuiObject *guiObject, const bool enable);
protected:
typedef std::map< ToolGuiObject *, ToolBar * > ToolList;
ToolList m_toolList;
private:
};
} // End namespace sw
#endif // SWTOOLGUIOBJECTMANAGER_H
| [
"john@64288482-8357-404e-ad65-de92a562ee98"
] | [
[
[
1,
87
]
]
] |
1a0c1096a1337683e98fbbd448bbd4b7df4e116d | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/src/MFileDBufReqIdxHandler.cpp | 4544672a74888da774147d0b238577db0f95f960 | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,489 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "MFileDBufReqIdxHandler.h"
#include "MultiFileDBufRequester.h"
#include "BitBuffer.h"
#include "TileMapUtil.h"
#ifndef USE_TRACE
#define USE_TRACE
#endif
#undef USE_TRACE
#ifdef USE_TRACE
#include "TraceMacros.h"
#endif
#define SET_STATE(s) setState(s, __LINE__)
using namespace std;
IndexMap::IndexMap( MemTracker* memTracker )
{
m_memTracker = memTracker;
m_indexBuf = NULL;
}
void
IndexMap::clear()
{
if ( m_indexBuf != NULL ) {
m_memTracker->releaseToPool( m_indexBuf->getBufferSize() );
}
m_map.clear();
delete m_indexBuf;
m_indexBuf = NULL;
for ( uint32 i = 0; i < m_singleAllocDescs.size(); ++i ) {
delete[] m_singleAllocDescs[ i ];
}
m_singleAllocDescs.clear();
}
IndexMap::~IndexMap()
{
clear();
}
uint32
IndexMap::size() const
{
return m_map.size();
}
bool
IndexMap::empty() const
{
return m_map.empty();
}
bool
IndexMap::setBuffer( BitBuffer* buf )
{
clear();
m_indexBuf = buf;
m_indexBuf->reset();
uint32 bufSize = m_indexBuf->readNextBALong() + 4;
if ( bufSize != m_indexBuf->getBufferSize() ) {
delete m_indexBuf;
m_indexBuf = NULL;
return false;
}
int nbrEntries = m_indexBuf->readNextBALong();
for ( int i = 0; i < nbrEntries; ++i ) {
const char* descr = m_indexBuf->readNextString();
int startOffset = m_indexBuf->readNextBALong();
int size = m_indexBuf->readNextBALong();
// Insert the read index entry last in the map since it is
// already sorted.
m_map.insert(
m_map.end(),
make_pair(descr, make_pair(startOffset,
size ) ) );
}
m_memTracker->allocateFromPool( m_indexBuf->getBufferSize() );
return true;
}
IndexMap::iterator
IndexMap::find( const char* desc )
{
return m_map.find( desc );
}
uint32
IndexMap::erase( const char* desc )
{
return m_map.erase( desc );
}
pair<int, int>&
IndexMap::operator[]( const char* desc )
{
char* newDesc = TileMapUtil::newStrDup( desc );
m_singleAllocDescs.push_back( newDesc );
return m_map[ newDesc ];
}
void
IndexMap::write( BitBuffer& buf ) const
{
buf.writeNextBALong( buf.getBufferSize() - 4 );
buf.writeNextBALong( m_map.size() );
for ( const_iterator it = m_map.begin();
it != m_map.end();
++it ) {
buf.writeNextString( it->first );
buf.writeNextBALong( it->second.first );
buf.writeNextBALong( it->second.second );
}
}
IndexMap::iterator
IndexMap::begin()
{
return m_map.begin();
}
IndexMap::iterator
IndexMap::end()
{
return m_map.end();
}
MFileDBufReqIdxHandler::
MFileDBufReqIdxHandler(MultiFileDBufRequester* listener,
vector <FileHandler*>& indexFiles,
int nbrHash,
const SharedBuffer* xorBuffer,
MemTracker* memTracker )
: m_indexFiles(indexFiles),
m_currentIndexFile(0),
m_nbrHash( nbrHash ),
m_memTracker( memTracker )
{
setXorBuffer( xorBuffer );
m_nbrFiles = indexFiles.size() / nbrHash;
m_listener = listener;
m_readBuffer = NULL;
m_writeBuffer = NULL;
m_indeces.resize( m_indexFiles.size() );
// VC++ does not handle these being non-pointers.
for ( uint32 i = 0; i < m_indeces.size(); ++i ) {
m_indeces[i] = new indexMap_t( m_memTracker );
}
m_state = IDLE;
m_shuttingDown = false;
}
MFileDBufReqIdxHandler::
~MFileDBufReqIdxHandler()
{
m_shuttingDown = true;
delete m_writeBuffer;
delete m_readBuffer;
for ( uint32 i = 0; i < m_indeces.size(); ++i ) {
delete m_indeces[i];
}
}
void
MFileDBufReqIdxHandler::setXorBuffer( const SharedBuffer* xorBuf)
{
m_xorBuffer = xorBuf;
}
void
MFileDBufReqIdxHandler::clearIndex(int nbr)
{
for ( int i = 0; i < m_nbrHash; ++i ) {
int idx = nbr * m_nbrHash + i;
m_indeces[ idx ]->clear();
}
}
void
MFileDBufReqIdxHandler::clearAllIndeces()
{
int length = m_nbrHash * m_nbrFiles;
for ( int i = 0; i < length; ++i ) {
m_indeces[ i ]->clear();
}
}
void
MFileDBufReqIdxHandler::shutDown()
{
m_shuttingDown = true;
}
void
MFileDBufReqIdxHandler::setState(state_t newState,
int line)
{
mc2log << "[MFDBRIH]: " << __FILE__ << ":" << line
<< " State change "
<< m_state << " -> " << newState << endl;
m_state = newState;
}
void
MFileDBufReqIdxHandler::find( const MC2SimpleString& desc,
int lastWrittenFileNbr,
int maxNbrFiles )
{
MC2_ASSERT( m_state == IDLE );
m_mode = MODE_FINDING;
m_nbrFilesLeftToSearch = m_nbrFiles;
if ( maxNbrFiles > 0 ) {
m_nbrFilesLeftToSearch = maxNbrFiles;
}
m_currentIndexFile = lastWrittenFileNbr;
m_currentDescToFind = desc;
startFinding();
}
void
MFileDBufReqIdxHandler::
updateMapIndex( int fileIdx,
const MC2SimpleString& desc,
int startOffset,
int size )
{
MC2_ASSERT( m_state == IDLE );
m_mode = MODE_WRITING;
m_currentIndexFile = fileIdx;
m_currentDescToFind = desc;
m_currentWritePosAndSize = make_pair(startOffset, size);
int idx = getIndexNbr( m_currentIndexFile, m_currentDescToFind );
// Start working
// Get the size of the index.
if ( ! m_indeces[ idx ]->empty() ) {
addCurrentMapToCurrentIndex();
writeIndex();
return;
}
// If we get here, the index table is already empty.
// m_indeces[ idx ]->clear();
SET_STATE( WRITING_MAP_READING_INDEX_LENGTH );
allocReadBuffer(4);
#if 1
// Trick
int len = m_indexFiles[ idx ]->getFileSize();
mc2log << "[MFDBRIH]: Length of index " << idx << " = "
<< len << endl;
if ( len > 4 ) {
m_readBuffer->writeNextBALong(len - 4);
m_readBuffer->reset();
readDone( m_readBuffer->getBufferSize() );
} else {
readDone( -1 );
}
return;
#endif
m_indexFiles[ idx ]->setPos(0);
m_indexFiles[ idx ]->read(m_readBuffer->getBufferAddress(),
m_readBuffer->getBufferSize(),
this);
}
void
MFileDBufReqIdxHandler::remove( const MC2SimpleString& desc )
{
MC2_ASSERT( m_state == IDLE );
m_mode = MODE_REMOVING;
m_currentIndexFile = 0;
m_currentDescToFind = desc;
m_nbrFilesLeftToSearch = m_nbrFiles;
startFinding();
}
void
MFileDBufReqIdxHandler::removeComplete()
{
SET_STATE( IDLE );
m_listener->removeComplete( m_currentDescToFind );
}
void
MFileDBufReqIdxHandler::allocReadBuffer(int size)
{
delete m_readBuffer;
m_readBuffer = new BitBuffer( size );
}
void
MFileDBufReqIdxHandler::startFinding()
{
int idx = getIndexNbr( m_currentIndexFile, m_currentDescToFind );
if ( ! m_indeces[ idx ]->empty() ) {
if ( m_mode == MODE_FINDING ) {
offsetAndSize_t offsetAndSize = findMapInCurrentIndexBuffer();
bool found = offsetAndSize.first != -1;
if ( found ) {
// Found the desc.
findComplete(offsetAndSize.first, offsetAndSize.second);
} else {
// Move to next index.
moveToNextIdxOrStop();
}
} else {
MC2_ASSERT( m_mode == MODE_REMOVING );
// Will do the moving to next file etc.
removeFromIndex();
}
return;
}
// If we get here, the index table is already empty.
// m_indeces[ idx ]->clear();
// Get the size of the index.
if ( m_mode == MODE_FINDING ) {
SET_STATE( FINDING_MAP_READING_INDEX_LENGTH );
} else {
SET_STATE( REMOVING_MAP_READING_INDEX_LENGTH );
}
allocReadBuffer(4);
#if 1
// Trick
int len = m_indexFiles[ idx ]->getFileSize();
mc2log << "[MFDBRIH]: Length of index " << idx << " = "
<< len << endl;
if ( len > 4 ) {
m_readBuffer->writeNextBALong(len - 4);
m_readBuffer->reset();
readDone( m_readBuffer->getBufferSize() );
} else {
readDone( -1 );
}
return;
#endif
// Rewind the file
m_indexFiles[ idx ]->setPos(0);
// Request the read.
m_indexFiles[ idx ]->read(m_readBuffer->getBufferAddress(),
m_readBuffer->getBufferSize(),
this);
}
void
MFileDBufReqIdxHandler::startReadingIndex()
{
MC2_ASSERT( m_state == FINDING_MAP_READING_INDEX_LENGTH ||
m_state == WRITING_MAP_READING_INDEX_LENGTH ||
m_state == REMOVING_MAP_READING_INDEX_LENGTH );
m_readBuffer->reset();
int indexLength = m_readBuffer->readNextBALong();
// Get the index
if ( m_state == FINDING_MAP_READING_INDEX_LENGTH ) {
SET_STATE( FINDING_MAP_READING_INDEX );
} else if ( m_state == WRITING_MAP_READING_INDEX_LENGTH ) {
SET_STATE ( WRITING_MAP_READING_INDEX );
} else if ( m_state == REMOVING_MAP_READING_INDEX_LENGTH ) {
SET_STATE( REMOVING_MAP_READING_INDEX );
}
allocReadBuffer( indexLength + 4 );
int idx = getIndexNbr( m_currentIndexFile, m_currentDescToFind );
// Rewind the file to the correct position.
m_indexFiles[ idx ]->setPos(0);
m_indexFiles[ idx ]->read( m_readBuffer->getBufferAddress(),
m_readBuffer->getBufferSize(),
this );
}
void
MFileDBufReqIdxHandler::createIndex()
{
int idx = getIndexNbr( m_currentIndexFile, m_currentDescToFind );
if ( ! m_indeces[ idx ]->empty() ) {
return;
}
// If we get here, the index table is already empty.
// m_indeces[ idx ]->clear();
BitBuffer& indexBuf = *m_readBuffer;
indexBuf.reset();
if ( m_xorBuffer ) {
indexBuf.xorBuffer( *m_xorBuffer );
}
if ( ! m_indeces[ idx ]->setBuffer( new BitBuffer( indexBuf ) ) ) {
if ( m_xorBuffer ) {
mc2log << "[MFDBRIH]: Wrong length of buffer after xor " << endl;
} else {
mc2log << "[MFDBRIH]: Wrong length of buffer without xor " << endl;
}
m_indexFiles[ idx ]->clearFile();
return;
}
}
MFileDBufReqIdxHandler::offsetAndSize_t
MFileDBufReqIdxHandler::findMapInCurrentIndexBuffer()
{
createIndex();
int idx = getIndexNbr( m_currentIndexFile, m_currentDescToFind );
indexMap_t::iterator findit =
m_indeces[ idx ]->find( m_currentDescToFind.c_str() );
offsetAndSize_t offsetAndSize(-1, -1);
if ( findit != m_indeces[ idx ]->end() ) {
// Found.
offsetAndSize = (*findit).second;
}
checkClearIndex();
return offsetAndSize;
}
void
MFileDBufReqIdxHandler::writeIndex()
{
MC2_ASSERT( m_writeBuffer == NULL );
SET_STATE( WRITING_INDEX );
int stringSum = 0;
int idx = getIndexNbr( m_currentIndexFile, m_currentDescToFind );
int indexSize = m_indeces[ idx ]->size();
{
for ( indexMap_t::const_iterator it =
m_indeces[ idx ]->begin();
it != m_indeces[ idx ]->end();
++it ) {
stringSum += strlen( it->first ) + 1;
}
}
m_writeBuffer = new BitBuffer( 4 + 4 + stringSum + ( indexSize * 8 ) );
m_indeces[ idx ]->write( *m_writeBuffer );
// Check if to clear the index.
checkClearIndex();
if ( m_xorBuffer ) {
m_writeBuffer->xorBuffer( *m_xorBuffer );
}
// Activate the writing.
m_indexFiles[ idx ]->setPos(0);
// XXX: This is only necessary if we have removed something from
// the index!!
m_indexFiles[ idx ]->setSize( m_writeBuffer->getCurrentOffset() );
m_indexFiles[ idx ]->write( m_writeBuffer->getBufferAddress(),
m_writeBuffer->getCurrentOffset(),
this );
}
void
MFileDBufReqIdxHandler::findComplete(int startOffet, int size)
{
SET_STATE ( IDLE );
m_listener->findComplete(m_currentDescToFind,
m_currentIndexFile,
startOffet, size);
}
bool
MFileDBufReqIdxHandler::updateFindIndex()
{
m_nbrFilesLeftToSearch--;
if ( m_nbrFilesLeftToSearch == 0 ) {
return false;
} else {
m_currentIndexFile--;
if ( m_currentIndexFile < 0 ) {
m_currentIndexFile = m_nbrFiles - 1;
}
return true;
}
}
void
MFileDBufReqIdxHandler::moveToNextIdxOrStop()
{
if ( updateFindIndex() ) {
startFinding();
} else {
if ( m_mode == MODE_FINDING ) {
findComplete(-1, -1);
} else {
MC2_ASSERT( m_mode == MODE_REMOVING );
removeComplete();
}
}
}
void
MFileDBufReqIdxHandler::addCurrentMapToCurrentIndex()
{
mc2log << "[MFDBRIH]: Adding map "
<< m_currentDescToFind << " to index "
<< m_currentIndexFile << endl;
int idx = getIndexNbr( m_currentIndexFile, m_currentDescToFind );
(*m_indeces[idx])[ m_currentDescToFind.c_str() ] =
m_currentWritePosAndSize;
}
int
MFileDBufReqIdxHandler::removeCurrentMapFromCurrentIndex()
{
int idx = getIndexNbr( m_currentIndexFile, m_currentDescToFind );
uint32 nbrErased =
m_indeces[ idx ]->erase( m_currentDescToFind.c_str() );
if ( nbrErased > 0 ) {
mc2log << "[MFDBRIH]: Removed map "
<< m_currentDescToFind << " from index "
<< m_currentIndexFile
<< endl;
} else {
mc2log << "[MFDBRIH]: Desc " << m_currentDescToFind
<< " not found in index " << m_currentIndexFile
<< endl;
}
return nbrErased > 0;
}
void
MFileDBufReqIdxHandler::indexWritten()
{
if ( m_mode == MODE_WRITING ) {
SET_STATE( IDLE );
m_listener->indexWritten(m_currentDescToFind);
} else {
moveToNextIdxOrStop();
}
}
void
MFileDBufReqIdxHandler::removeFromIndex()
{
if ( removeCurrentMapFromCurrentIndex() ) {
writeIndex();
} else {
moveToNextIdxOrStop();
}
}
void
MFileDBufReqIdxHandler::readDone(int nbrRead)
{
#ifdef USE_TRACE
TRACE_FUNC();
#endif
if ( m_shuttingDown ) {
return;
}
switch ( m_state ) {
case FINDING_MAP_READING_INDEX_LENGTH:
if ( nbrRead != (int)m_readBuffer->getBufferSize() ) {
/// Read error
mc2log << "[MFDBRIH]: Read returned " << nbrRead
<< " for file number " << m_currentIndexFile << endl;
moveToNextIdxOrStop();
} else {
startReadingIndex();
}
break;
case FINDING_MAP_READING_INDEX:
if ( nbrRead != (int)m_readBuffer->getBufferSize() ) {
// Read error
mc2log << "[MFDBRIH]: Read returned " << nbrRead
<< " for file number " << m_currentIndexFile << endl;
moveToNextIdxOrStop();
} else {
offsetAndSize_t offsetAndSize = findMapInCurrentIndexBuffer();
bool found = offsetAndSize.first != -1;
if ( found ) {
mc2log << "[MFDBRIH]: Found " << m_currentDescToFind
<< " in index " << endl;
findComplete(offsetAndSize.first, offsetAndSize.second);
} else {
// Try the next one or give up.
moveToNextIdxOrStop();
}
}
break;
case WRITING_MAP_READING_INDEX_LENGTH:
case REMOVING_MAP_READING_INDEX_LENGTH:
if ( nbrRead != (int)m_readBuffer->getBufferSize() ) {
// Probably empty.
mc2log << warn << "[MFDBRIH]: Could not read index "
<< endl;
if ( m_mode == MODE_REMOVING ) {
removeFromIndex();
} else {
addCurrentMapToCurrentIndex();
writeIndex();
}
} else {
// Index found and ok
startReadingIndex();
}
break;
case WRITING_MAP_READING_INDEX:
case REMOVING_MAP_READING_INDEX:
if ( nbrRead != (int)m_readBuffer->getBufferSize() ) {
// Something went wrong
indexWritten();
} else {
// Add the map to the index.
createIndex();
if ( m_mode == MODE_REMOVING ) {
removeFromIndex();
} else {
addCurrentMapToCurrentIndex();
writeIndex();
}
}
break;
case IDLE:
case WRITING_INDEX:
mc2log << error << "[Should not be idle now]" << endl;
break;
}
}
void
MFileDBufReqIdxHandler::writeDone(int nbrWritten)
{
if ( m_shuttingDown ) {
return;
}
MC2_ASSERT( m_state == WRITING_INDEX );
delete m_writeBuffer;
m_writeBuffer = NULL;
mc2log << "[MFDBRIH]: nbrWritten = " << nbrWritten << endl;
if ( m_mode == MODE_WRITING ) {
indexWritten();
} else {
// Means that we are removing from all indeces
moveToNextIdxOrStop();
}
}
void
MFileDBufReqIdxHandler::checkClearIndex()
{
m_memTracker->checkCleanMemUsage();
}
void
MFileDBufReqIdxHandler::cleanUpMemUsage()
{
if ( m_state == IDLE ) {
// Does not seem like we're doing anything right now.
// Clean up.
mc2log << "[MFDBReq:] cleanUpMemUsage IDLE" << endl;
clearAllIndeces();
}
}
| [
"[email protected]"
] | [
[
[
1,
691
]
]
] |
3cafd02a428e058c6c181bfa4d1c737f59fd47ff | 0a7a70f6d547867755f317e5569e63709672eba1 | /src/ndssys/ndssystem.cpp | 1d511ef5d1b9085e8adf8de5db62b643fde3ffc0 | [] | no_license | ballercat/ends | f787b03f90638ca3ad03735c65875f386456dad3 | e3bb04481e289c272387d30ede8a7526226ba14d | refs/heads/master | 2016-09-10T09:41:55.820693 | 2009-08-30T00:14:10 | 2009-08-30T00:14:10 | 35,772,611 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,218 | cpp | #include "ndssys.h"
#include "ndscartridge.h"
#include <cstdio>
#include <cstring>
NDSSYSTEM::NDSSYSTEM()
{
mmu = new NDSMMU;
cpu = new NDSCPU(mmu);
#ifndef NDS_DEBUG
if(!SDL_Init(SDL_INIT_EVERYTHING))
{
screen = SDL_SetVideoMode(256, 192*2, 16, SDL_DOUBLEBUF);
if( screen )
SDL_WM_SetCaption("e-NDS","e-NDS");
}
vid = new NDSVIDEO(screen,mmu);
#endif
rom = NULL;
}
NDSSYSTEM::~NDSSYSTEM()
{
delete(mmu);
delete(cpu);
#ifndef NDS_DEBUG
SDL_FreeSurface(screen);
#endif
fclose(rom);
}
bool NDSSYSTEM::nds_loadfile(const char *fpath)
{
struct nds_header_t header;
rom = fopen(fpath, "rb");
if( !rom )
return false;
else{
fseek(rom, 0, SEEK_SET);
fread(&header, sizeof(struct nds_header_t), sizeof(u8), rom);
fseek(rom, header.ARM9rom_offset, SEEK_SET);
/* Arm9 program */
fread(mmu->memory, header.ARM9size, sizeof(u8), rom);
memcpy(&mmu->memory[0x400000], mmu->memory, sizeof(u8)*0x400000);
memcpy(&mmu->memory[0x800000], mmu->memory, sizeof(u8)*0x400000);
memcpy(&mmu->memory[0xC00000], mmu->memory, sizeof(u8)*0x400000);
/* Header */
memcpy(&mmu->memory[0x7FFFE0], &header, sizeof(struct nds_header_t) );
cpu->m_newpc = header.ARM9entry_adress;
cpu->m_r[15] = header.ARM9entry_adress;
cpu->arm9_entry = cpu->m_newpc;
cpu->arm7_entry = header.ARM9entry_adress;
cpu->arm9size = header.ARM9size;
cpu->arm7size = header.ARM7size;
return true;
}
return false;
}
#ifndef NDS_DEBUG
int NDSSYSTEM::exec()
{
while( parseinput() != -1 )
{
cpu->exec();
vid->render2D();
SDL_Flip(screen);
}
return 0;
}
int NDSSYSTEM::parseinput()
{
SDL_Event event;
while( SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
return -1;
case SDL_KEYDOWN:
return 0;
case SDL_KEYUP:
return 1;
}
}
return 0;
}
#endif
| [
"whinemore@5982b672-94f9-11de-9b71-cb34e3bcb0e2"
] | [
[
[
1,
100
]
]
] |
ad9b21017a47f197801482d82b3f0ae22887270f | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/npc_dev.cpp | 82131045a610163017c7ffb65507a1f5fabfeaad | [] | no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | WINDOWS-1251 | C++ | false | false | 16,350 | cpp | #include "config.hpp"
#include "npc_dev.hpp"
#include "core/module_c.hpp"
#include "core/npcs.hpp"
#include "vehicles.hpp"
#include "weapons.hpp"
#include "player_money.hpp"
#include <fstream>
#include <boost/filesystem.hpp>
REGISTER_IN_APPLICATION(npc_dev);
npc_dev::npc_dev()
:play_npc_name("npc_dev_play")
,play_record_vehicle_id(0)
{
}
npc_dev::~npc_dev() {
}
void npc_dev::create() {
command_add("npc_dev_record", std::tr1::bind(&npc_dev::cmd_record, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("npc_dev_play", std::tr1::bind(&npc_dev::cmd_play, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("npc_dev_create_vehicle", std::tr1::bind(&npc_dev::cmd_create_vehicle, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
}
void npc_dev::configure_pre() {
is_enable = false;
recording_vehicle_health = 1000.0f;
acceleration_multiplier = 1.2f;
deceleration_multiplier = 0.8f;
}
void npc_dev::configure(buffer::ptr const& buff, def_t const& def) {
SERIALIZE_ITEM(is_enable);
SERIALIZE_ITEM(recording_vehicle_health);
SERIALIZE_ITEM(acceleration_multiplier);
SERIALIZE_ITEM(deceleration_multiplier);
}
void npc_dev::configure_post() {
}
void npc_dev::on_connect(player_ptr_t const& player_ptr) {
npc_dev_player_item::ptr item(new npc_dev_player_item(*this), &player_item::do_delete);
player_ptr->add_item(item);
}
void npc_dev::on_npc_connect(npc_ptr_t const& npc_ptr) {
if (play_npc_name == npc_ptr->name_get()) {
// Это наш бот для проигрования :)
npc_dev_npc_item::ptr item(new npc_dev_npc_item(*this), &npc_item::do_delete);
npc_ptr->add_item(item);
}
}
bool npc_dev::access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name) {
return is_enable;
}
command_arguments_rezult npc_dev::cmd_record(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
npc_dev_player_item::ptr npc_dev_player_item_ptr = player_ptr->get_item<npc_dev_player_item>();
npc_dev_player_item_ptr->is_wait_recording = !npc_dev_player_item_ptr->is_wait_recording;
if (npc_dev_player_item_ptr->is_wait_recording) {
if (arguments.empty()) {
npc_dev_player_item_ptr->recording_prefix = "record";
}
else {
npc_dev_player_item_ptr->recording_prefix = arguments;
}
player_ptr->get_item<weapons_item>()->weapon_reset();
player_ptr->get_item<player_money_item>()->reset();
params("prefix", npc_dev_player_item_ptr->recording_prefix);
pager("$(cmd_npc_dev_record_on_player)");
sender("$(cmd_npc_dev_record_on_log)", msg_log);
}
else {
if (npc_dev_player_item_ptr->is_recording) {
npc_dev_player_item_ptr->recording_stop();
}
pager("$(cmd_npc_dev_record_off_player)");
sender("$(cmd_npc_dev_record_off_log)", msg_log);
}
return cmd_arg_ok;
}
command_arguments_rezult npc_dev::cmd_play(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
if (arguments.empty()) {
return cmd_arg_syntax_error;
}
{
int vehicle_id;
int model_id;
bool is_driver;
if (player_ptr->get_vehicle(vehicle_id, model_id, is_driver)) {
play_record_vehicle_id = vehicle_id;
}
else {
play_record_vehicle_id = 0;
}
}
play_record_name = arguments;
npcs::instance()->add_npc(play_npc_name);
params("record_name", play_record_name);
pager("$(cmd_npc_dev_play_player)");
sender("$(cmd_npc_dev_play_log)", msg_log);
return cmd_arg_ok;
}
command_arguments_rezult npc_dev::cmd_create_vehicle(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
int model_id;
{ // Парсинг
if (!vehicles::instance()->get_model_id_by_name(arguments, model_id)) {
std::istringstream iss(arguments);
iss>>model_id;
if (iss.fail() || !iss.eof()) {
return cmd_arg_syntax_error;
}
}
}
{ // Проверяем, находится ли игрок в транспорте
int vehicle_id = samp::api::instance()->get_player_vehicle_id(player_ptr->get_id());
int model_id = samp::api::instance()->get_vehicle_model(vehicle_id);
if (0 != model_id) {
pager("$(npc_dev_create_vehicle_error_invehicle)");
return cmd_arg_process_error;
}
}
pos4 pos = player_ptr->get_item<player_position_item>()->pos_get();
int vehicle_id = vehicles::instance()->vehicle_create(pos_vehicle(model_id, pos.x, pos.y, pos.z + 1.5f, pos.interior, pos.world, pos.rz, -1, -1));
samp::api::instance()->put_player_in_vehicle(player_ptr->get_id(), vehicle_id, 0);
params
("model_id", model_id)
("vehicle_id", vehicle_id)
;
pager("$(npc_dev_create_vehicle_done_player)");
sender("$(npc_dev_create_vehicle_done_log)", msg_log);
return cmd_arg_ok;
}
npc_dev_player_item::npc_dev_player_item(npc_dev& manager)
:manager(manager)
,is_wait_recording(false)
,is_recording(false)
,recording_vehicle_id(-1)
,recording_time_start(0)
,is_accelerate(false)
{
}
npc_dev_player_item::~npc_dev_player_item() {
}
void npc_dev_player_item::on_timer250() {
if (!is_recording || 0 == recording_vehicle_id || !is_accelerate) {
return;
}
int vehicle_id;
int model_id;
bool is_driver;
if (get_root()->get_vehicle(vehicle_id, model_id, is_driver) && is_driver) {
samp::api::ptr api_ptr = samp::api::instance();
float x, y, z;
int keys;
int updown;
int leftright;
api_ptr->get_vehicle_velocity(vehicle_id, x, y, z);
api_ptr->get_player_keys(get_root()->get_id(), keys, updown, leftright);
if (keys & vehicle_accelerate) {
api_ptr->set_vehicle_velocity(vehicle_id, accelerate(x), accelerate(y), accelerate(z));
}
else if (keys & vehicle_decelerate) {
api_ptr->set_vehicle_velocity(vehicle_id, decelerate(x), decelerate(y), decelerate(z));
}
}
}
void npc_dev_player_item::on_keystate_change(int keys_new, int keys_old) {
if (!is_wait_recording) {
return;
}
if (is_recording && 0 != recording_vehicle_id) {
if (recording_is_can_use_nitro) {
if (is_key_just_down(mouse_lbutton, keys_new, keys_old)) {
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
// Можем поставить нитро :)
vehicle_ptr->add_component("nto_b_tw");
}
}
else if (is_key_just_down(KEY_SUBMISSION, keys_new, keys_old)) {
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
// Убираем нитро
vehicle_ptr->remove_component("nto_b_tw");
}
}
}
if (is_key_just_down(KEY_ACTION, keys_new, keys_old)) {
is_accelerate = true;
}
else if (is_key_just_up(KEY_ACTION, keys_new, keys_old)) {
is_accelerate = false;
}
}
if (is_key_just_down(KEY_LOOK_BEHIND, keys_new, keys_old) && !get_root()->vehicle_is_driver()) {
// Запуск/остановка записи пешком
if (is_recording) {
recording_stop();
}
else {
recording_start(false);
}
}
else if (is_key_just_down(KEY_LOOK_RIGHT | KEY_LOOK_LEFT, keys_new, keys_old) && get_root()->vehicle_is_driver()) {
// Запуск/остановка записи на транспорте
if (is_recording) {
recording_stop();
}
else {
recording_start(true);
}
}
}
bool npc_dev_player_item::on_update() {
if (is_recording) {
samp::api::ptr api_ptr = samp::api::instance();
int vehicle_id;
int model_id;
bool is_driver;
if (get_root()->get_vehicle(vehicle_id, model_id, is_driver) && is_driver) {
if (manager.recording_vehicle_health != api_ptr->get_vehicle_health(vehicle_id)) {
//api_ptr->set_vehicle_health(vehicle_id, manager.recording_vehicle_health);
api_ptr->repair_vehicle(vehicle_id);
}
}
else {
}
}
return true;
}
void npc_dev_player_item::recording_start(bool is_vehicle) {
if (is_recording) {
assert(false);
return;
}
recording_name = get_next_recording_filename();
recording_desc = npc_recording_desc_t();
recording_vehicle_id = 0;
recording_is_can_use_nitro = false;
is_accelerate = false;
samp::api::ptr api_ptr = samp::api::instance();
recording_desc.skin_id = api_ptr->get_player_skin(get_root()->get_id());
if (is_vehicle) {
bool is_driver;
int model_id;
get_root()->get_vehicle(recording_vehicle_id, model_id, is_driver);
api_ptr->get_vehicle_pos(recording_vehicle_id, recording_desc.point_begin.x, recording_desc.point_begin.y, recording_desc.point_begin.z);
recording_desc.point_begin.rz = api_ptr->get_vehicle_zangle(recording_vehicle_id);
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
if (vehicle_def_cptr_t vehicle_def_cptr = vehicle_ptr->get_def()) {
recording_desc.model_name = vehicle_def_cptr->sys_name;
}
recording_is_can_use_nitro = vehicle_ptr->is_valid_component("nto_b_tw");
}
api_ptr->repair_vehicle(recording_vehicle_id);
}
else {
int player_id = get_root()->get_id();
api_ptr->get_player_pos(player_id, recording_desc.point_begin.x, recording_desc.point_begin.y, recording_desc.point_begin.z);
recording_desc.point_begin.rz = api_ptr->get_player_facing_angle(player_id);
}
recording_desc.point_begin.interior = api_ptr->get_player_interior(get_root()->get_id());
messages_item msg_item;
msg_item.get_params()
("player_name", get_root()->name_get_full())
("recording_name", recording_name)
;
if (is_vehicle) {
if (recording_is_can_use_nitro) {
msg_item.get_sender()
("$(npc_dev_recordind_vehicle_nitro_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_vehicle_nitro_start_log)", msg_log);
}
else {
msg_item.get_sender()
("$(npc_dev_recordind_vehicle_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_vehicle_start_log)", msg_log);
}
api_ptr->start_recording_player_data(get_root()->get_id(), samp::api::PLAYER_RECORDING_TYPE_DRIVER, recording_name);
}
else {
msg_item.get_sender()
("$(npc_dev_recordind_onfoot_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_onfoot_start_log)", msg_log);
api_ptr->start_recording_player_data(get_root()->get_id(), samp::api::PLAYER_RECORDING_TYPE_ONFOOT, recording_name);
}
recording_time_start = time_base::tick_count_milliseconds();
is_recording = true;
}
void npc_dev_player_item::recording_stop() {
if (!is_recording) {
assert(false);
return;
}
samp::api::ptr api_ptr = samp::api::instance();
time_base::millisecond_t recording_time_stop = time_base::tick_count_milliseconds();
api_ptr->stop_recording_player_data(get_root()->get_id());
is_recording = false;
if (recording_desc.is_on_vehicle()) {
api_ptr->get_vehicle_pos(recording_vehicle_id, recording_desc.point_end.x, recording_desc.point_end.y, recording_desc.point_end.z);
recording_desc.point_end.rz = api_ptr->get_vehicle_zangle(recording_vehicle_id);
}
else {
int player_id = get_root()->get_id();
api_ptr->get_player_pos(player_id, recording_desc.point_end.x, recording_desc.point_end.y, recording_desc.point_end.z);
recording_desc.point_end.rz = api_ptr->get_player_facing_angle(player_id);
}
recording_desc.duration = (recording_time_stop - recording_time_start);
{ // Сохраняем файл с методанными
std::ofstream meta_file(recording_get_meta_filename(recording_name).c_str());
if (meta_file) {
meta_file << recording_desc;
}
}
messages_item msg_item;
msg_item.get_params()
("player_name", get_root()->name_get_full())
("recording_name", recording_name)
("recording_desc", boost::format("%1%") % recording_desc)
;
msg_item.get_sender()
("$(npc_dev_recordind_stop_player)", msg_player(get_root()))
("$(npc_dev_recordind_stop_log)", msg_log);
}
std::string npc_dev_player_item::get_next_recording_filename() const {
/*
if (!boost::filesystem::exists(recording_get_rec_filename(recording_prefix))) {
// В начале пытаемся имя без цифрового суфикса
return recording_prefix;
}
*/
for (int i = 0; i < 1000; ++i) {
std::string name = (boost::format("%1%%2$02d") % recording_prefix % i).str();
if (!boost::filesystem::exists(recording_get_rec_filename(name))) {
return name;
}
}
assert(false);
return "fuck";
}
std::string npc_dev_player_item::recording_get_meta_filename(std::string const& recording_name) {
return "scriptfiles/" + recording_name + ".meta";
}
std::string npc_dev_player_item::recording_get_rec_filename(std::string const& recording_name) {
return "scriptfiles/" + recording_name + ".rec";
}
float npc_dev_player_item::accelerate(float val) const {
return val * manager.acceleration_multiplier;
}
float npc_dev_player_item::decelerate(float val) const {
return val * manager.deceleration_multiplier;
}
npc_dev_npc_item::npc_dev_npc_item(npc_dev& manager)
:manager(manager)
{
}
npc_dev_npc_item::~npc_dev_npc_item() {
}
void npc_dev_npc_item::on_connect() {
get_root()->set_spawn_info(11, pos4(1958.3783f, 1343.1572f, 15.3746f, 0, 0, 90.0f));
get_root()->set_color(0xff000020);
}
void npc_dev_npc_item::on_spawn() {
if (manager.play_record_vehicle_id) {
// Сажаем в транспорт
get_root()->put_to_vehicle(manager.play_record_vehicle_id);
}
else {
// Включаем запись просто
get_root()->playback_start(npc::playback_type_onfoot, manager.play_record_name);
}
}
void npc_dev_npc_item::on_enter_vehicle(int vehicle_id) {
if (manager.play_record_vehicle_id) {
get_root()->playback_start(npc::playback_type_driver, manager.play_record_name);
}
}
void npc_dev_npc_item::on_playback_end() {
get_root()->kick();
}
void npc_dev_npc_item::on_disconnect(samp::player_disconnect_reason reason) {
}
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] | [
[
[
1,
434
]
]
] |
ddae4399ec4f8c3a5f1ad94c1a76d2cb9c31588b | db0d644f1992e5a82e22579e6287f45a8f8d357a | /Caster/Ntrip/MountTable.cpp | 32fabb4d9797560f32495c2e08d477f3ee6315c8 | [] | no_license | arnout/nano-cast | 841a6dc394bfb30864134bce70e11d29b77c2411 | 5d11094da4dbb5027ce0a3c870b6a6cc9fcc0179 | refs/heads/master | 2021-01-01T05:14:29.996348 | 2011-01-15T17:27:48 | 2011-01-15T17:27:48 | 58,049,740 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,955 | cpp | #include "MountTable.h"
#include "Parse.h"
#include <string.h>
#include <stdio.h>
static bool ReadLine(FILE* f, byte* buf, int size);
MountPoint::MountPoint()
{
Init("");
}
MountPoint::~MountPoint()
{
}
bool MountPoint::ValidPassword(const char *password)
////////////////////////////////////////////////////////////////////////////
// ValidPassword is true if the password is valid for this mountpoint
////////////////////////////////////////////////////////////////////////////
{
return (Password[0] == '\0' || strcmp(Password, password) == 0);
}
bool MountPoint::IsMounted()
///////////////////////////////////////////////////////////////////////////////
// IsMounted is true if the mountpoint has a server attached.
///////////////////////////////////////////////////////////////////////////////
{
return State != UNMOUNTED;
}
bool MountPoint::Mount()
{
debug("MountPoint::Mount() Name=%s\n", Name);
if (IsMounted())
return Error("Mountpoint %s is already mounted\n", Name);
Buf.Init();
State = MOUNTED;
return OK;
}
bool MountPoint::Unmount()
{
debug("MountPoint::Unmount() - Name=%s\n", Name);
State = UNMOUNTED;
Buf.waiters.WakeupWaiters();
return OK;
}
bool MountPoint::Init(const char* name)
{
debug("MountPoint::Init(%s)\n", name);
if (strlen(name) > MaxName)
return Error("MountPoint: name too long\n");
strcpy(Name, name);
strcpy(Password, "");
strcpy(STR, "");
State = UNMOUNTED;
return OK;
}
bool MountPoint::SetPassword(const char* password)
{
if (strlen(password) > MaxPassword)
return Error("MountPoint: password too long\n");
strcpy(Password, password);
return OK;
}
bool MountPoint::SetSTR(const char* str)
{
if (strlen(str) > MaxSTR)
return Error("MountPoint: STR entry too long\n");
strcpy(STR, str);
return OK;
}
MountTable::MountTable() {}
MountTable::~MountTable(){}
MountPoint* MountTable::CreateMount(const char* name)
////////////////////////////////////////////////////////////////////////////////////
// CreateMount creates a new mount point in the mount table.
// typically done during initialization
////////////////////////////////////////////////////////////////////////////////////
{
// Make sure the mountpoint name is valid
if (name[0] == '\0')
{Error("Create: Can't create null mount point\n"); return NULL;}
if (Lookup(name) != NULL)
{Error("Create: Mount Point %s lready Defined\n", name); return NULL;}
// Find an empty slot in the mount table
MountPoint* mnt = Lookup("");
if (mnt == NULL)
{Error("Create: Too many mountpoints (%s)\n", name); return NULL;}
// Use the slot
if (mnt->Init(name) != OK)
{Error("CreateMount: invalid name %s\n", name); return NULL;}
return mnt;
}
bool MountTable::DestroyMount(const char* name)
{
MountPoint* mnt = Lookup(name);
if (mnt == NULL)
return Error("Can't destroy - mount point %s doesn't exist\n", name);
mnt->Init("");
return OK;
}
MountPoint* MountTable::Lookup(const char* name)
///////////////////////////////////////////////////////////////////////////
// Lookup finds the mountpoint in the mount table
//////////////////////////////////////////////////////////////////////
{
for (int i=0; i<MaxMounts; i++)
if (strcmp(Mounts[i].Name, name) == 0)
return &Mounts[i];
return NULL;
}
bool MountTable::ReadFromFile(const char* path)
////////////////////////////////////////////////////////////////////////
// ReadFromFile reads the mount points from the configuration file
// and fills in the mount table
/////////////////////////////////////////////////////////////////////////
{
// Open the file
// TODO: If there are errors, we will abort, although we really should close the file
FILE *f = fopen(path, "r");
if (f == NULL) return SysError("Can't open source table %s\n", path);
// Read it a line at a time.
// Each line is of the form: mountpoint; password; STR data
while (!feof(f)) {
byte line[MaxSTR+MaxName+MaxPassword+25]; // TODO: get it out of stack
if (ReadLine(f, line, sizeof(line)) != OK)
return SysError("Trouble reading from source table file %s\n", path);
// Get the mount point name.
Parse token(line, strlen((char*)line));
char name[MaxName+1];
token.Next(";");
if (token == "") return Error("Empty mount point not valid\n");
token.GetToken(name, sizeof(name));
// Get the password
char password[MaxPassword+1];
token.Next(";");
token.GetToken(password, sizeof(password));
// Get the Stream Record entry (STR) - all entries up to end of line.
char str[MaxSTR+1];
token.Next("\r\n");
token.GetToken(str, sizeof(str));
// Create a new entry with the password and STR data
MountPoint* mnt = CreateMount(name);
if (mnt == NULL || mnt->SetPassword(password) != OK | mnt->SetSTR(str) != OK)
return Error("Problem creating new mountpoint %s\n", name);
}
fclose(f);
return OK;
}
static bool ReadLine(FILE *f, byte* buf, int size)
{
int i;
for (i=0; i+2< size; i++) {
int c;
buf[i] = c = getc(f);
if (c == EOF || buf[i] == '\n') break;
// Ignore "CR" since we don't know if file was edited by windows or unix
if (buf[i] == '\r') i--;
}
if (i+2 >= size) return Error("ReadLine: line longer than %d characters\n", size-3);
// Line is terminated with /r /n /0
buf[i] = '\r';
buf[i+1] = '\n';
buf[i+2] = '\0';
return OK;
}
| [
"[email protected]"
] | [
[
[
1,
219
]
]
] |
032053199709cc9e026e9934d1104d1118e149c0 | 941e1c9c87576247aac5c28db16e2d73a2bec0af | /SelectDlg.h | f2b8702892dc36cfd2f9c61301c1c2251bf6acd3 | [] | no_license | luochong/vc-gms-1 | 49a5ccc2edd3da74da2a7d9271352db8213324cb | 607b087e37cc0946b4562b681bb65875863bc084 | refs/heads/master | 2016-09-06T09:32:16.340313 | 2009-06-14T07:35:19 | 2009-06-14T07:35:19 | 32,432,320 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 637 | h | #pragma once
#include "afxwin.h"
// CSelectDlg 对话框
class CSelectDlg : public CDialog
{
DECLARE_DYNAMIC(CSelectDlg)
public:
CSelectDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~CSelectDlg();
// 对话框数据
enum { IDD = IDD_DIALOG_SELECT };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
CString m_gname;
CString m_gcode;
CListBox m_listbox;
CString m_gnameEx;
bool isgoods;
virtual BOOL OnInitDialog();
afx_msg void OnLbnSelchangeList1();
afx_msg void OnBnClickedButton1();
CString m_title;
};
| [
"luochong1987@29d93fdc-527c-11de-bf49-a932634fd5a9"
] | [
[
[
1,
33
]
]
] |
ab7f2df51c71525c94e3ce1dc1edc0f15b04e306 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/uavobjectbrowser/uavobjectbrowser.cpp | 9783d04c9ca74e3f276c94096fef1b33e5c75a0d | [] | no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,906 | cpp | /**
******************************************************************************
*
* @file uavobjectbrowser.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup UAVObjectBrowserPlugin UAVObject Browser Plugin
* @{
* @brief The UAVObject Browser gadget plugin
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "uavobjectbrowser.h"
#include "uavobjectbrowserwidget.h"
#include "uavobjectbrowserconfiguration.h"
UAVObjectBrowser::UAVObjectBrowser(QString classId, UAVObjectBrowserWidget *widget, QWidget *parent) :
IUAVGadget(classId, parent),
m_widget(widget)
{
}
UAVObjectBrowser::~UAVObjectBrowser()
{
}
void UAVObjectBrowser::loadConfiguration(IUAVGadgetConfiguration* config)
{
UAVObjectBrowserConfiguration *m = qobject_cast<UAVObjectBrowserConfiguration*>(config);
m_widget->setRecentlyUpdatedColor(m->recentlyUpdatedColor());
m_widget->setManuallyChangedColor(m->manuallyChangedColor());
m_widget->setRecentlyUpdatedTimeout(m->recentlyUpdatedTimeout());
}
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
] | [
[
[
1,
49
]
]
] |
199163c7189a838d2457d0fee20bf805e591dcf9 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/stage_id.inl | 9cb83d9647d4a95519a312230e78f2d0dfe48b76 | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 639 | inl | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
#ifndef AOSLCPP_AOSL__STAGE_ID_INL
#define AOSLCPP_AOSL__STAGE_ID_INL
// Begin prologue.
//
//
// End prologue.
#include "aosl/unique_id.inl"
namespace aosl
{
// Stage_id
//
}
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__STAGE_ID_INL
| [
"klaim@localhost"
] | [
[
[
1,
31
]
]
] |
a5cc53405a333321ea350f29887610a418cf430a | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/test/detail/null_padded_codecvt.hpp | 111cdbd73d1d67ffdfa02a0321134c14a3882d6d | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,699 | hpp | // (C) Copyright Jonathan Turkanis 2004
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
// Contains the definitions of two codecvt facets useful for testing code
// conversion. Both represent the "null padded" character encoding described as
// follows. A wide character can be represented by the encoding if its value V
// is within the range of an unsigned char. The first char of the sequence
// representing V is V % 3 + 1. This is followed by V % 3 null characters, and
// finally by V itself.
// The first codecvt facet, null_padded_codecvt, is statefull, with state_type
// equal to int.
// The second codecvt facet, stateless_null_padded_codecvt, is stateless. At
// each point in a conversion, no characters are consumed unless there is room
// in the output sequence to write an entire multibyte sequence.
#ifndef BOOST_IOSTREAMS_TEST_NULL_PADDED_CODECVT_HPP_INCLUDED
#define BOOST_IOSTREAMS_TEST_NULL_PADDED_CODECVT_HPP_INCLUDED
#include <boost/config.hpp> // NO_STDC_NAMESPACE
#include <boost/iostreams/detail/codecvt_helper.hpp>
#include <boost/iostreams/detail/config/wide_streams.hpp>
#include <cstddef> // mbstate_t.
#include <locale> // codecvt.
#include <boost/integer_traits.hpp> // const_max.
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::mbstate_t; }
#endif
namespace boost { namespace iostreams { namespace test {
//------------------Definition of null_padded_codecvt_state-------------------//
class null_padded_codecvt_state {
public:
null_padded_codecvt_state(int val = 0) : val_(val) { }
operator int() const { return val_; }
int& val() { return val_; }
const int& val() const { return val_; }
private:
int val_;
};
} } }
BOOST_IOSTREAMS_CODECVT_SPEC(boost::iostreams::test::null_padded_codecvt_state)
namespace boost { namespace iostreams { namespace test {
//------------------Definition of null_padded_codevt--------------------------//
//
// state is initially 0. After a single character is consumed, state is set to
// the number of characters in the current multibyte sequence and decremented
// as each character is consumed until its value reaches 0 again.
//
class null_padded_codecvt
: public iostreams::detail::codecvt_helper<
wchar_t, char, null_padded_codecvt_state
>
{
public:
typedef null_padded_codecvt_state state_type;
private:
std::codecvt_base::result
do_in( state_type& state, const char* first1, const char* last1,
const char*& next1, wchar_t* first2, wchar_t* last2,
wchar_t*& next2 ) const
{
using namespace std;
if (state < 0 || state > 3)
return codecvt_base::error;
next1 = first1;
next2 = first2;
while (next2 != last2 && next1 != last1) {
while (next1 != last1) {
if (state == 0) {
if (*next1 < 1 || *next1 > 3)
return codecvt_base::error;
state = *next1++;
} else if (state == 1) {
*next2++ = (unsigned char) *next1++;
state = 0;
break;
} else {
if (*next1++ != 0)
return codecvt_base::error;
--state.val();
}
}
}
return next2 == last2 ?
codecvt_base::ok :
codecvt_base::partial;
}
std::codecvt_base::result
do_out( state_type& state, const wchar_t* first1, const wchar_t* last1,
const wchar_t*& next1, char* first2, char* last2,
char*& next2 ) const
{
using namespace std;
if (state < 0 || state > 3)
return codecvt_base::error;
next1 = first1;
next2 = first2;
while (next1 != last1 && next2 != last2) {
while (next2 != last2) {
if (state == 0) {
if (*next1 > integer_traits<unsigned char>::const_max)
return codecvt_base::noconv;
state = *next1 % 3 + 1;
*next2++ = static_cast<char>(state);
} else if (state == 1) {
state = 0;
*next2++ = static_cast<unsigned char>(*next1++);
break;
} else {
--state.val();
*next2++ = 0;
}
}
}
return next1 == last1 ?
codecvt_base::ok :
codecvt_base::partial;
}
std::codecvt_base::result
do_unshift(state_type& state, char* first2, char* last2, char*& next2) const
{
using namespace std;
next2 = last2;
while (state.val()-- > 0)
if (next2 != last2)
*next2++ = 0;
else
return codecvt_base::partial;
return codecvt_base::ok;
}
bool do_always_noconv() const throw() { return false; }
int do_max_length() const throw() { return 4; }
int do_encoding() const throw() { return -1; }
int do_length( BOOST_IOSTREAMS_CODECVT_CV_QUALIFIER state_type& state,
const char* first1, const char* last1,
std::size_t len2 ) const throw()
{ // Implementation should follow that of do_in().
int st = state;
std::size_t result = 0;
const char* next1 = first1;
while (result < len2 && next1 != last1) {
while (next1 != last1) {
if (st == 0) {
if (*next1 < 1 || *next1 > 3)
return static_cast<int>(result); // error.
st = *next1++;
} else if (st == 1) {
++result;
st = 0;
break;
} else {
if (*next1++ != 0)
return static_cast<int>(result); // error.
--st;
}
}
}
return static_cast<int>(result);
}
};
//------------------Definition of stateless_null_padded_codevt----------------//
class stateless_null_padded_codecvt
: public std::codecvt<wchar_t, char, std::mbstate_t>
{
std::codecvt_base::result
do_in( state_type&, const char* first1, const char* last1,
const char*& next1, wchar_t* first2, wchar_t* last2,
wchar_t*& next2 ) const
{
using namespace std;
for ( next1 = first1, next2 = first2;
next1 != last1 && next2 != last2; )
{
int len = (unsigned char) *next1;
if (len < 1 || len > 3)
return codecvt_base::error;
if (last1 - next1 < len + 1)
return codecvt_base::partial;
++next1;
while (len-- > 1)
if (*next1++ != 0)
return codecvt_base::error;
*next2++ = (unsigned char) *next1++;
}
return next1 == last1 && next2 == last2 ?
codecvt_base::ok :
codecvt_base::partial;
}
std::codecvt_base::result
do_out( state_type&, const wchar_t* first1, const wchar_t* last1,
const wchar_t*& next1, char* first2, char* last2,
char*& next2 ) const
{
using namespace std;
for ( next1 = first1, next2 = first2;
next1 != last1 && next2 != last2; )
{
if (*next1 > integer_traits<unsigned char>::const_max)
return codecvt_base::noconv;
int skip = *next1 % 3 + 2;
if (last2 - next2 < skip)
return codecvt_base::partial;
*next2++ = static_cast<char>(--skip);
while (skip-- > 1)
*next2++ = 0;
*next2++ = (unsigned char) *next1++;
}
return codecvt_base::ok;
}
std::codecvt_base::result
do_unshift(state_type&, char* first2, char* last2, char*& next2) const
{
return std::codecvt_base::ok;
}
bool do_always_noconv() const throw() { return false; }
int do_max_length() const throw() { return 4; }
int do_encoding() const throw() { return -1; }
int do_length( BOOST_IOSTREAMS_CODECVT_CV_QUALIFIER state_type&,
const char* first1, const char* last1,
std::size_t len2 ) const throw()
{ // Implementation should follow that of do_in().
std::size_t result = 0;
for ( const char* next1 = first1;
next1 != last1 && result < len2; ++result)
{
int len = (unsigned char) *next1;
if (len < 1 || len > 3 || last1 - next1 < len + 1)
return static_cast<int>(result); // error.
++next1;
while (len-- > 1)
if (*next1++ != 0)
return static_cast<int>(result); // error.
++next1;
}
return static_cast<int>(result);
}
};
} } } // End namespaces detail, iostreams, boost.
#endif // #ifndef BOOST_IOSTREAMS_TEST_NULL_PADDED_CODECVT_HPP_INCLUDED
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
268
]
]
] |
cbd7054c40604974200ba675a0a4a0ca1135eecd | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/lang/wscNumber.cpp | a1f1717ba90d5d0c66b13fc4fb886e172cc39fec | [] | no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10T06:29:42.908096 | 2009-08-31T09:20:31 | 2009-08-31T09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 103 | cpp | #include "wscNumber.h"
wscNumber::wscNumber(void)
{
}
wscNumber::~wscNumber(void)
{
}
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
] | [
[
[
1,
12
]
]
] |
c94152890c940b22bdb79f243c4f1585d5936f63 | 024d621c20595be82b4622f534278009a684e9b7 | /SupportPosCalculator.h | a5e6a26a02bc832a3e52b38065da83d11c7d94e0 | [] | no_license | tj10200/Simple-Soccer | 98a224c20b5e0b66f0e420d7c312a6cf6527069b | 486a4231ddf66ae5984713a177297b0f9c83015f | refs/heads/master | 2021-01-19T09:02:02.791225 | 2011-03-15T01:38:15 | 2011-03-15T01:38:15 | 1,480,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,396 | h | #ifndef SUPPORTING_POS_CALCULATOR_H
#define SUPPORTING_POS_CALCULATOR_H
#include "GameHeaders.h"
#include "Player.h"
class SupportPosCalculator
{
private:
D3DXVECTOR2 **regions,
goal,
RegSize;
Player *teammate,
*oppTeam,
*ballCarrier;
int rows,
cols,
numPlayers,
homeTeamIdxOffset;
double **passPotential,
**goalPotential,
**supportRegions,
**distValue;
bool regionsAvail;
void passPotentialCalc ();
void goalPotentialCalc ();
void distFromAttackerCalc();
void setBallCarrier ();
public:
SupportPosCalculator (D3DXVECTOR2 **Regs, D3DXVECTOR2 Goal, Player *sameTeam,
Player *opposing, int RegRows, int RegCols,
int players, bool isHomeTeam, int regOffset){
regions = Regs;
goal = Goal;
teammate = sameTeam;
oppTeam = opposing;
passPotential = new double *[RegRows];
goalPotential = new double *[RegRows];
supportRegions = new double *[RegRows];
distValue = new double *[RegRows];
for (int x = 0; x < RegRows; x++)
{
passPotential[x] = new double [RegCols];
goalPotential[x] = new double [RegCols];
supportRegions[x]= new double [RegCols];
distValue[x] = new double [RegCols];
}
rows = RegRows;
cols = RegCols;
numPlayers = players;
homeTeamIdxOffset = regOffset;
regionsAvail = false;
}
D3DXVECTOR2 getBestSupportPos ();
double getPassPotential ( int regX,
int regY);
double getGoalPotential ( int regX,
int regY);
Player *getClosestTeammate ( Player p,
Player *team);
Player *getClosestToTgt ( Player *team,
D3DXVECTOR2 tgt);
D3DXVECTOR2 getGoalShot ( Player *p);
D3DXVECTOR2 getPassShot ( Player *p,
Player *team);
void calcSupportingRegions ( Player *ballCarrier);
D3DXVECTOR2 getSupportPos ( Player *p,
Player *ball);
bool isShotSafe ( D3DXVECTOR2 startLoc,
D3DXVECTOR2 endLoc);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
84
]
]
] |
fefc953311bbdd7ec91f1d0047afbc4eb01ce354 | 10c14a95421b63a71c7c99adf73e305608c391bf | /gui/core/qsize.cpp | a55b26ea65d32ffc8b573f00f2e2391ec6a953df | [] | no_license | eaglezzb/wtlcontrols | 73fccea541c6ef1f6db5600f5f7349f5c5236daa | 61b7fce28df1efe4a1d90c0678ec863b1fd7c81c | refs/heads/master | 2021-01-22T13:47:19.456110 | 2009-05-19T10:58:42 | 2009-05-19T10:58:42 | 33,811,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,576 | cpp | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsize.h"
// #include "qdatastream.h"
// #include "qdebug.h"
QT_BEGIN_NAMESPACE
/*!
\class QSize
\ingroup multimedia
\brief The QSize class defines the size of a two-dimensional
object using integer point precision.
A size is specified by a width() and a height(). It can be set in
the constructor and changed using the setWidth(), setHeight(), or
scale() functions, or using arithmetic operators. A size can also
be manipulated directly by retrieving references to the width and
height using the rwidth() and rheight() functions. Finally, the
width and height can be swapped using the transpose() function.
The isValid() function determines if a size is valid (a valid size
has both width and height greater than zero). The isEmpty()
function returns true if either of the width and height is less
than, or equal to, zero, while the isNull() function returns true
only if both the width and the height is zero.
Use the expandedTo() function to retrieve a size which holds the
maximum height and width of \e this size and a given
size. Similarly, the boundedTo() function returns a size which
holds the minimum height and width of \e this size and a given
size.
QSize objects can be streamed as well as compared.
\sa QSizeF, QPoint, QRect
*/
/*****************************************************************************
QSize member functions
*****************************************************************************/
/*!
\fn QSize::QSize()
Constructs a size with an invalid width and height (i.e., isValid()
returns false).
\sa isValid()
*/
/*!
\fn QSize::QSize(int width, int height)
Constructs a size with the given \a width and \a height.
\sa setWidth(), setHeight()
*/
/*!
\fn bool QSize::isNull() const
Returns true if both the width and height is 0; otherwise returns
false.
\sa isValid(), isEmpty()
*/
/*!
\fn bool QSize::isEmpty() const
Returns true if either of the width and height is less than or
equal to 0; otherwise returns false.
\sa isNull(), isValid()
*/
/*!
\fn bool QSize::isValid() const
Returns true if both the width and height is equal to or greater
than 0; otherwise returns false.
\sa isNull(), isEmpty()
*/
/*!
\fn int QSize::width() const
Returns the width.
\sa height(), setWidth()
*/
/*!
\fn int QSize::height() const
Returns the height.
\sa width(), setHeight()
*/
/*!
\fn void QSize::setWidth(int width)
Sets the width to the given \a width.
\sa rwidth(), width(), setHeight()
*/
/*!
\fn void QSize::setHeight(int height)
Sets the height to the given \a height.
\sa rheight(), height(), setWidth()
*/
/*!
Swaps the width and height values.
\sa setWidth(), setHeight()
*/
void QSize::transpose()
{
int tmp = wd;
wd = ht;
ht = tmp;
}
/*!
\fn void QSize::scale(int width, int height, Qt::AspectRatioMode mode)
Scales the size to a rectangle with the given \a width and \a
height, according to the specified \a mode:
\list
\i If \a mode is Qt::IgnoreAspectRatio, the size is set to (\a width, \a height).
\i If \a mode is Qt::KeepAspectRatio, the current size is scaled to a rectangle
as large as possible inside (\a width, \a height), preserving the aspect ratio.
\i If \a mode is Qt::KeepAspectRatioByExpanding, the current size is scaled to a rectangle
as small as possible outside (\a width, \a height), preserving the aspect ratio.
\endlist
Example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 0
\sa setWidth(), setHeight()
*/
/*!
\fn void QSize::scale(const QSize &size, Qt::AspectRatioMode mode)
\overload
Scales the size to a rectangle with the given \a size, according to
the specified \a mode.
*/
void QSize::scale(const QSize &s, Qt::AspectRatioMode mode)
{
if (mode == Qt::IgnoreAspectRatio || wd == 0 || ht == 0) {
wd = s.wd;
ht = s.ht;
} else {
bool useHeight;
qint64 rw = qint64(s.ht) * qint64(wd) / qint64(ht);
if (mode == Qt::KeepAspectRatio) {
useHeight = (rw <= s.wd);
} else { // mode == Qt::KeepAspectRatioByExpanding
useHeight = (rw >= s.wd);
}
if (useHeight) {
wd = rw;
ht = s.ht;
} else {
ht = qint32(qint64(s.wd) * qint64(ht) / qint64(wd));
wd = s.wd;
}
}
}
/*!
\fn int &QSize::rwidth()
Returns a reference to the width.
Using a reference makes it possible to manipulate the width
directly. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 1
\sa rheight(), setWidth()
*/
/*!
\fn int &QSize::rheight()
Returns a reference to the height.
Using a reference makes it possible to manipulate the height
directly. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 2
\sa rwidth(), setHeight()
*/
/*!
\fn QSize &QSize::operator+=(const QSize &size)
Adds the given \a size to \e this size, and returns a reference to
this size. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 3
*/
/*!
\fn QSize &QSize::operator-=(const QSize &size)
Subtracts the given \a size from \e this size, and returns a
reference to this size. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 4
*/
/*!
\fn QSize &QSize::operator*=(qreal factor)
\overload
Multiplies both the width and height by the given \a factor, and
returns a reference to the size.
Note that the result is rounded to the nearest integer.
\sa scale()
*/
/*!
\fn bool operator==(const QSize &s1, const QSize &s2)
\relates QSize
Returns true if \a s1 and \a s2 are equal; otherwise returns false.
*/
/*!
\fn bool operator!=(const QSize &s1, const QSize &s2)
\relates QSize
Returns true if \a s1 and \a s2 are different; otherwise returns false.
*/
/*!
\fn const QSize operator+(const QSize &s1, const QSize &s2)
\relates QSize
Returns the sum of \a s1 and \a s2; each component is added separately.
*/
/*!
\fn const QSize operator-(const QSize &s1, const QSize &s2)
\relates QSize
Returns \a s2 subtracted from \a s1; each component is subtracted
separately.
*/
/*!
\fn const QSize operator*(const QSize &size, qreal factor)
\relates QSize
Multiplies the given \a size by the given \a factor, and returns
the result rounded to the nearest integer.
\sa QSize::scale()
*/
/*!
\fn const QSize operator*(qreal factor, const QSize &size)
\overload
\relates QSize
Multiplies the given \a size by the given \a factor, and returns
the result rounded to the nearest integer.
*/
/*!
\fn QSize &QSize::operator/=(qreal divisor)
\overload
Divides both the width and height by the given \a divisor, and
returns a reference to the size.
Note that the result is rounded to the nearest integer.
\sa QSize::scale()
*/
/*!
\fn const QSize operator/(const QSize &size, qreal divisor)
\relates QSize
\overload
Divides the given \a size by the given \a divisor, and returns the
result rounded to the nearest integer.
\sa QSize::scale()
*/
/*!
\fn QSize QSize::expandedTo(const QSize & otherSize) const
Returns a size holding the maximum width and height of this size
and the given \a otherSize.
\sa boundedTo(), scale()
*/
/*!
\fn QSize QSize::boundedTo(const QSize & otherSize) const
Returns a size holding the minimum width and height of this size
and the given \a otherSize.
\sa expandedTo(), scale()
*/
/*****************************************************************************
QSize stream functions
*****************************************************************************/
// #ifndef QT_NO_DATASTREAM
// /*!
// \fn QDataStream &operator<<(QDataStream &stream, const QSize &size)
// \relates QSize
//
// Writes the given \a size to the given \a stream, and returns a
// reference to the stream.
//
// \sa {Format of the QDataStream Operators}
// */
//
// QDataStream &operator<<(QDataStream &s, const QSize &sz)
// {
// if (s.version() == 1)
// s << (qint16)sz.width() << (qint16)sz.height();
// else
// s << (qint32)sz.width() << (qint32)sz.height();
// return s;
// }
//
// /*!
// \fn QDataStream &operator>>(QDataStream &stream, QSize &size)
// \relates QSize
//
// Reads a size from the given \a stream into the given \a size, and
// returns a reference to the stream.
//
// \sa {Format of the QDataStream Operators}
// */
//
// QDataStream &operator>>(QDataStream &s, QSize &sz)
// {
// if (s.version() == 1) {
// qint16 w, h;
// s >> w; sz.rwidth() = w;
// s >> h; sz.rheight() = h;
// }
// else {
// qint32 w, h;
// s >> w; sz.rwidth() = w;
// s >> h; sz.rheight() = h;
// }
// return s;
// }
// #endif // QT_NO_DATASTREAM
//
// #ifndef QT_NO_DEBUG_STREAM
// QDebug operator<<(QDebug dbg, const QSize &s) {
// dbg.nospace() << "QSize(" << s.width() << ", " << s.height() << ')';
// return dbg.space();
// }
// #endif
/*!
\class QSizeF
\brief The QSizeF class defines the size of a two-dimensional object
using floating point precision.
\ingroup multimedia
A size is specified by a width() and a height(). It can be set in
the constructor and changed using the setWidth(), setHeight(), or
scale() functions, or using arithmetic operators. A size can also
be manipulated directly by retrieving references to the width and
height using the rwidth() and rheight() functions. Finally, the
width and height can be swapped using the transpose() function.
The isValid() function determines if a size is valid. A valid size
has both width and height greater than or equal to zero. The
isEmpty() function returns true if either of the width and height
is \e less than (or equal to) zero, while the isNull() function
returns true only if both the width and the height is zero.
Use the expandedTo() function to retrieve a size which holds the
maximum height and width of this size and a given
size. Similarly, the boundedTo() function returns a size which
holds the minimum height and width of this size and a given size.
The QSizeF class also provides the toSize() function returning a
QSize copy of this size, constructed by rounding the width and
height to the nearest integers.
QSizeF objects can be streamed as well as compared.
\sa QSize, QPointF, QRectF
*/
/*****************************************************************************
QSizeF member functions
*****************************************************************************/
/*!
\fn QSizeF::QSizeF()
Constructs an invalid size.
\sa isValid()
*/
/*!
\fn QSizeF::QSizeF(const QSize &size)
Constructs a size with floating point accuracy from the given \a
size.
\sa toSize()
*/
/*!
\fn QSizeF::QSizeF(qreal width, qreal height)
Constructs a size with the given \a width and \a height.
*/
/*!
\fn bool QSizeF::isNull() const
Returns true if both the width and height is 0; otherwise returns
false.
\sa isValid(), isEmpty()
*/
/*!
\fn bool QSizeF::isEmpty() const
Returns true if either of the width and height is less than or
equal to 0; otherwise returns false.
\sa isNull(), isValid()
*/
/*!
\fn bool QSizeF::isValid() const
Returns true if both the width and height is equal to or greater
than 0; otherwise returns false.
\sa isNull(), isEmpty()
*/
/*!
\fn int QSizeF::width() const
Returns the width.
\sa height(), setWidth()
*/
/*!
\fn int QSizeF::height() const
Returns the height.
\sa width(), setHeight()
*/
/*!
\fn void QSizeF::setWidth(qreal width)
Sets the width to the given \a width.
\sa width(), rwidth(), setHeight()
*/
/*!
\fn void QSizeF::setHeight(qreal height)
Sets the height to the given \a height.
\sa height(), rheight(), setWidth()
*/
/*!
\fn QSize QSizeF::toSize() const
Returns an integer based copy of this size.
Note that the coordinates in the returned size will be rounded to
the nearest integer.
\sa QSizeF()
*/
/*!
Swaps the width and height values.
\sa setWidth(), setHeight()
*/
void QSizeF::transpose()
{
qreal tmp = wd;
wd = ht;
ht = tmp;
}
/*!
\fn void QSizeF::scale(qreal width, qreal height, Qt::AspectRatioMode mode)
Scales the size to a rectangle with the given \a width and \a
height, according to the specified \a mode.
\list
\i If \a mode is Qt::IgnoreAspectRatio, the size is set to (\a width, \a height).
\i If \a mode is Qt::KeepAspectRatio, the current size is scaled to a rectangle
as large as possible inside (\a width, \a height), preserving the aspect ratio.
\i If \a mode is Qt::KeepAspectRatioByExpanding, the current size is scaled to a rectangle
as small as possible outside (\a width, \a height), preserving the aspect ratio.
\endlist
Example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 5
\sa setWidth(), setHeight()
*/
/*!
\fn void QSizeF::scale(const QSizeF &size, Qt::AspectRatioMode mode)
\overload
Scales the size to a rectangle with the given \a size, according to
the specified \a mode.
*/
void QSizeF::scale(const QSizeF &s, Qt::AspectRatioMode mode)
{
if (mode == Qt::IgnoreAspectRatio || qIsNull(wd) || qIsNull(ht)) {
wd = s.wd;
ht = s.ht;
} else {
bool useHeight;
qreal rw = s.ht * wd / ht;
if (mode == Qt::KeepAspectRatio) {
useHeight = (rw <= s.wd);
} else { // mode == Qt::KeepAspectRatioByExpanding
useHeight = (rw >= s.wd);
}
if (useHeight) {
wd = rw;
ht = s.ht;
} else {
ht = s.wd * ht / wd;
wd = s.wd;
}
}
}
/*!
\fn int &QSizeF::rwidth()
Returns a reference to the width.
Using a reference makes it possible to manipulate the width
directly. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 6
\sa rheight(), setWidth()
*/
/*!
\fn int &QSizeF::rheight()
Returns a reference to the height.
Using a reference makes it possible to manipulate the height
directly. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 7
\sa rwidth(), setHeight()
*/
/*!
\fn QSizeF &QSizeF::operator+=(const QSizeF &size)
Adds the given \a size to this size and returns a reference to
this size. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 8
*/
/*!
\fn QSizeF &QSizeF::operator-=(const QSizeF &size)
Subtracts the given \a size from this size and returns a reference
to this size. For example:
\snippet doc/src/snippets/code/src_corelib_tools_qsize.cpp 9
*/
/*!
\fn QSizeF &QSizeF::operator*=(qreal factor)
\overload
Multiplies both the width and height by the given \a factor and
returns a reference to the size.
\sa scale()
*/
/*!
\fn bool operator==(const QSizeF &s1, const QSizeF &s2)
\relates QSizeF
Returns true if \a s1 and \a s2 are equal; otherwise returns
false.
*/
/*!
\fn bool operator!=(const QSizeF &s1, const QSizeF &s2)
\relates QSizeF
Returns true if \a s1 and \a s2 are different; otherwise returns false.
*/
/*!
\fn const QSizeF operator+(const QSizeF &s1, const QSizeF &s2)
\relates QSizeF
Returns the sum of \a s1 and \a s2; each component is added separately.
*/
/*!
\fn const QSizeF operator-(const QSizeF &s1, const QSizeF &s2)
\relates QSizeF
Returns \a s2 subtracted from \a s1; each component is subtracted
separately.
*/
/*!
\fn const QSizeF operator*(const QSizeF &size, qreal factor)
\overload
\relates QSizeF
Multiplies the given \a size by the given \a factor and returns
the result.
\sa QSizeF::scale()
*/
/*!
\fn const QSizeF operator*(qreal factor, const QSizeF &size)
\overload
\relates QSizeF
Multiplies the given \a size by the given \a factor and returns
the result.
*/
/*!
\fn QSizeF &QSizeF::operator/=(qreal divisor)
\overload
Divides both the width and height by the given \a divisor and
returns a reference to the size.
\sa scale()
*/
/*!
\fn const QSizeF operator/(const QSizeF &size, qreal divisor)
\relates QSizeF
\overload
Divides the given \a size by the given \a divisor and returns the
result.
\sa QSizeF::scale()
*/
/*!
\fn QSizeF QSizeF::expandedTo(const QSizeF & otherSize) const
Returns a size holding the maximum width and height of this size
and the given \a otherSize.
\sa boundedTo(), scale()
*/
/*!
\fn QSizeF QSizeF::boundedTo(const QSizeF & otherSize) const
Returns a size holding the minimum width and height of this size
and the given \a otherSize.
\sa expandedTo(), scale()
*/
/*****************************************************************************
QSizeF stream functions
*****************************************************************************/
// #ifndef QT_NO_DATASTREAM
// /*!
// \fn QDataStream &operator<<(QDataStream &stream, const QSizeF &size)
// \relates QSizeF
//
// Writes the the given \a size to the given \a stream and returns a
// reference to the stream.
//
// \sa {Format of the QDataStream Operators}
// */
//
// QDataStream &operator<<(QDataStream &s, const QSizeF &sz)
// {
// s << double(sz.width()) << double(sz.height());
// return s;
// }
//
// /*!
// \fn QDataStream &operator>>(QDataStream &stream, QSizeF &size)
// \relates QSizeF
//
// Reads a size from the given \a stream into the given \a size and
// returns a reference to the stream.
//
// \sa {Format of the QDataStream Operators}
// */
//
// QDataStream &operator>>(QDataStream &s, QSizeF &sz)
// {
// double w, h;
// s >> w;
// s >> h;
// sz.setWidth(qreal(w));
// sz.setHeight(qreal(h));
// return s;
// }
// #endif // QT_NO_DATASTREAM
//
// #ifndef QT_NO_DEBUG_STREAM
// QDebug operator<<(QDebug dbg, const QSizeF &s) {
// dbg.nospace() << "QSizeF(" << s.width() << ", " << s.height() << ')';
// return dbg.space();
// }
// #endif
QT_END_NAMESPACE
| [
"zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7"
] | [
[
[
1,
824
]
]
] |
95b8bd0d1d67aecef62debe119e19bdfbd551fea | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/plugins/zeropad/Windows/gui.cpp | 09a8f8716b679d6bee710198996bd75b2d890fbb | [] | 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 | 3,243 | cpp | /* ZeroPAD - author: zerofrog(@gmail.com)
* Copyright (C) 2006-2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "win.h"
void SaveConfig()
{
char *szTemp;
char szIniFile[256], szValue[256], szProf[256];
int i, j;
GetModuleFileName(GetModuleHandle((LPCSTR)hInst), szIniFile, 256);
szTemp = strrchr(szIniFile, '\\');
if (!szTemp) return;
strcpy(szTemp, "\\inis\\zeropad.ini");
for (j = 0; j < 2; j++)
{
for (i = 0; i < PADKEYS; i++)
{
sprintf(szProf, "%d_%d", j, i);
sprintf(szValue, "%d", conf.keys[j][i]);
WritePrivateProfileString("Interface", szProf, szValue, szIniFile);
}
}
sprintf(szValue, "%u", conf.log);
WritePrivateProfileString("Interface", "Logging", szValue, szIniFile);
}
void LoadConfig()
{
FILE *fp;
char *szTemp;
char szIniFile[256], szValue[256], szProf[256];
int i, j;
memset(&conf, 0, sizeof(conf));
#ifdef _WIN32
conf.keys[0][0] = 'W'; // L2
conf.keys[0][1] = 'O'; // R2
conf.keys[0][2] = 'A'; // L1
conf.keys[0][3] = ';'; // R1
conf.keys[0][4] = 'I'; // TRIANGLE
conf.keys[0][5] = 'L'; // CIRCLE
conf.keys[0][6] = 'K'; // CROSS
conf.keys[0][7] = 'J'; // SQUARE
conf.keys[0][8] = 'V'; // SELECT
conf.keys[0][11] = 'N'; // START
conf.keys[0][12] = 'E'; // UP
conf.keys[0][13] = 'F'; // RIGHT
conf.keys[0][14] = 'D'; // DOWN
conf.keys[0][15] = 'S'; // LEFT
#endif
conf.log = 0;
GetModuleFileName(GetModuleHandle((LPCSTR)hInst), szIniFile, 256);
szTemp = strrchr(szIniFile, '\\');
if (!szTemp) return ;
strcpy(szTemp, "\\inis\\zeropad.ini");
fp = fopen("inis\\zeropad.ini", "rt");//check if usbnull.ini really exists
if (!fp)
{
CreateDirectory("inis", NULL);
SaveConfig();//save and return
return ;
}
fclose(fp);
for (j = 0; j < 2; j++)
{
for (i = 0; i < PADKEYS; i++)
{
sprintf(szProf, "%d_%d", j, i);
GetPrivateProfileString("Interface", szProf, NULL, szValue, 20, szIniFile);
conf.keys[j][i] = strtoul(szValue, NULL, 10);
}
}
GetPrivateProfileString("Interface", "Logging", NULL, szValue, 20, szIniFile);
conf.log = strtoul(szValue, NULL, 10);
}
void SysMessage(char *fmt, ...)
{
va_list list;
char tmp[512];
va_start(list, fmt);
vsprintf(tmp, fmt, list);
va_end(list);
MessageBox(0, tmp, "PADwinKeyb Msg", 0);
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
] | [
[
[
1,
110
]
]
] |
c7a4570fcfd2d39c0de0ce3915e5ebeca466bfc9 | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Include/Nuclex/Video/VertexDeclaration.h | 618d553b5eafe32bd1783280e2056fe7a78de2bf | [] | no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,912 | h | // //
// # # ### # # -= Nuclex Library =- //
// ## # # # ## ## VertexDeclaration.h - Vertex declaration //
// ### # # ### //
// # ### # ### Defines the components of a vertex and their memory layout //
// # ## # # ## ## //
// # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#ifndef NUCLEX_VIDEO_VERTEXDECLARATION_H
#define NUCLEX_VIDEO_VERTEXDECLARATION_H
#include "Nuclex/Nuclex.h"
#include "Nuclex/Support/Exception.h"
#include <vector>
namespace Nuclex { namespace Video {
// //
// Nuclex::Video::VertexDeclaration //
// //
/// Vertex Declaration
/** Defines the structure of a vertex stored in a vertex buffer.
Required for the graphics adapter to extract the data it needs
for rendering from each vertex
*/
class VertexDeclaration {
public:
/// How a vertex component will be used
enum Usage {
U_POSITION = 0,
U_BLENDWEIGHT,
U_BLENDINDICES,
U_NORMAL,
U_PSIZE,
U_TEXCOORD,
U_TANGENT,
U_BINORMAL,
U_TESSFACTOR,
U_POSITIONT,
U_COLOR,
U_FOG,
U_DEPTH,
U_SAMPLE
};
/// Method to use for processing the vertex
enum Method {
M_DEFAULT = 0,
M_PARTIALU,
M_PARTIALV,
M_CROSSUV, ///< Normal
M_UV,
M_LOOKUP, ///< Lookup a displacement map
M_LOOKUPPRESAMPLED ///< Lookup a pre-sampled displacement map
};
/// Data type of a vertex component
enum Type {
T_NONE = 0, ///< When the type field in a decl is unused.
T_FLOAT1, ///< 1D float expanded to (value, 0., 0., 1.)
T_FLOAT2, ///< 2D float expanded to (value, value, 0., 1.)
T_FLOAT3, ///< 3D float expanded to (value, value, value, 1.)
T_FLOAT4, ///< 4D float
T_COLOR, ///< 4D packed unsigned bytes mapped to 0. to 1. range. Input is in D3DCOLOR format (ARGB) expanded to (R, G, B, A)
T_UBYTE4, ///< 4D unsigned byte
T_SHORT2, ///< 2D signed short expanded to (value, value, 0., 1.)
T_SHORT4 ///< 4D signed short
};
/// A vertex component
struct Element {
/// Constructor
/** Initializes an instance of element
@param nOffset Offset in bytes within the stream to read from
@param eType Variable type of the input data
@param eMethod Predefined operations to be performed by the tesselator
@param eUsage How the element will be used
@param cUsageIndex Additional usage index (if you have multiple elements with
the same type)
*/
inline Element(unsigned short nOffset,
Type eType, Method eMethod, Usage eUsage,
unsigned char cUsageIndex) :
nOffset(nOffset),
eType(eType),
eMethod(eMethod),
eUsage(eUsage),
cUsageIndex(cUsageIndex) {}
/// Copy constructor
/** Initializes an instance of Element as copy of an existing instance
@param Other Element to copy
*/
inline Element(const Element &Other) :
nOffset(Other.nOffset),
eType(Other.eType),
eMethod(Other.eMethod),
eUsage(Other.eUsage),
cUsageIndex(Other.cUsageIndex) {}
unsigned short nOffset; ///< Offset in the stream in bytes
Type eType; ///< Data type
Method eMethod; ///< Processing method
Usage eUsage; ///< Semantics
unsigned char cUsageIndex; ///< Semantic index
};
/// Constructor
NUCLEX_API inline VertexDeclaration() :
m_nCurrentOffset(0),
m_nSize(0) {}
/// Destructor
NUCLEX_API inline ~VertexDeclaration() {}
/// Build position element
NUCLEX_API inline static Element Position(unsigned char cUsageIndex = 0, unsigned short nOffset = 0) {
return Element(nOffset, T_FLOAT3, M_DEFAULT, U_POSITION, cUsageIndex);
}
/// Build pretransformed position element
NUCLEX_API inline static Element PretransformedPosition(unsigned char cUsageIndex = 0, unsigned short nOffset = 0) {
return Element(nOffset, T_FLOAT4, M_DEFAULT, U_POSITIONT, cUsageIndex);
}
/// Build normal vector element
NUCLEX_API inline static Element Normal(unsigned char cUsageIndex = 0, unsigned short nOffset = 0) {
return Element(nOffset, T_FLOAT3, M_DEFAULT, U_NORMAL, cUsageIndex);
}
/// Build color element
NUCLEX_API inline static Element Color(unsigned char cUsageIndex = 0, unsigned short nOffset = 0) {
return Element(nOffset, T_COLOR, M_DEFAULT, U_COLOR, cUsageIndex);
}
/// Build texture coordinate element
NUCLEX_API inline static Element TexCoord(unsigned char cUsageIndex = 0, unsigned short nOffset = 0) {
return Element(nOffset, T_FLOAT2, M_DEFAULT, U_TEXCOORD, cUsageIndex);
}
//
// VertexDeclaration implementation
//
public:
/// Append a component to the vertex declaration
NUCLEX_API inline VertexDeclaration &operator <<(const Element &ElementToAdd) {
Element e(ElementToAdd);
unsigned short nSize;
switch(e.eType) {
case T_NONE: break;
case T_FLOAT1: { nSize = 4; break; }
case T_FLOAT2: { nSize = 8; break; }
case T_FLOAT3: { nSize = 12; break; }
case T_FLOAT4: { nSize = 16; break; }
case T_COLOR: { nSize = 4; break; }
case T_UBYTE4: { nSize = 4; break; }
case T_SHORT2: { nSize = 4; break; }
case T_SHORT4: { nSize = 8; break; }
default: throw UnexpectedException(
"Nuclex::VertexDeclaration::operator <<()", "Unknown element type"
);
}
if(e.nOffset == 0) {
e.nOffset = m_nCurrentOffset;
m_nCurrentOffset += nSize;
}
if(e.nOffset + nSize > m_nSize)
m_nSize = e.nOffset + nSize;
m_Elements.push_back(e);
return *this;
}
/// Total number of bytes for a vertex
NUCLEX_API inline unsigned short getSize() const { return m_nSize; }
private:
/// A vector of declaration elements
typedef std::vector<Element> ElementVector;
/// The elements of the vertex declaration
ElementVector m_Elements;
/// Accumulated vertex offset
unsigned short m_nCurrentOffset;
/// Total space required for a single vertex in this declaration
unsigned short m_nSize;
};
}} // namespace Nuclex::Video
#endif // NUCLEX_VIDEO_VERTEXDECLARATION_H
| [
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
] | [
[
[
1,
191
]
]
] |
6e9d1065c2947aeede2f90632e405ba4d048ae10 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhplay/dhplay/playmanage.h | cd5b2080be55008805f07504480b472884fcaf86 | [] | no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,775 | h | /********************************************************************
created: 2006/01/10
created: 10:1:2006 8:51
filename: playmanage.h
file base: playmanage
file ext: h
author: chenmy
purpose:
*********************************************************************/
#ifndef PLAYMANAGE_H
#define PLAYMANAGE_H
#include "stdafx.h"
#include "play.h"
#include "callback.h"
#include "HI_PLAY_AudioIN.h"
#ifdef DHVECPLAY
#include "dhvecplay.h"
#else
#include "dhplay.h"
#endif
/*#include "Multimon.H"*/
#include <vector>
#include "AccurateTimer.h"
#define MAX_CHUNKSIZE 65536
//sdk的版本定义
#ifdef DHVECPLAY
//高16位表示当前的build号。9~16位表示主版本号,1~8位表示次版本号。
#define VERSION 0x1207 //表示xx.yy
#define BUILD_VER 0x0200 //编译版本
#else
#define VERSION 28
#define BUILD_VER 3
#define MEND_VER 3
#endif
//端口状态
typedef enum _PORT_STATE
{
PORT_STATE_FREE,
PORT_STATE_BUSY
}PORT_STATE;
//系统信息(需要提供给用户的系统信息)
typedef struct _SYS_INFO
{
int nstatus; //系统支持状态(按位表示)
DWORD dwVersion; //SDK版本号
//。。。。 //其他系统信息
}SYS_INFO;
//消息相关信息
typedef struct _MSG_INFO {
BOOL nMsgFlag; //1设置有效
HWND hWnd; //消息窗口句柄
UINT nMsg; //消息
_MSG_INFO(){
nMsgFlag = FALSE ;
hWnd = NULL ;
}
}MSG_INFO;
struct DeviceInfo
{
LPSTR lpDeviceDescription ;
LPSTR lpDeviceName ;
// HMONITOR* hMonitor ;
} ;
//播放管理类定义
class CDHPLAY_MANAGE
{
public:
int m_nSoundPort; //当前音频端口,独占方式
std::vector<int> m_nShareSoundPortList ;//共享声音播放端口列表
// int m_volume;
int m_nFluency[FUNC_MAX_PORT];
int m_nQuality[FUNC_MAX_PORT]; //画质
int m_nStreamMode[FUNC_MAX_PORT];
int m_nTimer1Cnt;
SYS_INFO m_pSysInfo; //系统信息,包括显卡、声卡等一些系统信息
char m_DLLPath[256+1024];//playsdk.dll所在的路径
std::vector<DeviceInfo*>DeviceInfoList ;
int m_supportmultidevice;
int m_error[FUNC_MAX_PORT] ; //错误类型
CRITICAL_SECTION m_interfaceCritSec[FUNC_MAX_PORT] ;
CDHPlay *pDHPlay[FUNC_MAX_PORT]; //播放对象指针表
CDHAVData *pDHFile[FUNC_MAX_PORT] ; //播放文件指针表
CDisplay *pDisplay[FUNC_MAX_PORT] ;//显示类指针表
CCallback *pCallback[FUNC_MAX_PORT]; //回调指针表
MSG_INFO *pMsgFileEnd[FUNC_MAX_PORT];//文件播放结束消息
MSG_INFO *pMsgEncChang[FUNC_MAX_PORT]; //编码格式改变消息
PORT_STATE m_ePortState[FUNC_MAX_PORT];
DWORD m_dwTimerType[FUNC_MAX_PORT]; //端口对应的定时器类型
CACTimerManager m_ACTimerManager;
CRITICAL_SECTION m_PortStateCrit;
CHI_PLAY_AudioIn* pAudioRecored;
DhRenderManager m_YUVRenderMng;
//主要程序函数有:
CDHPLAY_MANAGE();
~CDHPLAY_MANAGE();
int GetCaps(); //获取当前系统信息,按位取;
int CheckPort(LONG nPort); //检测端口是否正常可控
DWORD GetError(LONG nPort); //获取错误码
DWORD GetSdkVersion(); //获取版本号
DWORD GetFileHeadLenth(); //获取文件头的长度
BOOL SetPortState(LONG lPort, PORT_STATE eState); //设置端口状态
BOOL GetPortState(LONG lPort, PORT_STATE *peState); //获取端口状态
int OpenYuvRender(int port, HWND hwnd, void (CALLBACK* DrawFun)(int nPort,HDC hDc));
int RenderYuv(int port, unsigned char* py, unsigned char* pu, unsigned char* pv, int width, int height);
int CloseYuvRender(int port);
protected:
private:
void init_sysinfo();
};
extern CDHPLAY_MANAGE g_cDHPlayManage;
#endif
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
] | [
[
[
1,
131
]
]
] |
b936f3a955ecefbb09da7befe095538714cdc373 | 638c9b075ac3bfdf3b2d96f1dd786684d7989dcd | /spark/source/SpTexturedQuadSg.h | 5f110bb67abed12a1c4f9514c69bcfe0d8507fca | [] | no_license | cycle-zz/archives | 4682d6143b9057b21af9845ecbd42d7131750b1b | f92b677342e75e5cb7743a0d1550105058aff8f5 | refs/heads/master | 2021-05-27T21:07:16.240438 | 2010-03-18T08:01:46 | 2010-03-18T08:01:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,848 | h | // #############################################################################
//! SpTexturedQuadSg.h : Quad-based stream geometry w/ texturing support
//
// Created : Aug 2004
// Copyright : (C) 2004 by Derek Gerstmann
// Email : [email protected]
//
// #############################################################################
// =============================================================================
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// =============================================================================
#ifndef SP_TEXTURED_QUAD_SG_H
#define SP_TEXTURED_QUAD_SG_H
#include "SpGlHeaders.h"
#include "SpStreamGeometry.h"
//----------------------------------------------------------------------------
namespace Spark:
{
//----------------------------------------------------------------------------
//! Quad-based stream geometry w/ texturing support
//----------------------------------------------------------------------------
class SpTexturedQuadSg : public SpStreamGeometry
{
//! Construction:
public:
SpTexturedQuadSg(
float fMinX = 0.0f, float fMinY = 0.0f,
float fMaxX = 1.0f, float fMaxY = 1.0f, float fZ=0.5f
float fMinS = 0.0f, float fMinT = 0.0f,
float fMaxS = 1.0f, float fMaxT = 1.0f)
) :
m_fMinX(fMinX), m_fMinY(fMinY),
m_fMaxX(fMaxX), m_fMaxY(fMaxY), m_fZ(fZ),
m_fMinS(fMinS), m_fMinT(fMinT),
m_fMaxS(fMaxS), m_fMaxT(fMaxT)
{
// EMPTY!
}
virtual ~SpTexturedQuadSg()
{
// EMPTY!
}
//! Operations:
public:
virtual void render()
{
glNormal3f(m_fMinX, m_fMinY, 1.0f);
glBegin(GL_QUADS);
{
glTexCoord2f(m_fMinS, m_fMinT); glVertex3f(m_fMinX, m_fMinY, m_fZ);
glTexCoord2f(m_fMaxS, m_fMinT); glVertex3f(m_fMaxX, m_fMinY, m_fZ);
glTexCoord2f(m_fMaxS, m_fMaxT); glVertex3f(m_fMaxX, m_fMaxY, m_fZ);
glTexCoord2f(m_fMinS, m_fMaxT); glVertex3f(m_fMinX, m_fMaxY, m_fZ);
}
glEnd();
}
inline void setVertexCoordRect(
float fMinX, float fMinY, float fMaxX, float fMaxY, float fZ = 0.5f)
{
m_fMinX = fMinX; m_fMaxX = fMaxX;
m_fMinY = fMinY; m_fMaxY = fMaxY;
m_fZ = fZ;
}
inline void setTexCoordRect(
float fMinS, float fMinT, float fMaxS, float fMaxT)
{
m_fMinS = fMinS; m_fMaxS = fMaxS;
m_fMinT = fMinT; m_fMaxT = fMaxT;
}
protected:
float m_fMinX;
float m_fMinY;
float m_fMaxX;
float m_fMaxY;
float m_fZ;
float m_fMinS;
float m_fMaxS;
float m_fMinT;
float m_fMaxT;
};
//----------------------------------------------------------------------------
} // end namespace: Spark
#endif | [
"[email protected]"
] | [
[
[
1,
111
]
]
] |
8cda3b78d0470c515696a6493e7088e0f425f110 | 8f8cc0ed96d272f1aee79becfc1138538abbefc9 | /prototype/bdk/BDK/Arithmetic_entropy_decoder.h | 99900ca63472238a8b7aaee0cf3eb793420cca67 | [] | no_license | BackupTheBerlios/picdatcom-svn | 0a417abb3b60df6aedb47c0eb52998d262e459b7 | 0696c6d6e0c7158ede88908257abea0e0a7e303c | refs/heads/master | 2016-09-02T07:52:18.882862 | 2010-06-10T22:43:50 | 2010-06-10T22:43:50 | 40,800,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,245 | h | // Arithmetic_entropy_decoder.h
//
// This header file defines the interfaces to the class Arithmetic_entropy_decoder
//
// This file was generate from a Dia Diagram using the xslt script file dia-uml2cpp.xsl
// which is copyright(c) Dave Klotzbach <[email protected]>
//
// The author asserts no additional copyrights on the derived product. Limitations
// on the uses of this file are the right and responsibility of authors of the source
// diagram.
//
// The dia-uml2cpp.xsl script 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.
//
// A copy of the GNU General Public License is available by writing to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.
//
#ifndef __ARITHMETIC_ENTROPY_DECODER_H__
#define __ARITHMETIC_ENTROPY_DECODER_H__
#include "ByteBuffer.h"
#include <fstream>
namespace BDK
{
#define CHIGH(i) ((i >> 16) & 0xFFFF)
#define SETCHIGH(c, ch) (c = (c & 0xFFFF) | ((ch << 16)& 0xFFFF0000))
class Arithmetic_entropy_decoder{
private:
//static fstream *file;
//static int count;
//static int id_count;
//int id;
public:
Arithmetic_entropy_decoder();
public:
virtual ~Arithmetic_entropy_decoder();
protected:
unsigned char d;
unsigned char cx;
unsigned int c_register;
unsigned int a_register;
static unsigned int qe[];
static unsigned int nmps[];
static unsigned int nlps[];
static unsigned int switcher[];
unsigned char* mps;
unsigned int* index;
int ct;
ByteBuffer* bytebuffer;
unsigned int b;
unsigned int b1;
unsigned int ii, qee;
unsigned int chigh;
protected:
virtual void decode();
void mps_exchange();
void lps_exchange();
void renormd();
virtual void bytein();
public:
unsigned char decoder(unsigned char cx_in);
virtual void initdec(ByteBuffer* bytebuffer, const int length, const unsigned int* default_mps, const unsigned int* default_index);
};
}
#endif // defined __ARITHMETIC_ENTROPY_DECODER_H__
| [
"uwebr@161c6524-834b-0410-aead-e7223efaf009"
] | [
[
[
1,
72
]
]
] |
9aedea3b5d55d80288ad9cd6bc094c2e7d84862f | d504537dae74273428d3aacd03b89357215f3d11 | /src/e6/e6_bbox.cpp | 2e08855b4a0bbb333b279b2feb477c784437f551 | [] | no_license | h0MER247/e6 | 1026bf9aabd5c11b84e358222d103aee829f62d7 | f92546fd1fc53ba783d84e9edf5660fe19b739cc | refs/heads/master | 2020-12-23T05:42:42.373786 | 2011-02-18T16:16:24 | 2011-02-18T16:16:24 | 237,055,477 | 1 | 0 | null | 2020-01-29T18:39:15 | 2020-01-29T18:39:14 | null | UTF-8 | C++ | false | false | 951 | cpp | #include "e6_BBox.h"
namespace e6
{
//
// ray-aabb intersection:
//
bool BBox::rayHitBox( const float o[3], const float d[3] ,float& tnear,float& tfar)
{
const static float EPSILON = 0.0001f;
static float t1,t2,t;
tnear = -0xffffff;
tfar = 0xffffff;
for ( int a=0; a<3; a++ ) {
if ( d[a]>-EPSILON && d[a]<EPSILON ) {
if ( o[a]<m[a] || o[a]>M[a] )
return 0;
} else {
t1=(m[a]-o[a])/d[a];
t2=(M[a]-o[a])/d[a];
if (t1>t2) { t=t1; t1=t2; t2=t; }
if (t1>tnear) tnear=t1;
if (t2<tfar) tfar=t2;
if (tnear>tfar || tfar<EPSILON)
return 0;
}
}
if (tnear>tfar || tfar<EPSILON)
return 0;
return 1;
}
} // e6
| [
"[email protected]"
] | [
[
[
1,
39
]
]
] |
a23c21c7e5151a57f955e62aaf1bddcad53d555a | cbdc078b00041668dd740917e1e781f74b6ea9f4 | /GiftFactoryCuda/src/TextureManager.cpp | 0503eb5e265dd1a40ae0040141a92e65edd6ab3b | [] | no_license | mireidril/gift-factory | f30d8075575af6a00a42d54bfdd4ad4c953f1936 | 4888b59b1ee25a107715742d0495e40b81752051 | refs/heads/master | 2020-04-13T07:19:09.351853 | 2011-12-16T11:36:05 | 2011-12-16T11:36:05 | 32,514,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | cpp | #include "TextureManager.hpp"
std::vector<TextureManager::Texture *> TextureManager::m_textures;
TextureManager::Texture* TextureManager::getTextIfExist(std::string name){
for(std::vector<Texture *>::iterator it = m_textures.begin(); it!=m_textures.end(); ++it) {
if( (*it)->texFileName == name)
return (*it);
}
return 0;
}
TextureManager::Texture* TextureManager::addAndLoadTexture(std::string name, std::string shaderUniformName){
// Init the texture data
Texture *tex = new Texture();
tex->texFileName = name;
tex->shaderUniformName = shaderUniformName;
// Load the texture image
#ifdef _WIN32
std::string texFile = "./textures/" + name;
#else
std::string texFile = "../textures/" + name;
#endif
std::cout << "loading : " << texFile << std::endl;
SDL_Surface *surf = IMG_Load(texFile.c_str());
tex->texPicture = surf;
// Add the texture to the list
m_textures.push_back(tex);
return m_textures[m_textures.size()-1];
}
| [
"celine.cogny@369dbe5e-add6-1733-379f-dc396ee97aaa",
"[email protected]@369dbe5e-add6-1733-379f-dc396ee97aaa"
] | [
[
[
1,
19
],
[
21,
31
]
],
[
[
20,
20
]
]
] |
d1d7bc332abd65d8a6948386ecc6b989a2bc1527 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak.Samples/Any.cpp | b0c2df7cea7875e1a0c46c6e686fa3c418082079 | [] | no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | cpp | #include <Halak.Samples/Samples.h>
#include <Halak/Any.h>
#include <Halak/Vector2.h>
#include <iostream>
#include <memory>
using Halak::Any;
using Halak::Vector2;
using std::cout;
using std::endl;
void Halak::Samples::AnySample(const std::vector<const char*>& /*args*/)
{
Any v1 = 10;
Any v2 = 10.0f;
// double d2 = v1.CastTo<double>();
cout << std::boolalpha;
cout << (v1.GetType() == Any::IntType) << endl;
cout << (v2.GetType() == Any::FloatType) << endl;
Any v3 = Any::Null;
{
std::tr1::shared_ptr<int> sp1(new int(24));
std::tr1::shared_ptr<int> sp2(sp1);
cout << "sp1 shared_count: " << sp1.use_count() << endl;
v3 = sp1;
cout << "sp1 shared_count: " << sp1.use_count() << endl;
}
std::tr1::shared_ptr<int> sp3 = v3.CastTo<std::tr1::shared_ptr<int>>();
cout << "v3 shared_count: " << sp3.use_count() << endl;
Any v4 = Vector2(1.0f, 2.0f);
Any v5 = v4;
int q = 10;
const int& w = q;
Any v6 = w;
} | [
"[email protected]"
] | [
[
[
1,
43
]
]
] |
ed8a7890014cfc377054b4fb0163b307ede77b7d | fe0851fdab6b35bc0f3059971824e036eb1d954b | /vs2010/cpuload/cpuload/cpuload.cpp | 29f6d0a064f553aee7c6dbabcff774e449b91ec4 | [] | no_license | van-smith/OPBM | 751f8f71e6823b7f1c95e5002909427910479f90 | 889d8ead026731f7f5ae0e9d5f0e730bb7731ffe | HEAD | 2016-08-07T10:44:54.348257 | 2011-12-21T22:50:06 | 2011-12-21T23:25:25 | 2,143,608 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,974 | cpp | // cpuload.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
HANDLE workerThread[32];
ULONG workerThreadId[32];
int workerThreads;
LARGE_INTEGER frequency;
double gPercent;
unsigned long gMaximum;
bool gTickTock, flagInfo, flagPause;
#define _TICK false
#define _TOCK true
unsigned long QueryPerformanceCounterInMilliseconds( void );
DWORD WINAPI computePi(LPVOID param);
int main(int argc, char* argv[])
{
int i;
SYSTEM_INFO info;
unsigned long appStart, appEnd, appDiff;
DWORD_PTR affinity_mask;
if (argc < 3)
{
// printf("Usage: cpuload %% duration [-info] [-pause]\n\n %% = CPU load to task with, as in 20%%\nduration = milliseconds to maintain workload, as in 5000 for 5 seconds\n");
exit(-1);
}
flagInfo = (argc >= 4 && _memicmp(argv[3], "-info", 5) == 0);
flagPause = (argc >= 5 && _memicmp(argv[4], "-pause", 6) == 0);
gMaximum = atol(argv[2]); // Maximum number of milliseconds
gPercent = atof(argv[1]); // Number of ticks out of 100
// Verify our target is within range
if (gPercent > 100.0)
gPercent = 100.0;
GetSystemInfo(&info);
workerThreads = info.dwNumberOfProcessors;
QueryPerformanceFrequency(&frequency);
if (flagInfo)
{
// printf("CPULOAD processing %u CPUs at %.0f%% for %u milliseconds\n", workerThreads, gPercent, gMaximum);
}
// Start out computing
gTickTock = _TOCK;
// Create a thread for every CPU (to give a true system workload)
// And assign affinity to each logically numbered CPU
// And set the thread priority above normal
appStart = QueryPerformanceCounterInMilliseconds();
for (i = 0; i < workerThreads; i++)
{
workerThread[i] = CreateThread(0, 0, computePi, 0, 0, &workerThreadId[i]);
affinity_mask = (DWORD_PTR)(1 << (i - 1));
SetThreadAffinityMask(workerThread[i], affinity_mask);
// SetThreadPriority(workerThread[i], THREAD_PRIORITY_ABOVE_NORMAL);
}
// Wait for threads to end
DWORD exitCode;
do {
exitCode = !STILL_ACTIVE;
for (i = 0; i < workerThreads; i++)
{
GetExitCodeThread(workerThread[i], &exitCode);
if (exitCode == STILL_ACTIVE)
break; // Still going on at least this one, so continue on
}
if (exitCode == STILL_ACTIVE)
Sleep(10);
else
break;
} while (1);
appEnd = QueryPerformanceCounterInMilliseconds();
appDiff = appEnd - appStart;
if (flagInfo)
{
// printf("CPULOAD processed for %u milliseconds\n", appDiff);
if (flagPause)
{
// printf("...pausing 5 seconds before existing");
Sleep(5000);
// printf(", done.\n");
}
}
return 0;
}
unsigned long QueryPerformanceCounterInMilliseconds( void )
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return ((unsigned long)(now.QuadPart * 1000 / frequency.QuadPart));
}
DWORD WINAPI computePi(LPVOID param)
{
long compute, sleep, swaps;
bool tickTock;
unsigned long start, now, ilast;
double iterate;
// Copy our global variables
tickTock = gTickTock;
// Begin ... NOW!
start = QueryPerformanceCounterInMilliseconds();
ilast = start;
compute = 0;
sleep = 0;
swaps = 0;
do {
now = QueryPerformanceCounterInMilliseconds();
iterate = (double)(now - ilast);
// _TICK = sleeping
// _TOCK = computing
if (tickTock == _TOCK)
{ // We are computing
if (iterate >= gPercent)
{ // But we've just switched over to sleeping
compute += (long)iterate;
++swaps;
tickTock = _TICK;
ilast = (unsigned long)now;
} else {
// Compute something, one pass through our "ComputePi" function
// Set the initial values of the polynomials, and the differences
double dP0 = 5.0;
double dP1 = 41.0;
double dP2 = 40.0;
double dQ0 = 3.0;
double dQ1 = 102.0;
double dQ2 = 288.0;
double dQ3 = 192.0;
// Perform a few iterations of the formula.
double dPi = 0.0, d = 1.0; // d is 4^k
for (int k = 0; k < 12; k++)
{
// Perform the even, addition step.
dPi = dPi + (dP0 / dQ0 / d);
dP0 = dP0 + dP1;
dP1 = dP1 + dP2;
dQ0 = dQ0 + dQ1;
dQ1 = dQ1 + dQ2;
dQ2 = dQ2 + dQ3;
d = d * 4.0;
// Perform the odd, subtraction step.
dPi = dPi - (dP0 / dQ0 / d);
dP0 = dP0 + dP1;
dP1 = dP1 + dP2;
dQ0 = dQ0 + dQ1;
dQ1 = dQ1 + dQ2;
dQ2 = dQ2 + dQ3;
d = d * 4.0;
}
// Display the result.
dPi = 2.0 * dPi;
}
} else {
// We are sleeping
if (iterate >= 100.0 - gPercent)
{ // But we've just switched over to computing
sleep += (long)iterate;
++swaps;
tickTock = _TOCK;
ilast = (unsigned long)now;
} else {
Sleep(1);
}
}
} while (now - start < gMaximum);
// if (flagInfo)
// printf("%.f%% Thread terminated %u sleeps, %u computes\n", gPercent, sleep / (swaps / 2), compute / (swaps / 2));
ExitThread(0);
} | [
"[email protected]"
] | [
[
[
1,
200
]
]
] |
a7c2d371a8662864421098ac237ce6d3c4331ef9 | a96b15c6a02225d27ac68a7ed5f8a46bddb67544 | /SetGame/Application.hpp | 76fef5eec3e63653410a8dbaf3329aa344342995 | [] | no_license | joelverhagen/Gaza-2D-Game-Engine | 0dca1549664ff644f61fe0ca45ea6efcbad54591 | a3fe5a93e5d21a93adcbd57c67c888388b402938 | refs/heads/master | 2020-05-15T05:08:38.412819 | 2011-04-03T22:22:01 | 2011-04-03T22:22:01 | 1,519,417 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | hpp | #ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include "Common.hpp"
#include "GazaApplication.hpp"
#include "GazaFrameSheet.hpp"
#include "GazaImageManager.hpp"
#include "GazaLogger.hpp"
#include "GameState.hpp"
#include "CardFrameSheetGenerator.hpp"
class Application : public Gaza::Application
{
public:
Application();
~Application();
Gaza::ImageManager * getImageManager();
private:
Gaza::ImageManager imageManager;
Gaza::FrameSheetCollection * cardFrames;
};
#endif | [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
2eed2acc235bfc5e5cfa05747d5e8a2258a9d663 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/contrib/pykillwinproc/src/pykillwinproc/pykillwinproc.cc | 2d0f015c533bf6bb0f1e7ba24820efa1ae86356c | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,672 | cc | //--------------------------------------------------------------------
// This is an extension module for Python that provides functions
// to kill processes on a Windows machine.
//
// Unfortunately there is no easy way in Python to kill a process
// and it's children on a Windows machine (os.kill() is simply
// missing on Windows). Using the win32api extensions one is able
// to kill a process but not it's children (at least not without
// resorting to using the Performance Data Helpers API and doing
// unspeakable things).
//
// (c) 2005 Vadim Macagon
//
// Contents are licensed under the terms of the Nebula License.
//--------------------------------------------------------------------
#ifdef _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG 1
#else
#include <Python.h>
#endif
#include <windows.h>
#include <tlhelp32.h>
//------------------------------------------------------------------------------
/**
Kills a process but not it's children.
*/
static void KillProcess(int pid)
{
HANDLE hProc = OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, false, pid);
if (hProc)
{
TerminateProcess(hProc, -1);
CloseHandle(hProc);
}
}
//------------------------------------------------------------------------------
/**
Kills a process but not it's children.
*/
static PyObject* pyKillWinProc_KillProcess(PyObject* self, PyObject* args)
{
int pid = 0;
if (!PyArg_ParseTuple(args, "i", &pid))
return NULL;
if (pid)
KillProcess(pid);
Py_INCREF(Py_None);
return Py_None;
}
//------------------------------------------------------------------------------
/**
Kills a process and its immediate children (but not the children's children).
*/
static PyObject* pyKillWinProc_KillProcessTree(PyObject* self, PyObject* args)
{
int pid = 0;
if (!PyArg_ParseTuple(args, "i", &pid))
return NULL;
if (pid)
{
HANDLE hProcSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hProcSnapshot)
{
PyErr_SetString(PyExc_Exception, "Failed to create process snapshot.");
return NULL;
}
KillProcess(pid);
PROCESSENTRY32 pe32;
// set the size of the structure before using it.
pe32.dwSize = sizeof(PROCESSENTRY32);
// kill all the children of the process
if (Process32First(hProcSnapshot, &pe32))
{
do
{
if (pe32.th32ParentProcessID == pid)
KillProcess(pe32.th32ProcessID);
} while (Process32Next(hProcSnapshot, &pe32));
}
CloseHandle(hProcSnapshot);
}
Py_INCREF(Py_None);
return Py_None;
}
//------------------------------------------------------------------------------
// method table
static PyMethodDef PyKillWinProcMethods[] = {
{"kill_process", pyKillWinProc_KillProcess, METH_VARARGS,
"kill_process(pid) \npid - process identifier of the process to kill. \nKill a Win32 Process but not its children."},
{"kill_process_tree", pyKillWinProc_KillProcessTree, METH_VARARGS,
"kill_process_tree(pid) \npid - process identifier of the process to kill. \nKill a Win32 Process and its immediate children."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
//------------------------------------------------------------------------------
// module initialisation
extern "C"
__declspec(dllexport)
void initpykillwinproc()
{
Py_InitModule("pykillwinproc", PyKillWinProcMethods);
}
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
119
]
]
] |
83184b7823427dbb500e80b21cc18d05f9552848 | 406b4b18f5c58c689d2324f49db972377fe8feb6 | /ANE/Include/Memory/IMemoryPool.h | cd118b1a3cd79d2f003a329221fb47c1e0b00b8c | [] | no_license | Mobiwoom/ane | e17167de36699c451ed92eab7bf733e7d41fe847 | ec20667c556a99351024f3ae9c8880e944c5bfbd | refs/heads/master | 2021-01-17T13:09:57.966141 | 2010-03-23T16:30:17 | 2010-03-23T16:30:17 | 33,132,357 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 258 | h | #pragma once
namespace Ane
{
class IMemoryPool
{
public:
IMemoryPool(){}
virtual ~IMemoryPool(){}
virtual void* Alloc() = 0;
virtual void* Alloc(unsigned int Size) = 0;
virtual void Free(void* pMemory) = 0;
};
} | [
"inthejm@5abed23c-1faa-11df-9e62-c93c6248c2ac"
] | [
[
[
1,
14
]
]
] |
d88a40953265794788a36e632eba8bd0df644090 | 658129adb8f10b4cccdb2e432430d67c0977d37e | /cpp/cs311/profs_examples/dlist.cpp | 59513f46c766689c73b56a0ba3381076ce534744 | [] | no_license | amiel/random-useless-scripts | e2d473940bdb968ad0f8d31514654b79a760edd4 | 166195329bc93c780d7c8fd088d93e3a697062a0 | refs/heads/master | 2020-12-24T13:21:37.358940 | 2009-03-29T06:08:26 | 2009-03-29T06:14:02 | 140,835 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 359 | cpp | // dlist.cpp (UNFINISHED)
// Glenn G. Chappell
// 11 Nov 2006
//
// For CS 311
// Source for DList class:
// Doubly Linked List
#include "dlist.h"
// ************************************************************************
// class DList - Member function definitions
// ************************************************************************
| [
"[email protected]"
] | [
[
[
1,
14
]
]
] |
c2f3b91856d6244d2e3904d7b4f98f5ee30039bc | 584d088c264ac58050ed0757b08d032b6c7fc83b | /FileDiffTool/Diff/Diff.cpp | 1da3a22661f0d2857a0403e1c26829a11956ab5a | [] | no_license | littlewingsoft/lunaproject | a843ca37c04bdc4e1e4e706381043def1789ab39 | 9102a39deaad74b2d73ee0ec3354f37f6f85702f | refs/heads/master | 2020-05-30T15:21:20.515967 | 2011-02-04T18:41:43 | 2011-02-04T18:41:43 | 32,302,109 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,405 | cpp | // Diff.cpp : 응용 프로그램에 대한 클래스 동작을 정의합니다.
//
#include "stdafx.h"
#include "Diff.h"
#include "DiffDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CDiffApp
BEGIN_MESSAGE_MAP(CDiffApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CDiffApp 생성
CDiffApp::CDiffApp()
{
// TODO: 여기에 생성 코드를 추가합니다.
// InitInstance에 모든 중요한 초기화 작업을 배치합니다.
}
// 유일한 CDiffApp 개체입니다.
CDiffApp theApp;
// CDiffApp 초기화
BOOL CDiffApp::InitInstance()
{
// _crtBreakAlloc = 2659;
// 응용 프로그램 매니페스트가 ComCtl32.dll 버전 6 이상을 사용하여 비주얼 스타일을
// 사용하도록 지정하는 경우, Windows XP 상에서 반드시 InitCommonControlsEx()가 필요합니다.
// InitCommonControlsEx()를 사용하지 않으면 창을 만들 수 없습니다.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 응용 프로그램에서 사용할 모든 공용 컨트롤 클래스를 포함하도록
// 이 항목을 설정하십시오.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
//AfxEnableControlContainer();
// 표준 초기화
// 이들 기능을 사용하지 않고 최종 실행 파일의 크기를 줄이려면
// 아래에서 필요 없는 특정 초기화
// 루틴을 제거해야 합니다.
// 해당 설정이 저장된 레지스트리 키를 변경하십시오.
// TODO: 이 문자열을 회사 또는 조직의 이름과 같은
// 적절한 내용으로 수정해야 합니다.
SetRegistryKey(_T("로컬 응용 프로그램 마법사에서 생성된 응용 프로그램"));
CDiffDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 여기에 [확인]을 클릭하여 대화 상자가 없어질 때 처리할
// 코드를 배치합니다.
}
else if (nResponse == IDCANCEL)
{
// TODO: 여기에 [취소]를 클릭하여 대화 상자가 없어질 때 처리할
// 코드를 배치합니다.
}
// 대화 상자가 닫혔으므로 응용 프로그램의 메시지 펌프를 시작하지 않고 응용 프로그램을 끝낼 수 있도록 FALSE를
// 반환합니다.
return FALSE;
}
| [
"jungmoona@2e9c511a-93cf-11dd-bb0a-adccfa6872b9"
] | [
[
[
1,
81
]
]
] |
9b4db7735e3a865a2213fe3360d3c93ba6b87ebe | 17e1b436ba01206d97861ec9153943592002ecbe | /uppsrc/Web/ScgiServer.cpp | 4bcdbfc3a5d46148393105b91dd2e6ff8d2add0a | [
"BSD-2-Clause"
] | permissive | ancosma/upp-mac | 4c874e858315a5e68ea74fbb1009ea52e662eca7 | 5e40e8e31a3247e940e1de13dd215222a7a5195a | refs/heads/master | 2022-12-22T17:04:27.008533 | 2010-12-30T16:38:08 | 2010-12-30T16:38:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,688 | cpp | #include <signal.h>
#include <Core/Core.h>
#include <Web/Web.h>
#include "ScgiServer.h"
namespace Upp {
bool run = true;
void sighandler(int sig)
{
run = false;
}
ScgiServer::ScgiServer(int port)
{
this->port = port;
signal(SIGABRT, sighandler);
signal(SIGINT, sighandler);
signal(SIGTERM, sighandler);
}
void ScgiServer::Run()
{
ServerSocket(serverSock, port);
while (run) {
if (serverSock.Accept(clientSock, &clientIP)) {
OnAccepted();
String sLen = clientSock.ReadUntil(':');
int len = atoi(sLen);
String data;
if (clientSock.IsOpen() && !clientSock.IsEof() && !clientSock.IsError()) {
// len + 1 = data plus the trailing , as in SCGI spec
data = clientSock.ReadCount(len+1, 3000);
}
String key;
int spos = 0;
for (int i=0; i < data.GetCount(); i++) {
if (data[i] == 0) {
if (key.IsEmpty())
key = data.Mid(spos, i-spos);
else {
String value = data.Mid(spos, i-spos);
serverVars.Add(key, value);
key.Clear();
}
spos = i + 1;
}
}
query.SetURL("?" + serverVars.Get("QUERY_STRING"));
hasPostData = false;
if (serverVars.Get("REQUEST_METHOD") == "POST") {
len = atoi(serverVars.Get("CONTENT_LENGTH"));
if (len > 0 && clientSock.IsOpen() && !clientSock.IsEof() &&
!clientSock.IsError())
{
data = clientSock.ReadCount(len, 3000);
post.SetURL("?" + data);
hasPostData = true;
}
}
OnRequest();
clientSock.Close();
serverVars.Clear();
query.Clear();
post.Clear();
OnClosed();
}
}
}
}; | [
"[email protected]"
] | [
[
[
1,
85
]
]
] |
2a93fd814f2f7f65bcea901b2f129061be11f72a | 9ca13ebd1e9c48c3cfcd4c3f845db35ec4b4db94 | /resources/xmlRunner.tpl | c496d6fdd8d1cb65229d3494f4142f6f5acd9071 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | gimias/CSnake | 929f4238858376fef834022855e2a2765455ec12 | 189390dd0749787ff1f856899957f44a9fe9cd55 | refs/heads/master | 2021-01-24T04:12:59.492590 | 2011-07-22T12:20:00 | 2011-07-22T12:20:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | tpl | // -*- C++ -*-
// This is the default test runner.
//
#include <cxxtest/XmlPrinter.h>
#include <fstream>
// The CxxTest "world"
<CxxTest world>
/**
\brief Main method to run project tests.
\param argc The number of arguments (should be 2).
\param argv The arguments: the name of the command and the name of the xml file where to output test results.
*/
int main( int argc, char** argv )
{
if ( argc != 2 )
{
fprintf( stderr, "Usage: %s <output file name>\n", argv[0] );
return -1;
}
std::ofstream ofs( argv[1] );
const int ret = CxxTest::XmlPrinter( ofs ).run();
ofs.close();
return ret;
}
| [
"ymartelli@9ffc3505-93cb-cd4b-9e5d-8a77f6415fcf"
] | [
[
[
1,
27
]
]
] |
525af3bb40da2fba099278023c502243c016cd62 | 8523123cacd378d808dbd3f02bbe0b66e2c69290 | /SC2 Multi Lossbot/SC2 Multi Lossbot/stdafx.cpp | 85e2d2dc6ef6d2d771ec5c65a6994306a8fa7263 | [] | no_license | shneezyn/sc2-multi-lossbot | 568194a12cba168b0bbac9ed046a2fb717cd6bb3 | 47ed28853067689679d7e189344599b716ae4c5f | refs/heads/master | 2016-08-09T07:33:50.243624 | 2010-11-30T20:32:22 | 2010-11-30T20:32:22 | 44,065,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Multi Lossbot.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | [
[
[
1,
8
]
]
] |
ee385e9c7aa9ea025896bf641b8e8516e40e14c1 | 8258620cb8eca7519a58dadde63e84f65d99cc80 | /sandbox/dani/visual_extern_simulator/robot.h | 0f5b9c59d51112894c90a7cad0047f55b3fd5eac | [] | no_license | danieleferro/3morduc | bfdf4c296243dcd7c5ba5984bc899001bf74732b | a27901ae90065ded879f5dd119b2f44a2933c6da | refs/heads/master | 2016-09-06T06:02:39.202421 | 2011-03-23T08:51:56 | 2011-03-23T08:51:56 | 32,210,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,601 | h | #include "stdafx.h"
//#include <windows.h> // Header File For Windows
#include <math.h> // Math Library Header File
//#include <stdio.h> // Header File For Standard Input/Output
//#include "GL\glut.h" // Header File For Standard Input/Output
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include "CCronometer.h"
class ROBOT
{
public:
GLfloat xr; // posizione
GLfloat yr;
GLfloat tetar;
public:
GLfloat vlim; /// v max
GLfloat wlim; /// w max
CCronometer ck; //base dei tempi
public:
int n ; //gear ratio
int res ; //risoluzione encoder
GLfloat d ; //diametro della ruota
GLfloat cm ;
public:
//GLfloat xr; // posizione
//GLfloat yr;
//GLfloat tetar;
float Time; // tempo
GLfloat dxr,dyr,dtetar;
float vrx,vry;
GLfloat l; //distanza tra ruote
GLfloat v;
GLfloat w;
//float dnr = (2*v+w*l)/(2*cm); //passi encoder destro
//float dnl = (2*v-w*l)/(2*cm); //passi encoder sinistro
GLfloat radius; // max dimension
FILE *fp;
int collisions;
ROBOT();
ROBOT(float x1, float x2, float ang3);
void move();
//void PaintRobot();
void PaintRobot2();
void SetW(float set);
void SetV(float set);
void movetank(float l, float r);
bool LoadSPFromFile(char *string,int kk);
int RobColl(OBJECT *coll, bool activecontrol);
int RobColl2(OBJECT *coll, bool activecontrol);
}; | [
"loris.fichera@9b93cbac-0697-c522-f574-8d8975c4cc90"
] | [
[
[
1,
60
]
]
] |
5a04d961e3f4e7336fdedaba737bd190c0697a6a | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/preprocessed/src/quote.cpp | 1ee1592c46c25eb8c0df37b3a5bb983fbd167721 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | cpp |
// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /cvsroot/boost/boost/libs/mpl/preprocessed/src/quote.cpp,v $
// $Date: 2006/06/12 05:11:54 $
// $Revision: 1.3.8.1 $
#define BOOST_MPL_PREPROCESSING_MODE
#include <boost/config.hpp>
#include <boost/mpl/quote.hpp>
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
16
]
]
] |
ed5168fdd5ff96cb648a69c38eaf4a0f5ce7a1cc | 7bfc60c56b4c12957c53657d0549a136b6e6cdb2 | /array.hpp | 0108381932da37981fdd605d871227c06db6bcad | [
"BSL-1.0"
] | permissive | bolero-MURAKAMI/CEL---ConstExpr-Library | 867ef5656ff531ececaf5747594f8b948d872f34 | 1ad865dd8845c63e473a132870347e913ff91c1c | refs/heads/master | 2021-01-17T22:03:25.021662 | 2011-11-26T12:59:00 | 2011-11-26T12:59:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,920 | hpp | // Copyright (C) 2011 RiSK (sscrisk)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#if !defined(SSCRISK_CEL_ARRAY_HPP)
#define SSCRISK_CEL_ARRAY_HPP
// array.hpp
#include<cstddef>
#include<iterator>
#include<algorithm>
#include<utility>
#include<stdexcept>
#include<sscrisk/cel/algorithm.hpp>
namespace sscrisk{ namespace cel{
template<class T, std::size_t N>
struct array
{
typedef T& reference;
typedef T const & const_reference;
typedef T* iterator;
typedef T const * const_iterator;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef T const * const_pointer;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
T elems[N ? N : 1];
void fill(T const & value){ std::fill_n(begin(), N, value); }
void swap(array<T, N>& rhs) noexcept(noexcept(std::swap(std::declval<T&>(), std::declval<T&>())))
{
std::swap_ranges(begin(), end(), rhs.begin());
}
iterator begin() noexcept{ return elems; }
constexpr const_iterator begin() const noexcept{ return &elems[0]; }
iterator end() noexcept{ return elems + N; }
constexpr const_iterator end() const noexcept{ return &elems[0] + N; }
reverse_iterator rbegin() noexcept{ return reverse_iterator(end()); }
const_reverse_iterator rbegin() const noexcept{ return const_reverse_iterator(end()); }
reverse_iterator rend() noexcept{ return reverse_iterator(begin()); }
const_reverse_iterator rend() const noexcept{ return const_reverse_iterator(begin()); }
constexpr const_iterator cbegin() const noexcept{ return elems; }
constexpr const_iterator cend() const noexcept{ return elems + N; }
const_reverse_iterator crbegin() const noexcept{ return const_reverse_iterator(end()); }
const_reverse_iterator crend() const noexcept{ return const_reverse_iterator(begin()); }
constexpr size_type size() noexcept{ return N; }
constexpr size_type max_size() noexcept{ return N; }
constexpr bool empty() noexcept{ return !N; }
reference operator[](size_type n){ return elems[n]; }
constexpr const_reference operator[](size_type n) const{ return elems[n]; }
const_reference at(size_type n) const
{
if(n >= size())throw std::out_of_range("array<T, N>::at(size_type) const, out of range");
return elems[n];
}
reference at(size_type n)
{
if(n >= size())throw std::out_of_range("array<T, N>::at(size_type), out of range");
return elems[n];
}
reference front(){ return elems[0]; }
constexpr const_reference front() const{ return elems[0]; }
reference back(){ return elems[N - 1]; }
constexpr const_reference back() const{ return elems[N - 1]; }
T * data() noexcept{ return elems; }
constexpr const T * data() const noexcept{ return elems; }
};
template<class T, std::size_t N>
constexpr bool operator==(array<T, N> const & x, array<T, N> const & y)
{
return equal(x.begin(), x.end(), y.begin());
}
template<class T, std::size_t N>
constexpr bool operator!=(array<T, N> const & x, array<T, N> const & y)
{
return !(x == y);
}
template<class T, std::size_t N>
constexpr bool operator<(array<T, N> const & x, array<T, N> const & y)
{
return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
}
template<class T, std::size_t N>
constexpr bool operator>(array<T, N> const & x, array<T, N> const & y)
{
return y < x;
}
template<class T, std::size_t N>
constexpr bool operator<=(array<T, N> const & x, array<T, N> const & y)
{
return !(x > y);
}
template<class T, std::size_t N>
constexpr bool operator>=(array<T, N> const & x, array<T, N> const & y)
{
return !(x < y);
}
}}
namespace std{
template<class T, std::size_t N>
void swap(sscrisk::cel::array<T, N>& x, sscrisk::cel::array<T, N>& y) noexcept(noexcept(x.swap(y)))
{
x.swap(y);
}
template<class T>
class tuple_size;
template<std::size_t I, class T>
class tuple_element;
template<class T, std::size_t N>
struct tuple_size<sscrisk::cel::array<T, N>>
{
static const std::size_t value = N;
};
template<std::size_t I, class T, std::size_t N>
struct tuple_element<I, sscrisk::cel::array<T, N>>
{
static_assert(I < N, "out of bounds");
typedef T type;
};
template<std::size_t I, class T, std::size_t N>
T& get(sscrisk::cel::array<T, N>& a) noexcept
{
static_assert(I < N, "out of bounds");
return a[I];
}
template<std::size_t I, class T, std::size_t N>
T&& get(sscrisk::cel::array<T, N>&& a) noexcept
{
return std::move(get<I>(a));
}
template<std::size_t I, class T, std::size_t N>
constexpr T const & get(const sscrisk::cel::array<T, N>& a) noexcept
{
static_assert(I < N, "out of bounds");
return a[I];
}
}
#endif
| [
"[email protected]"
] | [
[
[
1,
170
]
]
] |
242a19b001b15faf8d4950b5d7c2a749955bb38e | 68127d36b179fd5548a1e593e2c20791db6b48e3 | /estruturaDeDados/CONTMED.CPP | 0e61089ff6b53af810dfb1d181922f6d3e8ff831 | [] | no_license | renatomb/engComp | fa50b962dbdf4f9387fd02a28b3dc130b683ed02 | b533c876b50427d44cfdb92c507a6e74b1b7fa79 | refs/heads/master | 2020-04-11T06:22:05.209022 | 2006-04-26T13:40:08 | 2018-12-13T04:25:08 | 161,578,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,457 | cpp |
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<stdlib.h>
#include<stdio.h>
#include<dos.h>
#define num 1500
long I,F,T[5];
int n,i,troca,aux,a[num],b[num];
void salva();
void metodo1();
void metodo2();
void metodo3();
void metodo4();
void metodo5();
long tempo()
{
long h,m,s,hs,t1;
struct time t;
gettime(&t);
h=t.ti_hour;
m=t.ti_min;
s=t.ti_sec;
hs=t.ti_hund;
t1=(h*360+m*60+s)*100+hs;
return t1;}
void salva()
{
for(i=0;i<n;i++)
b[i]=a[i];
}
void metodo1()
{
I=tempo();
troca=1;
while(troca==1)
{
troca=0;
for(i=0;i<n-1;i++)
{
if(b[i]>b[i+1])
{
troca=1;
aux=b[i];
b[i]=b[i+1];
b[i+1]=aux;
}
}
}
// for(i=0;i<n;i++)
// cout<<"\n"<<b[i];
F=tempo();
T[0]=F-I;
// cout<<"\nTEMPO DO METODO 1 "<<T[0];
}
void metodo2()
{
I=tempo();
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(b[i]>b[j])
{
aux=b[i];
b[i]=b[j];
b[j]=aux;
}
}
}
//for(i=0;i<n;i++)
// cout<<"\n"<<b[i];
F=tempo();
T[1]=F-I;
//cout<<"\nTEMPO DO METODO 2 "<<T[1];
}
void metodo3()
{
I=tempo();
int menor,k;
for(int i=0;i<n-1;i++)
{
menor=b[i];
k=i;
for(int j=i+1;j<n;j++)
{
if(menor>b[j])
{
menor=b[j];
k=j;
}
}
aux=b[i];
b[i]=b[k];
b[k]=aux;
}
//for(i=0;i<n;i++)
// cout<<"\n"<<b[i];
F=tempo();
T[2]=F-I;
//cout<<"\nTEMPO DO METODO 3 "<<T[2];
}
void metodo4()
{
I=tempo();
int c[num],j;
for(i=0;i<(n-1);i++)
for(j=(i+1);j<n;j++)
if(b[i]>b[j])
c[i]++;
else
c[j]++;
// for(i=0;i<n;i++)
// for(j=0;j<n;j++)
// if(c[j]==i)
// cout<<"\n"<<b[j];
F=tempo();
T[3]=F-I;
//cout<<"\nTEMPO DO METODO 4 "<<T[3];
}
void metodo5()
{
I=tempo();
int k;
k=n;
while(1)
{k=int(k/1.3);
if(k<1)
{k=1;
troca=0;
}
for(i=0;i<(n-k);i++)
if(b[i]>b[i+k])
{aux=b[i];
b[i]=b[i+k];
b[i+k]=aux;
troca=1;
}
if(troca==0&&k==1)
break;
}
//for (i=0;i<n;i++)
// cout<<"\n"<<b[i];
//break;
F=tempo();
T[4]=F-I;
//cout<<"\nTEMPO DO METODO 5 "<<T[4];
}
void main()
{
char ch;
while(1)
{
clrscr();
printf("\nEntre como a quantidade de numeros p/ ordenar : ");
cin>>n;
randomize();
for(i=0;i<n;i++)
{
a[i]=random(10000);
//printf("\na[%d]= %d", i+1,a[i]);
}
//getch();
salva();
metodo1();
salva();
metodo2();
salva();
metodo3();
salva();
metodo4();
salva();
metodo5();
clrscr();
cout<<"\n TEMPO DE EXECUCAO";
cout<<"\n\n METODO 1 = "<<T[0];
cout<<"\n METODO 2 = "<<T[1];
cout<<"\n METODO 3 = "<<T[2];
cout<<"\n METODO 4 = "<<T[3];
cout<<"\n METODO 5 = "<<T[4];
cout<<"\n\n DIGITE ENTRE PARA SABER O METODO MAIS RAPIDO :";
getch();
n=5;
for(i=0;i<n;i++)
{b[i]=T[i];
a[i]=T[i];}
metodo1();
clrscr();
if(b[0]==a[0])
cout<<"\nMETODO 1 E MAIS RAPIDO COM O TEMPO DE "<<a[0];
if(b[0]==a[1])
cout<<"\nMETODO 2 E MAIS RAPIDO COM O TEMPO DE "<<a[1];
if(b[0]==a[2])
cout<<"\nMETODO 3 E MAIS RAPIDO COM O TEMPO DE "<<a[2];
if(b[0]==a[3])
cout<<"\nMETODO 4 E MAIS RAPIDO COM O TEMPO DE "<<a[3];
if(b[0]==a[4])
cout<<"\nMETODO 5 E MAIS RAPIDO COM O TEMPO DE "<<a[4];
printf("\n\n<ESC> para terminar: ");
ch=getch();
if(ch==27)
break;
}
}
| [
"[email protected]"
] | [
[
[
1,
221
]
]
] |
64ceb84bfde0c56e82627a9bac15d50b077eed63 | da32684647cac4dcdbb60db49496eb8d10a8ea6d | /Deadbeef/Classes/Box2D/Dynamics/b2Fixture.cpp | bb4ea5470d16a4bdaf17bc5606c94777b0d6c807 | [] | no_license | jweinberg/deadbeef | a1f10bc37de3aee5ac6b5953d740be9990083246 | 8126802454ff5815a7a55feae82e80d026a89726 | refs/heads/master | 2016-09-06T06:13:46.704284 | 2010-06-18T21:51:07 | 2010-06-18T21:51:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,173 | cpp | /*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2Fixture.h"
#include "Contacts/b2Contact.h"
#include "../Collision/Shapes/b2CircleShape.h"
#include "../Collision/Shapes/b2PolygonShape.h"
#include "../Collision/b2BroadPhase.h"
#include "../Collision/b2Collision.h"
#include "../Common/b2BlockAllocator.h"
b2Fixture::b2Fixture()
{
m_userData = NULL;
m_body = NULL;
m_next = NULL;
m_proxyId = b2BroadPhase::e_nullProxy;
m_shape = NULL;
m_density = 0.0f;
m_physicsSprite = NULL;
}
b2Fixture::~b2Fixture()
{
b2Assert(m_shape == NULL);
b2Assert(m_proxyId == b2BroadPhase::e_nullProxy);
}
void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def)
{
m_userData = def->userData;
m_friction = def->friction;
m_restitution = def->restitution;
m_body = body;
m_next = NULL;
m_filter = def->filter;
m_isSensor = def->isSensor;
m_isMagnetic = def->isMagnetic;
m_shape = def->shape->Clone(allocator);
m_density = def->density;
}
void b2Fixture::Destroy(b2BlockAllocator* allocator)
{
// The proxy must be destroyed before calling this.
b2Assert(m_proxyId == b2BroadPhase::e_nullProxy);
// Free the child shape.
switch (m_shape->m_type)
{
case b2Shape::e_circle:
{
b2CircleShape* s = (b2CircleShape*)m_shape;
s->~b2CircleShape();
allocator->Free(s, sizeof(b2CircleShape));
}
break;
case b2Shape::e_polygon:
{
b2PolygonShape* s = (b2PolygonShape*)m_shape;
s->~b2PolygonShape();
allocator->Free(s, sizeof(b2PolygonShape));
}
break;
default:
b2Assert(false);
break;
}
m_shape = NULL;
}
void b2Fixture::CreateProxy(b2BroadPhase* broadPhase, const b2Transform& xf)
{
b2Assert(m_proxyId == b2BroadPhase::e_nullProxy);
// Create proxy in the broad-phase.
m_shape->ComputeAABB(&m_aabb, xf);
m_proxyId = broadPhase->CreateProxy(m_aabb, this);
}
void b2Fixture::DestroyProxy(b2BroadPhase* broadPhase)
{
if (m_proxyId == b2BroadPhase::e_nullProxy)
{
return;
}
// Destroy proxy in the broad-phase.
broadPhase->DestroyProxy(m_proxyId);
m_proxyId = b2BroadPhase::e_nullProxy;
}
void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2)
{
if (m_proxyId == b2BroadPhase::e_nullProxy)
{
return;
}
// Compute an AABB that covers the swept shape (may miss some rotation effect).
b2AABB aabb1, aabb2;
m_shape->ComputeAABB(&aabb1, transform1);
m_shape->ComputeAABB(&aabb2, transform2);
m_aabb.Combine(aabb1, aabb2);
b2Vec2 displacement = transform2.position - transform1.position;
broadPhase->MoveProxy(m_proxyId, m_aabb, displacement);
}
void b2Fixture::SetFilterData(const b2Filter& filter)
{
m_filter = filter;
if (m_body == NULL)
{
return;
}
// Flag associated contacts for filtering.
b2ContactEdge* edge = m_body->GetContactList();
while (edge)
{
b2Contact* contact = edge->contact;
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
if (fixtureA == this || fixtureB == this)
{
contact->FlagForFiltering();
}
edge = edge->next;
}
}
void b2Fixture::SetSensor(bool sensor)
{
m_isSensor = sensor;
}
| [
"bhelgeland@9c1d8119-421d-44e4-8328-69b580a11e1d"
] | [
[
[
1,
165
]
]
] |
5c13c3bfca5956016b3a5d8e6573643ffb834a70 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/coreplugin/icore.cpp | e6de9860d7ee2e84868a7082464416a6e241e126 | [] | no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,820 | cpp | /**
******************************************************************************
*
* @file icore.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation ([email protected]) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "icore.h"
/*!
\namespace Core
\brief The Core namespace contains all classes that make up the Core plugin
which constitute the basic functionality of the OpenPilot GCS.
*/
/*!
\namespace Core::Internal
\internal
*/
/*!
\class Core::ICore
\brief The ICore class allows access to the different part that make up
the basic functionality of the OpenPilot GCS.
You should never create a subclass of this interface. The one and only
instance is created by the Core plugin. You can access this instance
from your plugin through \c{Core::instance()}.
\mainclass
*/
/*!
\fn QStringList ICore::showNewItemDialog(const QString &title,
const QList<IWizard *> &wizards,
const QString &defaultLocation = QString())
\brief Opens a dialog where the user can choose from a set of \a wizards that
create new files/classes/projects.
The \a title argument is shown as the dialogs title. The path where the
files will be created (if the user doesn't change it) is set
in \a defaultLocation. It defaults to the path of the file manager's
current file.
\sa Core::FileManager
*/
/*!
\fn bool ICore::showOptionsDialog(const QString &group = QString(),
const QString &page = QString())
\brief Opens the application options/preferences dialog with preselected
\a page in a specified \a group.
The arguments refer to the string IDs of the corresponding IOptionsPage.
*/
/*!
\fn bool ICore::showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
const QString &settingsCategory = QString(),
const QString &settingsId = QString(),
QWidget *parent = 0);
\brief Show a warning message with a button that opens a settings page.
Should be used to display configuration errors and point users to the setting.
Returns true if the settings dialog was accepted.
*/
/*!
\fn ActionManager *ICore::actionManager() const
\brief Returns the application's action manager.
The action manager is responsible for registration of menus and
menu items and keyboard shortcuts.
*/
/*!
\fn FileManager *ICore::fileManager() const
\brief Returns the application's file manager.
The file manager keeps track of files for changes outside the application.
*/
/*!
\fn UniqueIDManager *ICore::uniqueIDManager() const
\brief Returns the application's id manager.
The unique ID manager transforms strings in unique integers and the other way round.
*/
/*!
\fn MessageManager *ICore::messageManager() const
\brief Returns the application's message manager.
The message manager is the interface to the "General" output pane for
general application debug messages.
*/
/*!
\fn ExtensionSystem::PluginManager *ICore::pluginManager() const
\brief Returns the application's plugin manager.
The plugin manager handles the plugin life cycles and manages
the common object pool.
*/
/*!
\fn EditorManager *ICore::editorManager() const
\brief Returns the application's editor manager.
The editor manager handles all editor related tasks like opening
documents, the stack of currently open documents and the currently
active document.
*/
/*!
\fn VariableManager *ICore::variableManager() const
\brief Returns the application's variable manager.
The variable manager is used to register application wide string variables
like \c MY_PROJECT_DIR such that strings like \c{somecommand ${MY_PROJECT_DIR}/sub}
can be resolved/expanded from anywhere in the application.
*/
/*!
\fn ThreadManager *ICore::threadManager() const
\brief Returns the application's thread manager.
The thread manager is used to manage application wide QThread objects,
allowing certain critical objects to synchronize directly within the same
real time thread - anywhere in the application.
*/
/*!
\fn ModeManager *ICore::modeManager() const
\brief Returns the application's mode manager.
The mode manager handles everything related to the instances of IMode
that were added to the plugin manager's object pool as well as their
buttons and the tool bar with the round buttons in the lower left
corner of the OpenPilot GCS.
*/
/*!
\fn MimeDatabase *ICore::mimeDatabase() const
\brief Returns the application's mime database.
Use the mime database to manage mime types.
*/
/*!
\fn QSettings *ICore::settings() const
\brief Returns the application's main settings object.
You can use it to retrieve or set application wide settings
(in contrast to session or project specific settings).
\see settingsDatabase()
*/
/*!
\fn SettingsDatabase *ICore::settingsDatabase() const
\brief Returns the application's settings database.
The settings database is meant as an alternative to the regular settings
object. It is more suitable for storing large amounts of data. The settings
are application wide.
\see SettingsDatabase
*/
/*!
\fn QString ICore::resourcePath() const
\brief Returns the absolute path that is used for resources like
project templates and the debugger macros.
This abstraction is needed to avoid platform-specific code all over
the place, since e.g. on Mac the resources are part of the application bundle.
*/
/*!
\fn QMainWindow *ICore::mainWindow() const
\brief Returns the main application window.
For use as dialog parent etc.
*/
/*!
\fn IContext *ICore::currentContextObject() const
\brief Returns the context object of the current main context.
\sa ICore::addAdditionalContext()
\sa ICore::addContextObject()
*/
/*!
\fn void ICore::addAdditionalContext(int context)
\brief Register additional context to be currently active.
Appends the additional \a context to the list of currently active
contexts. You need to call ICore::updateContext to make that change
take effect.
\sa ICore::removeAdditionalContext()
\sa ICore::hasContext()
\sa ICore::updateContext()
*/
/*!
\fn void ICore::removeAdditionalContext(int context)
\brief Removes the given \a context from the list of currently active contexts.
You need to call ICore::updateContext to make that change
take effect.
\sa ICore::addAdditionalContext()
\sa ICore::hasContext()
\sa ICore::updateContext()
*/
/*!
\fn bool ICore::hasContext(int context) const
\brief Returns if the given \a context is currently one of the active contexts.
\sa ICore::addAdditionalContext()
\sa ICore::addContextObject()
*/
/*!
\fn void ICore::addContextObject(IContext *context)
\brief Registers an additional \a context object.
After registration this context object gets automatically the
current context object whenever its widget gets focus.
\sa ICore::removeContextObject()
\sa ICore::addAdditionalContext()
\sa ICore::currentContextObject()
*/
/*!
\fn void ICore::removeContextObject(IContext *context)
\brief Unregisters a \a context object from the list of know contexts.
\sa ICore::addContextObject()
\sa ICore::addAdditionalContext()
\sa ICore::currentContextObject()
}
*/
/*!
\fn void ICore::updateContext()
\brief Update the list of active contexts after adding or removing additional ones.
\sa ICore::addAdditionalContext()
\sa ICore::removeAdditionalContext()
*/
/*!
\fn void ICore::openFiles(const QStringList &fileNames)
\brief Open all files from a list of \a fileNames like it would be
done if they were given to the OpenPilot GCS on the command line, or
they were opened via \gui{File|Open}.
*/
/*!
\fn ICore::ICore()
\internal
*/
/*!
\fn ICore::~ICore()
\internal
*/
/*!
\fn void ICore::coreOpened()
\brief Emitted after all plugins have been loaded and the main window shown.
*/
/*!
\fn void ICore::saveSettingsRequested()
\brief Emitted to signal that the user has requested that the global settings
should be saved to disk.
At the moment that happens when the application is closed, and on \gui{Save All}.
*/
/*!
\fn void ICore::optionsDialogRequested()
\brief Signal that allows plugins to perform actions just before the \gui{Tools|Options}
dialog is shown.
*/
/*!
\fn void ICore::coreAboutToClose()
\brief Plugins can do some pre-end-of-life actions when they get this signal.
The application is guaranteed to shut down after this signal is emitted.
It's there as an addition to the usual plugin lifecycle methods, namely
IPlugin::shutdown(), just for convenience.
*/
/*!
\fn void ICore::contextAboutToChange(Core::IContext *context)
\brief Sent just before a new \a context becomes the current context
(meaning that its widget got focus).
*/
/*!
\fn void ICore::contextChanged(Core::IContext *context)
\brief Sent just after a new \a context became the current context
(meaning that its widget got focus).
*/
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
] | [
[
[
1,
339
]
]
] |
2a3998dfbb7f416adedaaa6a2a6bd1c8aad0b649 | fac8de123987842827a68da1b580f1361926ab67 | /inc/math/HMVector2.h | 055dba27272e22dc3acc80ec642228f79082f368 | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 14,432 | h | #ifndef HYPERMATH_VECTOR2
#define HYPERMATH_VECTOR2
#include "math/HMath.h"
namespace hmath
{
class v2
{
public : union
{
struct
{
f32 x;
f32 y;
};
f32 val[2];
};
inline v2();
inline v2(const f32 fX, const f32 fY );
inline explicit v2( const f32 scaler );
inline explicit v2( const f32 afCoordinate[2] );
inline explicit v2( const int afCoordinate[2] );
inline explicit v2( f32* const r );
inline v2( const v2& rkVector );
inline f32 operator [] ( const size_t i ) const;
inline f32& operator [] ( const size_t i );
inline v2& operator = ( const v2& rkVector );
inline v2& operator = ( const f32 fScalar);
inline bit operator == ( const v2& rkVector ) const;
inline bit operator != ( const v2& rkVector ) const;
inline v2 operator + ( const v2& rkVector ) const;
inline v2 operator - ( const v2& rkVector ) const;
inline v2 operator * ( const f32 fScalar ) const;
inline v2 operator * ( const v2& rhs) const;
inline v2 operator / ( const f32 fScalar ) const;
inline v2 operator / ( const v2& rhs) const;
inline const v2& operator + () const;
inline v2 operator - () const;
inline friend v2 operator * ( const f32 fScalar, const v2& rkVector );
inline friend v2 operator / ( const f32 fScalar, const v2& rkVector );
inline friend v2 operator + (const v2& lhs, const f32 rhs);
inline friend v2 operator + (const f32 lhs, const v2& rhs);
inline friend v2 operator - (const v2& lhs, const f32 rhs);
inline friend v2 operator - (const f32 lhs, const v2& rhs);
inline v2& operator += ( const v2& rkVector );
inline v2& operator += ( const f32 fScaler );
inline v2& operator -= ( const v2& rkVector );
inline v2& operator -= ( const f32 fScaler );
inline v2& operator *= ( const f32 fScalar );
inline v2& operator *= ( const v2& rkVector );
inline v2& operator /= ( const f32 fScalar );
inline v2& operator /= ( const v2& rkVector );
inline f32 len () const;
inline f32 sqlen () const;
inline f32 dot(const v2& vec) const;
inline f32 norm();
inline v2 mid( const v2& vec ) const;
inline bit operator < ( const v2& rhs ) const;
inline bit operator > ( const v2& rhs ) const;
inline void floor( const v2& cmp );
inline void ceil( const v2& cmp );
inline v2 up(void) const;
inline f32 cross( const v2& rkVector ) const;
inline bit iszerolen(void) const;
inline v2 reflect(const v2& normal) const;
static const v2 zero;
static const v2 unitX;
static const v2 unitY;
static const v2 neg_unitX;
static const v2 neg_unitY;
static const v2 unit;
};
v2::v2()
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2::v2(const f32 fX, const f32 fY )
: x( fX ), y( fY )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2::v2( const f32 scaler )
: x( scaler), y( scaler )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2::v2( const f32 afCoordinate[2] )
: x( afCoordinate[0] ),
y( afCoordinate[1] )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2::v2( const int afCoordinate[2] )
{
x = (f32)afCoordinate[0];
y = (f32)afCoordinate[1];
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2::v2( f32* const r )
: x( r[0] ), y( r[1] )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2::v2( const v2& rkVector )
: x( rkVector.x ), y( rkVector.y )
{
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v2::operator [] ( const size_t i ) const
{
assert( i < 2 );
return *(&x+i);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32& v2::operator [] ( const size_t i )
{
assert( i < 2 );
return *(&x+i);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator = ( const v2& rkVector )
{
x = rkVector.x;
y = rkVector.y;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator = ( const f32 fScalar)
{
x = fScalar;
y = fScalar;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v2::operator == ( const v2& rkVector ) const
{
return ( x == rkVector.x && y == rkVector.y );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v2::operator != ( const v2& rkVector ) const
{
return ( x != rkVector.x || y != rkVector.y );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::operator + ( const v2& rkVector ) const
{
return v2(
x + rkVector.x,
y + rkVector.y);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::operator - ( const v2& rkVector ) const
{
return v2(
x - rkVector.x,
y - rkVector.y);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::operator * ( const f32 fScalar ) const
{
return v2(
x * fScalar,
y * fScalar);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::operator * ( const v2& rhs) const
{
return v2(
x * rhs.x,
y * rhs.y);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::operator / ( const f32 fScalar ) const
{
assert( fScalar != 0.0 );
f32 fInv = f32(1.0) / fScalar;
return v2(
x * fInv,
y * fInv);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::operator / ( const v2& rhs) const
{
return v2(
x / rhs.x,
y / rhs.y);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
const v2& v2::operator + () const
{
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::operator - () const
{
return v2(-x, -y);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 operator * ( const f32 fScalar, const v2& rkVector )
{
return v2( fScalar * rkVector.x,fScalar * rkVector.y );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 operator / ( const f32 fScalar, const v2& rkVector )
{
return v2( fScalar / rkVector.x,fScalar / rkVector.y );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 operator + (const v2& lhs, const f32 rhs)
{
return v2(
lhs.x + rhs,
lhs.y + rhs);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 operator + (const f32 lhs, const v2& rhs)
{
return v2( lhs + rhs.x, lhs + rhs.y);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 operator - (const v2& lhs, const f32 rhs)
{
return v2( lhs.x - rhs, lhs.y - rhs);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 operator - (const f32 lhs, const v2& rhs)
{
return v2( lhs - rhs.x,lhs - rhs.y );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator += ( const v2& rkVector )
{
x += rkVector.x;
y += rkVector.y;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator += ( const f32 fScaler )
{
x += fScaler;
y += fScaler;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator -= ( const v2& rkVector )
{
x -= rkVector.x;
y -= rkVector.y;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator -= ( const f32 fScaler )
{
x -= fScaler;
y -= fScaler;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator *= ( const f32 fScalar )
{
x *= fScalar;
y *= fScalar;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator *= ( const v2& rkVector )
{
x *= rkVector.x;
y *= rkVector.y;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator /= ( const f32 fScalar )
{
assert( fScalar != 0.0 );
f32 fInv = f32(1.0) / fScalar;
x *= fInv;
y *= fInv;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2& v2::operator /= ( const v2& rkVector )
{
x /= rkVector.x;
y /= rkVector.y;
return *this;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v2::len () const
{
return sqrt( x * x + y * y );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v2::sqlen () const
{
return x * x + y * y;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v2::dot(const v2& vec) const
{
return x * vec.x + y * vec.y;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v2::norm()
{
f32 fLength = sqrt( x * x + y * y);
if ( fLength > 1e-08 )
{
f32 fInvLength = f32(1.0) / fLength;
x *= fInvLength;
y *= fInvLength;
}
return fLength;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::mid( const v2& vec ) const
{
return v2( ( x + vec.x ) * f32(0.5), ( y + vec.y ) * f32(0.5) );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v2::operator < ( const v2& rhs ) const
{
if( x < rhs.x && y < rhs.y )
return true;
return false;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v2::operator > ( const v2& rhs ) const
{
if( x > rhs.x && y > rhs.y )
return true;
return false;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
void v2::floor( const v2& cmp )
{
if( cmp.x < x ) x = cmp.x;
if( cmp.y < y ) y = cmp.y;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
void v2::ceil( const v2& cmp )
{
if( cmp.x > x ) x = cmp.x;
if( cmp.y > y ) y = cmp.y;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::up(void) const
{
return v2 (-y, x);
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
f32 v2::cross( const v2& rkVector ) const
{
return x * rkVector.y - y * rkVector.x;
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
bit v2::iszerolen(void) const
{
f32 sqlen = (x * x) + (y * y);
return (sqlen < (1e-06 * 1e-06));
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
v2 v2::reflect(const v2& normal) const
{
return v2( *this - ( 2 * this->dot(normal) * normal ) );
}
//覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧
};
#endif
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
487
]
]
] |
63601d52d33c9d54071905905b58be453a896972 | 992d3f90ab0f41ca157000c4b18d071087d14d85 | /draw/CPPCODER.CPP | df1cbad125fdc62a8c9606dc67eae4e1c7b1039d | [] | no_license | axemclion/visionizzer | cabc53c9be41c07c04436a4733697e4ca35104e3 | 5b0158f8a3614e519183055e50c27349328677e7 | refs/heads/master | 2020-12-25T19:04:17.853016 | 2009-05-22T14:44:53 | 2009-05-22T14:44:53 | 29,331,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,855 | cpp | # include <process.h>
# include <graphics.h>
# include <dos.h>
# include <stdio.h>
# include <ctype.h>
# include <stdlib.h>
# include <string.h>
# include <dir.h>
# include <conio.h>
# include <mouse.h>
int fc(char *file1,char *file2,char *dest);
void ccoder(char *);
int main(int argc,char *argv[])
{
if (argc < 1)
return 1;
ccoder(argv[1]);
char path[100],path1[100];
strcpy(path,argv[1]);
strcpy(path1,path);
strcat(path1,"prog.java");
fc("code.cpp",NULL,path1);
strcpy(path1,path);
strcat(path1,"code.h");
remove(path1);
remove("head");
fc("head","code.tmp",path1);
remove("head");
FILE *fp = fopen("end.bat","wt");
fprintf(fp,"cls");
fclose(fp);
strcpy(path1,path);
return 0;
}
void ccoder(char *path)
{
char object[100];
remove("code.cpp");
strcat(path,"\\");
char *path1 =(char *)calloc(1,100);
#ifdef AXE
printf("%s",path);
getch();getch();
click();
# endif
char *name;
if (!path1)
return;
strcpy(path1,path);
FILE *fp,*prog,*draw;
strcat(path1,"code.cpp");
prog=fopen("code.cpp","wt");
if (prog == NULL)
return ;
strcpy(path1,path);
/**********writing to file ***********/
fprintf(prog,"import java.awt.*;\n");
fprintf(prog,"import javax.swing.*;\n");
fprintf(prog,"import java.applet.*;\n");
fp = fopen ("object.tmp","rt");
if (fp != NULL)
{
fprintf(prog,"\n\nvoid redraw();\n\n");
draw = fopen("draw.ini","rt");
int type=0,c=0;
fgets(object,100,fp);
if (object[strlen(object)-1] == '\n')
object[strlen(object)-1] = NULL;
fgets(path1,100,fp);
do
{
rewind(draw);
while (path1[c] != '=' && path1[c]!= NULL)
c++;
type = atoi(path1+c+1);
c = 0;
fscanf(draw,"%d %s",&c,path1);
do{
char ss[100];
fscanf(draw,"%s\n",ss);
if (type == c)
break;
fscanf(draw,"%d %s",&c,path1);
}while(!feof(draw));
fprintf(prog,"%s %s(",path1,object);
{
FILE *head;
head = fopen("head","at");
fprintf(head,"extern %s %s;\n",path1,object);
fclose(head);
}
//fist arguement
fgets(path1,100,fp);
c=0;
while (path1[c] != '=' && path1[c]!= NULL)
c++;
name = path1+c+1;
if (name[strlen(name)-1] == '\n')
name[strlen(name)-1] = NULL;
if (isdigit(name[0])) fprintf(prog,"%d",atoi(name));
else fprintf(prog,"\"%s\"",name);
fgets(path1,100,fp);c=0;
do{
while (path1[c] != '=' && path1[c]!= NULL)
c++;
name = path1+c+1;
if (name[strlen(name)-1] == '\n')
name[strlen(name)-1] = NULL;
if (isdigit(name[0]))
fprintf(prog,",%d",atoi(name));
else
fprintf(prog,",\"%s\"",name);
fgets(path1,100,fp);c=0;
}while (strcmp(path1,"**********\n") != 0 && !(feof(fp)));
fprintf(prog,");\n");
fgets(object,100,fp);fgets(path1,100,fp);
object[strlen(object)-1] = NULL;
}while (!feof(fp));
fclose(draw);
fclose(fp);
}
fprintf(prog,"\n\nint main()\n{\n");
fprintf(prog,"\tint gdriver = VGA, gmode=VGAMED, errorcode;\n");fprintf(prog,"\tinitgraph(&gdriver, &gmode,\"\");\n");
fprintf(prog,"\terrorcode = graphresult();");fprintf(prog,"\n\tif (errorcode != grOk) // an error occurred \n");fprintf(prog,"\t\t{\n");
fprintf(prog,"\t\tprintf(\"Graphics error:\");\n");fprintf(prog,"\t\tprintf(\"Press any key to halt:\");\n");fprintf(prog,"\t\tgetch();\n");fprintf(prog,"\t\texit(1);\n\t\t}\n");
fprintf(prog,"\nredraw();");
fprintf(prog,"\nmouse_present();\nshow_mouse();");
fprintf(prog,"\nwhile(1)\n{\nfocus = -1;key = 0;\n");
fprintf(prog,"\tmouse1 = mouse;\n\tmouse = status();");
fprintf(prog,"\tif (kbhit()) \n\t\tkey = getch();\n");
//start of events
fp = fopen("object.tmp","rt");
draw = fopen("code.tmp","rt");
if (fp != NULL && draw != NULL)
{
fgets(object,100,fp);
do{
object[strlen(object)-1] = NULL;
fprintf(prog,"\tif (inarea(mouse.x,mouse.y,%s.x1,%s.y1,%s.x2,%s.y2))\n\t{\n\t\tfocus = %s.action();\n",
object,object,object,object,object);
//events are writen here
rewind(draw);
fgets(path1,100,draw);
do{
int op = 0;
while (path1[op++] != ' ');
name=path1+op;
if (path1[strlen(path1) -1] == '\n')
path1[strlen(path1) -1] = NULL;
if (strncmp(object,name,strlen(object)) == 0)
fprintf(prog,"\t\t%s;\n",name);
op = 1;fgetc(draw);
while (op != 0)
{
if (path1[0] == '\"')
while (fgetc(draw) == '\"');
else if (path1[0] == '\'')
while (fgetc(draw) == '\'');
else if (path1[0] =='{') op++;
else if (path1[0] =='}') op--;
path1[0] = fgetc(draw);
}//read till end of function
fgets(path1,100,draw);
}while (!feof(draw));
//events are completed here
fprintf(prog,"\t}//end of %s\n\n",object);
while (strcmp(object,"**********\n") != 0)
fgets(object,100,fp);
fgets(object,100,fp);
fgets(path1,100,fp);
}while(!feof(fp));
fclose(fp);
}
fclose(draw);
//end of events
fprintf(prog,"\n}//end of main program execution loop");
fprintf(prog,"\n}//end of function main");
fprintf(prog,"\n\nvoid redraw()\n\t{\n");
fprintf(prog,"char pattern[8];\n");
fp = fopen("draw.tmp","rt");
while (!feof(fp) && fp != NULL)
{
fscanf(fp,"%s ",&object);
int sx,sy,ex,ey,thk,ls,col,fs,fc;
unsigned int fonts,fontn,fontdir;
char cp[8];
sx=sy=ex=ey=thk=ls=col=fs=fc=fonts=fontn=fontdir=0;
if (strcmp(object,"object") == 0)
{
fgets(object,100,fp);
*(object + strlen(object) -1 ) = NULL;
fprintf(prog,"%s.draw();\n",object);
}//end of drawing objects
else if (strcmp(object,"print") == 0)
{
fscanf(fp,"%03d,%03d,",
&sx,&sy);
fgets(object,100,fp);
*(object + strlen(object) -1 ) = NULL;
fprintf(prog,"gotoxy(%d,%d);\n",sx,sy);
fprintf(prog,"printf(\"%s\");\n",object);
}//end of text
else if (strcmp(object,"line") == 0 || strcmp(object,"rectangle") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%07d\n",
&sx,&sy,&ex,&ey,&col,&thk,&ls,&fontn);
fprintf(prog,"setcolor(%d);setlinestyle(%d,%d,%d);\n",col,ls,fontn,thk);
if (strcmp(object,"rectangle") == 0)
fprintf(prog,"rectangle(%d,%d,%d,%d);\n",sx,sy,ex,ey);
else
fprintf(prog,"line(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}//end of drawing a line
else if (strcmp(object,"bar") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,&fc,&fs);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"bar(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}//end of drawing a rectangle
else if (strcmp(object,"barp") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,&fc,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"\nsetfillpattern(pattern,%d);\n",fc);
fprintf(prog,"bar(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}
else if (strcmp(object,"text") == 0)
{
fscanf(fp,"%02d,%03d,%03d,%02d,%02d,%02d,",
&col,&sx,&sy,
&fontn,&fontdir,&fonts);
fgets(object,100,fp);
*(object + strlen(object) -1 ) = NULL;
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"settextstyle(%d,%d,%d);\n",fontn,fontdir,fonts);
fprintf(prog,"outtextxy(%d,%d,\"%s\");\n",sx,sy,object);
}//end of text
else if (strcmp(object,"ellipse") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,&fonts,&fontn,&col,&thk);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"ellipse(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn);
}//end of ellipse
else if (strcmp(object,"pie") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,&fonts,&fontn,
&col,&thk,&fc,&fs);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"sector(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn);
}//end of drawing simple piechart
else if (strcmp(object,"piepattern") == 0)
{
int xradius,yradius;
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,
&ex,&ey,
&xradius,&yradius,
&col,&thk,&fc,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"setfillpattern(pattern,%d);\n",fc);
fprintf(prog,"sector(%d,%d,%d,%d,%d,%d);\n",sx,sy,ex,ey,fonts,fontn);
}//end of complex pie chart
else if (strcmp(object,"fillellipse") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,
&col,&thk,&fc,&fs);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"fillellipse(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}//end of fillellipse simple
else if (strcmp(object,"fillellipsep") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&ex,&ey,
&col,&thk,&fc,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
fprintf(prog,"setcolor(%d);\n",col);
fprintf(prog,"setlinestyle(0,0,%d);\n",thk);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"setfillpattern(pattern,%d);\n",fc);
fprintf(prog,"fillellipse(%d,%d,%d,%d);\n",sx,sy,ex,ey);
}//end of complex ellipse filler
else if (strcmp(object,"fillstyle") == 0)
{
fscanf(fp,"%03d,%03d,%02d,%02d,%02d\n",
&sx,&sy,&col,&fc,&fs);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"floodfill(%d,%d,%d);\n",sx,sy,col);
}//end of floodfilling
else if (strcmp(object,"fillpattern") == 0)
{
fscanf(fp,"%03d,%03d,%02d,%02d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&sx,&sy,&col,&fc,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"setfillpattern(pattern,%d);\n",fc);
fprintf(prog,"floodfill(%d,%d,%d);\n",sx,sy,col);
}//end of fill pattern
else if (strcmp(object,"polygon") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%07d\n",
&fontdir,&col,&ls,&thk,&fontn);
int points[30];
fprintf(prog,"{\nint poly[] = {");
for (int i = 0; i < fontdir*2 && i < 30;i+=2)
{
fscanf(fp,"%03d,%03d",&points[i],&points[i+1]);
fprintf(prog,"%3d,%3d,",points[i],points[i+1]);
}//end of for next loop
fprintf(prog,"0};\nsetcolor(%d);\n",col);
fprintf(prog,"setlinestyle(%d,%d,%d);\n",ls,fontn,thk);
fprintf(prog,"drawpoly(%d,poly);}\n",fontdir);
}//end of simple polygon
else if (strcmp(object,"fillpolygon") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%03d,%07d\n",
&fontdir,&col,&ls,&thk,&fc,&fs,&fontn);
int points[30];
fprintf(prog,"{\nint poly[] = {");
for (int i = 0; i < fontdir*2 && i < 30;i+=2)
{
fscanf(fp,"%03d,%03d",&points[i],&points[i+1]);
fprintf(prog,"%3d,%3d,",points[i],points[i+1]);
}//end of for next loop
fprintf(prog,"0};\nsetcolor(%d);\n",col);
fprintf(prog,"setlinestyle(%d,0,%d);\n",ls,fontn,thk);
fprintf(prog,"setfillstyle(%d,%d);\n",fs,fc);
fprintf(prog,"fillpoly(%d,poly);}\n",fontdir);
}//end of simple polygon filling simple
else if (strcmp(object,"fillpolygonp") == 0)
{
fscanf(fp,"%03d,%03d,%03d,%03d,%03d,%07d,%03d,%03d,%03d,%03d,%03d,%03d,%03d,%03d\n",
&fontdir,&col,&ls,&thk,&fc,&fontn,
&cp[0],&cp[1],&cp[2],&cp[3],&cp[4],&cp[5],&cp[6],&cp[7]);
int points[30];
fprintf(prog,"{\nint poly[] = {");
for (int i = 0; i < fonts*2 && i < 30;i+=2)
{
fscanf(fp,"%03d,%03d",&points[i],&points[i+1]);
fprintf(prog,"%3d,%3d,",points[i],points[i+1]);
}//end of for next loop
fprintf(prog,"0};\nsetcolor(%d);\n",col);
fprintf(prog,"setlinestyle(%d,%d,%d);\n",ls,fontn,thk);
fprintf(prog,"\npattern[0] = %d;",cp[0]);fprintf(prog,"\npattern[1] = %d;",cp[1]);fprintf(prog,"\npattern[2] = %d;",cp[2]);fprintf(prog,"\npattern[3] = %d;",cp[3]);
fprintf(prog,"\npattern[4] = %d;",cp[4]);fprintf(prog,"\npattern[5] = %d;",cp[5]);fprintf(prog,"\npattern[6] = %d;",cp[6]);fprintf(prog,"\npattern[7] = %d;",cp[7]);
fprintf(prog,"setfillpattern(pattern,%d);\n",fc);
fprintf(prog,"fillpoly(%d,poly);}\n",fontdir);
}//end of simple polygon filling simple
else if (strcmp(object,"bmp") == 0)
{
int sx,sy,ex,ey;
fscanf(fp,"%03d,%03d,%03d,%03d,%s\n",
&sx,&sy,&ex,&ey,&object);
fprintf(prog,"loadbmp(\"%s\",%d,%d,%d,%d);\n",object,sx,sy,ex,ey);
}//end of loading bitmaps
}//end of parsing all values
fclose(fp);
fprintf(prog,"\n\t}//end of redrawing all objects\n\n");
fclose(prog);
free(path);
free(path1);
}//end of function
int fc(char *file1,char *file2,char *dest)
{
FILE *src,*dst;
src = fopen(file1,"rt");
dst = fopen(dest,"at");
if (dst == NULL)
return 1;
char *buffer = (char *)calloc(1,100);
if (src != NULL)
{
fgets(buffer,100,src);
do{
fprintf(dst,"%s",buffer);
fgets(buffer,100,src);
}while (!feof(src));
fclose(src);
}
src = fopen(file2,"rt");
if (src != NULL)
{
fgets(buffer,100,src);
do{
fprintf(dst,"%s",buffer);
fgets(buffer,100,src);
}while (!feof(src));
fclose(src);
}
free(buffer);
fclose(dst);
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
448
]
]
] |
8035ccc7d046ac5873440e066dd65b97cd1c72a1 | 9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab | /face/popoface/IMToolWin.h | e2a945525d08524b640858194b3aff6249e833fa | [] | no_license | zzjs2001702/sfsipua-svn | ca3051b53549066494f6264e8f3bf300b8090d17 | e8768338340254aa287bf37cf620e2c68e4ff844 | refs/heads/master | 2022-01-09T20:02:20.777586 | 2006-03-29T13:24:02 | 2006-03-29T13:24:02 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,118 | h | #if !defined(AFX_IMTOOLWIN_H__74F305D8_437F_47DC_BA1A_3BF4BA6240B2__INCLUDED_)
#define AFX_IMTOOLWIN_H__74F305D8_437F_47DC_BA1A_3BF4BA6240B2__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// IMToolWin.h : header file
//
#include <vector>
using namespace std;
/////////////////////////////////////////////////////////////////////////////
// CIMToolWin window
class CIMToolWinItem
{
public:
CIMToolWinItem(const char *t,int img)
: Title(t),Image(img) {}
virtual ~CIMToolWinItem(){}
CString Title;
int Image;
};
class CIMToolWinFolder
{
public:
CIMToolWinFolder(const char *t,int img) : Title(t),Image(img) {}
~CIMToolWinFolder() {}
void AddItem(const char *t, int img);
BOOL Expended;
CString Title;
int Image;
vector<CIMToolWinItem *> Items;
};
#define TOOLWIN_STATUS_NORMAL 0x0000
#define TOOLWIN_STATUS_PRESSED 0x0001
#define TOOLWIN_STATUS_IN 0x0002
#define TOOLWIN_STATUS_OUT 0x0004
#define TOOLWIN_ITEM_HEIGHT 20
class CIMToolWin : public CWnd
{
enum{ //Folder颜色定义
TOOLWIN_COLOR_FOLDER_BK_IN = 0, // Background color when mouse is INside
TOOLWIN_COLOR_FOLDER_FG_IN, // Text color when mouse is INside
TOOLWIN_COLOR_FOLDER_BK_OUT, // Background color when mouse is OUTside
TOOLWIN_COLOR_FOLDER_FG_OUT, // Text color when mouse is OUTside
//Item颜色定义
TOOLWIN_COLOR_ITEM_BK_IN, // Background color when mouse is INside
TOOLWIN_COLOR_ITEM_FG_IN, // Text color when mouse is INside
TOOLWIN_COLOR_ITEM_BK_OUT, // Background color when mouse is OUTside
TOOLWIN_COLOR_ITEM_FG_OUT, // Text color when mouse is OUTside
TOOLWIN_MAX_COLORS
};
// Construction
public:
CIMToolWin();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CIMToolWin)
//}}AFX_VIRTUAL
// Implementation
public:
void SetImageList(CImageList *ImageList);
virtual ~CIMToolWin();
int GetFolderCount();
void AddItem(int Folder,const char *t,int img);
int AddFolder(const char *text,int img);
// Generated message map functions
protected:
DWORD SetColor(BYTE byColorIndex, COLORREF crColor, BOOL bRepaint);
virtual void DrawFolder(CDC *pDC,int Folder);
virtual void DrawAll(CDC *pDC);
vector<CIMToolWinFolder *> folders;
//{{AFX_MSG(CIMToolWin)
afx_msg void OnPaint();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
CSkin* m_pSkin;
CImageList *Icons;
COLORREF StartBgColor;
COLORREF EndBgColor;
COLORREF FontColor;
COLORREF FolderBgColor;
COLORREF ItemBgColor;
COLORREF m_crColors[TOOLWIN_MAX_COLORS]; // Colors to be used
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_IMTOOLWIN_H__74F305D8_437F_47DC_BA1A_3BF4BA6240B2__INCLUDED_)
| [
"yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd"
] | [
[
[
1,
124
]
]
] |
cfc728d6673a3c1c76bac9366a1872b5e4f88149 | b0252ba622183d115d160eb28953189930ebf9c0 | /Source/IntroState.h | a4340a9a89fc926b08eec22cd6d1b3765e73bccc | [] | no_license | slewicki/khanquest | 6c0ced33bffd3c9ee8a60c1ef936139a594fe2fc | f2d68072a1d207f683c099372454add951da903a | refs/heads/master | 2020-04-06T03:40:18.180208 | 2008-08-28T03:43:26 | 2008-08-28T03:43:26 | 34,305,386 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,827 | h | //////////////////////////////////////////////////////////
// File: "CIntroState.h"
//
// Author: Dennis Wallace (DW)
//
// Purpose: To contain functionality of the CIntroState state
//////////////////////////////////////////////////////////
#pragma once
#include "CBitmapfont.h"
#include "IGameState.h"
class CSGD_WaveManager;
class CSGD_TextureManager;
class CSGD_DirectInput;
class CIntroState : public IGameState
{
CSGD_TextureManager* m_pTM;
CSGD_DirectInput* m_pDI;
CBitmapFont m_BF;
CSGD_WaveManager* m_pWM;
bool m_bPaused;
bool m_bTitle;
float m_fTimer;
float m_fEscTimer;
int m_nTitle;
int m_nImageID;
int m_nTitleID;
POINT m_ptImageLoc, m_ptImageSize;
char* m_szImageFile;
bool m_bAlpha;
int m_nAlpha;
CIntroState(void);
CIntroState(const CIntroState&);
CIntroState& operator=(const CIntroState&);
~CIntroState(void);
public:
static CIntroState* GetInstance(void)
{
static CIntroState instance;
return &instance;
}
//////////////////////////////////////////////////////
// Function: “Enter”
// Last Modified: Aug 2, 2008
// Purpose: To load up all required information
//////////////////////////////////////////////////////
void Enter(void);
//////////////////////////////////////////////////////
// Function: “Exit”
// Last Modified: Aug 2, 2008
// Purpose: To unload any needed information
//////////////////////////////////////////////////////
void Exit(void);
//////////////////////////////////////////////////////
// Function: “Input”
// Last Modified: Aug 2, 2008
// Purpose: To get input from the user to interact
// with the state
//////////////////////////////////////////////////////
bool Input(float fElapsedTime);
//////////////////////////////////////////////////////
// Function: “Update”
// Last Modified: Aug 2, 2008
// Purpose: To update our information after input
//////////////////////////////////////////////////////
void Update(float fElapsedTime);
//////////////////////////////////////////////////////
// Function: “Render”
// Last Modified: Aug 2, 2008
// Purpose: To render our information to the screen
//////////////////////////////////////////////////////
void Render(float fElapsedTime);
//////////////////////////////////////////////////////
// Function: “Parse”
// Last Modified: Aug 2, 2008
// Purpose: To parce menu info
//////////////////////////////////////////////////////
bool Parse(char* szFilename);
//////////////////////////////////////////////////////
// Function: “FadeOut”
// Last Modified: Aug 2, 2008
// Purpose: fade out of screen
//////////////////////////////////////////////////////
void FadeOut(float fElapsedTime);
}; | [
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec",
"[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec"
] | [
[
[
1,
7
],
[
85,
89
],
[
91,
96
]
],
[
[
8,
84
],
[
90,
90
],
[
97,
98
]
]
] |
0a59a4e065907363be188ebbc578a279d2e3fa47 | a2904986c09bd07e8c89359632e849534970c1be | /topcoder/TestCurve.cpp | b64ef3eaee6045c7223d5924162b68bd901976ab | [] | no_license | naturalself/topcoder_srms | 20bf84ac1fd959e9fbbf8b82a93113c858bf6134 | 7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5 | refs/heads/master | 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,370 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "TestCurve.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define debug(p) cout << #p << "=" << p << endl;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
#define pb push_back
class TestCurve {
public:
vector <int> determineGrades(vector <int> scores) {
vector <int> ret;
int max_sc = 0;
forv(i,scores){
max_sc = max(scores[i],max_sc);
}
forv(i,scores){
int s = (int)(((double)scores[i]*100.0)/(double)max_sc);
ret.pb(s);
}
return ret;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { int Arr0[] = {15, 27, 8, 33, 19, 50}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {30, 54, 16, 66, 38, 100 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(0, Arg1, determineGrades(Arg0)); }
void test_case_1() { int Arr0[] = {0, 0, 0, 3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 0, 0, 100 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(1, Arg1, determineGrades(Arg0)); }
void test_case_2() { int Arr0[] = {67, 89, 72, 100, 95, 88}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {67, 89, 72, 100, 95, 88 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(2, Arg1, determineGrades(Arg0)); }
void test_case_3() { int Arr0[] = {1234, 3483, 234, 5738, 3421, 5832, 4433}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {21, 59, 4, 98, 58, 100, 76 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(3, Arg1, determineGrades(Arg0)); }
void test_case_4() { int Arr0[] = {8765}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(4, Arg1, determineGrades(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
TestCurve ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"shin@CF-7AUJ41TT52JO.(none)"
] | [
[
[
1,
72
]
]
] |
65b5bd03b2f88d5cde9c58c16f17ccd3932609fa | 2c4649c50e914b3fcad25c57480781e24115a1da | /ImageSamplers/itkImageGridSampler.h | 3351a0eeb373a2e4e8a11b1487392a23df503b31 | [] | no_license | midas-journal/midas-journal-743 | a9763a9df1d47343afacf7da995ade91171ceb4d | 283d76b3f887d5711bca81911b22a69a268857e5 | refs/heads/master | 2020-03-26T18:40:35.851601 | 2011-08-22T13:47:27 | 2011-08-22T13:47:27 | 2,248,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,739 | h | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __ImageGridSampler_h
#define __ImageGridSampler_h
#include "itkImageSamplerBase.h"
namespace itk
{
/** \class ImageGridSampler
*
* \brief Samples image voxels on a regular grid.
*
* This ImageSampler samples voxels that lie on a regular grid.
* The grid can be specified by an integer downsampling factor for
* each dimension.
*
* \parameter SampleGridSpacing: This parameter controls the spacing
* of the uniform grid in all dimensions. This should be given in
* index coordinates. \n
* example: <tt>(SampleGridSpacing 4 4 4)</tt> \n
* Default is 2 in each dimension.
*
*
* \ingroup ImageSamplers
*/
template < class TInputImage >
class ImageGridSampler :
public ImageSamplerBase< TInputImage >
{
public:
/** Standard ITK-stuff. */
typedef ImageGridSampler Self;
typedef ImageSamplerBase< TInputImage > Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( ImageGridSampler, ImageSamplerBase );
/** Typedefs inherited from the superclass. */
typedef typename Superclass::DataObjectPointer DataObjectPointer;
typedef typename Superclass::OutputVectorContainerType OutputVectorContainerType;
typedef typename Superclass::OutputVectorContainerPointer OutputVectorContainerPointer;
typedef typename Superclass::InputImageType InputImageType;
typedef typename Superclass::InputImagePointer InputImagePointer;
typedef typename Superclass::InputImageConstPointer InputImageConstPointer;
typedef typename Superclass::InputImageRegionType InputImageRegionType;
typedef typename Superclass::InputImagePixelType InputImagePixelType;
typedef typename Superclass::ImageSampleType ImageSampleType;
typedef typename Superclass::ImageSampleContainerType ImageSampleContainerType;
typedef typename Superclass::MaskType MaskType;
/** The input image dimension. */
itkStaticConstMacro( InputImageDimension, unsigned int,
Superclass::InputImageDimension );
/** Other typdefs. */
typedef typename InputImageType::IndexType InputImageIndexType;
typedef typename InputImageType::PointType InputImagePointType;
/** Typedefs for support of user defined grid spacing for the spatial samples. */
typedef typename InputImageType::OffsetType SampleGridSpacingType;
typedef typename SampleGridSpacingType::OffsetValueType SampleGridSpacingValueType;
typedef typename InputImageType::SizeType SampleGridSizeType;
typedef InputImageIndexType SampleGridIndexType;
typedef typename InputImageType::SizeType InputImageSizeType;
/** Set/Get the sample grid spacing for each dimension (only integer factors)
* This function overrules previous calls to SetNumberOfSamples.
* Moreover, it calls SetNumberOfSamples(0) (see below), to make sure
* that the user-set sample grid spacing is never overruled. */
void SetSampleGridSpacing( SampleGridSpacingType arg )
{
this->SetNumberOfSamples(0);
if ( this->m_SampleGridSpacing != arg )
{
this->m_SampleGridSpacing = arg;
this->Modified();
}
}
itkGetConstMacro(SampleGridSpacing, SampleGridSpacingType);
/** Define an isotropic SampleGridSpacing such that the desired number
* of samples is approximately realised. The following formula is used:
*
* spacing = max[ 1, round( (availablevoxels/nrofsamples)^(1/dimension) ) ],
* with
* availablevoxels = nr of voxels in input image region.
*
* The InputImageRegion needs to be specified beforehand. A mask is ignored,
* so the realised number of samples could be significantly lower than expected.
* However, the sample grid spacing is recomputed in the update phase, when the
* bounding box of the mask is known. Supplying nrofsamples=0 turns off the
* (re)computation of the SampleGridSpacing. Once nrofsamples=0 has been given,
* the last computed SampleGridSpacing is simply considered as a user parameter,
* which is not modified automatically anymore.
*
* This function overrules any previous calls to SetSampleGridSpacing.
*/
virtual void SetNumberOfSamples( unsigned long nrofsamples );
/** Selecting new samples makes no sense if nothing changed. The same
* samples would be selected anyway. */
virtual bool SelectNewSamplesOnUpdate(void)
{
return false;
};
/** Returns whether the sampler supports SelectNewSamplesOnUpdate() */
virtual bool SelectingNewSamplesOnUpdateSupported( void ) const
{
return false;
}
protected:
/** The constructor. */
ImageGridSampler()
{
this->m_RequestedNumberOfSamples = 0;
}
/** The destructor. */
virtual ~ImageGridSampler() {};
/** PrintSelf. */
void PrintSelf( std::ostream& os, Indent indent ) const;
/** Function that does the work. */
virtual void GenerateData( void );
/** An array of integer spacing factors */
SampleGridSpacingType m_SampleGridSpacing;
/** The number of samples entered in the SetNumberOfSamples method */
unsigned long m_RequestedNumberOfSamples;
private:
/** The private constructor. */
ImageGridSampler( const Self& ); // purposely not implemented
/** The private copy constructor. */
void operator=( const Self& ); // purposely not implemented
}; // end class ImageGridSampler
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkImageGridSampler.txx"
#endif
#endif // end #ifndef __ImageGridSampler_h
| [
"[email protected]"
] | [
[
[
1,
174
]
]
] |
c4ab3dfaef1a8239e53b2ee0d4b5f79eeff19733 | 4e8581b6eaaabdd58b1151201d64b45c7147dac7 | /src/Direction.h | 4222efa696a82a056182af970d0fbd7670521d4c | [] | no_license | charmingbrew/bioinformatics-mscd-2011 | c4a390bf25d2197d4e912d7976619cb02c666587 | 04d81d0f05001d3ed82911459cff6dddb3c7f252 | refs/heads/master | 2020-05-09T12:56:08.625451 | 2011-05-17T05:55:14 | 2011-05-17T05:55:14 | 33,334,714 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | h | class Node;
/**
* @file Direction.h
* @class Direction
* @brief Directions in a guide tree node.
* A direction contains a direction (as in left
* or right) OR a direction.
* A direction can only have three states:
* -# Empty: A node or a sequence can be placed.
* -# Sequence: Only A sequence can be contained.
* -# Node: Only a branch down the tree.
* Never can it have both a sequence and a branch.
* These should members should be called from the
* Node Object.
*/
#ifndef _DIRECTION_H
#define _DIRECTION_H
#include "Sequence.h"
class Direction
{
private:
Node * next;
Sequence * seq;
public:
Direction();
Direction(Sequence *seq);
Direction(Node *n);
Sequence *GetSequence();
void SetSequence(Sequence *s);
Node *GetNode();
void SetNextNode(Node *next);
void SetScore();
/// Checks for an empty Direction Object
bool isOpen();
};
#endif // _DIRECTION_H
| [
"[email protected]@e9cc6749-363d-4b58-5071-845f21bc09f4",
"millardfillmoreesquire@e9cc6749-363d-4b58-5071-845f21bc09f4"
] | [
[
[
1,
2
],
[
4,
39
]
],
[
[
3,
3
]
]
] |
0f80f8f22afb8a18bf6c8fec5f53894097cf9a23 | 2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4 | /OUAN/OUAN/Src/Game/GameObject/GameObjectParticleSystem.h | c936081eb51d6aab1d9510ea47b5df4eb717d937 | [] | no_license | juanjmostazo/once-upon-a-night | 9651dc4dcebef80f0475e2e61865193ad61edaaa | f8d5d3a62952c45093a94c8b073cbb70f8146a53 | refs/heads/master | 2020-05-28T05:45:17.386664 | 2010-10-06T12:49:50 | 2010-10-06T12:49:50 | 38,101,059 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,870 | h | #ifndef GameObjectParticleSystemH_H
#define GameObjectParticleSystemH_H
#include "GameObject.h"
#include "../../Graphics/RenderComponent/RenderComponentInitial.h"
#include "../../Graphics/RenderComponent/RenderComponentPositional.h"
#include "../../Graphics/RenderComponent/RenderComponentParticleSystem.h"
#include "../../Logic/LogicComponent/LogicComponent.h"
namespace OUAN
{
/// Models a light source object
class GameObjectParticleSystem : public GameObject, public boost::enable_shared_from_this<GameObjectParticleSystem>
{
private:
/// Holds the information related to visual rendering
RenderComponentParticleSystemPtr mRenderComponentParticleSystem;
/// Holds information related to the object's position in space
RenderComponentInitialPtr mRenderComponentInitial;
RenderComponentPositionalPtr mRenderComponentPositional;
/// Logic component: it'll represent the 'brains' of the game object
/// containing information on its current state, its life and health(if applicable),
/// or the world(s) the object belongs to
LogicComponentPtr mLogicComponent;
public:
//Constructor
GameObjectParticleSystem(const std::string& name);
//Destructor
~GameObjectParticleSystem();
/// Set logic component
void setLogicComponent(LogicComponentPtr logicComponent);
/// return logic component
LogicComponentPtr getLogicComponent();
/// Get light component
/// @return light component
RenderComponentParticleSystemPtr getRenderComponentParticleSystem() const;
/// Set light component
/// @param pRenderComponentLight the light component to set
void setRenderComponentParticleSystem(RenderComponentParticleSystemPtr pRenderComponentParticleSystem);
/// Set positional component
/// @param pRenderComponentPositional the component containing the positional information
void setRenderComponentPositional(RenderComponentPositionalPtr pRenderComponentPositional);
/// Set initial component
void setRenderComponentInitial(RenderComponentInitialPtr pRenderComponentInitial);
void setVisible(bool visible);
/// Return positional component
/// @return positional component
RenderComponentPositionalPtr getRenderComponentPositional() const;
/// Return initial component
/// @return initial component
RenderComponentInitialPtr getRenderComponentInitial() const;
void changeToWorld(int newWorld, double perc);
void changeWorldFinished(int newWorld);
void changeWorldStarted(int newWorld);
/// Reset object
virtual void reset();
bool hasPositionalComponent() const;
RenderComponentPositionalPtr getPositionalComponent() const;
/// Process collision event
/// @param gameObject which has collision with
void processCollision(GameObjectPtr pGameObject, Ogre::Vector3 pNormal);
/// Process collision event
/// @param gameObject which has collision with
void processEnterTrigger(GameObjectPtr pGameObject);
/// Process collision event
/// @param gameObject which has collision with
void processExitTrigger(GameObjectPtr pGameObject);
bool hasLogicComponent() const;
LogicComponentPtr getLogicComponent() const;
};
/// Transport object carrying around data from the level loader
/// to the ParticleSystem object
class TGameObjectParticleSystemParameters: public TGameObjectParameters
{
public:
/// Default constructor
TGameObjectParticleSystemParameters();
/// Default destructor
~TGameObjectParticleSystemParameters();
/// Light-specific parameters
TRenderComponentParticleSystemParameters tRenderComponentParticleSystemParameters;
/// Positional parameters
TRenderComponentPositionalParameters tRenderComponentPositionalParameters;
///Logic parameters
TLogicComponentParameters tLogicComponentParameters;
};
}
#endif | [
"wyern1@1610d384-d83c-11de-a027-019ae363d039",
"juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039",
"ithiliel@1610d384-d83c-11de-a027-019ae363d039"
] | [
[
[
1,
2
],
[
4,
4
],
[
6,
8
],
[
10,
12
],
[
14,
18
],
[
20,
47
],
[
51,
56
],
[
61,
64
],
[
71,
73
],
[
75,
83
],
[
88,
111
]
],
[
[
3,
3
],
[
5,
5
],
[
9,
9
],
[
19,
19
],
[
48,
50
],
[
57,
60
],
[
66,
68
],
[
74,
74
]
],
[
[
13,
13
],
[
65,
65
],
[
69,
70
],
[
84,
87
]
]
] |
c46c38778c25b7e09b2689ceff62a453ab6ef328 | 1e299bdc79bdc75fc5039f4c7498d58f246ed197 | /stdobj/LockedResource.h | 642cab08bed579bbe9a8e5e6f5565787b92315be | [] | no_license | moosethemooche/Certificate-Server | 5b066b5756fc44151b53841482b7fa603c26bf3e | 887578cc2126bae04c09b2a9499b88cb8c7419d4 | refs/heads/master | 2021-01-17T06:24:52.178106 | 2011-07-13T13:27:09 | 2011-07-13T13:27:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 902 | h | //--------------------------------------------------------------------------------
//
// Copyright (c) 2000 MarkCare Solutions
//
// Programming by Rich Schonthal
//
//--------------------------------------------------------------------------------
#ifndef _LOCKEDRESOURCE_H_
#define _LOCKEDRESOURCE_H_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//--------------------------------------------------------------------------------
class CLockedResource
{
public:
CLockedResource();
virtual ~CLockedResource();
protected:
CMutex m_mutex;
long m_nCurrentUserCount;
public:
CSingleLock* CreateExclusiveLock(DWORD = INFINITE);
bool GetExclusiveLock(CSingleLock&, DWORD = INFINITE);
bool AddUser(DWORD = INFINITE);
void RemoveUser();
long GetCurrentUserCount() const;
CMutex& GetMutex();
};
#endif // _LOCKEDRESOURCE_H_
| [
"[email protected]"
] | [
[
[
1,
38
]
]
] |
c1cf7984f64e984f30cb9feda9b202a2765f95e2 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/tools/inspect/unnamed_namespace_check.cpp | 149bb0c654b05c768fd33b3e3508a2886fd7780b | [
"BSL-1.0"
] | permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp | // unnamed_namespace_check -----------------------------------------//
// Copyright Gennaro Prota 2006.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "boost/regex.hpp"
#include "boost/lexical_cast.hpp"
#include "unnamed_namespace_check.hpp"
namespace
{
boost::regex unnamed_namespace_regex(
"\\<namespace\\s(\\?\\?<|\\{)" // trigraph ??< or {
);
} // unnamed namespace (ironical? :-)
namespace boost
{
namespace inspect
{
unnamed_namespace_check::unnamed_namespace_check() : m_errors(0)
{
register_signature( ".h" );
register_signature( ".hh" ); // just in case
register_signature( ".hpp" );
register_signature( ".hxx" ); // just in case
register_signature( ".inc" );
register_signature( ".ipp" );
register_signature( ".inl" );
}
void unnamed_namespace_check::inspect(
const string & library_name,
const path & full_path, // example: c:/foo/boost/filesystem/path.hpp
const string & contents ) // contents of file to be inspected
{
if (contents.find( "boostinspect:" "nounnamed" ) != string::npos) return;
boost::sregex_iterator cur(contents.begin(), contents.end(), unnamed_namespace_regex), end;
for( ; cur != end; ++cur, ++m_errors )
{
const string::size_type
ln = std::count( contents.begin(), (*cur)[0].first, '\n' ) + 1;
error( library_name, full_path, string(name()) + " unnamed namespace at line "
+ lexical_cast<string>(ln) );
}
}
} // namespace inspect
} // namespace boost
| [
"metrix@Blended.(none)"
] | [
[
[
1,
63
]
]
] |
83dd25a7cf62512cfd39d00e7968a85a1d862aa5 | 507d733770b2f22ea6cebc2b519037a5fa3cceed | /gs2d/src/Audio/Audiere/gs2dAudiere.h | 5a846b2596b01289400012f3eb63391af4961b0d | [] | no_license | andresan87/Torch | a3e7fa338a675b0e552afa914cb86050d641afeb | cecdbb9b4ea742b6f03e609f9445849a932ed755 | refs/heads/master | 2021-01-20T08:47:25.624168 | 2011-07-08T12:40:55 | 2011-07-08T12:40:55 | 2,014,722 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,694 | h | /*-----------------------------------------------------------------------
gameSpace2d (C) Copyright 2008-2011 Andre Santee
http://www.asantee.net/gamespace/
http://groups.google.com/group/gamespacelib
This file is part of gameSpace2d.
gameSpace2d 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.
gameSpace2d 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 gameSpace2d. If not, see
<http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------*/
#ifndef GS2D_AUDIERE_H_
#define GS2D_AUDIERE_H_
#include "../../gs2daudio.h"
#include "audiere/src/audiere.h"
namespace gs2d {
class AudiereContext : public Audio
{
audiere::AudioDevicePtr m_device;
bool CreateAudioDevice(boost::any data);
boost::weak_ptr<AudiereContext> weak_this;
AudiereContext();
public:
static boost::shared_ptr<AudiereContext> Create(boost::any data);
AudioSamplePtr LoadSampleFromFile(const std::wstring& fileName, const GS_SAMPLE_TYPE type = GSST_UNKNOWN);
AudioSamplePtr LoadSampleFromFileInMemory(void *pBuffer, const unsigned int bufferLength, const GS_SAMPLE_TYPE type = GSST_UNKNOWN);
boost::any GetAudioContext();
};
typedef boost::shared_ptr<AudiereContext> AudiereContextPtr;
class AudiereSample : public AudioSample
{
audiere::OutputStreamPtr m_output;
int m_position;
GS_SAMPLE_STATUS m_status;
GS_SAMPLE_TYPE m_type;
AudioWeakPtr m_audio;
bool LoadSampleFromFile(AudioWeakPtr audio, const std::wstring& fileName, const GS_SAMPLE_TYPE type = GSST_UNKNOWN);
bool LoadSampleFromFileInMemory(AudioWeakPtr audio, void *pBuffer, const unsigned int bufferLength, const GS_SAMPLE_TYPE type = GSST_UNKNOWN);
public:
AudiereSample();
~AudiereSample();
bool SetLoop(const bool enable);
bool GetLoop() const;
bool Play();
GS_SAMPLE_STATUS GetStatus();
bool IsPlaying();
bool Pause();
bool Stop();
GS_SAMPLE_TYPE GetType() const;
bool SetSpeed(const float speed);
float GetSpeed() const;
bool SetVolume(const float volume);
float GetVolume() const;
bool SetPan(const float pan);
float GetPan() const;
};
} // namespace gs2d
#endif | [
"Andre@AndreDell.(none)"
] | [
[
[
1,
94
]
]
] |
a69843a4eeba4791c039316c5f5436ddfa1ef4ca | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/techdemo2/engine/ui/src/ActionChoiceWindow.cpp | 1b753c4b306fa54cb168324a6fc0aa909792adf8 | [
"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-1 | C++ | false | false | 12,755 | cpp | /* 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.
*/
#include <boost/bind.hpp>
#include "UiPrerequisites.h"
#include <set>
#include <algorithm>
#include "Action.h"
#include "ActionManager.h"
#include "GameObject.h"
#include "Person.h"
#include "UiSubsystem.h"
#include "Exception.h"
#include "ActionChoiceWindow.h"
using namespace CEGUI;
using namespace std;
using namespace Ogre;
namespace rl {
const int MAX_NUM_ACTIONS = 4;
const int MAX_NUM_SUBACTIONS = 7;
ActionChoiceWindow::ActionChoiceWindow(Person* actor)
: CeGuiWindow("actionchoicewindow.xml", WND_MOUSE_INPUT),
mActor(actor)
{
mHint = getStaticText("ActionChoiceWindow/Hint");
getWindow("ActionChoiceWindow")->subscribeEvent(
Window::EventMouseClick,
boost::bind(
&ActionChoiceWindow::handleClickNotOnButtons,
this,
_1));
}
ActionChoiceWindow::~ActionChoiceWindow()
{
/*for (unsigned int i = 0; i<mButtons.size(); i++)
{
mWindow->removeChildWindow(mButtons[i]);
CEGUI::WindowManager::getSingleton().destroyWindow(mButtons[i]);
}
mButtons.clear();*/
}
bool ActionChoiceWindow::handleClickNotOnButtons(const EventArgs& evt)
{
MouseEventArgs mevt = static_cast<const MouseEventArgs&>(evt);
if (mevt.clickCount == 1) // Doppelklicks von der Truhe rausfiltern
{
destroyWindow();
return true;
}
return false;
}
int ActionChoiceWindow::showActionsOfObject(GameObject* object)
{
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"Start", "ActionChoiceWindow::showActionsOfObject");
mObject = object;
for (unsigned int i = 0; i<mButtons.size(); i++)
{
mWindow->removeChildWindow(mButtons[i]);
CEGUI::WindowManager::getSingleton().destroyWindow(mButtons[i]);
}
mButtons.clear();
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"Buttons gelöscht", "ActionChoiceWindow::showActionsOfObject");
CEGUI::Point center = mWindow->relativeToAbsolute(CEGUI::Point(0.5, 0.5));
static int RADIUS = 80;
ActionVector actions = object->getValidActions(mActor);
if (actions.size() != 0)
{
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"Aktionen ermittelt", "ActionChoiceWindow::showActionsOfObject");
ActionNode* actionTree = ActionNode::createActionTree(actions);
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"Baum erzeugt", "ActionChoiceWindow::showActionsOfObject");
createButtons(actionTree, center, RADIUS, 0, 360);
mButtonCancel = createButton("cancelbutton", center);
bindClickToCloseWindow(mButtonCancel);
mWindow->addChildWindow(mButtonCancel);
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"Buttons erzeugt", "ActionChoiceWindow::showActionsOfObject");
setButtonActions(actionTree, actionTree);
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"Ende", "ActionChoiceWindow::showActionsOfObject");
}
return actions.size();
}
void ActionChoiceWindow::setButtonActions(ActionNode* actions, ActionNode* treeRoot)
{
PushButton* button = actions->getButton();
if (actions->isLeaf())
{
Action* action = actions->getAction();
if (actions->getGroup() != NULL)
button->setVisible(false);
else
button->setVisible(true);
button->subscribeEvent(
Window::EventMouseClick,
boost::bind(
&ActionChoiceWindow::activateAction, this, action));
button->subscribeEvent(
Window::EventMouseEnters,
boost::bind(
&ActionChoiceWindow::showHint, this, action->getDescription()));
button->subscribeEvent(
Window::EventMouseLeaves,
boost::bind(
&ActionChoiceWindow::showHint, this, ""));
}
else
{
ActionGroup* gr = actions->getGroup();
if (gr != NULL && gr->getParent() != NULL)
{
button->setVisible(false);
}
else if (button != NULL)
button->setVisible(true);
if (button != NULL)
{
const NodeSet nodesToHide =
ActionNode::getAllNodesNotBelow(treeRoot, actions);
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
StringConverter::toString(nodesToHide.size())+" nodes to hide",
"ActionChoiceWindow::setButtonActions");
for (NodeSet::const_iterator iter = nodesToHide.begin(); iter != nodesToHide.end(); iter++)
{
button->subscribeEvent(
Window::EventMouseEnters,
boost::bind(
&ActionChoiceWindow::setButtonVisible,
this,
(*iter)->getButton(),
false));
}
}
const NodeSet children = actions->getChildren();
for (NodeSet::const_iterator iter = children.begin(); iter != children.end(); iter++)
{
if (button != NULL)
{
button->subscribeEvent(
Window::EventMouseEnters,
boost::bind(
&ActionChoiceWindow::setButtonVisible,
this,
(*iter)->getButton(),
true));
}
setButtonActions(*iter, treeRoot);
}
}
}
bool ActionChoiceWindow::activateAction(Action* action)
{
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"Start", "ActionChoiceWindow::activateAction");
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
action->getName().c_str(), "ActionChoiceWindow::activateAction");
try
{
//TODO: Ask for target
action->doAction(mObject, mActor, NULL);
}
catch( ScriptInvocationFailedException& sife )
{
Logger::getSingleton().log(Logger::UI, Logger::LL_ERROR, sife.toString() );
}
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"Ende", "ActionChoiceWindow::activateAction");
destroyWindow();
return true;
}
void ActionChoiceWindow::createButtons(
ActionNode* actions, const CEGUI::Point& center,
float radius, float angle, float angleWidth)
{
PushButton* button = NULL;
if (actions->isLeaf())
{
button = createButton(actions->getAction()->getName(), center);
}
else
{
if (actions->getGroup() != NULL)
{
button = createButton(actions->getGroup()->getName(), center);
}
const NodeSet children = actions->getChildren();
float angleStep = angleWidth / (float)children.size();
float ang = children.size()>1 ? angle - angleWidth : angle - 180;
for (NodeSet::const_iterator iter = children.begin();
iter != children.end(); iter++)
{
CEGUI::Point centerChild = getPositionOnCircle(center, radius, ang);
createButtons(*iter, centerChild, radius, ang, 60);
ang += angleStep;
}
}
actions->setButton(button);
if (button != NULL)
mWindow->addChildWindow(button);
}
PushButton* ActionChoiceWindow::createButton(const CeGuiString& name, const CEGUI::Point& pos)
{
Window* button = CeGuiWindow::loadWindow("buttons/"+name+".xml");
if (button == NULL)
{
button =
CeGuiWindow::loadWindow(
"buttons/defaultbutton.xml");
}
CEGUI::Size size = button->getAbsoluteSize();
button->setPosition(
Absolute, pos - CEGUI::Point(size.d_width/2, size.d_height/2));
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
(button->getText()+" "+
StringConverter::toString(button->getAbsoluteXPosition()) + ", " +
StringConverter::toString(button->getAbsoluteYPosition())).c_str(),
"createButton");
return static_cast<PushButton*>(button);
}
bool ActionChoiceWindow::setButtonVisible(PushButton* button, bool visible)
{
Ogre::String showHide;
if (visible)
showHide = "Show ";
else
showHide = "Hide ";
if (button == NULL)
{
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
showHide + "NULL", "ActionChoiceWindow::setButtonVisible");
return true;
}
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL, (showHide+button->getName()).c_str());
CEGUI::Point p = button->getRelativePosition();
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"("+StringConverter::toString(p.d_x)+", "+StringConverter::toString(p.d_y)+")");
if (visible)
button->show();
else
button->hide();
return true;
}
bool ActionChoiceWindow::showHint(const CeGuiString& hint)
{
mHint->setText(hint);
return true;
}
CEGUI::Point ActionChoiceWindow::getPositionOnCircle(
const CEGUI::Point& center, float radius, float angle)
{
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"center="+StringConverter::toString(center.d_x)+","+StringConverter::toString(center.d_y)+
" radius="+StringConverter::toString(radius)+
" angle="+StringConverter::toString(angle)
);
static const float PI = 3.1415926;
float relX = radius * sin(PI * angle/180);
float relY = radius * cos(PI * angle/180);
Logger::getSingleton().log(Logger::UI, Logger::LL_TRIVIAL,
"diff="+StringConverter::toString(relX)+","+StringConverter::toString(relY));
return center + CEGUI::Point(relX, relY);
}
ActionChoiceWindow::ActionNode*
ActionChoiceWindow::ActionNode::createActionTree(const ActionVector& actions, ActionGroup* rootGroup)
{
ActionNode* root = new ActionNode(false);
root->setGroup(rootGroup);
set<ActionGroup*> groups;
ActionVector rest;
for (ActionVector::const_iterator iter = actions.begin(); iter != actions.end(); iter++)
{
Action* action = *iter;
ActionGroup* group = action->getGroup();
if (group == NULL || group == rootGroup )
rest.push_back(action);
else if (groups.find(group) == groups.end())
groups.insert(group);
}
if (actions.size() / 1.2 <= rest.size() + groups.size())
{
groups.clear();
rest = actions;
}
for (set<ActionGroup*>::iterator groupIter = groups.begin();
groupIter != groups.end(); groupIter++)
{
ActionVector actionsThisGroup;
ActionGroup* thisGroup = *groupIter;
for (ActionVector::const_iterator actionIter = actions.begin();
actionIter != actions.end(); actionIter++)
{
Action* action = *actionIter;
if (action->getGroup() == thisGroup)
actionsThisGroup.push_back(action);
}
if (actionsThisGroup.size() > 0)
{
ActionNode* actionNodeGroup = createActionTree(actionsThisGroup, thisGroup);
root->addChild(actionNodeGroup);
}
}
for (ActionVector::iterator iter = rest.begin(); iter != rest.end(); iter++)
{
ActionNode* node = new ActionNode(true);
node->setAction(*iter);
root->addChild(node);
}
return root;
}
void ActionChoiceWindow::ActionNode::addChild(ActionChoiceWindow::ActionNode* child)
{
child->setParent(this);
mChildren.insert(child);
}
const ActionChoiceWindow::NodeSet& ActionChoiceWindow::ActionNode::getChildren()
{
return mChildren;
}
void ActionChoiceWindow::ActionNode::getAllNodes(ActionNode* treeRoot, NodeSet& nodes)
{
nodes.insert(treeRoot);
const NodeSet children = treeRoot->getChildren();
for (NodeSet::const_iterator iter = children.begin(); iter != children.end(); iter++)
getAllNodes(*iter, nodes);
}
ActionChoiceWindow::NodeSet ActionChoiceWindow::ActionNode::getAllNodesNotBelow(
ActionNode* treeRoot, ActionChoiceWindow::ActionNode* targetNode)
{
NodeSet allNodes;
getAllNodes(treeRoot, allNodes);
NodeSet nodes;
for (NodeSet::iterator iter = allNodes.begin(); iter != allNodes.end(); iter++)
{
bool leaveOut = false;
if ((*iter)->getParent() == treeRoot ||
*iter == targetNode ||
(*iter)->getButton() == NULL)
{
leaveOut = true;
continue;
}
ActionNode* node = *iter;
while(node->getParent() != NULL)
{
node = node->getParent();
if (node == targetNode)
{
leaveOut = true;
continue;
}
}
if (!leaveOut)
nodes.insert(*iter);
}
return nodes;
}
}
| [
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
442
]
]
] |
25832fdc7d4dc5fcea0f8ff4b84f1808833f913c | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/sax/Locator.hpp | 7d428070a0ebecd43a3a7b91ec36eedb2f1673db | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,106 | hpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log: Locator.hpp,v $
* Revision 1.5 2004/09/08 13:56:19 peiyongz
* Apache License Version 2.0
*
* Revision 1.4 2003/03/07 18:10:06 tng
* Return a reference instead of void for operator=
*
* Revision 1.3 2002/11/04 14:56:26 tng
* C++ Namespace Support.
*
* Revision 1.2 2002/05/27 18:33:07 tng
* To get ready for 64 bit large file, use XMLSSize_t to represent line and column number.
*
* Revision 1.1.1.1 2002/02/01 22:22:08 peiyongz
* sane_include
*
* Revision 1.6 2000/03/02 19:54:35 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.5 2000/02/24 20:12:55 abagchi
* Swat for removing Log from API docs
*
* Revision 1.4 2000/02/12 03:31:55 rahulj
* Removed duplicate CVS Log entries.
*
* Revision 1.3 2000/02/09 01:55:06 abagchi
* Removed private function docs
*
* Revision 1.2 2000/02/06 07:47:58 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:07:46 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:45:01 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#ifndef LOCATOR_HPP
#define LOCATOR_HPP
#include <xercesc/util/XercesDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
/**
* Interface for associating a SAX event with a document location.
*
* <p>If a SAX parser provides location information to the SAX
* application, it does so by implementing this interface and then
* passing an instance to the application using the document
* handler's setDocumentLocator method. The application can use the
* object to obtain the location of any other document handler event
* in the XML source document.</p>
*
* <p>Note that the results returned by the object will be valid only
* during the scope of each document handler method: the application
* will receive unpredictable results if it attempts to use the
* locator at any other time.</p>
*
* <p>SAX parsers are not required to supply a locator, but they are
* very strong encouraged to do so. If the parser supplies a
* locator, it must do so before reporting any other document events.
* If no locator has been set by the time the application receives
* the startDocument event, the application should assume that a
* locator is not available.</p>
*
* @see DocumentHandler#setDocumentLocator
*/
class SAX_EXPORT Locator
{
public:
/** @name Constructors and Destructor */
//@{
/** Default constructor */
Locator()
{
}
/** Destructor */
virtual ~Locator()
{
}
//@}
/** @name The locator interface */
//@{
/**
* Return the public identifier for the current document event.
* <p>This will be the public identifier
* @return A string containing the public identifier, or
* null if none is available.
* @see #getSystemId
*/
virtual const XMLCh* getPublicId() const = 0;
/**
* Return the system identifier for the current document event.
*
* <p>If the system identifier is a URL, the parser must resolve it
* fully before passing it to the application.</p>
*
* @return A string containing the system identifier, or null
* if none is available.
* @see #getPublicId
*/
virtual const XMLCh* getSystemId() const = 0;
/**
* Return the line number where the current document event ends.
* Note that this is the line position of the first character
* after the text associated with the document event.
* @return The line number, or -1 if none is available.
* @see #getColumnNumber
*/
virtual XMLSSize_t getLineNumber() const = 0;
/**
* Return the column number where the current document event ends.
* Note that this is the column number of the first
* character after the text associated with the document
* event. The first column in a line is position 1.
* @return The column number, or -1 if none is available.
* @see #getLineNumber
*/
virtual XMLSSize_t getColumnNumber() const = 0;
//@}
private :
/* Copy constructor */
Locator(const Locator&);
/* Assignment operator */
Locator& operator=(const Locator&);
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
] | [
[
[
1,
163
]
]
] |
e46d7dcfe2fe0452cc1ac9175a9a75ae61ae1b71 | 78fb44a7f01825c19d61e9eaaa3e558ce80dcdf5 | /guceGUI/include/guceGUI_CMeshViewerForm.h | c47bb26acce837e2b2985aaf4e276ccaecfc1e53 | [] | no_license | LiberatorUSA/GUCE | a2d193e78d91657ccc4eab50fab06de31bc38021 | a4d6aa5421f8799cedc7c9f7dc496df4327ac37f | refs/heads/master | 2021-01-02T08:14:08.541536 | 2011-09-08T03:00:46 | 2011-09-08T03:00:46 | 41,840,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,426 | h | /*
* guceGUI: GUCE module providing GUI functionality
* Copyright (C) 2002 - 2007. Dinand Vanvelzen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef GUCE_GUI_CMESHVIEWERFORM_H
#define GUCE_GUI_CMESHVIEWERFORM_H
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#ifndef GUCEF_GUI_CFILESYSTEMDIALOG_H
#include "gucefGUI_CFileSystemDialog.h"
#define GUCEF_GUI_CFILESYSTEMDIALOG_H
#endif /* GUCEF_GUI_CFILESYSTEMDIALOG_H ? */
#ifndef GUCEF_GUI_CSPINNER_H
#include "gucefGUI_CSpinner.h"
#define GUCEF_GUI_CSPINNER_H
#endif /* GUCEF_GUI_CSPINNER_H ? */
#ifndef GUCEF_GUI_CLISTBOX_H
#include "gucefGUI_CListbox.h"
#define GUCEF_GUI_CLISTBOX_H
#endif /* GUCEF_GUI_CLISTBOX_H ? */
#ifndef GUCEF_GUI_CEDITBOX_H
#include "gucefGUI_CEditbox.h"
#define GUCEF_GUI_CEDITBOX_H
#endif /* GUCEF_GUI_CEDITBOX_H ? */
#ifndef GUCEF_GUI_CCHECKBOX_H
#include "gucefGUI_CCheckbox.h"
#define GUCEF_GUI_CCHECKBOX_H
#endif /* GUCEF_GUI_CCHECKBOX_H ? */
#ifndef GUCE_GUI_COGREGUIRENDERCONTEXT_H
#include "guceGUI_COgreGUIRenderContext.h"
#define GUCE_GUI_COGREGUIRENDERCONTEXT_H
#endif /* GUCE_GUI_COGREGUIRENDERCONTEXT_H ? */
#ifndef GUCEF_GUI_CFORMEX_H
#include "gucefGUI_CFormEx.h"
#define GUCEF_GUI_CFORMEX_H
#endif /* GUCEF_GUI_CFORMEX_H ? */
#ifndef GUCE_GUI_MACROS_H
#include "guceGUI_macros.h"
#define GUCE_GUI_MACROS_H
#endif /* GUCE_GUI_MACROS_H ? */
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GUCE {
namespace GUI {
/*-------------------------------------------------------------------------//
// //
// CLASSES //
// //
//-------------------------------------------------------------------------*/
class GUCE_GUI_EXPORT_CPP CMeshViewerForm : public GUCEF::GUI::CFormEx
{
public:
CMeshViewerForm( void );
virtual ~CMeshViewerForm();
GUCEF::GUI::CButton* GetOpenMeshFileButton( void );
GUCEF::GUI::CButton* GetOpenMaterialDirButton( void );
GUCEF::GUI::CEditbox* GetMaterialDirEditbox( void );
GUCEF::GUI::CListbox* GetMaterialListbox( void );
GUCEF::GUI::CCheckbox* GetMaterialDirAsMeshDirCheckbox( void );
GUCEF::GUI::CButton* GetCloseButton( void );
GUCEF::GUI::CButton* GetShowMeshButton( void );
GUCEF::GUI::CButton* GetControlCameraButton( void );
GUCEF::GUI::CSpinner* GetPitchSpinner( void );
GUCEF::GUI::CSpinner* GetYawSpinner( void );
GUCEF::GUI::CSpinner* GetRollSpinner( void );
GUCEF::GUI::CSpinner* GetScaleSpinner( void );
GUCEF::GUI::CListbox* GetMeshListbox( void );
COgreGUIRenderContext* GetRenderContext( void );
virtual const CString& GetClassTypeName( void ) const;
protected:
virtual void OnPreLayoutLoad( void );
virtual void OnPostLayoutLoad( void );
private:
CMeshViewerForm( const CMeshViewerForm& src );
CMeshViewerForm& operator=( const CMeshViewerForm& src );
private:
GUCEF::GUI::CButton* m_openMeshFileButton;
GUCEF::GUI::CButton* m_openMaterialDirButton;
GUCEF::GUI::CButton* m_controlCameraButton;
GUCEF::GUI::CEditbox* m_materialDirEditbox;
GUCEF::GUI::CCheckbox* m_materialDirAsMeshDirCheckbox;
GUCEF::GUI::CListbox* m_materialListbox;
GUCEF::GUI::CButton* m_closeButton;
GUCEF::GUI::CButton* m_showButton;
GUCEF::GUI::CSpinner* m_pitchSpinner;
GUCEF::GUI::CSpinner* m_yawSpinner;
GUCEF::GUI::CSpinner* m_rollSpinner;
GUCEF::GUI::CSpinner* m_scaleSpinner;
GUCEF::GUI::CListbox* m_meshListbox;
COgreGUIRenderContext* m_renderContext;
};
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
} /* namespace GUI */
} /* namespace GUCE */
/*-------------------------------------------------------------------------*/
#endif /* GUCE_GUI_CMESHVIEWERFORM_H ? */
/*-------------------------------------------------------------------------//
// //
// Info & Changes //
// //
//-------------------------------------------------------------------------//
- 08-04-2007 :
- Initial implementation
---------------------------------------------------------------------------*/
| [
"[email protected]"
] | [
[
[
1,
173
]
]
] |
f329914a880d591b3a4e611b4fb58c9b45914898 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/phoenix/test/primitives_tests.cpp | 31992cff14c200bd28e0b49c4c44c6abc65e2f4c | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,325 | cpp | /*=============================================================================
Phoenix V1.2.1
Copyright (c) 2001-2003 Joel de Guzman
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <iostream>
#include <boost/detail/lightweight_test.hpp>
#define PHOENIX_LIMIT 15
#include <boost/spirit/phoenix/primitives.hpp>
using namespace phoenix;
using namespace std;
///////////////////////////////////////////////////////////////////////////////
int
main()
{
char c1 = '1';
int i1 = 1, i2 = 2, i = 4;
const char* s2 = "2";
///////////////////////////////////////////////////////////////////////////////
//
// Values, variables and arguments
//
///////////////////////////////////////////////////////////////////////////////
cout << val("Hello")() << val(' ')() << val("World")() << endl;
BOOST_TEST(arg1(c1) == c1);
BOOST_TEST(arg1(i1, i2) == i1);
BOOST_TEST(arg2(i1, s2) == s2);
BOOST_TEST(val(3)() == 3);
BOOST_TEST(var(i)() == 4);
BOOST_TEST(var(++i)() == 5);
return boost::report_errors();
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
42
]
]
] |
a9ff9bb669dea2a5453c32eb86120d8b3f60ea69 | 056229ca14aa1d0604c056d14dae103d4308d07e | /FuncItemManager.h | 694ef9c50b3bcf7074379687dbb4fd3cbba36860 | [] | no_license | bruderstein/ZenCoding-Python | 7f6463534859e7f778dbde05eb43a56a57246516 | d291792c6ab154e6ffe41781eab222a0eaeccbaf | refs/heads/master | 2021-01-10T19:25:48.160038 | 2011-03-22T19:32:09 | 2011-03-22T19:32:09 | 894,698 | 19 | 5 | null | 2018-10-21T06:18:18 | 2010-09-07T20:49:02 | Python | UTF-8 | C++ | false | false | 714 | h | #ifndef FUNCITEMMANAGER_H
#define FUNCITEMMANAGER_H
enum KeyModifiers
{
MODIFIER_NONE = 0,
MODIFIER_CTRL = 1,
MODIFIER_ALT = 2,
MODIFIER_SHIFT = 4
};
class FuncItemManager
{
public:
FuncItemManager();
~FuncItemManager();
int addFunction(const TCHAR *functionName,
PFUNCPLUGINCMD function,
ShortcutKey* shortcutKey = NULL,
bool initToChecked = false);
int addFunction(const TCHAR *functionName,
PFUNCPLUGINCMD function,
UCHAR key,
int modifiers,
bool initToChecked = false);
void addSplitter();
FuncItem* getFuncItems(int *funcCount);
private:
std::list<FuncItem*> m_funcList;
FuncItem* m_funcItems;
};
#endif // FUNCITEMMANAGER_H | [
"[email protected]"
] | [
[
[
1,
42
]
]
] |
713e70ede9658562cb5aea913b5b95d5e0b6a633 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib/src/mglgui/MglguiMfcView.cpp | 99726e8bdb2de3da49a011cdde680a88e14e0ef4 | [] | no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,996 | cpp | // CMglguiMfcView.cpp : インプリメンテーション ファイル
//
#include "stdafx.h"
#include "MglguiMfcView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMglguiMfcView
IMPLEMENT_DYNCREATE(CMglguiMfcView, CView)
CMglguiMfcView::CMglguiMfcView()
{
}
CMglguiMfcView::~CMglguiMfcView()
{
}
/*
const AFX_MSGMAP* PASCAL theClass::_GetBaseMessageMap(){ return &baseClass::messageMap; }
const AFX_MSGMAP* theClass::GetMessageMap() const { return &theClass::messageMap; }
AFX_COMDAT AFX_DATADEF const AFX_MSGMAP theClass::messageMap = {
&theClass::_GetBaseMessageMap, &theClass::_messageEntries[0]
};
AFX_COMDAT const AFX_MSGMAP_ENTRY theClass::_messageEntries[] = {
// Mapping
}
*/
BEGIN_MESSAGE_MAP(CMglguiMfcView, CView)
//{{AFX_MSG_MAP(CMglguiMfcView)
// メモ - ClassWizard はこの位置にマッピング用のマクロを追加または削除します。
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMglguiMfcView 描画
void CMglguiMfcView::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
// TODO: この位置に描画用のコードを追加してください
}
/////////////////////////////////////////////////////////////////////////////
// CMglguiMfcView 診断
#ifdef _DEBUG
void CMglguiMfcView::AssertValid() const
{
CView::AssertValid();
}
void CMglguiMfcView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMglguiMfcView メッセージ ハンドラ
void CMglguiMfcView::OnPrint(CDC* pDC, CPrintInfo* pInfo)
{
// TODO: この位置に固有の処理を追加するか、または基本クラスを呼び出してください
CView::OnPrint(pDC, pInfo);
}
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
] | [
[
[
1,
77
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.