blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bb15d0c26b7b8427a50a0b8f2423203bd6f9204e | c3a1c34a26351e2accff58a68a8a60127d9c1a8f | /src/data/notelistmodel.h | 26d2cab9ff56d29bc1f524c2ac7f7295bf52e11f | []
| no_license | remerico/schnote | f10c128f86860d6876e826dc5da44ce478f6373f | 15b4dc54ed03105914919968344cf0b5778a4a2d | refs/heads/master | 2020-04-22T08:46:07.238781 | 2010-11-02T03:00:15 | 2010-11-02T03:00:15 | 32,114,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,191 | h | #ifndef NOTELISTMODEL_H
#define NOTELISTMODEL_H
#include <QObject>
#include <QAbstractListModel>
#include <QDateTime>
#include <QRegExp>
#include "notedb.h"
#include "notedata.h"
class NoteListModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit NoteListModel(QObject *parent = 0);
NoteListModel(const NoteIndexList ¬esIndices, QObject *parent = 0)
: QAbstractListModel(parent), noteIndexList(notesIndices) {}
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
Note noteData(const QModelIndex &index) const;
private:
NoteIndexList noteIndexList;
signals:
public slots:
int appendNote(const Note ¬e);
QList<int> appendNote(const NoteList &list);
int insertNote(const Note ¬e, int row = -1);
int editNote(const Note ¬e, int row = -1);
void search(const QString &search);
void removeNote(int row);
void removeNoteById(int id);
void refreshData();
};
#endif // NOTELISTMODEL_H
| [
"remerico@1bb478cd-69f2-1541-6d56-611775ec9bb1"
]
| [
[
[
1,
44
]
]
]
|
2f845921c992d3500dc08e65925a1b40cc17059f | 35b299a28b33ac4b60257eaa2cbc02cd9006e605 | /critter.h | cdebd11ec656674e48700badf545c8b9bff58a30 | []
| no_license | pblomqvi/HackfestDemo | b2b865150c83d90b90a009b2239ed2d9852d302a | 9b8d589795ea69fb6bfcc6f586bd204b388098c0 | refs/heads/master | 2020-05-21T00:35:46.702915 | 2010-10-23T11:27:00 | 2010-10-23T11:27:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | h | #ifndef CRITTER_H
#define CRITTER_H
// Repserenset single entity which can work as particle emitter
#include <QBrush>
#include <QColor>
#include <QPointF>
#include <QRect>
#include <QRectF>
#include <QVector2D>
#include <QRadialGradient>
#include "tail.h"
class QPainter;
class Critter
{
public:
Critter(const QPointF &position, qreal radius, const qreal velocity);
~Critter();
void drawCritter(QPainter *painter);
void updateBrush();
void updateCache();
void clearSteering();
void steerForWander(qreal strength);
bool steerToTarget(QPointF target, qreal strength);
void steerToStayInScreen(qreal strength);
void move();
void setTentacleTarget(QPointF target);
QPointF pos();
void setExpandingColor(QColor newColor);
void updateColor();
private:
QBrush brush;
QPointF position;
QVector2D steeringVector;
QVector2D prevSteeringVector;
QVector2D directionVector; // last move direction
qreal vel;
qreal radius;
QColor innerColor;
QColor outerColor;
QImage *cache;
qreal radiantPos;
QBrush gradientBrush;
QList<Tentacle> tails;
QPointF tentacleTarget;
int wanderCounter;
bool wanderLeft;
};
#endif // CRITTER_H
| [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
a9f3fa2b4e2b34cce12fbd8cac412a6f93d21c0d | a04058c189ce651b85f363c51f6c718eeb254229 | /Src/Forms/M411EnterPersonForm.hpp | a064519a753bc5b346104192afbbf3114d2b185b | []
| no_license | kjk/moriarty-palm | 090f42f61497ecf9cc232491c7f5351412fba1f3 | a83570063700f26c3553d5f331968af7dd8ff869 | refs/heads/master | 2016-09-05T19:04:53.233536 | 2006-04-04T06:51:31 | 2006-04-04T06:51:31 | 18,799 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 870 | hpp | #ifndef __M411_ENTER_PERSON_FORM_HPP__
#define __M411_ENTER_PERSON_FORM_HPP__
#include "MoriartyForm.hpp"
class M411EnterPersonForm: public MoriartyForm
{
Field firstNameField_;
Field lastNameField_;
Field cityOrZipField_;
Control stateField_;
ArsLexis::String stateSymbol_;
void handleControlSelect(const EventType& data);
protected:
void attachControls();
void resize(const ArsRectangle& screenBounds);
bool handleEvent(EventType& event);
public:
M411EnterPersonForm(MoriartyApplication& app):
MoriartyForm(app, m411EnterPersonForm, true),
firstNameField_(*this),
lastNameField_(*this),
cityOrZipField_(*this),
stateField_(*this)
{
setFocusControlId(lastNameField);
}
~M411EnterPersonForm();
};
#endif | [
"andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c"
]
| [
[
[
1,
40
]
]
]
|
0355b2e0954b64c094f58068edb94fd45d16edd3 | 777399eafeb952743fcb973fbba392842c2e9b14 | /CyberneticWarrior/CyberneticWarrior/source/SGD Wrappers/CSGD_Direct3D.cpp | 8016bdab88440a3d1641efd178f2e0f8569a7c34 | []
| no_license | Warbeleth/cyberneticwarrior | 7c0af33ada4d461b90dc843c6a25cd5dc2ba056a | 21959c93d638b5bc8a881f75119d33d5708a3ea9 | refs/heads/master | 2021-01-10T14:31:27.017284 | 2010-11-23T23:16:28 | 2010-11-23T23:16:28 | 53,352,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,211 | cpp | ////////////////////////////////////////////////////////
// File : "CSGD_Direct3D.cpp"
//
// Author : Jensen Rivera (JR)
//
// Date Created : 5/25/2006
//
// Purpose : Wrapper class for Direct3D.
////////////////////////////////////////////////////////
/*
Disclaimer:
This source code was developed for and is the property of:
Full Sail University Game Development Curriculum 2008-2009 and
Full Sail Real World Education Game Design Curriculum 2000-2008
Full Sail students may not redistribute this code,
but may use it in any project for educational purposes.
*/
#include "CSGD_Direct3D.h"
// Initialize the static object.
CSGD_Direct3D CSGD_Direct3D::m_Instance;
///////////////////////////////////////////////////////////////////
// Function: "CSGD_Direct3D(Constructor)"
///////////////////////////////////////////////////////////////////
CSGD_Direct3D::CSGD_Direct3D(void)
{
m_lpDirect3DObject = NULL;
m_lpDirect3DDevice = NULL;
m_lpSprite = NULL;
m_lpFont = NULL;
m_lpLine = NULL;
memset(&m_PresentParams, 0, sizeof(D3DPRESENT_PARAMETERS));
}
///////////////////////////////////////////////////////////////////
// Function: "~CSGD_Direct3D(Destructor)"
///////////////////////////////////////////////////////////////////
CSGD_Direct3D::~CSGD_Direct3D(void)
{
}
///////////////////////////////////////////////////////////////////
// Function: "GetInstance"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: An instance to this class.
//
// Purpose: Returns an instance to this class.
///////////////////////////////////////////////////////////////////
CSGD_Direct3D* CSGD_Direct3D::GetInstance(void)
{
return &m_Instance;
}
///////////////////////////////////////////////////////////////////
// Function: "CSGD_Direct3D(Accessors)"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: A pointer to a data member in this class.
//
// Purpose: Accesses data members in this class.
///////////////////////////////////////////////////////////////////
LPDIRECT3D9 CSGD_Direct3D::GetDirect3DObject(void) { return m_lpDirect3DObject; }
LPDIRECT3DDEVICE9 CSGD_Direct3D::GetDirect3DDevice(void) { return m_lpDirect3DDevice; }
LPD3DXSPRITE CSGD_Direct3D::GetSprite(void) { return m_lpSprite; }
LPD3DXLINE CSGD_Direct3D::GetLine(void) { return m_lpLine; }
const D3DPRESENT_PARAMETERS*CSGD_Direct3D::GetPresentParams(void) { return &m_PresentParams; }
///////////////////////////////////////////////////////////////////
// Function: "InitDirect3D"
//
// Last Modified: 10/29/2008
//
// Input: hWnd A handle to the window to initialize
// Direct3D in.
// nScreenWidth The width to initialize the device into.
// nScreenHeight The height to initialize the device into.
// bIsWindowed The screen mode to initialize the device into.
// bVsync true to put the device into vsynced display mode.
//
// Return: true if successful.
//
// Purpose: Initializes Direct3D9.
///////////////////////////////////////////////////////////////////
bool CSGD_Direct3D::InitDirect3D(HWND hWnd, int nScreenWidth, int nScreenHeight, bool bIsWindowed, bool bVsync)
{
// Make sure the hWnd is valid.
if (!hWnd) return false;
// Set the handle to the window.
m_hWnd = hWnd;
// Create the Direct3D9 Object.
m_lpDirect3DObject = Direct3DCreate9(D3D_SDK_VERSION);
// Make sure the object is valid.
if (!m_lpDirect3DObject) DXERROR("Failed to Create D3D Object");
// Setup the parameters for using Direct3D.
m_PresentParams.BackBufferWidth = nScreenWidth;
m_PresentParams.BackBufferHeight = nScreenHeight;
m_PresentParams.BackBufferFormat = (bIsWindowed) ? D3DFMT_UNKNOWN : D3DFMT_R5G6B5;
m_PresentParams.BackBufferCount = 1;
m_PresentParams.MultiSampleType = D3DMULTISAMPLE_NONE;
m_PresentParams.MultiSampleQuality = 0;
m_PresentParams.SwapEffect = D3DSWAPEFFECT_COPY;
m_PresentParams.hDeviceWindow = hWnd;
m_PresentParams.Windowed = bIsWindowed;
m_PresentParams.EnableAutoDepthStencil = false;
m_PresentParams.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
m_PresentParams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
m_PresentParams.PresentationInterval = (bVsync) ? D3DPRESENT_INTERVAL_DEFAULT : D3DPRESENT_INTERVAL_IMMEDIATE;
// Create the Direct3D Device.
if (FAILED(m_lpDirect3DObject->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&m_PresentParams, &m_lpDirect3DDevice)))
DXERROR("Failed to Create D3D Device");
// Create Sprite Object.
if (FAILED(D3DXCreateSprite(m_lpDirect3DDevice, &m_lpSprite)))
DXERROR("Failed to Create the Sprite object");
// Create the Line Object.
if (FAILED(D3DXCreateLine(m_lpDirect3DDevice, &m_lpLine)))
DXERROR("Failed to Create the Line Object");
// Setup Line parameters.
m_lpLine->SetAntialias(TRUE);
m_lpLine->SetWidth(3.0f);
// Return success.
return true;
}
///////////////////////////////////////////////////////////////////
// Function: "Shutdown"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: void
//
// Purpose: Shuts down Direct3D9.
///////////////////////////////////////////////////////////////////
void CSGD_Direct3D::ShutdownDirect3D(void)
{
SAFE_RELEASE(m_lpFont);
SAFE_RELEASE(m_lpLine);
SAFE_RELEASE(m_lpSprite);
SAFE_RELEASE(m_lpDirect3DDevice);
SAFE_RELEASE(m_lpDirect3DObject);
}
///////////////////////////////////////////////////////////////////
// Function: "Clear"
//
// Last Modified: 5/25/2006
//
// Input: ucRed The amount of red to clear the screen with (0-255).
// ucGreen The amount of green to clear the screen with (0-255).
// ucBlue The amount of blue to clear the screen with (0-255).
//
// Return: void
//
// Purpose: Clears the screen to a given color.
///////////////////////////////////////////////////////////////////
void CSGD_Direct3D::Clear(unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue)
{
m_lpDirect3DDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(ucRed, ucGreen, ucBlue), 1.0f, 0);
// Check for lost device (could happen from an ALT+TAB or ALT+ENTER).
if (m_lpDirect3DDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
{
m_lpLine->OnLostDevice();
m_lpSprite->OnLostDevice();
m_lpDirect3DDevice->Reset(&m_PresentParams);
m_lpSprite->OnResetDevice();
m_lpLine->OnResetDevice();
}
}
///////////////////////////////////////////////////////////////////
// Function: "DeviceBegin"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: true if successful.
//
// Purpose: Begins the device for rendering.
///////////////////////////////////////////////////////////////////
bool CSGD_Direct3D::DeviceBegin(void)
{
if (FAILED(m_lpDirect3DDevice->BeginScene()))
DXERROR("Failed to begin device scene.")
return true;
}
///////////////////////////////////////////////////////////////////
// Function: "SpriteBegin"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: true if successful.
//
// Purpose: Begins the sprite for rendering.
///////////////////////////////////////////////////////////////////
bool CSGD_Direct3D::SpriteBegin(void)
{
if (FAILED(m_lpSprite->Begin(D3DXSPRITE_ALPHABLEND)))
DXERROR("Failed to begin sprite scene.")
return true;
}
///////////////////////////////////////////////////////////////////
// Function: "LineBegin"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: true if successful.
//
// Purpose: Begins the line for rendering.
///////////////////////////////////////////////////////////////////
bool CSGD_Direct3D::LineBegin(void)
{
if (FAILED(m_lpLine->Begin()))
DXERROR("Failed to begin line scene.")
return true;
}
///////////////////////////////////////////////////////////////////
// Function: "DeviceEnd"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: true if successful.
//
// Purpose: Ends the device for rendering.
///////////////////////////////////////////////////////////////////
bool CSGD_Direct3D::DeviceEnd(void)
{
if (FAILED(m_lpDirect3DDevice->EndScene()))
DXERROR("Failed to end device scene.")
return true;
}
///////////////////////////////////////////////////////////////////
// Function: "SpriteEnd"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: true if successful.
//
// Purpose: Ends the sprite for rendering.
///////////////////////////////////////////////////////////////////
bool CSGD_Direct3D::SpriteEnd(void)
{
if (FAILED(m_lpSprite->End()))
DXERROR("Failed to end sprite scene.")
return true;
}
///////////////////////////////////////////////////////////////////
// Function: "LineEnd"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: true if successful.
//
// Purpose: Ends the line for rendering.
///////////////////////////////////////////////////////////////////
bool CSGD_Direct3D::LineEnd(void)
{
if (FAILED(m_lpLine->End()))
DXERROR("Failed to end line scene.")
return true;
}
///////////////////////////////////////////////////////////////////
// Function: "Present"
//
// Last Modified: 5/25/2006
//
// Input: void
//
// Return: void
//
// Purpose: Renders your back buffer to the screen.
///////////////////////////////////////////////////////////////////
void CSGD_Direct3D::Present(void)
{
m_lpDirect3DDevice->Present(NULL, NULL, NULL, NULL);
}
///////////////////////////////////////////////////////////////////
// Function: "ChangeDisplayParam"
//
// Last Modified: 5/25/2006
//
// Input: nWidth The width to change the device to.
// nHeight The height to change the device to.
// bWindowed The mode to put the window in.
//
// Return: void
//
// Purpose: Changes the display parameters of the device.
///////////////////////////////////////////////////////////////////
void CSGD_Direct3D::ChangeDisplayParam(int nWidth, int nHeight, bool bWindowed)
{
// Set the new Presentation Parameters.
m_PresentParams.BackBufferFormat = (bWindowed) ? D3DFMT_UNKNOWN : D3DFMT_R5G6B5;
m_PresentParams.Windowed = bWindowed;
m_PresentParams.BackBufferWidth = nWidth;
m_PresentParams.BackBufferHeight = nHeight;
// Reset the device.
m_lpLine->OnLostDevice();
m_lpSprite->OnLostDevice();
m_lpDirect3DDevice->Reset(&m_PresentParams);
m_lpSprite->OnResetDevice();
m_lpLine->OnResetDevice();
// Setup window style flags
DWORD dwWindowStyleFlags = WS_VISIBLE;
if (bWindowed)
{
dwWindowStyleFlags |= WS_OVERLAPPEDWINDOW;
ShowCursor(TRUE); // show the mouse cursor
}
else
{
dwWindowStyleFlags |= WS_POPUP;
ShowCursor(FALSE); // hide the mouse cursor
}
SetWindowLong(m_hWnd, GWL_STYLE, dwWindowStyleFlags);
// Set the window to the middle of the screen.
if (bWindowed)
{
// Setup the desired client area size
RECT rWindow;
rWindow.left = 0;
rWindow.top = 0;
rWindow.right = nWidth;
rWindow.bottom = nHeight;
// Get the dimensions of a window that will have a client rect that
// will really be the resolution we're looking for.
AdjustWindowRectEx(&rWindow,
dwWindowStyleFlags,
FALSE,
WS_EX_APPWINDOW);
// Calculate the width/height of that window's dimensions
int windowWidth = rWindow.right - rWindow.left;
int windowHeight = rWindow.bottom - rWindow.top;
SetWindowPos(m_hWnd, HWND_TOP, (GetSystemMetrics(SM_CXSCREEN)>>1) - (windowWidth>>1),
(GetSystemMetrics(SM_CYSCREEN)>>1) - (windowHeight>>1),
windowWidth, windowHeight, SWP_SHOWWINDOW);
}
else
{
// Let windows know the window has changed.
SetWindowPos(m_hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
}
}
///////////////////////////////////////////////////////////////////
// Function: "DrawRect"
//
// Last Modified: 5/25/2006
//
// Input: rRt The region of the screen to fill.
// ucRed The amount of red to fill that region with (0-255).
// ucGreen The amount of green to fill that region with (0-255).
// ucBlue The amount of blue to fill that region with (0-255).
//
// Return: void
//
// Purpose: Draws a rectangle of a given color to the screen.
///////////////////////////////////////////////////////////////////
void CSGD_Direct3D::DrawRect(RECT rRt, unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue)
{
D3DRECT d3dRect;
d3dRect.x1 = rRt.left;
d3dRect.y1 = rRt.top;
d3dRect.x2 = rRt.right;
d3dRect.y2 = rRt.bottom;
m_lpDirect3DDevice->Clear(1, &d3dRect, D3DCLEAR_TARGET, D3DCOLOR_XRGB(ucRed, ucGreen, ucBlue), 1.0f, 0);
}
///////////////////////////////////////////////////////////////////
// Function: "DrawLine"
//
// Last Modified: 5/25/2006
//
// Input: nX1 The starting x of the line.
// nY1 The starting y of the line.
// nX2 The ending x of the line.
// nY2 The ending y of the line.
// ucRed The amount of red to draw the line with (0-255).
// ucGreen The amount of green to draw the line with (0-255).
// ucBlue The amount of blue to draw the line with (0-255).
//
// Return: void
//
// Purpose: Draws a rectangle of a given color to the screen.
///////////////////////////////////////////////////////////////////
void CSGD_Direct3D::DrawLine(int nX1, int nY1, int nX2, int nY2, unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue)
{
D3DXVECTOR2 verts[2];
verts[0].x = (float)nX1;
verts[0].y = (float)nY1;
verts[1].x = (float)nX2;
verts[1].y = (float)nY2;
m_lpLine->Draw(verts, 2, D3DCOLOR_XRGB(ucRed, ucGreen, ucBlue));
}
///////////////////////////////////////////////////////////////////
// Function: "DrawText"
//
// Last Modified: 5/25/2006
//
// Input: lpzText The text to draw to the screen.
// nX The x position to draw the text at.
// nY The y position to draw the text at.
// ucRed The amount of red to draw the text with (0-255).
// ucGreen The amount of green to draw the text with (0-255).
// ucBlue The amount of blue to draw the text with (0-255).
//
// Return: void
//
// Purpose: Draws text to the screen with a given color.
///////////////////////////////////////////////////////////////////
void CSGD_Direct3D::DrawText(char *lpzText, int nX, int nY, unsigned char ucRed, unsigned char ucGreen, unsigned char ucBlue)
{
// Pointer to the Back Buffer.
LPDIRECT3DSURFACE9 d3dBackBuffer = 0;
// Get the Back Buffer from the Device.
m_lpDirect3DDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &d3dBackBuffer);
// Get a Device Context.
HDC hdc = 0;
d3dBackBuffer->GetDC(&hdc);
// Print the string out to the screen.
SetTextColor(hdc, RGB(ucRed, ucGreen, ucBlue));
SetBkMode(hdc, TRANSPARENT);
TextOut(hdc, nX, nY, lpzText, (int)strlen(lpzText));
// Release the Device Context.
d3dBackBuffer->ReleaseDC(hdc);
SAFE_RELEASE(d3dBackBuffer);
}
| [
"[email protected]"
]
| [
[
[
1,
493
]
]
]
|
7fdbe19dedacb11efa720f9382b9e8f52cd55f1d | 651639abcfc06818971a0296944703b3dd050e8d | /Game.hpp | 20b61ad4bc49a27c1b494a6f952297aff1431504 | []
| no_license | reanag/snailfight | 5256dc373e3f3f3349f77c7e684cb0a52ccc5175 | c4f157226faa31d526684233f3c5cd4572949698 | refs/heads/master | 2021-01-19T07:34:17.122734 | 2010-01-20T17:16:36 | 2010-01-20T17:16:36 | 34,893,173 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 1,304 | hpp | #ifndef GAME_HPP
#define GAME_HPP
#include "..\Box2D_v2.0.1\Box2D\Include\Box2D.h"
#include <SFML/Graphics.hpp>
#include <iostream>
#include <math.h>
#include <vector>
#include "GameLogic.hpp"
#include "TempObjectHandler.hpp"
#include "Stage.hpp"
#include "Stage2.hpp"
#include "Snail.hpp"
#include "NetworkInterface.cpp"
#include "Pool.cpp"
#include "Menu.hpp"
#include "GameSurface.hpp"
using namespace std;
using namespace sf;
class GameLogic;
class Snail;
class Pool;
static Pool* pPoo;
class Game{
public:
int Width, Height; // Módosítva by CseAn 2010.01.18
RenderWindow* Window;
bool InGame;
b2World* world;
float32 timeStep;
int32 iterations;
GameLogic* Logic;
TempObjectHandler* TOH;
Stage2* GameStage;
GameSurface* Surface;
Snail* MySnail;
Snail* OtherSnail;
View GameView;
Game( RenderWindow* window, int i, string iP);
//1 Game( RenderWindow* window, int i, Pool* p);
void static ThreadCreateServerFunc(void* UserData);
void static ThreadCreateClientFunc(void* UserData);
string ip;
string* p;
void Show();
void GameLoop();
};
#endif
| [
"[email protected]@96fa20d8-dc45-11de-8f20-5962d2c82ea8",
"[email protected]@96fa20d8-dc45-11de-8f20-5962d2c82ea8"
]
| [
[
[
1,
6
],
[
11,
20
],
[
22,
41
],
[
45,
46
],
[
48,
48
],
[
50,
50
],
[
53,
68
]
],
[
[
7,
10
],
[
21,
21
],
[
42,
44
],
[
47,
47
],
[
49,
49
],
[
51,
52
]
]
]
|
e6d345c032797535680d73903b1c44db809c73bb | 995feb15e565ed62ed872932e02333aca400608a | /interface.h | 6d140238143813d9f22dafea0784f302548c0be4 | []
| no_license | wyyrepo/fann-excel | 89b34a8ab4f0a49e8152f774dcb65f4fbc274b27 | 447ba1937d59b503bf451b4d8b3d43856179b7e0 | refs/heads/master | 2021-05-29T13:33:43.841025 | 2009-08-29T18:30:53 | 2009-08-29T18:30:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,330 | h | #pragma once
#include <xlw/MyContainers.h>
#include <xlw/DoubleOrNothing.h>
//<xlw:libraryname=FANNExcel
std::string // Get library ID.
fannInqLibraryVersion();
bool // create training file for FANN network
fannCreateTrainingFile(const NEMatrix& inData // is input data matrix. Variables are in columns. Training sets in rows
, const NEMatrix& outData // is output data matrix. Variables in columns. Training sets in rows
, const std::string& trainFileName // is name of the training file to be created
);
bool // create a standard fully connected backpropagation neural network and save it into file.
fannCreateStandardArray( int nOfLayers // is number of layers
, const MyArray& neurons // vector with number of neurons in each layer (including input, hiddenand output layers)
, const std::string& netFileName // is the name of the created ANN file
);
double // train network on train file. Return MSE
fannTrainOnFile(const std::string& netFile // is the ANN file
, const std::string& trainFile // is name of the input training data file
, int maxEpochs // is maximum number of epochs,
, DoubleOrNothing desiredError // is desired error (MSE)
);
double // train network on in- and out-data. Return MSE
fannTrainOnData(const std::string& netFile // is the network defition ANN file
, const NEMatrix& inData // is input data matrix. Variables are in columns. Training sets in rows
, const NEMatrix& outData // is output data matrix. Variables in columns. Training sets in rows
, int maxEpochs // is maximum number of epochs,
, DoubleOrNothing desiredError // is desired error (MSE)
);
double // train on in/outTrainData and report MSE on test data.
fannTrainOnDataAndTest(const std::string& netFile // is the network defition ANN file
, const NEMatrix& inTrainData // is input train data matrix. Variables are in columns. Training sets in rows
, const NEMatrix& outTrainData // is output train data matrix. Variables in columns. Training sets in rows
, int maxEpochs // is maximum number of epochs,
, const NEMatrix& inTestData // is input test data matrix.
, const NEMatrix& outTestData // is output test data matrix
, DoubleOrNothing desiredError // is desired error (MSE)
);
double // test network on set of known in- and out-data withou modifying hte network. Return MSE
fannTestOnData(const std::string& netFile // is the network definition ANN file
, const NEMatrix& inData // is input data matrix. Variables are in columns. Training sets in rows
, const NEMatrix& outData // is output data matrix. Variables in columns. Training sets in rows
);
NEMatrix // run input through the neural network, returning an array of outputs, The variables are incolumns (equal to # of neurons inoutput layer), sets are in rows (equal to # of rows of the input data)
fannRun(const std::string& netFile // is the network definition ANN file
, const NEMatrix& inData // is input data matrix. Variables are in columns. Sets is in rows
);
bool // set new training bit-fail limit
fannSetBitFailLimit(const std::string& netFile // is the network definition ANN file
, double bitFailLimit // is the new bit fail limit
);
| [
"marek.ozana@62256918-840b-11de-97a7-19ffed92f3b0"
]
| [
[
[
1,
63
]
]
]
|
4f890b2e570564aae5662dafcd5d89906f44cc65 | b6bad03a59ec436b60c30fc793bdcf687a21cf31 | /som2416/wince5/pddlist.cpp | d789448ee32a9e48587cbc15bb5ba07f190a4daf | []
| no_license | blackfa1con/openembed | 9697f99b12df16b1c5135e962890e8a3935be877 | 3029d7d8c181449723bb16d0a73ee87f63860864 | refs/heads/master | 2021-01-10T14:14:39.694809 | 2010-12-16T03:20:27 | 2010-12-16T03:20:27 | 52,422,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
#include <windows.h>
#include <keybdpdd.h>
// Add NOP driver for USB HID and RDP support.
BOOL
WINAPI
PS2_NOP_Entry(
UINT uiPddId,
PFN_KEYBD_EVENT pfnKeybdEvent,
PKEYBD_PDD *ppKeybdPdd
);
BOOL
WINAPI
Matrix_Entry(
UINT uiPddId,
PFN_KEYBD_EVENT pfnKeybdEvent,
PKEYBD_PDD *ppKeybdPdd
);
PFN_KEYBD_PDD_ENTRY g_rgpfnPddEntries[] = {
PS2_NOP_Entry,
Matrix_Entry,
NULL
};
| [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
f7d522e4b77fea3c5ae61e3dc2152619b47c8d58 | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/WorkspaceTabDoc.h | 305b0e9098ecb0df657303ec274523eafe6a567e | []
| no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,127 | h | #if !defined(AFX_WORKSPACETABDOC_H__A90B50A0_583C_4B02_A502_5276AC639EF3__INCLUDED_)
#define AFX_WORKSPACETABDOC_H__A90B50A0_583C_4B02_A502_5276AC639EF3__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// WorkspaceTabDoc.h : header file
//
#include "FunctionProperties.h"
/////////////////////////////////////////////////////////////////////////////
// CWorkspaceTabDoc document
class CWorkspaceTabDoc : public CDocument
{
protected:
CWorkspaceTabDoc(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(CWorkspaceTabDoc)
// Attributes
public:
enum { nLinesPerPage = 12 };
enum { nMaxInfo = 10 };
CString m_szFileName;
CStringArray m_strInfoArray;
CMapFunctionProperties m_mapFunction;
// Operations
protected:
void SerializeTreeCtrl(CArchive& ar);
void AddToRecentFileList(LPCTSTR lpszPathName);
public:
void ProjectOpen();
void ProjectSave(CString sFileName);
void ProjectSaveAs();
void ProjectClose();
void ProjectNew();
//CFunctionProperties* CWorkspaceTabDoc::AddFunction( const TCHAR *szName, HTREEITEM item, const TCHAR *szFile, const TCHAR *szPath, int lang, int rtype);
//void PrintMap();
public:
static CWorkspaceTabDoc *GetWorkspaceDoc();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CWorkspaceTabDoc)
public:
virtual void Serialize(CArchive& ar); // overridden for document i/o
virtual void SetPathName(LPCTSTR lpszPathName, BOOL bAddToMRU = TRUE);
protected:
virtual BOOL OnNewDocument();
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CWorkspaceTabDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CWorkspaceTabDoc)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_WORKSPACETABDOC_H__A90B50A0_583C_4B02_A502_5276AC639EF3__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
80
]
]
]
|
3fdaecb541c7f1e1d45bafa848e095d0060a9e84 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizer/Fitting.cpp | 2887e6655ab4a5683c81fe299583e32e675f314e | [
"LicenseRef-scancode-public-domain"
]
| permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,990 | cpp | #include "plotlib/lm_lsqr.h"
#include "Numerics.h"
#include "Fitting.h"
#include "data_plot.h"
#include <sstream>
using namespace std;
namespace numerics
{
FitObject::FitObject(std::vector< std::vector<double> >* xy, size_t x_column, size_t y_column, string output_dir) :
m_xy(xy),
m_x(m_xy->size()),
m_y(m_xy->size()),
m_yfit(m_xy->size()),
base_params(10, 1),
IsGoodFit(false),
output_dir(output_dir),
dx(1)
{
if (m_xy->size() < MinDataPoints())
return;
std::sort(m_xy->begin(), m_xy->end());
for (size_t i = 0; i < m_xy->size(); i++)
{
m_x[i] = (*m_xy)[i][x_column];
m_y[i] = (*m_xy)[i][y_column]; //TODO: make this more robust
}
//bin for equal x-coordinates
unsigned num_unique = 1;
for (size_t i = 1; i < m_x.size(); i++)
if (m_x[i] != m_x[i - 1])
num_unique++;
xb = std::vector<double>(num_unique, 0);
yb = std::vector<double>(num_unique, 0);
unsigned j = 0;
unsigned nbin = 1;
xb[0] = m_x[0];
yb[0] = m_y[0];
for (size_t i = 1; i < m_x.size(); i++)
{
if ( (m_x[i] != m_x[i - 1]) )
{
yb[j] /= nbin;
j++;
xb[j] = m_x[i];
nbin = 0;
}
yb[j] += m_y[i];
nbin++;
}
yb[j] /= nbin;
dx = fabs(xb[0] - xb.back()) / xb.size();
}
FitObject::~FitObject()
{
while (!Guesses.empty())
{
delete Guesses.back();
Guesses.pop_back();
}
}
void FitObject::fcn(const double* params, double* fvec)
{
fitfunction(params, m_x, m_yfit);
for (size_t i = 0; i < m_y.size(); i++)
fvec[i] = m_y[i] - m_yfit[i];
}
bool FitObject::HasValidData()
{
return base_params.size() > 0 && fit_params.size() > 0 && m_x.size() > MinDataPoints();
}
bool FitObject::DoFit()
{
if ( m_x.size() <= MinDataPoints() )
return false;
ParamsGuess* BestGuess = 0;
for (size_t i = 0; i < Guesses.size(); i++)
{
base_params = Guesses[i]->GuessBaseParams(this);
fit_params = Guesses[i]->InitialFitParams(this);
cout << endl;
cout << "===== Initial parameters ======" << endl << endl;
UpdateParams();
PrintParams(&cout);
cout << endl;
cout << "===============================" << endl << endl;
LM_LeastSquare lm_lsqr(static_cast<int>(m_x.size()), fit_params, this);
lm_lsqr.Fit();
fit_params = lm_lsqr.GetVariables();
Guesses[i]->fit_params = fit_params;
Guesses[i]->EuclideanNorm = lm_lsqr.GetEuclideanNorm();
BestGuess = BetterGuess(Guesses[i], BestGuess);
cout << "===== Final parameters ======" << endl << endl;
UpdateParams();
PrintParams(&cout);
ofstream ff((output_dir + "fit.txt").c_str());
PrintParams(&ff);
cout << endl;
cout << "===============================" << endl << endl;
}
if (BestGuess)
{
fit_params = BestGuess->fit_params;
base_params = BestGuess->base_params;
UpdateParams();
CheckFit();
}
return HasValidData();
}
FitObject::ParamsGuess* FitObject::BetterGuess(FitObject::ParamsGuess* g1, FitObject::ParamsGuess* g2)
{
if (!g1) return g2;
if (!g2) return g1;
return g1->EuclideanNorm < g2->EuclideanNorm ? g1 : g2;
}
void FitObject::PlotFit(data_plot* plot, double xOffset, double /*xScale*/)
{
UpdateParams();
unsigned nPlotPoints = 1000;
xfit.resize(nPlotPoints);
yfit.resize(xfit.size());
double xMin = *min_element(m_x.begin(), m_x.end());
double xMax = *max_element(m_x.begin(), m_x.end());
double xRange = xMax - xMin;
for (size_t i = 0; i < xfit.size(); i++)
xfit[i] = xMin + i * xRange / (xfit.size() - 1);
fitfunction(&(fit_params[0]), xfit, yfit);
fitYmin = *min_element(yfit.begin(), yfit.end());
fitYmax = *max_element(yfit.begin(), yfit.end());
for (size_t i = 0; i < xfit.size(); i++)
xfit[i] -= xOffset;
ostringstream oss;
PrintParams(&oss);
string s = oss.str();
for (size_t i = 0; i < s.length(); i++)
if (s[i] == '\r' || s[i] == '\n')
s[i] = ' ';
plot->addCurveXY("FIT", xfit, yfit);
}
}
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
]
| [
[
[
1,
194
]
]
]
|
c66e30f5a4626422af0ec845c13b658f9b23de0b | df5277b77ad258cc5d3da348b5986294b055a2be | /ChatServer/Server/ServerRoutines.cpp | 2e7e13e12d93472b448d7fd62fa0742bd8cc6748 | []
| no_license | beentaken/cs260-last2 | 147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22 | 61b2f84d565cc94a0283cc14c40fb52189ec1ba5 | refs/heads/master | 2021-03-20T16:27:10.552333 | 2010-04-26T00:47:13 | 2010-04-26T00:47:13 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 11,147 | cpp | /**************************************************************************************************/
/*!
@file ServerRoutines.cpp
@author Robert Onulak
@author Justin Keane
@par email: robert.onulak@@digipen.edu
@par email: justin.keane@@digipen.edu
@par Course: CS260
@par Assignment #3
----------------------------------------------------------------------------------------------------
@attention © Copyright 2010: DigiPen Institute of Technology (USA). All Rights Reserved.
*/
/**************************************************************************************************/
#include "ServerRoutines.hpp"
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// ClientRoutine Protected Methods
/**************************************************************************************************/
/**************************************************************************************************/
void ClientRoutine::ProcessCommands()
{
Lock lock(mutex);
while (!commands.empty())
{
Command cmd = commands.front();
commands.pop();
switch (cmd.id_)
{
case CID_NewUser:
socket->Send(NAPI::PT_ADD_NICK, cmd.str_.c_str(), cmd.str_.size());
break;
case CID_RemoveUser:
socket->Send(NAPI::PT_DEL_NICK, cmd.str_.c_str(), cmd.str_.size());
break;
case CID_SendMessage:
socket->Send(NAPI::PT_DATA_STRING, cmd.str_.c_str(), cmd.str_.size());
break;
}
Sleep(200);
}
}
/**************************************************************************************************/
/**************************************************************************************************/
void ClientRoutine::SendFileTransferInfo( const FileTransferInfo *info )
{
socket->Send(NAPI::PT_DIRECTED, info, sizeof(FileTransferInfo));
}
/**************************************************************************************************/
/**************************************************************************************************/
void ClientRoutine::AddCommand(Command cmd)
{
Lock lock(mutex);
commands.push(cmd);
}
/**************************************************************************************************/
/**************************************************************************************************/
void ClientRoutine::InitializeThread( void )
{
// ask for username
socket->Send(NAPI::PT_REQ_NAME,0,0);
for (Timer timeout; timeout.TimeElapsed() < TIMEOUT_REQ_NAME;)
{
int ret = socket->Recieve();
if (ret == SOCKET_ERROR)
;//Sleep(100); // wait for the user to respond...
else if (socket->GetMsg().Type() == NAPI::PT_DATA_STRING)
{
// save the name in the routine and in the socket
name = socket->GetMsg().DataToStr();
socket->SetID(name);
// add user to the active users list so it can recieve commands.
if (host->SetUserActive(GetID())) // if it couldn't be added, server is shutting down.
{
// inform the users of this new user
CommandCenter->PostMsg(name, CID_NewUser);
socket->ToggleBlocking(false);
running = true;
break;
}
else
{
socket->ToggleBlocking(false);
std::string msg( "Nickname already taken." );
socket->Send(NAPI::PT_DATA_STRING, msg.c_str(), msg.size());
host->SetUserInactive(this);
break;
}
}
else
{
socket->ToggleBlocking(false);
std::string msg( "Wrong packet sent." );
socket->Send(NAPI::PT_DATA_STRING, msg.c_str(), msg.size());
host->SetUserInactive(this);
break;
}
}
}
/**************************************************************************************************/
/**************************************************************************************************/
void ClientRoutine::Run( void )
{
host->UpdateUserList(name);
// use a mutex inbetween calls to send and recieve on the socket
while (running)
{
// check for recieving data
int ret = socket->Recieve();
if (ret == 0) ///< Socket disconnected, be done with it.
{
running = false;
continue;
}
else if (ret != SOCKET_ERROR)
{
// socket didn't block, and got data, interpret it.
switch (socket->GetMsg().Type())
{
case NAPI::PT_DATA_STRING: ///< Message recieved.
{
// Build the message and have the CommandCenter distribute it.
std::string msg(name.c_str());
msg += ": " + socket->GetMsg().DataToStr();
CommandCenter->PostMsg(msg, CID_Display);
CommandCenter->PostMsg(msg, CID_SendMessage);
}
break;
case NAPI::PT_DIRECTED: ///< Direct this message towards a single user.
host->ProcessFileTransferRequest( socket->GetMsg().Data() );
break;
}
}
// socket blocked, process commands
ProcessCommands();
}
CommandCenter->PostMsg(name, CID_RemoveUser);
}
/**************************************************************************************************/
/**************************************************************************************************/
void ClientRoutine::ExitThread( void ) throw()
{
// Send fin message to client, unless an error has occured.
host->SetUserInactive(this);
NAPI::NetAPI->CloseSocket(socket);
socket = 0;
}
/**************************************************************************************************/
/**************************************************************************************************/
void ClientRoutine::FlushThread( void )
{
running = false;
// TODO: maybe need to do other stuff...
}
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// HostRoutine Protected Methods / Static Data
ClientIDTag HostRoutine::idBase = 0;
/**************************************************************************************************/
/**************************************************************************************************/
bool HostRoutine::SetUserActive(ClientIDTag id)
{
if (!hosting)
return false;
Lock lock(mutex);
ClientRoutineMap::iterator client = pendingUsers.find(id);
if (client != pendingUsers.end())
{
activeUsers[client->second->GetNick()] = client->second;
pendingUsers.erase(client);
return true;
}
return false;
}
/**************************************************************************************************/
/**************************************************************************************************/
bool HostRoutine::SetUserInactive(ClientRoutine *client)
{
Lock lock(mutex);
if (activeUsers.count(client->GetNick()))
{
inactiveUsers[client->GetID()] = client;
activeUsers.erase(client->GetNick());
return true;
}
else if (pendingUsers.count(client->GetID()))
{
inactiveUsers[client->GetID()] = client;
pendingUsers.erase(client->GetID());
return true;
}
return false;
}
/**************************************************************************************************/
/**************************************************************************************************/
void HostRoutine::DistributeMessage(Command cmd)
{
Lock lock(mutex);
ActiveUserMap::iterator begin = activeUsers.begin(), end = activeUsers.end();
while (begin != end)
begin++->second->AddCommand(cmd);
}
/**************************************************************************************************/
/**************************************************************************************************/
void HostRoutine::ProcessFileTransferRequest( const void *info_ )
{
const FileTransferInfo *info = reinterpret_cast<const FileTransferInfo*>(info_);
if (activeUsers.count(info->to_))
activeUsers[info->to_]->SendFileTransferInfo(info);
}
/**************************************************************************************************/
/**************************************************************************************************/
void HostRoutine::UpdateUserList(const std::string &name)
{
// Add all the current users to the new client's userlist.
Lock lock(mutex);
ClientRoutine *client = activeUsers[name];
ActiveUserMap::iterator begin = activeUsers.begin(), end = activeUsers.end();
while (begin != end) {
client->AddCommand(Command(CID_NewUser, begin++->first));
//Sleep(100);
}
}
/**************************************************************************************************/
/**************************************************************************************************/
void HostRoutine::InitializeThread( void )
{
// TODO: some exception checking later...
listener = NAPI::NetAPI->NewTCPSocket("HostListener");
listener->Bind(port);
listener->Listen();
hosting = true;
}
/**************************************************************************************************/
/**************************************************************************************************/
void HostRoutine::Run( void )
{
while (hosting)
{
// listen for clients, create a ClientRoutine, send it on it's way.
NAPI::TCPSOCKET contact = 0;
// threading will catch exception thrown
contact = listener->Accept();
// Create the new ClientRoutine and give it an ID. It will add itself to active users later.
ClientRoutine *client = new ClientRoutine(idBase++,contact,this);
pendingUsers[client->GetID()] = client; // Add to the clientele, but not active users.
client->BeginSession(); // Asks for username, then posts a message that the user has joined.
}
}
/**************************************************************************************************/
/**************************************************************************************************/
void HostRoutine::ExitThread( void ) throw()
{
// kick all users.
hosting = false;
ActiveUserMap::iterator aib = activeUsers.begin(), aie = activeUsers.end();
while (aib != aie)
aib++->second->EndSession();
// clean up all data.
ClientRoutineMap::iterator cib = inactiveUsers.begin(), cie = inactiveUsers.end();
while (cib != cie)
delete cib++->second;
}
/**************************************************************************************************/
/**************************************************************************************************/
void HostRoutine::FlushThread( void )
{
// TODO: FIX THIS!!! WON'T TERMINATE!!!!
hosting = false;
quit_.Release();
thread_.Terminate();
}
| [
"rziugy@af704e40-745a-32bd-e5ce-d8b418a3b9ef",
"ProstheticMind43@af704e40-745a-32bd-e5ce-d8b418a3b9ef"
]
| [
[
[
1,
15
]
],
[
[
16,
295
]
]
]
|
746fb749bd05fa9e34d8323afa9c75183f4d0c61 | 12203ea9fe0801d613bbb2159d4f69cab3c84816 | /Export/cpp/windows/obj/src/cpp/rtti/FieldNumericIntegerLookup.cpp | 6d1dbacbcf796a69e489e7f00b5cd883667d4a75 | []
| no_license | alecmce/haxe_game_of_life | 91b5557132043c6e9526254d17fdd9bcea9c5086 | 35ceb1565e06d12c89481451a7bedbbce20fa871 | refs/heads/master | 2016-09-16T00:47:24.032302 | 2011-10-10T12:38:14 | 2011-10-10T12:38:14 | 2,547,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | #include <hxcpp.h>
#ifndef INCLUDED_cpp_rtti_FieldNumericIntegerLookup
#include <cpp/rtti/FieldNumericIntegerLookup.h>
#endif
namespace cpp{
namespace rtti{
Class FieldNumericIntegerLookup_obj::__mClass;
void FieldNumericIntegerLookup_obj::__register()
{
Static(__mClass) = hx::RegisterClass(HX_CSTRING("cpp.rtti.FieldNumericIntegerLookup"), hx::TCanCast< FieldNumericIntegerLookup_obj> ,0,0,
0, 0,
&super::__SGetClass(), 0, 0);
}
} // end namespace cpp
} // end namespace rtti
| [
"[email protected]"
]
| [
[
[
1,
20
]
]
]
|
d8dc58468797b73c1fbad9c97d587bc52643582b | 2fd3cf69d422c2e62db908a5f6ec85890cc12f80 | /__OBSOLETE__/Dictionary.h | 2899044c65a2846805c8d4f75bda501683cfb3a3 | []
| no_license | ksherlock/BShisen | 24ec5fb05c8bda250a1090ec32f7dc6f3df7c036 | f5f9db386d847ea3f26a1116ff465676290b3aa9 | refs/heads/master | 2016-09-06T01:37:57.086749 | 2010-06-10T02:18:14 | 2010-06-10T02:18:14 | 18,947,831 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,267 | h | #ifndef __DICTIONARY_H__
#define __DICTIONARY_H__
template <class KEY, class VALUE>
class Dictionary
{
public:
Dictionary(int size = 5):
_data(NULL),
_resize(size),
_currsize(0),
_numentries(0)
{
if (!_resize) _resize = 5; //must have a value
_data = new ddata[resize];
if (_data) _currsize = _resize;
};
~Dictionary()
{
if (_data) delete []data;
};
void AddValue(KEY key, VALUE value)
{
// must I resize the dictionary?
if (_currsize == _numentries)
{
ddata *old;
old = _data;
_data = new ddata[_currsize + _resize];
memcpy(_data, old, sizeof(struct ddata) * _currsize);
_currsize += _resize;
delete []old;
}
_data[_num_entries].key = key;
_data[_num_entries].value = value;
_numentries++;
};
VALUE GetValue(KEY key) const
{
register int i;
VALUE ret_val = (VALUE)NULL;
for (i = 0; i < _numentries; i++)
{
if (_data[i].key == key)
{
ret_val = _data[i].value;
break;
}
}
return ret_val;
};
private:
int _resize; // amt to resize in
int _currsize; // current size of dictionary
int _numentries; // current # of entries
struct ddata
{
KEY key;
VALUE value;
};
struct ddata *_data;
};
#endif
| [
"(no author)@5590a31f-7b70-45f8-8c82-aa3a8e5f4507"
]
| [
[
[
1,
75
]
]
]
|
a8e6e9d285835bf76b24232b3ace4790a9e8e686 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Common/KNN/itkANNFixedRadiusTreeSearch.h | 035720414f5f0d4d9b4a918b79b61f82a817914e | []
| 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 | 3,627 | 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 __itkANNFixedRadiusTreeSearch_h
#define __itkANNFixedRadiusTreeSearch_h
#include "itkBinaryANNTreeSearchBase.h"
namespace itk
{
/**
* \class ANNFixedRadiusTreeSearch
*
* \brief
*
*
* \ingroup ANNwrap
*/
template < class TListSample >
class ANNFixedRadiusTreeSearch : public BinaryANNTreeSearchBase< TListSample >
{
public:
/** Standard itk. */
typedef ANNFixedRadiusTreeSearch Self;
typedef BinaryANNTreeSearchBase< TListSample > Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** New method for creating an object using a factory. */
itkNewMacro( Self );
/** ITK type info. */
itkTypeMacro( ANNFixedRadiusTreeSearch, BinaryANNTreeSearchBase );
/** Typedef's from Superclass. */
typedef typename Superclass::ListSampleType ListSampleType;
typedef typename Superclass::BinaryTreeType BinaryTreeType;
typedef typename Superclass::MeasurementVectorType MeasurementVectorType;
typedef typename Superclass::IndexArrayType IndexArrayType;
typedef typename Superclass::DistanceArrayType DistanceArrayType;
typedef typename Superclass::ANNPointType ANNPointType; // double *
typedef typename Superclass::ANNIndexType ANNIndexType; // int
typedef typename Superclass::ANNIndexArrayType ANNIndexArrayType; // int *
typedef typename Superclass::ANNDistanceType ANNDistanceType; // double
typedef typename Superclass::ANNDistanceArrayType ANNDistanceArrayType; // double *
typedef typename Superclass::BinaryANNTreeType BinaryANNTreeType;
/** Set and get the error bound eps. */
itkSetClampMacro( ErrorBound, double, 0.0, 1e14 );
itkGetConstMacro( ErrorBound, double );
/** Set and get the squared radius search bound. */
itkSetMacro( SquaredRadius, double );
itkGetConstMacro( SquaredRadius, double );
/** Search the nearest neighbours of a query point qp. */
virtual void Search( const MeasurementVectorType & qp, IndexArrayType & ind,
DistanceArrayType & dists );
/** Search the nearest neighbours of a query point qp. */
virtual void Search( const MeasurementVectorType & qp, IndexArrayType & ind,
DistanceArrayType & dists, double sqRad );
protected:
ANNFixedRadiusTreeSearch();
virtual ~ANNFixedRadiusTreeSearch();
/** Member variables. */
double m_ErrorBound;
double m_SquaredRadius;
private:
ANNFixedRadiusTreeSearch( const Self& ); // purposely not implemented
void operator=( const Self& ); // purposely not implemented
}; // end class ANNFixedRadiusTreeSearch
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkANNFixedRadiusTreeSearch.txx"
#endif
#endif // end #ifndef __itkANNFixedRadiusTreeSearch_h
| [
"[email protected]"
]
| [
[
[
1,
107
]
]
]
|
02542e17834f6b8af8ce3d2fc14ec43d8d8dddc2 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osgParticle/SectorPlacer | ef971412a5e3549e1509a6dd0649c6e4413be143 | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,520 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
//osgParticle - Copyright (C) 2002 Marco Jez
#ifndef OSGPARTICLE_SECTOR_PLACER
#define OSGPARTICLE_SECTOR_PLACER 1
#include <osgParticle/CenteredPlacer>
#include <osgParticle/Particle>
#include <osgParticle/range>
#include <osg/CopyOp>
#include <osg/Object>
#include <osg/Vec3>
#include <osg/Math>
namespace osgParticle
{
/** A sector-shaped particle placer.
This placer sets the initial position of incoming particle by choosing a random position
within a circular sector; this sector is defined by three parameters: a <I>center point</I>,
which is inherited directly from <CODE>osgParticle::CenteredPlacer</CODE>, a range of values
for <I>radius</I>, and a range of values for the <I>central angle</I> (sometimes called <B>phi</B>).
*/
class SectorPlacer: public CenteredPlacer {
public:
inline SectorPlacer();
inline SectorPlacer(const SectorPlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY);
/// Get the range of possible values for radius.
inline const rangef& getRadiusRange() const;
/// Set the range of possible values for radius.
inline void setRadiusRange(const rangef& r);
/// Set the range of possible values for radius.
inline void setRadiusRange(float r1, float r2);
/// Get the range of possible values for the central angle.
inline const rangef& getPhiRange() const;
/// Set the range of possible values for the central angle.
inline void setPhiRange(const rangef& r);
/// Set the range of possible values for the central angle.
inline void setPhiRange(float r1, float r2);
META_Object(osgParticle, SectorPlacer);
/// Place a particle. Do not call it manually.
inline void place(Particle* P) const;
/// return the control position
inline osg::Vec3 getControlPosition() const;
protected:
virtual ~SectorPlacer() {}
SectorPlacer& operator=(const SectorPlacer&) { return *this; }
private:
rangef _rad_range;
rangef _phi_range;
};
// INLINE FUNCTIONS
inline SectorPlacer::SectorPlacer()
: CenteredPlacer(), _rad_range(0, 1), _phi_range(0, osg::PI*2)
{
}
inline SectorPlacer::SectorPlacer(const SectorPlacer& copy, const osg::CopyOp& copyop)
: CenteredPlacer(copy, copyop), _rad_range(copy._rad_range), _phi_range(copy._phi_range)
{
}
inline const rangef& SectorPlacer::getRadiusRange() const
{
return _rad_range;
}
inline const rangef& SectorPlacer::getPhiRange() const
{
return _phi_range;
}
inline void SectorPlacer::setRadiusRange(const rangef& r)
{
_rad_range = r;
}
inline void SectorPlacer::setRadiusRange(float r1, float r2)
{
_rad_range.minimum = r1;
_rad_range.maximum = r2;
}
inline void SectorPlacer::setPhiRange(const rangef& r)
{
_phi_range = r;
}
inline void SectorPlacer::setPhiRange(float r1, float r2)
{
_phi_range.minimum = r1;
_phi_range.maximum = r2;
}
inline void SectorPlacer::place(Particle* P) const
{
float rad = _rad_range.get_random_sqrtf();
float phi = _phi_range.get_random();
osg::Vec3 pos(
getCenter().x() + rad * cosf(phi),
getCenter().y() + rad * sinf(phi),
getCenter().z());
P->setPosition(pos);
}
inline osg::Vec3 SectorPlacer::getControlPosition() const
{
return getCenter();
}
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
140
]
]
]
|
|
5df7bc42eb98a3f6a03d5642aefea1ed0eb0f62d | 507d733770b2f22ea6cebc2b519037a5fa3cceed | /gs2d/src/Platform/Platform.h | 01036e17a3cd0a1283402ec019100eecef23d948 | []
| 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,436 | h | /*-----------------------------------------------------------------------
Ethanon Engine (C) Copyright 2009-2011 Andre Santee
http://www.asantee.net/ethanon/
This file is part of Ethanon Engine.
Ethanon Engine 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.
Ethanon Engine 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 Ethanon Engine. If not, see
<http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------*/
#ifndef PLATFORM_H_
#define PLATFORM_H_
#include "../gs2dtypes.h"
// TODO implement wchar_t support on Android... not yet supported by the NDK
#ifndef ANDROID
#include <xstring>
#endif
#include <string>
namespace Platform {
gs2d::str_type::string GetFileName(const gs2d::str_type::string &source);
// TODO implement wchar_t support on Android... not yet supported by the NDK
#ifndef ANDROID
std::wstring AddLastSlash(const std::wstring& path);
std::string AddLastSlash(const std::string& path);
std::wstring& FixSlashes(std::wstring& path);
std::string& FixSlashes(std::string& path);
gs2d::str_type::string GetModulePath();
gs2d::str_type::string GetCurrentDirectoryPath();
std::wstring ConvertUtf8ToUnicode(const char* utf8String); // use it in low-level only. utf8::converter is a high-level wrapper
std::string ConvertUnicodeToUtf8(const wchar_t* unicodeString); // use it in low-level only. utf8::converter is a high-level wrapper
std::wstring ConvertAsciiToUnicode(const char* asciiString); // use it in low-level only. utf8::converter is a high-level wrapper
std::string ConvertUnicodeToAscii(const wchar_t* unicodeString); // use it in low-level only. utf8::converter is a high-level wrapper
#else
gs2d::str_type::string AddLastSlash(const gs2d::str_type::string& path);
gs2d::str_type::string& FixSlashes(gs2d::str_type::string& path);
gs2d::str_type::string GetModulePath();
#endif // #ifndef ANDROID
}
// namespace Platform
#endif | [
"Andre@AndreDell.(none)"
]
| [
[
[
1,
61
]
]
]
|
d3b2940b322a8e0db66b5871c972ff07866f9ef5 | 02cd7f7be30f7660f6928a1b8262dc935673b2d7 | / invols --username [email protected]/CT_draw.cpp | 6c10722ac73e1ce5a752d4d51ebfd5bc27f6ffcf | []
| no_license | hksonngan/invols | f0886a304ffb81594016b3b82affc58bd61c4c0b | 336b8c2d11d97892881c02afc2fa114dbf56b973 | refs/heads/master | 2021-01-10T10:04:55.844101 | 2011-11-09T07:44:24 | 2011-11-09T07:44:24 | 46,898,469 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,098 | cpp | #include <stdio.h>
#include <stdlib.h>
#include "AllDef.h"
#include "Mouse.h"
#include "Camera.h"
#include "Draw.h"
#include "Render.h"
#include "Draw2D.h"
#include <Math.h>
#include <ivec3.h>
#include "output.h"
#include "CT.h"
#include "MainFrame.h"
#include "GLCanvas.h"
#include "DicomReader.h"
#include "CPU_VD.h"
#include "RenderToTexture.h"
namespace CT
{
void DrawScene();
float fps=0;
float *screen_depth=0;
void UpdateScreenDepth()
{
if(screen_depth)delete[]screen_depth;
screen_depth = new float[width * height];
glReadPixels(0, 0, width, height,GL_DEPTH_COMPONENT,GL_FLOAT, screen_depth);
}
float GetScreenDepth(int x,int y)
{
float res;
glReadBuffer(GL_FRONT);
glReadPixels(x, height-y,1,1,GL_DEPTH_COMPONENT,GL_FLOAT, &res);
return res;
}
float DepthToLength(float depth)
{
float n = Z_NEAR,f = Z_FAR,res;
if(CT::cam.GetProjection())
{
if(depth==1.0f)
res = -1;
else
res = f*n/(f-(f-n)*depth);
}
else
{
res = depth*(f-n)+n;
}
return res;
// return clamp((dot(ps,nav)-z_near)/(z_far-z_near),0.01,0.99);
}
vec3 marker(0);
vec3 GetPointByDepth(int x,int y)
{
Ray ray = cam.GetRay(x,y);
return ray.pos + ray.nav*DepthToLength(GetScreenDepth(x,y));
}
void SetupGL()
{
glewInit();
glClearColor(bg_color.x,bg_color.y,bg_color.z,1.0);
//glShadeModel(GL_FLAT);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LINE_SMOOTH);
glLineStipple(1,15+(15<<8));
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
bool need_InitInterlace=1;
void InitInterlace()
{
need_InitInterlace = 1;
}
void InitInterlace_()
{
need_InitInterlace = 0;
glDisable(GL_LINE_SMOOTH);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
Begin2D(width,height);
glEnable(GL_STENCIL_TEST);
glClearStencil(0);
//glStencilMask(1);
glClear (GL_STENCIL_BUFFER_BIT);
glStencilFunc(GL_ALWAYS, 1, 1);
glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
glBegin(GL_LINES);
for(int i=0;i<height;i+=2)
{
glVertex2f(0,i);
glVertex2f(width,i);
}
glEnd();
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glDisable(GL_STENCIL_TEST);
End2D();
glEnable(GL_LINE_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
}
void Resize(int _width,int _height)
{
bool resized = (_width!=width)||(_height!=height);
if(RM_pic_man)
{
}
width=_width;
height=_height;
rtt_Resize(width,height);
cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,0,0,width,height);
//if(resized)
if(stereo_on==3)InitInterlace();
CT::need_rerender=1;
}
float glfwGetTime()
{
return GetTickCount()*0.001f;
}
void CalcFPS()
{
static int frames = 0;
static double start = glfwGetTime ( );
double time = glfwGetTime ( );
if ( ( time - start ) > 1.0 || frames == 0 )
{
fps = frames / ( time - start );
start = time;
frames = 0;
/*
if(auto_fps)
{
if(fps>25)
iso->SetStepLength(max(iso->GetStepLength()*0.9f,0.002f));
if(fps<10)
iso->SetStepLength(min(iso->GetStepLength()*2,0.02f));
}
*/
}
frames++;
}
void InitGL()
{
// glClearColor(0,0,0,0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// glEnable(GL_POLYGON_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glLineStipple(1,15+(15<<8));
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// glEnable(GL_MULTISAMPLE_ARB);
glClearColor(bg_color.x,bg_color.y,bg_color.z,1.0);
}
void UploadVD(int id)
{
if(CPU_VD::full_data.GetSlices())
{
CT::GetData(id)->Upload(CPU_VD::full_data);
vec3 scale1 = CPU_VD::full_data.spacing*CPU_VD::gpu_size.ToVec3()*CPU_VD::scale;
iso->volume_transform[id].center=CPU_VD::real_gpu_b1;
iso->volume_transform[id].x.set(scale1.x,0,0);
iso->volume_transform[id].y.set(0,scale1.y,0);
iso->volume_transform[id].z.set(0,0,scale1.z);
iso->ReLoadShader();
}
}
void FullDraw()
{
if(need_reload_volume_data)
{
UploadVD(CT::GetCurDataID());
need_reload_volume_data=0;
}
CalcFPS();
InitGL();
if(IsFastView())cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,0,0,width/fast_res,height/fast_res);
else cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,0,0,width,height);
//InitInterlace();
if(need_InitInterlace)InitInterlace_();
//SetLight(cam.GetPosition());
switch(stereo_on)
{
case 0:
{
CT::gl_back_buffer_target = GL_BACK;
// if(IsFastView())rtt_Begin(0);
//glClearColor(0,0,0,0);
if(need_rerender)glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// if(IsFastView())rtt_End();
DrawScene();
}
break;
case 1:
CT::gl_back_buffer_target = GL_BACK;
{
//vec3 ps = cam.GetCenter();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(CT::RenderingType==2)
{
is_left=!is_left;
DrawScene();
glFlush();
}else
{
glClear(GL_ACCUM_BUFFER_BIT);
is_left=0;
DrawScene();
//glFlush();
glAccum(GL_LOAD, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
is_left=1;
DrawScene();
//glFlush();
glAccum(GL_ACCUM, 1.0f);
glAccum(GL_RETURN, 1.0f);
}
}
break;
case 2:
{
CT::gl_back_buffer_target = GL_BACK;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(CT::RenderingType==2)
{
is_left=!is_left;
cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,is_left*width/2,0,width/2,height);
DrawScene();
glFlush();
}else
{
glClear(GL_ACCUM_BUFFER_BIT);
is_left=0;
cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,is_left*width/2,0,width/2,height);
DrawScene();
//glFlush();
glAccum(GL_LOAD, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
is_left=1;
cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,is_left*width/2,0,width/2,height);
DrawScene();
//glFlush();
glAccum(GL_ACCUM, 1.0f);
glAccum(GL_RETURN, 1.0f);
}
/*
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
vec3 ps = cam.GetCenter();
cam.SetCenter(ps-cam.GetLeft()*stereo_step);
cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,0,0,width/2,height);
DrawScene();
cam.SetCenter(ps+cam.GetLeft()*stereo_step);
cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,width/2,0,width/2,height);
DrawScene();
cam.SetCenter(ps);
*/
}
break;
case 3:
{
CT::gl_back_buffer_target = GL_BACK;
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 0, 1);
is_left=0;
DrawScene();
glStencilFunc(GL_EQUAL, 1, 1);
is_left=1;
DrawScene();
glDisable(GL_STENCIL_TEST);
}
break;
case 4:
{
is_left=0;
CT::gl_back_buffer_target = GL_BACK_LEFT;
glDrawBuffer(CT::gl_back_buffer_target);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear color and depth buffers
DrawScene();
is_left=1;
CT::gl_back_buffer_target = GL_BACK_RIGHT;
glDrawBuffer(CT::gl_back_buffer_target);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear color and depth buffers
DrawScene();
}
break;
}
}
void SetStereoMode(int stereo_mode)
{
switch(stereo_on)
{
case 0: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
MyApp::frame->m_canvas[0]->SwapBuffers();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
break;
case 1: iso->SetAnag(0,0);
break;
case 2: cam.SetupProjection(CAMERA_ANGLE,Z_NEAR,Z_FAR,0,0,width,height);
break;
case 4:glDrawBuffer(CT::gl_back_buffer_target);
break;
}
stereo_on = stereo_mode;
if(stereo_on==3)InitInterlace();
need_rerender=1;
}
} | [
"[email protected]"
]
| [
[
[
1,
376
]
]
]
|
4f107643a8050686bf7cb8fcbc8d525c9db38d08 | a0155e192c9dc2029b231829e3db9ba90861f956 | /MFInstWizard/InstallDlg.cpp | 51750b6a8a81afaa1277f95e6b2540621addc84e | []
| no_license | zeha/mailfilter | d2de4aaa79bed2073cec76c93768a42068cfab17 | 898dd4d4cba226edec566f4b15c6bb97e79f8001 | refs/heads/master | 2021-01-22T02:03:31.470739 | 2010-08-12T23:51:35 | 2010-08-12T23:51:35 | 81,022,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,447 | cpp | // InstallDlg.cpp : Implementierungsdatei
//
#include "stdafx.h"
#include "MFInstWizard.h"
#include "InstallDlg.h"
// InstallDlg-Dialogfeld
IMPLEMENT_DYNAMIC(InstallDlg, CPropertyPage)
InstallDlg::InstallDlg()
: CPropertyPage(InstallDlg::IDD)
{
m_pPSP->dwFlags |= PSP_HIDEHEADER;
m_pPSP->dwFlags &= ~PSP_HASHELP;
}
InstallDlg::~InstallDlg()
{
}
void InstallDlg::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
CInstApp* app = (CInstApp*)AfxGetApp();
DDX_Text(pDX, IDC_SERVER, app->mf_ServerName);
DDX_Check(pDX, IDC_CHECK1, app->mf_LoadMailFilter);
}
BEGIN_MESSAGE_MAP(InstallDlg, CPropertyPage)
END_MESSAGE_MAP()
// InstallDlg-Meldungshandler
BOOL InstallDlg::OnSetActive(void)
{
CPropertySheet* psheet = (CPropertySheet*) GetParent();
psheet->SetFinishText("Install");
psheet->SetWizardButtons(PSWIZB_FINISH|PSWIZB_BACK);
CFont *headerFont = new CFont();
VERIFY(headerFont->CreateFont(-14,0,0,0,FW_BOLD,FALSE,FALSE,0,ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH | FF_SWISS,"Verdana"));
CStatic* headerCtrl = ((CStatic*)this->GetDlgItem(IDC_TITLE));
headerCtrl->SetFont(headerFont);
CInstApp* app = (CInstApp*)AfxGetApp();
if (app->mf_IsUpgrade)
headerCtrl->SetWindowText("Upgrade MailFilter");
else
headerCtrl->SetWindowText("Finish Installation");
return CPropertyPage::OnSetActive();
}
| [
"[email protected]"
]
| [
[
[
1,
56
]
]
]
|
838a92a549f9683c9f2ad1219072cc433d641a61 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/bctestlauncher/inc/bctestconf.h | d08a8cbd7338fc3f7a359fc1e1636b0b5b6dd365 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,594 | h | /*
* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Test case class, user will create own test case class by
* deriving from the class.
*
*/
#ifndef C_CBCTESTCONFIG_H
#define C_CBCTESTCONFIG_H
#include <e32std.h>
#include <e32base.h>
#include <f32file.h>
#include "bctestlauncherdefs.h"
/**
* BC test configurator, read all BC applications from an XML file.
*/
class CBCTestConf : public CBase
{
public: // constructor
static CBCTestConf* NewLC();
/**
* C++ default constructor
*/
CBCTestConf();
void ConstructL();
/**
* Destructor
*/
virtual ~CBCTestConf();
// new funcs
TBool NextL();
const TDesC& Name();
TInt AppUID();
TInt ViewUID();
TInt Timeout();
TInt Version();
private:
void OpenConfigL();
void CloseConfig();
TBool ReadBlockDataL();
/**
* @return EFalse for EOF, otherwise it returns ETrue
*/
TBool ReadLineL( TDes& aLine );
// data
RFile iFile;
TBuf<KNameLength> iName;
TInt iAppUID;
TInt iViewUID;
TInt iTimeout; // [min]
TInt iVersion; // S60 30, 31, 32
};
#endif // C_CBCTESTCONFIG_H
| [
"none@none"
]
| [
[
[
1,
79
]
]
]
|
19fb5ae4313c78a57d213d64062a7ecfdf41ef88 | dabebde2349df353f5092933778727993a79300d | /SobMainWin.hh | 03e649ea3594eeceb9055ac0f2442869886f9879 | []
| no_license | Athantor/sobel | 0d3f6c200e6ae2ceeec48487a27eec9dfb0810b0 | 31e92430809c6953e3fe3746e36cbdb2454046ca | refs/heads/master | 2020-05-07T19:15:15.155489 | 2009-05-10T07:47:54 | 2009-05-10T07:47:54 | 92,925 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,438 | hh | /*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
---
Copyright (C) 2008, Krzysztof Kundzicz <[email protected]>
*/
#ifndef _SobMainWin_h_
#define _SobMainWin_h_
#include <iostream>
#include <memory>
#include <stdint.h>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <list>
#include <functional>
#include <limits>
#include <numeric>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>
#include <boost/shared_array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/foreach.hpp>
#include <QMainWindow>
#include <QImage>
#include <QPixmap>
#include <QString>
#include <QFileDialog>
#include <QMessageBox>
#include <QLabel>
#include <QDir>
#include <QColor>
#include <QTime>
#include <QBrush>
#include <QProgressDialog>
#include <QTextStream>
#include <QFile>
#include <QDateTime>
#include <QInputDialog>
#include <QMouseEvent>
#include <QPainter>
#include "ui_sobel.h"
class SobMainWin: public QMainWindow {
Q_OBJECT
public:
SobMainWin();
~SobMainWin();
typedef boost::shared_array<int64_t> gradarr_t;
typedef std::pair<boost::shared_ptr<QImage>, boost::shared_ptr<QImage> >
igrads_t; //x-grad img, y-grad img
//typedef boost::shared_array< gradarr_t > vgrad_t; //grad of [x][y]
typedef std::vector<std::vector<int64_t> > vgrad_t;
typedef std::pair<vgrad_t, vgrad_t> vgrads_t; // raw: x-grad vals, y-grad vals
typedef boost::tuple<gradarr_t, gradarr_t, igrads_t, vgrads_t> grad_t; //grad-x, grad-y, grad images, grad vals
typedef gradarr_t featarr_t;
typedef boost::tuple<featarr_t, featarr_t, uint, uint, uint> feat_t; // x-max[], y-max[], eye area tol. hgt, face mid. x dist, face mid. y dist
// y-max: left 1st max, l 2nd m, right 1st m, r 2nd m
// x-max: eye line, eye brows, hair, nose, mouth, chin
typedef boost::tuple<QPoint, QPoint, double, double, QPoint, QPoint> eyeloc_t; // left eye, right eye, eye width, eye height, ALEP, AREP
typedef std::list<boost::tuple<uint, uint, uint> > hought_t; // x, y, val
typedef boost::tuple<gradarr_t, gradarr_t, QPoint> vpf_s_t; //vpf_h, vpf_v, center
typedef boost::tuple<gradarr_t, gradarr_t, gradarr_t, gradarr_t> vpf_t; //vpf_h_l, vpf_v_l, vpf_h_r, vpf_v_r
private:
boost::scoped_ptr<Ui::MainWindow> mwin_ui;
boost::scoped_ptr<QImage> in_im;
boost::scoped_ptr<QImage> out_im;
QString fn;
bool sobel;
bool bin;
char kropuj;
const double XTOLPCT;
const double YTOLPCT;
void connects();
QRgb To_gray(QRgb);
//void Gamma( float );
void Smooth();
//void Binarize();
void Pss(int, const QString & cmt = QString());
inline int n_rgb(int r) {
int myr = r > 255 ? 255 : r;
myr = myr < 0 ? 0 : myr;
return myr;
}
inline double d2r(double d) {
return (d * M_PI) / 180.0;
}
inline double r2d(double r) {
return r * (180.0 / M_PI);
}
inline ptrdiff_t Find_eyeline_el(uint t, uint p, gradarr_t gx) {
return std::max_element(gx.get() + t, gx.get() + p) - gx.get();
}
private:
void canny_edge_trace(QImage &, uint8_t, uint64_t, uint64_t, std::pair<
int8_t, int8_t>, const std::vector<std::vector<uint8_t> > &,
const std::vector<std::vector<uint64_t> > &, const uint64_t,
const uint64_t);
void canny_supr_nonmax(QImage &, uint8_t, uint64_t, uint64_t, std::pair<
int8_t, int8_t>, const std::vector<std::vector<uint8_t> > &,
const std::vector<std::vector<uint64_t> > &, const uint64_t);
uint64_t canny_et_mkrowcol(uint64_t, uint64_t, int8_t, bool &) const;
private slots:
void Load_file(bool);
void Save_file(bool);
void Do_ops(bool);
void To_gray(bool = false);
void Avg_blur(bool);
void Gauss_blur(bool);
void Median_fr(bool);
void Otsus_bin(bool);
void Lame_bin(bool);
void Sobel_op(bool);
void Canny_ed(bool);
boost::shared_ptr<vpf_s_t> Vpf_simple(const QPoint &, const QPoint&, double, double);
//boost::shared_ptr<vpf_t> Vpf(const eyeloc &);
void Approx_eyes_with_otsu(QPoint &, QPoint &);
boost::shared_ptr<hought_t> Hough_tm(bool, uint = 30);
void Do_enables(bool);
void Display_imgs();
void Prep_to_extr(bool, uint = 3, bool = false, bool = false);
boost::shared_ptr<grad_t> Make_grads(bool);
boost::shared_ptr<feat_t> Make_feats(bool);
boost::shared_ptr<SobMainWin::eyeloc_t> Find_iris_ht(bool);
void Face_find_cs(bool);
void Set_gamma_lbl(int);
void Disp_grad(bool);
void Disp_feat(bool);
void Disp_eyes_ht(bool);
void Disp_eyes_sob(bool);
void Disp_eyes_otsu(bool);
void Disp_eyes_vpf(bool);
void Crop_face(bool);
//void Crop_face_manual(bool);
void Do_auto(bool);
//virtual void mouseReleaseEvent ( QMouseEvent * );
};
#endif // _SobMainWin_h_
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
86
],
[
90,
154
],
[
160,
176
],
[
179,
180
],
[
182,
185
],
[
187,
190
]
],
[
[
87,
89
],
[
155,
157
],
[
178,
178
]
],
[
[
158,
159
],
[
177,
177
],
[
181,
181
],
[
186,
186
]
]
]
|
20dc092334277222de5664050e147e969b7d7cc8 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/intrusive/example/doc_assoc_optimized_code.cpp | 411ab9a83a7f3733e4c17652809c8cb5bd96ea77 | [
"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 | 6,754 | cpp | /////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2008
//
// 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/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
//[doc_assoc_optimized_code_normal_find
#include <boost/intrusive/set.hpp>
#include <boost/intrusive/unordered_set.hpp>
#include <cstring>
using namespace boost::intrusive;
// Hash function for strings
struct StrHasher
{
std::size_t operator()(const char *str) const
{
std::size_t seed = 0;
for(; *str; ++str) boost::hash_combine(seed, *str);
return seed;
}
};
class Expensive : public set_base_hook<>, public unordered_set_base_hook<>
{
std::string key_;
// Other members...
public:
Expensive(const char *key)
: key_(key)
{} //other expensive initializations...
const std::string & get_key() const
{ return key_; }
friend bool operator < (const Expensive &a, const Expensive &b)
{ return a.key_ < b.key_; }
friend bool operator == (const Expensive &a, const Expensive &b)
{ return a.key_ == b.key_; }
friend std::size_t hash_value(const Expensive &object)
{ return StrHasher()(object.get_key().c_str()); }
};
// A set and unordered_set that store Expensive objects
typedef set<Expensive> Set;
typedef unordered_set<Expensive> UnorderedSet;
// Search functions
Expensive *get_from_set(const char* key, Set &set_object)
{
Set::iterator it = set_object.find(Expensive(key));
if( it == set_object.end() ) return 0;
return &*it;
}
Expensive *get_from_uset(const char* key, UnorderedSet &uset_object)
{
UnorderedSet::iterator it = uset_object.find(Expensive (key));
if( it == uset_object.end() ) return 0;
return &*it;
}
//]
//[doc_assoc_optimized_code_optimized_find
// These compare Expensive and a c-string
struct StrExpComp
{
bool operator()(const char *str, const Expensive &c) const
{ return std::strcmp(str, c.get_key().c_str()) < 0; }
bool operator()(const Expensive &c, const char *str) const
{ return std::strcmp(c.get_key().c_str(), str) < 0; }
};
struct StrExpEqual
{
bool operator()(const char *str, const Expensive &c) const
{ return std::strcmp(str, c.get_key().c_str()) == 0; }
bool operator()(const Expensive &c, const char *str) const
{ return std::strcmp(c.get_key().c_str(), str) == 0; }
};
// Optimized search functions
Expensive *get_from_set_optimized(const char* key, Set &set_object)
{
Set::iterator it = set_object.find(key, StrExpComp());
if( it == set_object.end() ) return 0;
return &*it;
}
Expensive *get_from_uset_optimized(const char* key, UnorderedSet &uset_object)
{
UnorderedSet::iterator it = uset_object.find(key, StrHasher(), StrExpEqual());
if( it == uset_object.end() ) return 0;
return &*it;
}
//]
//[doc_assoc_optimized_code_normal_insert
// Insertion functions
bool insert_to_set(const char* key, Set &set_object)
{
Expensive *pobject = new Expensive(key);
bool success = set_object.insert(*pobject).second;
if(!success) delete pobject;
return success;
}
bool insert_to_uset(const char* key, UnorderedSet &uset_object)
{
Expensive *pobject = new Expensive(key);
bool success = uset_object.insert(*pobject).second;
if(!success) delete pobject;
return success;
}
//]
//[doc_assoc_optimized_code_optimized_insert
// Optimized insertion functions
bool insert_to_set_optimized(const char* key, Set &set_object)
{
Set::insert_commit_data insert_data;
bool success = set_object.insert_check(key, StrExpComp(), insert_data).second;
if(success) set_object.insert_commit(*new Expensive(key), insert_data);
return success;
}
bool insert_to_uset_optimized(const char* key, UnorderedSet &uset_object)
{
UnorderedSet::insert_commit_data insert_data;
bool success = uset_object.insert_check
(key, StrHasher(), StrExpEqual(), insert_data).second;
if(success) uset_object.insert_commit(*new Expensive(key), insert_data);
return success;
}
//]
int main()
{
Set set;
UnorderedSet::bucket_type buckets[10];
UnorderedSet unordered_set(UnorderedSet::bucket_traits(buckets, 10));
const char * const expensive_key
= "A long string that avoids small string optimization";
Expensive value(expensive_key);
if(get_from_set(expensive_key, set)){
return 1;
}
if(get_from_uset(expensive_key, unordered_set)){
return 1;
}
if(get_from_set_optimized(expensive_key, set)){
return 1;
}
if(get_from_uset_optimized(expensive_key, unordered_set)){
return 1;
}
Set::iterator setit = set.insert(value).first;
UnorderedSet::iterator unordered_setit = unordered_set.insert(value).first;
if(!get_from_set(expensive_key, set)){
return 1;
}
if(!get_from_uset(expensive_key, unordered_set)){
return 1;
}
if(!get_from_set_optimized(expensive_key, set)){
return 1;
}
if(!get_from_uset_optimized(expensive_key, unordered_set)){
return 1;
}
set.erase(setit);
unordered_set.erase(unordered_setit);
if(!insert_to_set(expensive_key, set)){
return 1;
}
if(!insert_to_uset(expensive_key, unordered_set)){
return 1;
}
{
Expensive *ptr = &*set.begin();
set.clear();
delete ptr;
}
{
Expensive *ptr = &*unordered_set.begin();
unordered_set.clear();
delete ptr;
}
if(!insert_to_set_optimized(expensive_key, set)){
return 1;
}
if(!insert_to_uset_optimized(expensive_key, unordered_set)){
return 1;
}
{
Expensive *ptr = &*set.begin();
set.clear();
delete ptr;
}
{
Expensive *ptr = &*unordered_set.begin();
unordered_set.clear();
delete ptr;
}
setit = set.insert(value).first;
unordered_setit = unordered_set.insert(value).first;
if(insert_to_set(expensive_key, set)){
return 1;
}
if(insert_to_uset(expensive_key, unordered_set)){
return 1;
}
if(insert_to_set_optimized(expensive_key, set)){
return 1;
}
if(insert_to_uset_optimized(expensive_key, unordered_set)){
return 1;
}
set.erase(value);
unordered_set.erase(value);
return 0;
}
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
260
]
]
]
|
9d03e0dee88732b68e0516d4e54221fcb4107122 | 38d9a3374e52b67ca01ed8bbf11cd0b878cce2a5 | /branches/tbeta/CCV-fid/addons/ofxTuioMultiplexer/src/Communication/TUIOSender.h | 693a94be9ce2506a7bee8d9e38642622be94cd6a | []
| no_license | hugodu/ccv-tbeta | 8869736cbdf29685a62d046f4820e7a26dcd05a7 | 246c84989eea0b5c759944466db7c591beb3c2e4 | refs/heads/master | 2021-04-01T10:39:18.368714 | 2011-03-09T23:05:24 | 2011-03-09T23:05:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,555 | h | /*
* TUIO.h
*
*
* Created on 2/2/09.
* Copyright 2009 NUI Group. All rights reserved.
*
*/
#ifndef TUIO_H
#define TUIO_H
//#include "../Tracking/ContourFinder.h"
#include "ofxOsc.h"
#include "ofxNetwork.h"
//#include "ofxFiducial.h"
#include "ofMain.h"
//#include "ofxTuioMultiplexer.h"
#include "Blob.h"
#include "TuioObject.h"
//#include "Calibration/Calibration.h"
//class ofxTuioMultiplexer;
class TUIOSender {
public:
TUIOSender();
~TUIOSender();
//methods
void setup( const char* host, int port, int flashport,int netinterfaceID, string tuio_application_name);
void setup_tuio_source_String(int id, string applicationName);
void setNetworkInterface(int id);
//void sendTUIO(std::map<int, Blob> * blobs);
void sendTUIO(std::vector<Blob> &blobs, std::list<TUIO::TuioObject> &tobjList);//, std::list <ofxFiducial> *fiducialsList
//TCP Network
ofxTCPServer m_tcpServer;
//OSC Network
ofxOscSender TUIOSocket;
const char* localHost;
int TUIOPort;
int TUIOFlashPort;
bool bHeightWidth;
bool bOSCMode;
bool bTCPMode;
bool bIsConnected;
//added by Stefan Schlupek
char* tuio_source_String;//
char* host_name;//ip Adress
const char* tuio_source_application;
int camWidth;//need the dimension from the Camera to Normalize the Fiducial Positions
int camHeight;
//------------------
private:
int frameseq;
bool send(string message);
string partialPrevMsg;
};
#endif | [
"schlupek@463ed9da-a5aa-4e33-a7e2-2d3b412cff85"
]
| [
[
[
1,
68
]
]
]
|
f915705ec8dfb2250676b6919669cb27dcf73e5b | 1d513e1d125c286d55688e93ec08876a8bdccc17 | /samples/example1/Example1.cpp | d39385a135a87a6891a6adf2b6d705004506073f | [
"MIT"
]
| permissive | croesnick/muparser | 6dc21a545d543663902f0046635486a8fd8540f7 | a41a634d6dc1b8d9ed4c47ed7e5ff7c39dffe304 | refs/heads/master | 2020-06-01T02:59:54.058788 | 2010-06-10T15:06:25 | 2010-06-10T15:06:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,498 | cpp | //---------------------------------------------------------------------------
//
// __________
// _____ __ __\______ \_____ _______ ______ ____ _______
// / \ | | \| ___/\__ \ \_ __ \/ ___/_/ __ \\_ __ \
// | Y Y \| | /| | / __ \_| | \/\___ \ \ ___/ | | \/
// |__|_| /|____/ |____| (____ /|__| /____ > \___ >|__|
// \/ \/ \/ \/
// (C) 2010 Ingo Berg
//
// Example 1 - using the parser as a static library
//
//---------------------------------------------------------------------------
#include "muParserTest.h"
/** \brief This macro will enable mathematical constants like M_PI. */
#define _USE_MATH_DEFINES
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <locale>
#include <limits>
#include <ios>
#include <iomanip>
#include "muParser.h"
#include "muParserInt.h"
//#include "muParserComplex.h"
#if defined( USINGDLL ) && defined( _WIN32 )
#error This sample can be used only with STATIC builds of muParser (on win32)
#endif
using namespace std;
using namespace mu;
// Operator callback functions
value_type Mega(value_type a_fVal) { return a_fVal * 1e6; }
value_type Milli(value_type a_fVal) { return a_fVal / (value_type)1e3; }
value_type Rnd(value_type v) { return v*std::rand()/(value_type)(RAND_MAX+1.0); }
value_type Not(value_type v) { return v==0; }
value_type Add(value_type v1, value_type v2) { return v1+v2; }
value_type Mul(value_type v1, value_type v2) { return v1*v2; }
//---------------------------------------------------------------------------
value_type Or(value_type v1, value_type v2)
{
return v1!=1 || v2!=1;
}
//---------------------------------------------------------------------------
value_type StrFun2(const char_type *v1, value_type v2,value_type v3)
{
mu::console() << v1 << std::endl;
return v2+v3;
}
//---------------------------------------------------------------------------
value_type Ping()
{
mu::console() << "ping\n"; return 0;
}
//---------------------------------------------------------------------------
mu::value_type SampleQuery(const char_type *szMsg)
{
if (szMsg)
mu::console() << szMsg << std::endl;
return 999;
};
//---------------------------------------------------------------------------
// Factory function for creating new parser variables
// This could as well be a function performing database queries.
value_type* AddVariable(const char_type *a_szName, void *a_pUserData)
{
// I don't want dynamic allocation here, so i used this static buffer
// If you want dynamic allocation you must allocate all variables dynamically
// in order to delete them later on. Or you find other ways to keep track of
// variables that have been created implicitely.
static value_type afValBuf[100];
static int iVal = 0;
mu::console() << _T("Generating new variable \"")
<< a_szName << _T("\" (slots left: ")
<< 99-iVal << _T(")")
<< _T(" User data pointer is:")
<< std::hex << a_pUserData <<endl;
afValBuf[iVal] = 0;
if (iVal>=99)
throw mu::ParserError( _T("Variable buffer overflow.") );
return &afValBuf[iVal++];
}
//---------------------------------------------------------------------------
void Splash()
{
mu::console() << _T(" __________ \n");
mu::console() << _T(" _____ __ __\\______ \\_____ _______ ______ ____ _______\n");
mu::console() << _T(" / \\ | | \\| ___/\\__ \\ \\_ __ \\/ ___/_/ __ \\\\_ __ \\ \n");
mu::console() << _T(" | Y Y \\| | /| | / __ \\_| | \\/\\___ \\ \\ ___/ | | \\/ \n");
mu::console() << _T(" |__|_| /|____/ |____| (____ /|__| /____ > \\___ >|__| \n");
mu::console() << _T(" \\/ \\/ \\/ \\/ \n");
mu::console() << _T(" Version ") << Parser().GetVersion() << _T("\n");
mu::console() << _T(" (C) 2010 Ingo Berg\n");
}
//---------------------------------------------------------------------------
void SelfTest()
{
mu::console() << _T( "-----------------------------------------------------------\n");
mu::console() << _T( "Configuration:\n\n");
#if defined(_DEBUG)
mu::console() << _T( "- DEBUG build\n");
#else
mu::console() << _T( "- RELEASE build\n");
#endif
#if defined(_UNICODE)
mu::console() << _T( "- UNICODE build\n");
#else
mu::console() << _T( "- ASCII build\n");
#endif
mu::console() << _T( "-----------------------------------------------------------\n");
mu::console() << _T( "Running test suite:\n\n");
mu::Test::ParserTester pt;
pt.Run();
mu::console() << _T( "-----------------------------------------------------------\n");
mu::console() << _T( "Commands:\n\n");
mu::console() << _T( " list var - list parser variables\n");
mu::console() << _T( " list exprvar - list expression variables\n");
mu::console() << _T( " list const - list all numeric parser constants\n");
mu::console() << _T( " locale de - switch to german locale\n");
mu::console() << _T( " locale en - switch to english locale\n");
mu::console() << _T( " locale reset - reset locale\n");
mu::console() << _T( " quit - exits the parser\n");
mu::console() << _T( "\nConstants:\n\n");
mu::console() << _T( " \"_e\" 2.718281828459045235360287\n");
mu::console() << _T( " \"_pi\" 3.141592653589793238462643\n");
mu::console() << _T( "-----------------------------------------------------------\n");
}
////---------------------------------------------------------------------------
//void CheckLocale()
//{
// // Local names:
// // "C" - the classic C locale
// // "de_DE" - not for Windows?
// // "en_US" - not for Windows?
// // "German_germany" - For MSVC8
// try
// {
// std::locale loc("German_germany");
// console() << _T("Locale settings:\n");
// console() << _T(" Decimal point: '") << std::use_facet<numpunct<char_type> >(loc).decimal_point() << "'\n";
// console() << _T(" Thousands sep: '") << std::use_facet<numpunct<char_type> >(loc).thousands_sep() << "'\n";
// console() << _T(" Grouping: \"") << std::use_facet<numpunct<char_type> >(loc).grouping() << "\"\n";
// console() << _T(" True is named: \"") << std::use_facet<numpunct<char_type> >(loc).truename() << "\"\n";
// console() << _T(" False is named: \"") << std::use_facet<numpunct<char_type> >(loc).falsename() << "\"\n";
// console() << _T("-----------------------------------------------------------\n");
// }
// catch(...)
// {
// console() << _T("Locale settings:\n");
// console() << _T(" invalid locale name\n");
// console() << _T("-----------------------------------------------------------\n");
// }
//}
//---------------------------------------------------------------------------
void ListVar(const mu::ParserBase &parser)
{
// Query the used variables (must be done after calc)
mu::varmap_type variables = parser.GetVar();
if (!variables.size())
return;
cout << "\nParser variables:\n";
cout << "-----------------\n";
cout << "Number: " << (int)variables.size() << "\n";
varmap_type::const_iterator item = variables.begin();
for (; item!=variables.end(); ++item)
mu::console() << _T("Name: ") << item->first << _T(" Address: [0x") << item->second << _T("]\n");
}
//---------------------------------------------------------------------------
void ListConst(const mu::ParserBase &parser)
{
mu::console() << _T("\nParser constants:\n");
mu::console() << _T("-----------------\n");
mu::valmap_type cmap = parser.GetConst();
if (!cmap.size())
{
mu::console() << _T("Expression does not contain constants\n");
}
else
{
valmap_type::const_iterator item = cmap.begin();
for (; item!=cmap.end(); ++item)
mu::console() << _T(" ") << item->first << _T(" = ") << item->second << _T("\n");
}
}
//---------------------------------------------------------------------------
void ListExprVar(const mu::ParserBase &parser)
{
string_type sExpr = parser.GetExpr();
if (sExpr.length()==0)
{
cout << _T("Expression string is empty\n");
return;
}
// Query the used variables (must be done after calc)
mu::console() << _T("\nExpression variables:\n");
mu::console() << _T("---------------------\n");
mu::console() << _T("Expression: ") << parser.GetExpr() << _T("\n");
varmap_type variables = parser.GetUsedVar();
if (!variables.size())
{
mu::console() << _T("Expression does not contain variables\n");
}
else
{
mu::console() << _T("Number: ") << (int)variables.size() << _T("\n");
mu::varmap_type::const_iterator item = variables.begin();
for (; item!=variables.end(); ++item)
mu::console() << _T("Name: ") << item->first << _T(" Address: [0x") << item->second << _T("]\n");
}
}
//---------------------------------------------------------------------------
/** \brief Check for external keywords.
*/
bool CheckKeywords(const mu::char_type *a_szLine, mu::Parser &a_Parser)
{
string_type sLine(a_szLine);
if ( sLine == _T("quit") )
{
exit(0);
}
else if ( sLine == _T("list var") )
{
ListVar(a_Parser);
return true;
}
else if ( sLine == _T("list const") )
{
ListConst(a_Parser);
return true;
}
else if ( sLine == _T("list exprvar") )
{
ListExprVar(a_Parser);
return true;
}
else if ( sLine == _T("list const") )
{
ListConst(a_Parser);
return true;
}
else if ( sLine == _T("locale de") )
{
mu::console() << _T("Setting german locale: ArgSep=';' DecSep=',' ThousandsSep='.'\n");
a_Parser.SetArgSep(';');
a_Parser.SetDecSep(',');
a_Parser.SetThousandsSep('.');
return true;
}
else if ( sLine == _T("locale en") )
{
mu::console() << _T("Setting english locale: ArgSep=',' DecSep='.' ThousandsSep=''\n");
a_Parser.SetArgSep(',');
a_Parser.SetDecSep('.');
a_Parser.SetThousandsSep();
return true;
}
else if ( sLine == _T("locale reset") )
{
mu::console() << _T("Resetting locale\n");
a_Parser.ResetLocale();
return true;
}
return false;
}
//---------------------------------------------------------------------------
void CheckDiff()
{
mu::Parser parser;
value_type x = 1,
v1,
v2,
v3,
eps(pow(std::numeric_limits<value_type>::epsilon(), 0.2));
parser.DefineVar(_T("x"), &x);
parser.SetExpr(_T("_e^-x*sin(x)"));
v1 = parser.Diff(&x, 1),
v2 = parser.Diff(&x, 1, eps);
v3 = cos((value_type)1.0)/exp((value_type)1) - sin((value_type)1.0)/exp((value_type)1); //-0.110793765307;
mu::console() << parser.GetExpr() << "\n";
mu::console() << "v1 = " << v1 << "; v1-v3 = " << v1-v3 << "\n";
mu::console() << "v2 = " << v2 << "; v2-v3 = " << v2-v3 << "\n";
}
//---------------------------------------------------------------------------
void Calc()
{
mu::Parser parser;
mu::ParserInt int_parser;
// mu::ParserComplex cmplx_parser;
// Change locale settings if necessary
// function argument separator: sum(2;3;4) vs. sum(2,3,4)
// decimal separator: 3,14 vs. 3.14
// thousands separator: 1000000 vs 1.000.000
//#define USE_GERMAN_LOCALE
#ifdef USE_GERMAN_LOCALE
parser.SetArgSep(';');
parser.SetDecSep(',');
parser.SetThousandsSep('.');
#else
// this is the default, so i it's commented:
//parser.SetArgSep(',');
//parser.SetDecSep('.');
//parser.SetThousandsSep('');
#endif
// Add some variables
value_type vVarVal[] = { 1, 2 }; // Values of the parser variables
parser.DefineVar(_T("a"), &vVarVal[0]); // Assign Variable names and bind them to the C++ variables
parser.DefineVar(_T("b"), &vVarVal[1]);
parser.DefineStrConst(_T("strBuf"), _T("hello world") );
// Add user defined unary operators
parser.DefinePostfixOprt(_T("M"), Mega);
parser.DefinePostfixOprt(_T("m"), Milli);
parser.DefineInfixOprt(_T("!"), Not);
parser.DefineFun(_T("query"), SampleQuery, false);
parser.DefineFun(_T("rnd"), Rnd, false); // Add an unoptimizeable function
parser.DefineFun(_T("strfun2"), StrFun2, false); // Add an unoptimizeable function
parser.DefineFun(_T("ping"), Ping, false);
parser.DefineOprt(_T("add"), Add, 0);
parser.DefineOprt(_T("mul"), Mul, 1);
parser.DefineOprt(_T("$"), Mul, 1);
// Define the variable factory
parser.SetVarFactory(AddVariable, &parser);
for(;;)
{
try
{
string_type sLine;
std::getline(mu::console_in(), sLine);
if (CheckKeywords(sLine.c_str(), parser))
continue;
//#define MUP_EXAMPLE_INT_PARSER
//#define MUP_EXAMPLE_COMPLEX_PARSER
#ifdef MUP_EXAMPLE_INT_PARSER
int_parser.SetExpr(sLine);
mu::console() << int_parser.Eval() << "\n";
#elif defined MUP_EXAMPLE_COMPLEX_PARSER
cmplx_parser.SetExpr(sLine);
mu::console() << cmplx_parser.Eval() << "\n";
#else
if (!sLine.length())
continue;
parser.SetExpr(sLine);
mu::console() << std::setprecision(12);
// The first call to eval implicitely creates the bytecode, and resets
// an internal pointer to the bytecode parsing function. Next time you call Eval
// the bytecode is used automatically!
mu::console() << "Parsing from string (slow): " << parser.Eval() << "\n";
// the second call automatically uses the bytecode for calculation, no interaction needed
mu::console() << "Parsing from bytecode (fast): " << parser.Eval() << "\n";
// mu::console() << parser.GetExpr() << "\n";
#endif
}
catch(mu::Parser::exception_type &e)
{
mu::console() << _T("\nError:\n");
mu::console() << _T("------\n");
mu::console() << _T("Message: ") << e.GetMsg() << _T("\n");
mu::console() << _T("Expression: \"") << e.GetExpr() << _T("\"\n");
mu::console() << _T("Token: \"") << e.GetToken() << _T("\"\n");
mu::console() << _T("Position: ") << (int)e.GetPos() << _T("\n");
mu::console() << _T("Errc: ") << std::dec << e.GetCode() << _T("\n");
}
} // while running
}
//---------------------------------------------------------------------------
int main(int, char**)
{
Splash();
SelfTest();
// CheckLocale();
// CheckDiff();
mu::console() << _T("Enter an expression or a command:\n");
try
{
Calc();
}
catch(Parser::exception_type &e)
{
// Only erros raised during the initialization will end up here
// formula related errors are treated in Calc()
console() << _T("Initialization error: ") << e.GetMsg() << endl;
string_type sBuf;
console_in() >> sBuf;
}
catch(std::exception & /*exc*/)
{
// there is no unicode compliant way to query exc.what()
// so i'll leave it for this example.
console() << _T("Internal error aborting...\n");
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
448
]
]
]
|
5371920c0a92803a2f4849a7a503a483e8edfae7 | f43c7dc0c3ca9031175fc3f13461a86b9c4ce667 | /dllsrc/scintilla/src/LexMatlab.cxx | f43f5c1715161915ed7af0d06638c4fdb634d8ba | [
"LicenseRef-scancode-scintilla"
]
| permissive | ebakker/aseisql | 998c8b10f4ba3499d53c2e74b2276620a694ef28 | faf31bf448dfb18b66b4f395188201989ccd3ced | refs/heads/master | 2021-01-18T20:19:41.247243 | 2009-11-09T21:45:48 | 2009-11-09T21:45:48 | 36,292,766 | 0 | 1 | null | null | null | null | MacCentralEurope | C++ | false | false | 5,290 | cxx | // Scintilla source code edit control
/** @file LexMatlab.cxx
** Lexer for Matlab.
** Written by Josť Fonseca
**/
// Copyright 1998-2001 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsMatlabComment(Accessor &styler, int pos, int len) {
return len > 0 && (styler[pos] == '%' || styler[pos] == '!') ;
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static void ColouriseMatlabDoc(unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler) {
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
bool transpose = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_MATLAB_OPERATOR) {
if (sc.chPrev == '.') {
if (sc.ch == '*' || sc.ch == '/' || sc.ch == '\\' || sc.ch == '^') {
sc.ForwardSetState(SCE_MATLAB_DEFAULT);
transpose = false;
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_MATLAB_DEFAULT);
transpose = true;
} else {
sc.SetState(SCE_MATLAB_DEFAULT);
}
} else {
sc.SetState(SCE_MATLAB_DEFAULT);
}
} else if (sc.state == SCE_MATLAB_KEYWORD) {
if (!isalnum(sc.ch) && sc.ch != '_') {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (keywords.InList(s)) {
sc.SetState(SCE_MATLAB_DEFAULT);
transpose = false;
} else {
sc.ChangeState(SCE_MATLAB_IDENTIFIER);
sc.SetState(SCE_MATLAB_DEFAULT);
transpose = true;
}
}
} else if (sc.state == SCE_MATLAB_NUMBER) {
if (!isdigit(sc.ch) && sc.ch != '.'
&& !(sc.ch == 'e' || sc.ch == 'E')
&& !((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E'))) {
sc.SetState(SCE_MATLAB_DEFAULT);
transpose = true;
}
} else if (sc.state == SCE_MATLAB_STRING) {
// Matlab doubles quotes to preserve them, so just end this string
// state now as a following quote will start again
if (sc.ch == '\'') {
sc.ForwardSetState(SCE_MATLAB_DEFAULT);
}
} else if (sc.state == SCE_MATLAB_COMMENT || sc.state == SCE_MATLAB_COMMAND) {
if (sc.atLineEnd) {
sc.SetState(SCE_MATLAB_DEFAULT);
transpose = false;
}
}
if (sc.state == SCE_MATLAB_DEFAULT) {
if (sc.ch == '%') {
sc.SetState(SCE_MATLAB_COMMENT);
} else if (sc.ch == '!') {
sc.SetState(SCE_MATLAB_COMMAND);
} else if (sc.ch == '\'') {
if (transpose) {
sc.SetState(SCE_MATLAB_OPERATOR);
} else {
sc.SetState(SCE_MATLAB_STRING);
}
} else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) {
sc.SetState(SCE_MATLAB_NUMBER);
} else if (isalpha(sc.ch)) {
sc.SetState(SCE_MATLAB_KEYWORD);
} else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '@' || sc.ch == '\\') {
if (sc.ch == ')' || sc.ch == ']') {
transpose = true;
} else {
transpose = false;
}
sc.SetState(SCE_MATLAB_OPERATOR);
} else {
transpose = false;
}
}
}
sc.Complete();
}
static void FoldMatlabDoc(unsigned int startPos, int length, int,
WordList *[], Accessor &styler) {
int endPos = startPos + length;
// Backtrack to previous line in case need to fix its fold status
int lineCurrent = styler.GetLine(startPos);
if (startPos > 0) {
if (lineCurrent > 0) {
lineCurrent--;
startPos = styler.LineStart(lineCurrent);
}
}
int spaceFlags = 0;
int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsMatlabComment);
char chNext = styler[startPos];
for (int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) {
int lev = indentCurrent;
int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsMatlabComment);
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
// Only non whitespace lines can be headers
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {
// Line after is blank so check the next - maybe should continue further?
int spaceFlags2 = 0;
int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsMatlabComment);
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
}
}
indentCurrent = indentNext;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
}
}
}
LexerModule lmMatlab(SCLEX_MATLAB, ColouriseMatlabDoc, "matlab", FoldMatlabDoc);
| [
"[email protected]@9f3282c0-2842-11de-b858-7de967f63ef5"
]
| [
[
[
1,
168
]
]
]
|
8a9c33589572fd0f98a6cea300666797d6c8c857 | fd196fe7f1a57a3d589dd987127391b6428dbc9f | /Projects/Platform2DGameTest/Game/GameStageEditor.h | c4030713f5ed1b7e0e9481debf9dac42eb1ba0bd | []
| no_license | aosyang/Graphic-Workbench | 73651b597b7ad9f759618bad30313bfad12a35b5 | 48c3b4b034ea332fb926ac0a0bd1f7c1fc1a2bb1 | refs/heads/master | 2021-01-22T23:25:48.330855 | 2011-11-29T09:27:52 | 2011-11-29T09:27:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,945 | h | /********************************************************************
created: 2011/10/16
filename: GameStageEditor.h
author: Mwolf
purpose: Map editor for game
*********************************************************************/
#ifndef GameStageEditor_h__
#define GameStageEditor_h__
#include "Math/GWVectors.h"
#include "GWCommon.h"
#include "GWInputDeviceEnum.h"
#include "BoundBox.h"
#include <string>
class GameStage;
struct AreaTrigger;
enum PaintToolType
{
PAINT_TOOL_PENCIL,
PAINT_TOOL_BRUSH,
};
enum PaintToolState
{
TOOL_STATE_IDLE,
TOOL_STATE_DRAWING,
};
class GameStageEditor
{
public:
GameStageEditor();
~GameStageEditor();
void Render();
void SetGameStage(GameStage* stage);
GameStage* GetGameStage() const { return m_GameStage; }
//Add by YLL for right click picking mode
void StartPicking( bool bStart = true );
void EndPicking(){ StartPicking( false ); }
void StartPainting();
void EndPainting();
void PaintTileAtCursor();
void PickupTileTypeAtCursor();
void SetPaintTool(PaintToolType tool) { m_PaintTool = tool; }
PaintToolType GetPaintTool() const { return m_PaintTool; }
void MarkMapUnsaved() { m_MapUnsaved = true; }
void MarkMapSaved() { m_MapUnsaved = false; }
bool IsMapUnsaved() const { return m_MapUnsaved; }
void ZoomView(int zoom);
GWAngle GetFovy() const { return m_Fovy; }
private:
Vector2 CursorToTilePos(int x_pos, int y_pos);
GameStage* m_GameStage;
std::string m_TileTypeToPaint;
bool m_bPicking;
Vector2 m_PopupMenuPos;
int m_PopupMenuScreenPosX,
m_PopupMenuScreenPosY;
bool m_RemoveTrigger;
int m_ToolBoxSelectedTriggerNameIndex;
AreaTrigger* m_SelectedAreaTrigger;
GWAngle m_Fovy;
PaintToolType m_PaintTool;
BoundBox m_SelectedArea;
PaintToolState m_ToolState;
bool m_MapUnsaved;
};
#endif // GameStageEditor_h__ | [
"[email protected]@b4c0308a-e464-ec88-fcea-6ff8c68c914a",
"[email protected]@b4c0308a-e464-ec88-fcea-6ff8c68c914a"
]
| [
[
[
1,
43
],
[
48,
68
],
[
71,
88
]
],
[
[
44,
47
],
[
69,
70
]
]
]
|
572295d76eb5677736d0a834cc96dc91c55c82c1 | d43d7825a000108a3e430d51c9309b03d7bc4698 | /PDR/FileDialogEx.h | 04fcaba1ff0f647ed0b19c7ab33355df0ac642d1 | []
| no_license | yinxufeng/php-desktop-runtime | fa788cd2a448ebd9e7fc028e1064902b485f0114 | 6fd871d028d0fbcdcff4ed5d21276126d04703d7 | refs/heads/master | 2020-05-18T16:42:50.660916 | 2010-07-05T07:06:46 | 2010-07-05T07:06:46 | 39,054,630 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | h |
/////////////////////////////////////////////////////////////////////////////
// CFileDialogEx dialog
class CFileDialogEx : public CFileDialog
{
public:
CFileDialogEx(
BOOL bOpenFileDialog, // TRUE for FileOpen, FALSE for FileSaveAs
LPCTSTR lpszDefExt = NULL,
LPCTSTR lpszFileName = NULL,
DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
LPCTSTR lpszFilter = NULL,
CWnd* pParentWnd = NULL,
DWORD dwSize = 0 ,
LPCTSTR psTitle = NULL
);
LPCTSTR m_psTitle ;
virtual void OnInitDone( );
}; | [
"aleechou@5b0c8100-e6ff-11de-8de6-035db03795fd"
]
| [
[
[
1,
22
]
]
]
|
b878cb59884b42ae6b92d647ea43ea8db690160b | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/asio/test/socket_base.cpp | 50484f6b6c7efacee837b3c7a7c7f19d340aa4e9 | [
"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 | 24,510 | cpp | //
// socket_base.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include <boost/asio/socket_base.hpp>
#include <boost/asio.hpp>
#include "unit_test.hpp"
//------------------------------------------------------------------------------
// socket_base_compile test
// ~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks that all nested classes, enums and constants in
// socket_base compile and link correctly. Runtime failures are ignored.
namespace socket_base_compile {
void test()
{
using namespace boost::asio;
namespace ip = boost::asio::ip;
try
{
io_service ios;
ip::tcp::socket sock(ios);
char buf[1024];
// shutdown_type enumeration.
sock.shutdown(socket_base::shutdown_receive);
sock.shutdown(socket_base::shutdown_send);
sock.shutdown(socket_base::shutdown_both);
// message_flags constants.
sock.receive(buffer(buf), socket_base::message_peek);
sock.receive(buffer(buf), socket_base::message_out_of_band);
sock.send(buffer(buf), socket_base::message_do_not_route);
// broadcast class.
socket_base::broadcast broadcast1(true);
sock.set_option(broadcast1);
socket_base::broadcast broadcast2;
sock.get_option(broadcast2);
broadcast1 = true;
static_cast<bool>(broadcast1);
static_cast<bool>(!broadcast1);
static_cast<bool>(broadcast1.value());
// debug class.
socket_base::debug debug1(true);
sock.set_option(debug1);
socket_base::debug debug2;
sock.get_option(debug2);
debug1 = true;
static_cast<bool>(debug1);
static_cast<bool>(!debug1);
static_cast<bool>(debug1.value());
// do_not_route class.
socket_base::do_not_route do_not_route1(true);
sock.set_option(do_not_route1);
socket_base::do_not_route do_not_route2;
sock.get_option(do_not_route2);
do_not_route1 = true;
static_cast<bool>(do_not_route1);
static_cast<bool>(!do_not_route1);
static_cast<bool>(do_not_route1.value());
// keep_alive class.
socket_base::keep_alive keep_alive1(true);
sock.set_option(keep_alive1);
socket_base::keep_alive keep_alive2;
sock.get_option(keep_alive2);
keep_alive1 = true;
static_cast<bool>(keep_alive1);
static_cast<bool>(!keep_alive1);
static_cast<bool>(keep_alive1.value());
// send_buffer_size class.
socket_base::send_buffer_size send_buffer_size1(1024);
sock.set_option(send_buffer_size1);
socket_base::send_buffer_size send_buffer_size2;
sock.get_option(send_buffer_size2);
send_buffer_size1 = 1;
static_cast<int>(send_buffer_size1.value());
// send_low_watermark class.
socket_base::send_low_watermark send_low_watermark1(128);
sock.set_option(send_low_watermark1);
socket_base::send_low_watermark send_low_watermark2;
sock.get_option(send_low_watermark2);
send_low_watermark1 = 1;
static_cast<int>(send_low_watermark1.value());
// receive_buffer_size class.
socket_base::receive_buffer_size receive_buffer_size1(1024);
sock.set_option(receive_buffer_size1);
socket_base::receive_buffer_size receive_buffer_size2;
sock.get_option(receive_buffer_size2);
receive_buffer_size1 = 1;
static_cast<int>(receive_buffer_size1.value());
// receive_low_watermark class.
socket_base::receive_low_watermark receive_low_watermark1(128);
sock.set_option(receive_low_watermark1);
socket_base::receive_low_watermark receive_low_watermark2;
sock.get_option(receive_low_watermark2);
receive_low_watermark1 = 1;
static_cast<int>(receive_low_watermark1.value());
// reuse_address class.
socket_base::reuse_address reuse_address1(true);
sock.set_option(reuse_address1);
socket_base::reuse_address reuse_address2;
sock.get_option(reuse_address2);
reuse_address1 = true;
static_cast<bool>(reuse_address1);
static_cast<bool>(!reuse_address1);
static_cast<bool>(reuse_address1.value());
// linger class.
socket_base::linger linger1(true, 30);
sock.set_option(linger1);
socket_base::linger linger2;
sock.get_option(linger2);
linger1.enabled(true);
static_cast<bool>(linger1.enabled());
linger1.timeout(1);
static_cast<int>(linger1.timeout());
// enable_connection_aborted class.
socket_base::enable_connection_aborted enable_connection_aborted1(true);
sock.set_option(enable_connection_aborted1);
socket_base::enable_connection_aborted enable_connection_aborted2;
sock.get_option(enable_connection_aborted2);
enable_connection_aborted1 = true;
static_cast<bool>(enable_connection_aborted1);
static_cast<bool>(!enable_connection_aborted1);
static_cast<bool>(enable_connection_aborted1.value());
// non_blocking_io class.
socket_base::non_blocking_io non_blocking_io(true);
sock.io_control(non_blocking_io);
// bytes_readable class.
socket_base::bytes_readable bytes_readable;
sock.io_control(bytes_readable);
std::size_t bytes = bytes_readable.get();
(void)bytes;
}
catch (std::exception&)
{
}
}
} // namespace socket_base_compile
//------------------------------------------------------------------------------
// socket_base_runtime test
// ~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks the runtime operation of the socket options and I/O
// control commands defined in socket_base.
namespace socket_base_runtime {
void test()
{
using namespace boost::asio;
namespace ip = boost::asio::ip;
io_service ios;
ip::udp::socket udp_sock(ios, ip::udp::v4());
ip::tcp::socket tcp_sock(ios, ip::tcp::v4());
ip::tcp::acceptor tcp_acceptor(ios, ip::tcp::v4());
boost::system::error_code ec;
// broadcast class.
socket_base::broadcast broadcast1(true);
BOOST_CHECK(broadcast1.value());
BOOST_CHECK(static_cast<bool>(broadcast1));
BOOST_CHECK(!!broadcast1);
udp_sock.set_option(broadcast1, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::broadcast broadcast2;
udp_sock.get_option(broadcast2, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(broadcast2.value());
BOOST_CHECK(static_cast<bool>(broadcast2));
BOOST_CHECK(!!broadcast2);
socket_base::broadcast broadcast3(false);
BOOST_CHECK(!broadcast3.value());
BOOST_CHECK(!static_cast<bool>(broadcast3));
BOOST_CHECK(!broadcast3);
udp_sock.set_option(broadcast3, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::broadcast broadcast4;
udp_sock.get_option(broadcast4, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(!broadcast4.value());
BOOST_CHECK(!static_cast<bool>(broadcast4));
BOOST_CHECK(!broadcast4);
// debug class.
socket_base::debug debug1(true);
BOOST_CHECK(debug1.value());
BOOST_CHECK(static_cast<bool>(debug1));
BOOST_CHECK(!!debug1);
udp_sock.set_option(debug1, ec);
#if defined(__linux__)
// On Linux, only root can set SO_DEBUG.
bool not_root = (ec == boost::asio::error::access_denied);
BOOST_CHECK(!ec || not_root);
BOOST_WARN_MESSAGE(!ec, "Must be root to set debug socket option");
#else // defined(__linux__)
# if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
# else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
# endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
#endif // defined(__linux__)
socket_base::debug debug2;
udp_sock.get_option(debug2, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
# if defined(__linux__)
BOOST_CHECK(debug2.value() || not_root);
BOOST_CHECK(static_cast<bool>(debug2) || not_root);
BOOST_CHECK(!!debug2 || not_root);
# else // defined(__linux__)
BOOST_CHECK(debug2.value());
BOOST_CHECK(static_cast<bool>(debug2));
BOOST_CHECK(!!debug2);
# endif // defined(__linux__)
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
socket_base::debug debug3(false);
BOOST_CHECK(!debug3.value());
BOOST_CHECK(!static_cast<bool>(debug3));
BOOST_CHECK(!debug3);
udp_sock.set_option(debug3, ec);
#if defined(__linux__)
BOOST_CHECK(!ec || not_root);
#else // defined(__linux__)
# if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
# else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
# endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
#endif // defined(__linux__)
socket_base::debug debug4;
udp_sock.get_option(debug4, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
# if defined(__linux__)
BOOST_CHECK(!debug4.value() || not_root);
BOOST_CHECK(!static_cast<bool>(debug4) || not_root);
BOOST_CHECK(!debug4 || not_root);
# else // defined(__linux__)
BOOST_CHECK(!debug4.value());
BOOST_CHECK(!static_cast<bool>(debug4));
BOOST_CHECK(!debug4);
# endif // defined(__linux__)
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
// do_not_route class.
socket_base::do_not_route do_not_route1(true);
BOOST_CHECK(do_not_route1.value());
BOOST_CHECK(static_cast<bool>(do_not_route1));
BOOST_CHECK(!!do_not_route1);
udp_sock.set_option(do_not_route1, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
socket_base::do_not_route do_not_route2;
udp_sock.get_option(do_not_route2, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(do_not_route2.value());
BOOST_CHECK(static_cast<bool>(do_not_route2));
BOOST_CHECK(!!do_not_route2);
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
socket_base::do_not_route do_not_route3(false);
BOOST_CHECK(!do_not_route3.value());
BOOST_CHECK(!static_cast<bool>(do_not_route3));
BOOST_CHECK(!do_not_route3);
udp_sock.set_option(do_not_route3, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
socket_base::do_not_route do_not_route4;
udp_sock.get_option(do_not_route4, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(!do_not_route4.value());
BOOST_CHECK(!static_cast<bool>(do_not_route4));
BOOST_CHECK(!do_not_route4);
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
// keep_alive class.
socket_base::keep_alive keep_alive1(true);
BOOST_CHECK(keep_alive1.value());
BOOST_CHECK(static_cast<bool>(keep_alive1));
BOOST_CHECK(!!keep_alive1);
tcp_sock.set_option(keep_alive1, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::keep_alive keep_alive2;
tcp_sock.get_option(keep_alive2, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(keep_alive2.value());
BOOST_CHECK(static_cast<bool>(keep_alive2));
BOOST_CHECK(!!keep_alive2);
socket_base::keep_alive keep_alive3(false);
BOOST_CHECK(!keep_alive3.value());
BOOST_CHECK(!static_cast<bool>(keep_alive3));
BOOST_CHECK(!keep_alive3);
tcp_sock.set_option(keep_alive3, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::keep_alive keep_alive4;
tcp_sock.get_option(keep_alive4, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(!keep_alive4.value());
BOOST_CHECK(!static_cast<bool>(keep_alive4));
BOOST_CHECK(!keep_alive4);
// send_buffer_size class.
socket_base::send_buffer_size send_buffer_size1(4096);
BOOST_CHECK(send_buffer_size1.value() == 4096);
tcp_sock.set_option(send_buffer_size1, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::send_buffer_size send_buffer_size2;
tcp_sock.get_option(send_buffer_size2, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(send_buffer_size2.value() == 4096);
socket_base::send_buffer_size send_buffer_size3(16384);
BOOST_CHECK(send_buffer_size3.value() == 16384);
tcp_sock.set_option(send_buffer_size3, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::send_buffer_size send_buffer_size4;
tcp_sock.get_option(send_buffer_size4, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(send_buffer_size4.value() == 16384);
// send_low_watermark class.
socket_base::send_low_watermark send_low_watermark1(4096);
BOOST_CHECK(send_low_watermark1.value() == 4096);
tcp_sock.set_option(send_low_watermark1, ec);
#if defined(WIN32) || defined(__linux__) || defined(__sun)
BOOST_CHECK(!!ec); // Not supported on Windows, Linux or Solaris.
#else
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif
socket_base::send_low_watermark send_low_watermark2;
tcp_sock.get_option(send_low_watermark2, ec);
#if defined(WIN32) || defined(__sun)
BOOST_CHECK(!!ec); // Not supported on Windows or Solaris.
#elif defined(__linux__)
BOOST_CHECK(!ec); // Not supported on Linux but can get value.
#else
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(send_low_watermark2.value() == 4096);
#endif
socket_base::send_low_watermark send_low_watermark3(8192);
BOOST_CHECK(send_low_watermark3.value() == 8192);
tcp_sock.set_option(send_low_watermark3, ec);
#if defined(WIN32) || defined(__linux__) || defined(__sun)
BOOST_CHECK(!!ec); // Not supported on Windows, Linux or Solaris.
#else
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif
socket_base::send_low_watermark send_low_watermark4;
tcp_sock.get_option(send_low_watermark4, ec);
#if defined(WIN32) || defined(__sun)
BOOST_CHECK(!!ec); // Not supported on Windows or Solaris.
#elif defined(__linux__)
BOOST_CHECK(!ec); // Not supported on Linux but can get value.
#else
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(send_low_watermark4.value() == 8192);
#endif
// receive_buffer_size class.
socket_base::receive_buffer_size receive_buffer_size1(4096);
BOOST_CHECK(receive_buffer_size1.value() == 4096);
tcp_sock.set_option(receive_buffer_size1, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
socket_base::receive_buffer_size receive_buffer_size2;
tcp_sock.get_option(receive_buffer_size2, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK(!ec); // Not supported under Windows CE but can get value.
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(receive_buffer_size2.value() == 4096);
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
socket_base::receive_buffer_size receive_buffer_size3(16384);
BOOST_CHECK(receive_buffer_size3.value() == 16384);
tcp_sock.set_option(receive_buffer_size3, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
BOOST_CHECK_MESSAGE(ec == boost::asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
socket_base::receive_buffer_size receive_buffer_size4;
tcp_sock.get_option(receive_buffer_size4, ec);
#if defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK(!ec); // Not supported under Windows CE but can get value.
#else // defined(BOOST_WINDOWS) && defined(UNDER_CE)
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(receive_buffer_size4.value() == 16384);
#endif // defined(BOOST_WINDOWS) && defined(UNDER_CE)
// receive_low_watermark class.
socket_base::receive_low_watermark receive_low_watermark1(4096);
BOOST_CHECK(receive_low_watermark1.value() == 4096);
tcp_sock.set_option(receive_low_watermark1, ec);
#if defined(WIN32) || defined(__sun)
BOOST_CHECK(!!ec); // Not supported on Windows or Solaris.
#else
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif
socket_base::receive_low_watermark receive_low_watermark2;
tcp_sock.get_option(receive_low_watermark2, ec);
#if defined(WIN32) || defined(__sun)
BOOST_CHECK(!!ec); // Not supported on Windows or Solaris.
#else
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(receive_low_watermark2.value() == 4096);
#endif
socket_base::receive_low_watermark receive_low_watermark3(8192);
BOOST_CHECK(receive_low_watermark3.value() == 8192);
tcp_sock.set_option(receive_low_watermark3, ec);
#if defined(WIN32) || defined(__sun)
BOOST_CHECK(!!ec); // Not supported on Windows or Solaris.
#else
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif
socket_base::receive_low_watermark receive_low_watermark4;
tcp_sock.get_option(receive_low_watermark4, ec);
#if defined(WIN32) || defined(__sun)
BOOST_CHECK(!!ec); // Not supported on Windows or Solaris.
#else
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(receive_low_watermark4.value() == 8192);
#endif
// reuse_address class.
socket_base::reuse_address reuse_address1(true);
BOOST_CHECK(reuse_address1.value());
BOOST_CHECK(static_cast<bool>(reuse_address1));
BOOST_CHECK(!!reuse_address1);
udp_sock.set_option(reuse_address1, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::reuse_address reuse_address2;
udp_sock.get_option(reuse_address2, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(reuse_address2.value());
BOOST_CHECK(static_cast<bool>(reuse_address2));
BOOST_CHECK(!!reuse_address2);
socket_base::reuse_address reuse_address3(false);
BOOST_CHECK(!reuse_address3.value());
BOOST_CHECK(!static_cast<bool>(reuse_address3));
BOOST_CHECK(!reuse_address3);
udp_sock.set_option(reuse_address3, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::reuse_address reuse_address4;
udp_sock.get_option(reuse_address4, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(!reuse_address4.value());
BOOST_CHECK(!static_cast<bool>(reuse_address4));
BOOST_CHECK(!reuse_address4);
// linger class.
socket_base::linger linger1(true, 60);
BOOST_CHECK(linger1.enabled());
BOOST_CHECK(linger1.timeout() == 60);
tcp_sock.set_option(linger1, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::linger linger2;
tcp_sock.get_option(linger2, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(linger2.enabled());
BOOST_CHECK(linger2.timeout() == 60);
socket_base::linger linger3(false, 0);
BOOST_CHECK(!linger3.enabled());
BOOST_CHECK(linger3.timeout() == 0);
tcp_sock.set_option(linger3, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::linger linger4;
tcp_sock.get_option(linger4, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(!linger4.enabled());
// enable_connection_aborted class.
socket_base::enable_connection_aborted enable_connection_aborted1(true);
BOOST_CHECK(enable_connection_aborted1.value());
BOOST_CHECK(static_cast<bool>(enable_connection_aborted1));
BOOST_CHECK(!!enable_connection_aborted1);
tcp_acceptor.set_option(enable_connection_aborted1, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::enable_connection_aborted enable_connection_aborted2;
tcp_acceptor.get_option(enable_connection_aborted2, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(enable_connection_aborted2.value());
BOOST_CHECK(static_cast<bool>(enable_connection_aborted2));
BOOST_CHECK(!!enable_connection_aborted2);
socket_base::enable_connection_aborted enable_connection_aborted3(false);
BOOST_CHECK(!enable_connection_aborted3.value());
BOOST_CHECK(!static_cast<bool>(enable_connection_aborted3));
BOOST_CHECK(!enable_connection_aborted3);
tcp_acceptor.set_option(enable_connection_aborted3, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::enable_connection_aborted enable_connection_aborted4;
tcp_acceptor.get_option(enable_connection_aborted4, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
BOOST_CHECK(!enable_connection_aborted4.value());
BOOST_CHECK(!static_cast<bool>(enable_connection_aborted4));
BOOST_CHECK(!enable_connection_aborted4);
// non_blocking_io class.
socket_base::non_blocking_io non_blocking_io1(true);
tcp_sock.io_control(non_blocking_io1, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::non_blocking_io non_blocking_io2(false);
tcp_sock.io_control(non_blocking_io2, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
// bytes_readable class.
socket_base::bytes_readable bytes_readable;
udp_sock.io_control(bytes_readable, ec);
BOOST_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
}
} // namespace socket_base_runtime
//------------------------------------------------------------------------------
test_suite* init_unit_test_suite(int, char*[])
{
test_suite* test = BOOST_TEST_SUITE("socket_base");
test->add(BOOST_TEST_CASE(&socket_base_compile::test));
test->add(BOOST_TEST_CASE(&socket_base_runtime::test));
return test;
}
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
653
]
]
]
|
9c0f3fa4f6c0e90a71431af46bc4288f1b056211 | 0b88542ea778e7cb8a4e8fc2b735c5dc53284ff4 | /cpp/libutil/test/testproperties.cpp | 74e9e05d790551770c0aa5da8eec66961e3a1230 | []
| no_license | GuoGuo-wen/library | 49cf889ef493ba779278932b6dcc8847b926dee3 | 680bc647f231f3dd1a8c095fef998f6afd54113b | refs/heads/master | 2021-11-23T21:25:00.693887 | 2011-10-28T00:32:35 | 2011-10-28T00:32:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | cpp | #pragma warning(disable: 4786)
#include <assert.h>
#include <iostream>
#include "properties.hpp"
using namespace util;
void Test()
{
Properties pro1("a.properties");
pro1.Set("dafd", "dafs{1}");
pro1.Set("a", "");
pro1.Save();
std::string v = pro1.Get("dafs");
std::cout << v << std::endl;
assert(v == "dafs");
std::cout << pro1.Get("dafd") << std::endl;
assert("dafs{1}" == pro1.Get("dafd"));
std::cout << pro1.Get("dafd", "test") << std::endl;
assert("dafstest" == pro1.Get("dafd", "test"));
pro1.Set("z", "zxcv");
pro1.Save();
Properties pro2("a.properties");
std::string v1 = pro1.Get("z");
std::cout << v1 << std::endl;
assert("zxcv" == v1);
}
int main()
{
Test();
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
8847dec485dafcf072dd8749929a6f0d1516a861 | fa609a5b5a0e7de3344988a135b923a0f655f59e | /Tests/Source/TestValueInt64.cpp | b3f2100a1270d000be34ed1f076873a60bf080d5 | [
"MIT"
]
| permissive | Sija/swift | 3edfd70e1c8d9d54556862307c02d1de7d400a7e | dddedc0612c0d434ebc2322fc5ebded10505792e | refs/heads/master | 2016-09-06T09:59:35.416041 | 2007-08-30T02:29:30 | 2007-08-30T02:29:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,160 | cpp | #include "stdafx.h"
#include <cppunit/extensions/HelperMacros.h>
#include "../../Source/stdafx.h"
#include "../../Source/values/Int64.h"
#include "../../Source/values/Bool.h"
using namespace Swift;
class TestValueInt64 : public CPPUNIT_NS::TestFixture {
public:
CPPUNIT_TEST_SUITE(TestValueInt64);
CPPUNIT_TEST(testInit);
CPPUNIT_TEST(testAssign);
CPPUNIT_TEST(testGet);
CPPUNIT_TEST(testSetClear);
CPPUNIT_TEST(testOperators);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() { }
void tearDown() { }
protected:
void testInit() {
CPPUNIT_ASSERT(iValue::hasTypeString(Values::Int64::id));
}
void testAssign() {
oValue i((__int64) 123);
oValue i1(24434342545455677);
CPPUNIT_ASSERT(i->getID() == Values::Int64::id);
CPPUNIT_ASSERT(i1->getID() == Values::Int64::id);
}
void testGet() {
CPPUNIT_ASSERT(oValue((__int64) 200) >> __int64() == 200);
CPPUNIT_ASSERT(((Values::Int64*) oValue((__int64) 15).get())->output() == 15);
}
void testSetClear() {
oValue v((__int64) 678);
v->clear();
CPPUNIT_ASSERT(v >> __int64() == 0);
Values::Int64* i = (Values::Int64*) v.get();
i->set(999);
CPPUNIT_ASSERT(v >> __int64() == 999);
}
void testOperators() {
CPPUNIT_ASSERT((oValue((__int64) 4) == oValue((__int64) 4)) >> bool());
CPPUNIT_ASSERT((oValue((__int64) 2) != oValue((__int64) 3)) >> bool());
CPPUNIT_ASSERT((oValue((__int64) 4) && oValue((__int64) 2)) >> bool());
CPPUNIT_ASSERT((oValue((__int64) 0) || oValue((__int64) 5)) >> bool());
CPPUNIT_ASSERT((-oValue((__int64) 15) == oValue((__int64) -15)) >> bool());
CPPUNIT_ASSERT(((oValue((__int64) 8) + oValue((__int64) 3)) == oValue((__int64) 11)) >> bool());
CPPUNIT_ASSERT(((oValue((__int64) 3) - oValue((__int64) 7)) == oValue((__int64) -4)) >> bool());
CPPUNIT_ASSERT(!(!oValue((__int64) 4) >> bool()));
CPPUNIT_ASSERT((oValue() << (__int64) 100)->getID() == Values::Int64::id);
CPPUNIT_ASSERT((oValue((__int64) 2090) >> __int64()) == 2090);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestValueInt64);
| [
"[email protected]"
]
| [
[
[
1,
72
]
]
]
|
819a63904db0990863a854ac11606854db246e82 | 2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83 | /BasicOgreFramework/PhysxSDK/Samples/SampleForceField/src/NxSampleForceField.cpp | 83367af936d4b08139167dbdeb98229c6b2244c3 | []
| no_license | mgq812/simengines-g2-code | 5908d397ef2186e1988b1d14fa8b73f4674f96ea | 699cb29145742c1768857945dc59ef283810d511 | refs/heads/master | 2016-09-01T22:57:54.845817 | 2010-01-11T19:26:51 | 2010-01-11T19:26:51 | 32,267,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,335 | cpp | // ===============================================================================
//
// AGEIA PhysX SDK Sample Program
//
// Title: Force Fields
// Description: This sample program shows how to use force fields
//
// This file contains the main application, the interesting parts (for learning
// about Force Fields) are the following sample files:
// * VortexSample.cpp - A vortex that can be moved around in a scene. Exclude shapes
// and NX_FFC_CYLINDRICAL coordinates are used.
// * WindSample.cpp - A straight blowing wind with a small animation.
// Exclude shapes and NX_FFC_CARTESIAN coordinates.
// * ExplosionSample.cpp - A simple explosion effect. NX_FFC_SPHERICAL coordinates
// are used in this sample.
//
// ===============================================================================
#define NOMINMAX
#ifdef WIN32
#include <windows.h>
#elif LINUX
#endif
// Physics code
#undef random
#include "NxSampleForceField.h"
#include "Utilities.h"
#include "cooking.h"
#include "SamplesVRDSettings.h"
#include "MySoftBody.h"
#include "NXU_helper.h"
DebugRenderer gDebugRenderer;
int gDebugRenderState = 0;
ErrorStream gErrorStream;
// Physics SDK globals
NxPhysicsSDK* gPhysicsSDK = NULL;
NxScene* gScene = NULL;
NxVec3 gDefaultGravity(0,-9.8f,0);
bool gSceneRunning = false;
#ifdef NX_DISABLE_HARDWARE
bool gHardwareSimulation = false;
#else
bool gHardwareSimulation = true;
#endif
bool gCookingInitialized = false;
unsigned gSampleIndex = 0;
NxArray<ForceFieldSample*> gSamples;
// Display globals
int gMainHandle;
bool gHelp = false;
char gDisplayString[512] = "";
char gTitleString[512] = "";
char gHelpString[512] = "";
// Camera globals
NxReal gCameraFov = 40.0f;
NxVec3 gCameraPos(0,8,25);
NxVec3 gCameraForward(0,0,-1);
NxVec3 gCameraRight(1,0,0);
NxReal gCameraSpeed = 0.2;
int gViewWidth = 0;
int gViewHeight = 0;
bool gRotateCamera = false;
// MouseGlobals
int mx = 0;
int my = 0;
// Keyboard globals
#define MAX_KEYS 256
bool gKeys[MAX_KEYS];
// Simulation globals
bool gPause = false;
bool gShadows = true;
bool gWireframeMode = false;
// fps
int gFrameCounter = 0;
float gPreviousTime = getCurrentTime();
NxForceField* gForceField = NULL;
NxActor* gForceFieldActor = NULL;
MySoftBody* gSoftBody = NULL;
bool InitNx()
{
// Initialize PhysicsSDK
NxPhysicsSDKDesc desc;
NxSDKCreateError errorCode = NXCE_NO_ERROR;
gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &gErrorStream, desc, &errorCode);
if(gPhysicsSDK == NULL)
{
printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode));
return false;
}
#if SAMPLES_USE_VRD
// The settings for the VRD host and port are found in SampleCommonCode/SamplesVRDSettings.h
if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger() && !gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected())
gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(SAMPLES_VRD_HOST, SAMPLES_VRD_PORT, SAMPLES_VRD_EVENTMASK);
#endif
gPhysicsSDK->setParameter(NX_VISUALIZE_FORCE_FIELDS, 1.0f);
#ifndef NX_DISABLE_HARDWARE
NxHWVersion hwCheck = gPhysicsSDK->getHWVersion();
if (hwCheck == NX_HW_VERSION_NONE)
{
printf("\nWarning: Unable to find a PhysX card, or PhysX card used by other application.");
printf("\nThe fluids will be simulated in software.\n\n");
gHardwareSimulation = false;
}
#endif
if (!gCookingInitialized)
{
gCookingInitialized = true;
if (!InitCooking())
{
printf("\nError: Unable to initialize the cooking library, exiting the sample.\n\n");
return false;
}
}
// Set the physics parameters
gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.005f);
// Set the debug visualization parameters
gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
gSamples[gSampleIndex]->setup();
if (gScene == NULL)
{
for (NxU32 i = 0; i < gPhysicsSDK->getNbScenes(); i++)
{
gScene = gPhysicsSDK->getScene(i);
break;
}
}
#if defined(_XBOX) | defined(__CELLOS_LV2__)
glutRemapButtonExt(3, 'x', false); //Demo-specific usage
#endif
// simulate one frame to make fluids and other things initialized
RunPhysics();
return true;
}
void WaitForPhysics()
{
if (gSceneRunning)
{
NxU32 error;
gScene->flushStream();
gScene->fetchResults(NX_ALL_FINISHED, true, &error);
assert(error == 0);
gSceneRunning = false;
}
}
void ReleaseNx()
{
WaitForPhysics();
if (gCookingInitialized)
{
CloseCooking();
gCookingInitialized = false;
}
if(gPhysicsSDK != NULL)
{
if(gScene != NULL) gPhysicsSDK->releaseScene(*gScene);
gScene = NULL;
NxReleasePhysicsSDK(gPhysicsSDK);
gPhysicsSDK = NULL;
}
NXU::releasePersistentMemory();
}
void ResetNx(NxU32 loadSample)
{
WaitForPhysics();
gSamples[gSampleIndex]->cleanup();
ReleaseNx();
gSampleIndex = loadSample;
if (!InitNx()) exit(0);
}
void RunPhysics()
{
if (gSceneRunning)
return;
NxReal deltaTime = 0.02f; //We are not simulating real time here, you should meassure the
// difference in real time since the last call and use that.
//Let the current sample update, if it needs to change anything before simulating
gSamples[gSampleIndex]->update();
gScene->simulate(deltaTime);
gSceneRunning = true;
WaitForPhysics();
gFrameCounter++;
}
// ------------------------------------------------------------------------------------
void DisplayText()
{
sprintf(gDisplayString, "%s%s", gTitleString, gHelp?gHelpString:"");
float y = 0.95f;
int len = strlen(gDisplayString);
len = (len < 1024)?len:1023;
int start = 0;
char textBuffer[1024];
for(int i=0;i<len;i++)
{
if(gDisplayString[i] == '\n' || i == len-1)
{
int offset = i;
if(i == len-1) offset= i+1;
memcpy(textBuffer, gDisplayString+start, offset-start);
textBuffer[offset-start]=0;
GLFontRenderer::print(0.01, y, 0.03f, textBuffer);
y -= 0.035f;
start = offset+1;
}
}
}
// ------------------------------------------------------------------------------------
void SetTitleString(char *demoName)
{
sprintf(gTitleString, "%s (%s)\nF1 for help\n", demoName, gHardwareSimulation ? "hardware" : "software");
}
// ------------------------------------------------------------------------------------
void SetHelpString(char *demoKeyString)
{
char tempString[512];
sprintf(gHelpString, "\nGeneral:\n");
sprintf(tempString, " 1-%d: choose scene\n", gSamples.size());
strcat(gHelpString, tempString);
strcat(gHelpString, " p: pause\n");
strcat(gHelpString, " o: single step\n");
#ifndef NX_DISABLE_HARDWARE
strcat(gHelpString, " h: hardware on/off\n");
#endif
strcat(gHelpString, " w,a,s,d: move/strafe\n");
strcat(gHelpString, " q,e: move up/down\n");
strcat(gHelpString, " space: shoot sphere\n");
strcat(gHelpString, " F1: toggle help\n");
strcat(gHelpString, " F5: toggle debug rendering\n");
strcat(gHelpString, " F10: Reset scene\n");
if (demoKeyString)
{
strcat(gHelpString, "\nDemo specific:\n");
strcat(gHelpString, demoKeyString);
}
}
// ------------------------------------------------------------------------------------
void ProcessKeys()
{
// Process keys
for (int i = 0; i < MAX_KEYS; i++)
{
if (!gKeys[i]) { continue; }
gSamples[gSampleIndex]->processKey(i);
switch (i)
{
// Camera controls
case 'w':{ gCameraPos += gCameraForward*gCameraSpeed; break; }
case 's':{ gCameraPos -= gCameraForward*gCameraSpeed; break; }
case 'a':{ gCameraPos -= gCameraRight*gCameraSpeed; break; }
case 'd':{ gCameraPos += gCameraRight*gCameraSpeed; break; }
case 'e':{ gCameraPos -= NxVec3(0,1,0)*gCameraSpeed; break; }
case 'q':{ gCameraPos += NxVec3(0,1,0)*gCameraSpeed; break; }
}
}
}
// ------------------------------------------------------------------------------------
void SetupCamera()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(gCameraFov, ((float)glutGet(GLUT_WINDOW_WIDTH)/(float)glutGet(GLUT_WINDOW_HEIGHT)), 1.0f, 10000.0f);
gluLookAt(gCameraPos.x,gCameraPos.y,gCameraPos.z,gCameraPos.x + gCameraForward.x, gCameraPos.y + gCameraForward.y, gCameraPos.z + gCameraForward.z, 0.0f, 1.0f, 0.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// ------------------------------------------------------------------------------------
inline void MyDrawArrow(const NxVec3& posA, const NxVec3& posB)
{
NxVec3 v3ArrowShape[] = {
NxVec3(posA), NxVec3(posB)
};
glVertexPointer(3, GL_FLOAT, sizeof(NxVec3), &v3ArrowShape[0].x);
glDrawArrays(GL_LINES, 0, sizeof(v3ArrowShape)/sizeof(NxVec3));
}
void SampleAndVisualizeForceFieldShapeGroup(NxForceField* field, NxForceFieldShapeGroup* group)
{
group->resetShapesIterator();
NxU32 nbShapes = group->getNbShapes();
while (nbShapes--)
{
NxForceFieldShape* shape = group->getNextShape();
NxBoxForceFieldShape* boxShape = shape->isBox();
if (!boxShape) continue;
NxVec3 dim = boxShape->getDimensions();
NxMat34 pose = boxShape->getPose();
if (boxShape->getForceField() != NULL)
{
pose = field->getPose() * pose;
if (gForceFieldActor != NULL)
pose = gForceFieldActor->getGlobalPose() * pose;
}
NxVec3 start = pose.t - (pose.M*dim);
int resolution = 10;
//NxVec3 step = dim * (2.0f / (float) resolution);
NxVec3 stepX = pose.M.getColumn(0) * dim.x * (2.0f / (float) resolution);
NxVec3 stepY = pose.M.getColumn(1) * dim.y * (2.0f / (float) resolution);
NxVec3 stepZ = pose.M.getColumn(2) * dim.z * (2.0f / (float) resolution);
NxVec3 samplePoint;
NxVec3 sampleForce;
NxVec3 sampleTorque;
for (int i = 0; i < resolution; i++)
{
for (int j = 0; j < resolution; j++)
{
for (int k = 0; k < resolution; k++)
{
samplePoint = start + stepX*i + stepY*j + stepZ*k;
field->samplePoints(1, &samplePoint, NULL, &sampleForce, &sampleTorque);
MyDrawArrow(samplePoint, samplePoint + sampleForce * 0.005f);
}
}
}
}
}
void SampleAndVisualizeForceField(NxForceField* field)
{
if (field == NULL) return;
#ifndef __CELLOS_LV2__
glPushAttrib(GL_ALL_ATTRIB_BITS);
#endif
glDisable(GL_LIGHTING);
glLineWidth(1.0f);
glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
glEnableClientState(GL_VERTEX_ARRAY);
glLoadIdentity();
// visualize all shape groups
field->resetShapeGroupsIterator();
NxU32 nbGroups = field->getNbShapeGroups();
while (nbGroups--)
{
NxForceFieldShapeGroup* group = field->getNextShapeGroup();
SampleAndVisualizeForceFieldShapeGroup(field, group);
}
SampleAndVisualizeForceFieldShapeGroup(field, &field->getIncludeShapeGroup());
glDisableClientState(GL_VERTEX_ARRAY);
#ifndef __CELLOS_LV2__
glPopAttrib();
#else
glEnable(GL_LIGHTING);
glColor4f(1.0f,1.0f,1.0f,1.0f);
#endif
}
void RenderForceFieldGroup(NxForceFieldShapeGroup* group)
{
const NxReal excludeCol[4] = {1.0f, 0.0f, 0.0f, 0.3f};
const NxReal includeCol[4] = {0.0f, 1.0f, 0.0f, 0.3f};
const NxReal* col = (group->getFlags() & NX_FFSG_EXCLUDE_GROUP) ? excludeCol : includeCol;
group->resetShapesIterator();
NxU32 nbShapes = group->getNbShapes();
NxMat34 ffPose;
ffPose.id();
NxForceField* ff = group->getForceField();
if(ff)
{
ffPose = ff->getPose();
NxActor* actor = ff->getActor();
if(actor)
ffPose = actor->getGlobalPose() * ffPose;
}
while (nbShapes--)
{
NxForceFieldShape* shape = group->getNextShape();
NxMat34 pose = ffPose * shape->getPose();
glPushMatrix();
SetupGLMatrix(pose.t, pose.M);
glColor4fv(col);
switch(shape->getType())
{
case NX_SHAPE_BOX:
{
NxBoxForceFieldShape* boxShape = shape->isBox();
NxVec3 boxDim = boxShape->getDimensions();
glScalef(boxDim.x, boxDim.y, boxDim.z);
glutSolidCube(2);
break;
}
case NX_SHAPE_SPHERE:
{
NxSphereForceFieldShape* sphereShape = shape->isSphere();
NxReal radius = sphereShape->getRadius();
glScalef(radius, radius, radius);
glutSolidSphere(1.0f, 12, 12);
break;
}
}
glPopMatrix();
}
}
void RenderForceField(NxForceField* field)
{
// render groups
field->resetShapeGroupsIterator();
NxU32 nbGroups = field->getNbShapeGroups();
while (nbGroups--)
{
NxForceFieldShapeGroup* group = field->getNextShapeGroup();
RenderForceFieldGroup(group);
}
RenderForceFieldGroup(&field->getIncludeShapeGroup());
}
void RenderScene(bool shadows)
{
// Render all the actors in the scene
int nbActors = gScene->getNbActors();
NxActor** actors = gScene->getActors();
while (nbActors--)
{
NxActor* actor = *actors++;
if (actor->userData == (void*)1) continue;
DrawActor(actor);
}
NxCloth** cloths = gScene->getCloths();
int nbCloths = gScene->getNbCloths();
while (nbCloths--)
{
NxCloth* cloth = *cloths++;
DrawCloth(cloth, true);
}
#if NX_USE_FLUID_API
NxFluid** fluids = gScene->getFluids();
int nbFluids = gScene->getNbFluids();
while (nbFluids--)
{
NxFluid* fluid = *fluids++;
DrawFluid(fluid);
}
#endif
if (gSoftBody != NULL)
{
//void simulateAndDraw(bool shadows, bool tetraMesh, bool tetraWireframe);
gSoftBody->simulateAndDraw(false, true, false);
}
if (gForceField != NULL && gDebugRenderState > 0)
{
//draw transparent boxes for where the force field shapes are
#ifndef __CELLOS_LV2__
glPushAttrib(GL_ALL_ATTRIB_BITS);
#endif
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(false);
NxU32 nbForceFields = gScene->getNbForceFields();
while(nbForceFields--)
{
RenderForceField(gScene->getForceFields()[nbForceFields]);
}
glDisable(GL_BLEND);
glDepthMask(true);
#ifndef __CELLOS_LV2__
glPopAttrib();
#endif
}
}
void RenderCallback()
{
ProcessKeys();
if (gScene && !gPause)
RunPhysics();
// Clear buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SetupCamera();
if (gDebugRenderState >= 2)
{
NxU32 nbForceFields = gScene->getNbForceFields();
while(nbForceFields--)
{
SampleAndVisualizeForceField(gScene->getForceFields()[nbForceFields]);
}
}
RenderScene(gShadows);
if (gDebugRenderState == 3)
gDebugRenderer.renderData(*(gScene->getDebugRenderable()));
DisplayText();
glutSwapBuffers();
}
void ReshapeCallback(int width, int height)
{
gViewWidth = width;
gViewHeight = height;
glViewport(0, 0, width, height);
}
void IdleCallback()
{
glutPostRedisplay();
float time = getCurrentTime();
float elapsedTime = time - gPreviousTime;
if (elapsedTime > 1.0f) {
char title[30];
sprintf(title, "SampleForceField %3.1f fps", (float)gFrameCounter / elapsedTime);
glutSetWindowTitle(title);
gPreviousTime = time;
gFrameCounter = 0;
}
getElapsedTime();
}
void KeyboardCallback(unsigned char key, int x, int y)
{
gKeys[key] = true;
if ('1' <= key && key <= '8')
{
unsigned index = key - '0' - 1;
if (index < gSamples.size())
{
ResetNx(index);
}
}
if (key == '0')
{
ResetNx((gSampleIndex + 1) % gSamples.size());
}
switch (key)
{
case 'p': { gPause = !gPause; break; }
case 'o': { if (!gPause) gPause = true; RunPhysics(); glutPostRedisplay(); break; }
case 'n': { gWireframeMode = !gWireframeMode; break; }
case ' ': {
NxActor *sphere = CreateSphere(gCameraPos, 1.0f, 1.0f);
sphere->setLinearVelocity(gCameraForward * 20.0f);
break;
}
#ifndef NX_DISABLE_HARDWARE
case 'h' : {
gHardwareSimulation = !gHardwareSimulation;
ResetNx(gSampleIndex);
break;
}
#endif
case 27 : { ReleaseNx(); exit(0); break; }
default : { break; }
}
gSamples[gSampleIndex]->onKeyPress(key, x, y);
}
void KeyboardUpCallback(unsigned char key, int x, int y)
{
gKeys[key] = false;
}
void SpecialCallback(int key, int x, int y)
{
switch (key)
{
// Reset PhysX
case GLUT_KEY_F9: toggleVSync(); return;
case GLUT_KEY_F10: ResetNx(gSampleIndex); return;
case GLUT_KEY_F1:
gHelp = !gHelp;
break;
case GLUT_KEY_F5:
{
gDebugRenderState++;
if (gDebugRenderState > 3) gDebugRenderState = 0;
WaitForPhysics();
if (gDebugRenderState == 3)
gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1.0f);
else
gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 0.0f);
break;
}
}
gSamples[gSampleIndex]->onVirtualKeyPress(key, x, y);
}
void MouseCallback(int button, int state, int x, int y)
{
mx = x;
my = y;
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
gRotateCamera = true;
}
if (state == GLUT_UP)
{
gRotateCamera = false;
}
}
void MotionCallback(int x, int y)
{
int dx = mx - x;
int dy = my - y;
if (gRotateCamera)
{
gCameraForward.normalize();
gCameraRight.cross(gCameraForward,NxVec3(0,1,0));
NxQuat qx(NxPiF32 * dx * 20 / 180.0f, NxVec3(0,1,0));
qx.rotate(gCameraForward);
NxQuat qy(NxPiF32 * dy * 20 / 180.0f, gCameraRight);
qy.rotate(gCameraForward);
}
mx = x;
my = y;
}
int main(int argc, char** argv)
{
//Make a list of the demos in this sample
gSamples.pushBack(new SampleVortex());
gSamples.pushBack(new SampleWind());
gSamples.pushBack(new SampleExplosion());
//Initialize GLUT
glutInit(&argc, argv);
glutInitWindowSize(800, 600);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
gMainHandle = glutCreateWindow("Force Field Sample");
glutSetWindow(gMainHandle);
glutDisplayFunc(RenderCallback);
glutReshapeFunc(ReshapeCallback);
glutIdleFunc(IdleCallback);
glutKeyboardFunc(KeyboardCallback);
glutKeyboardUpFunc(KeyboardUpCallback);
glutSpecialFunc(SpecialCallback);
glutMouseFunc(MouseCallback);
glutMotionFunc(MotionCallback);
MotionCallback(0,0);
// Setup default render states
glClearColor(0.52f, 0.60f, 0.71f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_SMOOTH);
#ifdef WIN32
glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
#endif
// Setup lighting
glEnable(GL_LIGHTING);
float AmbientColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientColor);
float DiffuseColor[] = { 0.6f, 0.6f, 0.6f, 0.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseColor);
float SpecularColor[] = { 0.7f, 0.7f, 0.7f, 0.0f }; glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularColor);
float Position[] = { 10.0f, 200.0f, 15.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_POSITION, Position);
glEnable(GL_LIGHT0);
// Initialize physics scene and start the application main loop if scene was created
if (InitNx())
glutMainLoop();
else
ReleaseNx();
}
| [
"erucarno@789472dc-e1c3-11de-81d3-db62269da9c1"
]
| [
[
[
1,
740
]
]
]
|
7c8a74ad10a496f9e58539613e6461a49425da8c | 4f89f1c71575c7a5871b2a00de68ebd61f443dac | /lib/boost/gil/extension/sdl/user_events.hpp | aecd7985e202a25fae741b3354385af11f4b75c4 | []
| no_license | inayatkh/uniclop | 1386494231276c63eb6cdbe83296cdfd0692a47c | 487a5aa50987f9406b3efb6cdc656d76f15957cb | refs/heads/master | 2021-01-10T09:43:09.416338 | 2009-09-03T16:26:15 | 2009-09-03T16:26:15 | 50,645,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 971 | hpp | // Copyright 2007 Christian Henning.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/*************************************************************************************************/
#ifndef USER_EVENTS_HPP
#define USER_EVENTS_HPP
namespace boost
{
namespace gil
{
namespace sdl
{
namespace detail
{
struct default_keyboard_event_handler
{
// Return true to trigger redraw.
bool key_up()
{
return false;
}
};
struct default_redraw_event_handler
{
void redraw( const bgra8_view_t& sdl_view ) {}
};
struct default_timer_event_handler
{
// Return true to trigger redraw.
bool time_elapsed()
{
return false;
}
};
struct default_quit_event_handler
{
void quit() {}
};
}
}
}
} // namespace boost::gil::sdl::detail
#endif // GIL_SDL_CONVERTERS_HPP
| [
"rodrigo.benenson@gmailcom"
]
| [
[
[
1,
54
]
]
]
|
40c227e59dc0a337c35a55f821c4181a9adefaf4 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/wave/preprocessing_hooks.hpp | cd068eac852c821d3a96f0b19bef40b3f7285402 | [
"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 | 13,989 | hpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2007 Hartmut Kaiser. 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(PREPROCESSING_HOOKS_HPP_338DE478_A13C_4B63_9BA9_041C917793B8_INCLUDED)
#define PREPROCESSING_HOOKS_HPP_338DE478_A13C_4B63_9BA9_041C917793B8_INCLUDED
#include <boost/wave/wave_config.hpp>
#include <vector>
// this must occur after all of the includes and before any code appears
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_PREFIX
#endif
///////////////////////////////////////////////////////////////////////////////
namespace boost {
namespace wave {
namespace context_policies {
///////////////////////////////////////////////////////////////////////////////
//
// The default_preprocessing_hooks class is a placeholder for all
// preprocessing hooks called from inside the preprocessing engine
//
///////////////////////////////////////////////////////////////////////////////
struct default_preprocessing_hooks {
///////////////////////////////////////////////////////////////////////////
//
// The function 'expanding_function_like_macro' is called, whenever a
// function-like macro is to be expanded.
//
// The macroname parameter marks the position, where the macro to expand
// is defined.
// The formal_args parameter holds the formal arguments used during the
// definition of the macro.
// The definition parameter holds the macro definition for the macro to
// trace.
//
// The macro call parameter marks the position, where this macro invoked.
// The arguments parameter holds the macro arguments used during the
// invocation of the macro
//
///////////////////////////////////////////////////////////////////////////
template <typename TokenT, typename ContainerT>
void expanding_function_like_macro(
TokenT const ¯odef, std::vector<TokenT> const &formal_args,
ContainerT const &definition,
TokenT const ¯ocall, std::vector<ContainerT> const &arguments)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'expanding_object_like_macro' is called, whenever a
// object-like macro is to be expanded .
//
// The macroname parameter marks the position, where the macro to expand
// is defined.
// The definition parameter holds the macro definition for the macro to
// trace.
//
// The macro call parameter marks the position, where this macro invoked.
//
///////////////////////////////////////////////////////////////////////////
template <typename TokenT, typename ContainerT>
void expanding_object_like_macro(TokenT const ¯o,
ContainerT const &definition, TokenT const ¯ocall)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'expanded_macro' is called, whenever the expansion of a
// macro is finished but before the rescanning process starts.
//
// The parameter 'result' contains the token sequence generated as the
// result of the macro expansion.
//
///////////////////////////////////////////////////////////////////////////
template <typename ContainerT>
void expanded_macro(ContainerT const &result)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'rescanned_macro' is called, whenever the rescanning of a
// macro is finished.
//
// The parameter 'result' contains the token sequence generated as the
// result of the rescanning.
//
///////////////////////////////////////////////////////////////////////////
template <typename ContainerT>
void rescanned_macro(ContainerT const &result)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'found_include_directive' is called, whenever a #include
// directive was located.
//
// The parameter 'filename' contains the (expanded) file name found after
// the #include directive. This has the format '<file>', '"file"' or
// 'file'.
// The formats '<file>' or '"file"' are used for #include directives found
// in the preprocessed token stream, the format 'file' is used for files
// specified through the --force_include command line argument.
//
// The parameter 'include_next' is set to true if the found directive was
// a #include_next directive and the BOOST_WAVE_SUPPORT_INCLUDE_NEXT
// preprocessing constant was defined to something != 0.
//
///////////////////////////////////////////////////////////////////////////
void
found_include_directive(std::string const &filename, bool include_next)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'opened_include_file' is called, whenever a file referred
// by an #include directive was successfully located and opened.
//
// The parameter 'filename' contains the file system path of the
// opened file (this is relative to the directory of the currently
// processed file or a absolute path depending on the paths given as the
// include search paths).
//
// The include_depth parameter contains the current include file depth.
//
// The is_system_include parameter denotes, whether the given file was
// found as a result of a #include <...> directive.
//
///////////////////////////////////////////////////////////////////////////
void
opened_include_file(std::string const &relname, std::string const &absname,
std::size_t include_depth, bool is_system_include)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'returning_from_include_file' is called, whenever an
// included file is about to be closed after it's processing is complete.
//
///////////////////////////////////////////////////////////////////////////
void
returning_from_include_file()
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'interpret_pragma' is called, whenever a #pragma command
// directive is found which isn't known to the core Wave library, where
// command is the value defined as the BOOST_WAVE_PRAGMA_KEYWORD constant
// which defaults to "wave".
//
// The parameter 'ctx' is a reference to the context object used for
// instantiating the preprocessing iterators by the user.
//
// The parameter 'pending' may be used to push tokens back into the input
// stream, which are to be used as the replacement text for the whole
// #pragma directive.
//
// The parameter 'option' contains the name of the interpreted pragma.
//
// The parameter 'values' holds the values of the parameter provided to
// the pragma operator.
//
// The parameter 'act_token' contains the actual #pragma token, which may
// be used for error output.
//
// If the return value is 'false', the whole #pragma directive is
// interpreted as unknown and a corresponding error message is issued. A
// return value of 'true' signs a successful interpretation of the given
// #pragma.
//
///////////////////////////////////////////////////////////////////////////
template <typename ContextT, typename ContainerT>
bool
interpret_pragma(ContextT const &ctx, ContainerT &pending,
typename ContextT::token_type const &option, ContainerT const &values,
typename ContextT::token_type const &act_token)
{
return false;
}
///////////////////////////////////////////////////////////////////////////
//
// The function 'defined_macro' is called, whenever a macro was defined
// successfully.
//
// The parameter 'name' is a reference to the token holding the macro name.
//
// The parameter 'is_functionlike' is set to true, whenever the newly
// defined macro is defined as a function like macro.
//
// The parameter 'parameters' holds the parameter tokens for the macro
// definition. If the macro has no parameters or if it is a object like
// macro, then this container is empty.
//
// The parameter 'definition' contains the token sequence given as the
// replacement sequence (definition part) of the newly defined macro.
//
// The parameter 'is_predefined' is set to true for all macros predefined
// during the initialisation phase of the library.
//
///////////////////////////////////////////////////////////////////////////
template <typename TokenT, typename ParametersT, typename DefinitionT>
void
defined_macro(TokenT const ¯o_name, bool is_functionlike,
ParametersT const ¶meters, DefinitionT const &definition,
bool is_predefined)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'undefined_macro' is called, whenever a macro definition
// was removed successfully.
//
// The parameter 'name' holds the name of the macro, which definition was
// removed.
//
///////////////////////////////////////////////////////////////////////////
template <typename TokenT>
void
undefined_macro(TokenT const ¯o_name)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'found_directive' is called, whenever a preprocessor
// directive was encountered, but before the corresponding action is
// executed.
//
// The parameter 'directive' is a reference to the token holding the
// preprocessing directive.
//
///////////////////////////////////////////////////////////////////////////
template <typename TokenT>
void
found_directive(TokenT const& directive)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'evaluated_conditional_expression' is called, whenever a
// conditional preprocessing expression was evaluated (the expression
// given to a #if, #ifdef or #ifndef directive)
//
// The parameter 'expression' holds the non-expanded token sequence
// comprising the evaluated expression.
//
// The parameter expression_value contains the result of the evaluation of
// the expression in the current preprocessing context.
//
///////////////////////////////////////////////////////////////////////////
template <typename ContainerT>
void
evaluated_conditional_expression(ContainerT const& expression,
bool expression_value)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'skipped_token' is called, whenever a token is about to be
// skipped due to a false preprocessor condition (code fragments to be
// skipped inside the not evaluated conditional #if/#else/#endif branches).
//
// The parameter 'token' refers to the token to be skipped.
//
//
///////////////////////////////////////////////////////////////////////////
template <typename TokenT>
void
skipped_token(TokenT const& token)
{}
///////////////////////////////////////////////////////////////////////////
//
// The function 'may_skip_whitespace' is called, will be called by the
// library, whenever a token is about to be returned to the calling
// application.
//
// The parameter 'ctx' is a reference to the context object used for
// instantiating the preprocessing iterators by the user.
//
// The 'token' parameter holds a reference to the current token. The policy
// is free to change this token if needed.
//
// The 'skipped_newline' parameter holds a reference to a boolean value
// which should be set to true by the policy function whenever a newline
// is going to be skipped.
//
// If the return value is true, the given token is skipped and the
// preprocessing continues to the next token. If the return value is
// false, the given token is returned to the calling application.
//
// ATTENTION!
// Caution has to be used, because by returning true the policy function
// is able to force skipping even significant tokens, not only whitespace.
//
///////////////////////////////////////////////////////////////////////////
template <typename ContextT, typename TokenT>
bool
may_skip_whitespace(ContextT const& ctx, TokenT& token, bool& skipped_newline)
{ return false; }
};
///////////////////////////////////////////////////////////////////////////////
} // namespace context_policies
} // namespace wave
} // namespace boost
// the suffix header occurs after all of the code
#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_SUFFIX
#endif
#endif // !defined(PREPROCESSING_HOOKS_HPP_338DE478_A13C_4B63_9BA9_041C917793B8_INCLUDED)
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
324
]
]
]
|
0bc423ca9f6b85a56328e02a8a51aadec65e0e63 | 6253ab92ce2e85b4db9393aa630bde24655bd9b4 | /Scene Estimator 2/IDGenerator.cpp | d7b1bddbab90e79608e9c2df13b925a01a43e186 | []
| no_license | Aand1/cornell-urban-challenge | 94fd4df18fd4b6cc6e12d30ed8eed280826d4aed | 779daae8703fe68e7c6256932883de32a309a119 | refs/heads/master | 2021-01-18T11:57:48.267384 | 2008-10-01T06:43:18 | 2008-10-01T06:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,763 | cpp | #include "IDGenerator.h"
#ifdef __cplusplus_cli
#pragma unmanaged
#endif
IDGenerator::IDGenerator()
{
/*
Default constructor for the ID generator class. Initializes
member variables with the first available track ID (1)
INPUTS:
none.
OUTPUTS:
none.
*/
//the first ID assigned will be this one
mLargestID = 1;
//initially mark "1" as the first free ID
mFreeIDs.push_back(1);
return;
}
int IDGenerator::GenerateID()
{
/*
Returns a new unique ID that is not currently in use.
INPUTS:
none.
OUTPUTS:
rID - the new ID that will be assigned to a track. NOTE:
this ID is not recycled until ReleaseID is called on it.
*/
int rID;
int nf = (int) mFreeIDs.size();
if (nf > 0)
{
//there was at least one free ID in the list, so return that one
rID = mFreeIDs[nf-1];
//and remove it from the list, as it is no longer free
mFreeIDs.pop_back();
}
else
{
//all IDs from 1 to mLargestID are assigned, so increment
mLargestID++;
rID = mLargestID;
}
//mark the ID as having been assigned
mAssignedIDs.insert(rID);
return rID;
}
void IDGenerator::ReleaseID(int iIDToRelease)
{
/*
Releases an ID from a track, so it may be reused for another track.
INPUTS:
iIDToRelease - the integer ID to release.
OUTPUTS:
none.
*/
//first check to see if the ID is actually assigned
set<int>::iterator idx = mAssignedIDs.find(iIDToRelease);
if (idx == mAssignedIDs.end())
{
//the track id didn't appear to be assigned in the first place
return;
}
//if code gets here, the ID was assigned, so free it
mAssignedIDs.erase(idx);
//mark the ID as being free
mFreeIDs.push_back(iIDToRelease);
return;
}
| [
"anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5"
]
| [
[
[
1,
91
]
]
]
|
7066ded527c31d65b884d09364528eab5dc770e8 | e41ff1b15d54fc77dd0b86abc83bcbefa0ff6c07 | /shard/SRSDLCanvas.h | 34aee74ccf0466be6f50e23aa11f85091492f3ec | []
| no_license | zerotri/WynterStorm_old | 8dd9c6e3932b5883bce6f4fa6709159e8ca46ed8 | dd289ed3419a7eaff8e824d7f818b31b03075f21 | refs/heads/master | 2020-12-24T13:44:58.837251 | 2010-03-22T10:21:56 | 2010-03-22T10:21:56 | 570,788 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | h | #ifndef SRSDLCANVAS_H
#define SRSDLCANVAS_H
#include <SRCanvas.h>
#include <SDL.h>
class SRSDLCanvas : public SRCanvas
{
private:
protected:
SDL_Surface* m_pCanvas;
public:
virtual void create(int w, int h);
virtual u8* getData();
virtual const CSRectangle<u32> getRectangle();
virtual void drawRectangle(CSRectangle<u32>& rectangle, CSColor<u32>& color);
virtual void drawFilledRectangle(CSRectangle<u32>& rectangle, CSColor<u32>& color);
virtual void drawRoundRectangle(CSRectangle<u32>& rectangle, u32 radius, CSColor<u32>& color);
virtual void drawCircle(CSPoint<u32>& center, u32 radius, CSColor<u32>& color);
virtual void drawFilledCircle(CSPoint<u32>& center, u32 radius, CSColor<u32>& color);
virtual void drawLine(CSLine<u32>& line, CSColor<u32>& color);
virtual void drawPixel(CSPoint<u32>& point, CSColor<u32>& color);
};
#endif | [
"[email protected]"
]
| [
[
[
1,
23
]
]
]
|
4d6d7cd95e040fade781c56047dbed638f957038 | 6e3cc7846bdba91f1d8dde0eb0a8b7c7bd8100c8 | /Projects/agent/TestAgent/TestAgent.cpp | 3a5e60ec5e72967cfb2e048dd3de2d846859beda | []
| no_license | shilinxu/hcmus-it-asset-management | fd74c9fdd7667f345bd9da4c7b95ef6caae3367c | 740c040a6b13463a826a98e437845b197f7b282f | refs/heads/master | 2020-05-04T10:47:24.800734 | 2010-07-13T06:51:36 | 2010-07-13T06:51:36 | 42,918,774 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,123 | cpp | // TestAgent.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "TestAgent.h"
#include "TestAgentDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CTestAgentApp
BEGIN_MESSAGE_MAP(CTestAgentApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CTestAgentApp construction
CTestAgentApp::CTestAgentApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CTestAgentApp object
CTestAgentApp theApp;
// CTestAgentApp initialization
BOOL CTestAgentApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CTestAgentDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"nghdiep@d3aa494c-0344-11df-8b0e-05a2803efa1e"
]
| [
[
[
1,
78
]
]
]
|
9c2accdf460c2c86f1628d5ecdf33c048c07243e | cb95e331a9b1a44df292f65edf9e0126826b44a0 | /inc/EggClockDocument.h | d3678b870eeedaa1a1a8f89cfc5383a80383a65d | []
| no_license | SymbiSoft/eggclock60 | 07a0fbf60824d84a3b02293b91f5cc3db68b2c79 | 0c57faa92449ad07b2190b1175999d934ff64e88 | refs/heads/master | 2021-01-10T15:04:55.830548 | 2011-05-27T14:19:39 | 2011-05-27T14:19:39 | 48,186,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,009 | h | /*
============================================================================
Name : EggClockDocument.h
Author : Michele Berionne
Version :
Copyright :
Description : Application document class (model)
============================================================================
*/
#ifndef __EGGCLOCKDOCUMENT_H__
#define __EGGCLOCKDOCUMENT_H__
// INCLUDES
#include <akndoc.h>
// FORWARD DECLARATIONS
class CEggClockAppUi;
class CEikApplication;
// CLASS DECLARATION
class CEggClockDocument : public CAknDocument
{
public: // Constructors and destructor
static CEggClockDocument* NewL( CEikApplication& aApp );
static CEggClockDocument* NewLC( CEikApplication& aApp );
virtual ~CEggClockDocument();
public: // Functions from base classes
CEikAppUi* CreateAppUiL();
private: // Constructors
void ConstructL();
CEggClockDocument( CEikApplication& aApp );
};
#endif // __EGGCLOCKDOCUMENT_H__
// End of File
| [
"mberionne@1c8bd404-c52a-0410-b554-e13d1092c3cc"
]
| [
[
[
1,
41
]
]
]
|
542fc19969fde30311113a1ac0233b1762eaa55c | b5ab57edece8c14a67cc98e745c7d51449defcff | /Captain's Log/MainGame/Source/GameObjects/CAppliedItem.h | e4a55711822f71ad38c368c750a19c9e363caa5f | []
| no_license | tabu34/tht-captainslog | c648c6515424a6fcdb628320bc28fc7e5f23baba | 72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2 | refs/heads/master | 2020-05-30T15:09:24.514919 | 2010-07-30T17:05:11 | 2010-07-30T17:05:11 | 32,187,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | h | #ifndef CAppliedItem_h__
#define CAppliedItem_h__
#include "CItem.h"
class CAppliedItem : public CItem
{
public:
CAppliedItem();
//void AddEffect();
//void RemoveEffect();
};
#endif // CAppliedItem_h__ | [
"notserp007@34577012-8437-c882-6fb8-056151eb068d",
"dpmakin@34577012-8437-c882-6fb8-056151eb068d"
]
| [
[
[
1,
8
],
[
13,
14
]
],
[
[
9,
12
]
]
]
|
ac16ca05f44728e8cb25f967035a48de990e58e4 | 1e4daaa1f0846720f608094479aadb58759e1021 | /p2p-simulation/atomic/transcoder/register.cpp | af9ac936195dfc626fb8388bb6726022b201599c | []
| no_license | DDionne/SpiderWeb | d7d69091a08aaf6b2ae7f50ad7a8bd40406cc693 | 0d3e78a0a053e4c0e826cf9b9eae332930929fc0 | refs/heads/master | 2021-01-16T19:56:44.257854 | 2011-06-07T19:33:40 | 2011-06-07T19:33:40 | 1,860,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cpp | /*******************************************************************
*
* DESCRIPTION: Simulator::registerNewAtomics()
*
* AUTHOR: Amir Barylko & Jorge Beyoglonian
*
* EMAIL: mailto://[email protected]
* mailto://[email protected]
*
* DATE: 27/6/1998
*
*******************************************************************/
#include "modeladm.h"
#include "mainsimu.h"
#include "demux.h" // class demultiplexer
void MainSimulator::registerNewAtomics()
{
SingleModelAdm::Instance().registerAtomic( NewAtomicFunction<Demux>() , "Demux" ) ;
};
| [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
ab2b720d5bc5c1fd77964a2aebd7dc0df4d94034 | 9f5ec465e1e40349168c910b15089e2cd1183404 | /acoutic_modem/acoutic_modem/Sender.h | aa6fd5c77e77de9ae50688c0e6d47beaeef4d192 | []
| no_license | gmalysa/ece4760-acoustic-modem | 466ba2aa7a0ba0850ba05c7fc829e0466b9b9993 | 9435938c49d0d1046f772e99f197368985cec7cb | refs/heads/master | 2021-01-10T21:19:44.846408 | 2010-05-05T17:24:29 | 2010-05-05T17:24:29 | 32,143,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 736 | h | #pragma once
#include "stdafx.h"
#include <string>
#include <time.h>
#define BYTE_DELAY 16
#define RESP_TIMEOUT 100
#define MAX_RETRIES 10
extern int doResend;
class Sender
{
public:
static const unsigned char header = 0x0A;
static const unsigned char resendHeader = 0x0F;
static const unsigned char successResponse = 0x3E;
int ignoreDuplicates;
Sender(wchar_t* port, int baud_rate);
Sender(const Sender &s);
void send(const unsigned char* data, size_t length, unsigned int delay);
void write(const unsigned char* data, size_t length, unsigned int delay);
unsigned char *read();
~Sender(void);
private:
HANDLE commPort;
HANDLE responseEvent;
HANDLE getResponseEvent;
char last_crc;
}; | [
"4romanen@27756a54-6646-6b34-56b7-074c8a0e1335"
]
| [
[
[
1,
33
]
]
]
|
2644ad40ef6548a286b87974c2423b33864a9601 | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/Graphics/include/TextureInputSampler.h | b7cfb837920265af7e4e466b37b85c11173dab03 | []
| no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | h | #pragma once
#ifndef __TEXTURE_INPUT_SAMPLER_H__
#define __TEXTURE_INPUT_SAMPLER_H__
#include "base.h"
#include "InputSampler.h"
class CTextureInputSampler :
public CInputSampler
{
public:
CTextureInputSampler() {};
~CTextureInputSampler() {Done();};
bool Init(int _iIndex, const string& _szName, bool _bIsCube);
protected:
virtual void Release() {};
};
#endif
| [
"sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485",
"Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
]
| [
[
[
1,
14
],
[
16,
24
]
],
[
[
15,
15
]
]
]
|
10ee202fbccb352bf251304b926138d3031083e9 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/aux_/value_wknd.hpp | d08fc3db61b4a46c455e4b5636080ed6ffd3f610 | []
| no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,236 | hpp |
#ifndef BOOST_MPL_AUX_VALUE_WKND_HPP_INCLUDED
#define BOOST_MPL_AUX_VALUE_WKND_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-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/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/aux_/value_wknd.hpp,v $
// $Date: 2006/04/17 23:48:05 $
// $Revision: 1.1 $
#include <boost/mpl/aux_/static_cast.hpp>
#include <boost/mpl/aux_/config/integral.hpp>
#include <boost/mpl/aux_/config/eti.hpp>
#include <boost/mpl/aux_/config/workaround.hpp>
#if defined(BOOST_MPL_CFG_BCC_INTEGRAL_CONSTANTS) \
|| defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG)
# include <boost/mpl/int.hpp>
namespace boost { namespace mpl { namespace aux {
template< typename C_ > struct value_wknd
: C_
{
};
#if defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG)
template<> struct value_wknd<int>
: int_<1>
{
using int_<1>::value;
};
#endif
}}}
#if !defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG)
# define BOOST_MPL_AUX_VALUE_WKND(C) \
::BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE::aux::value_wknd< C > \
/**/
# define BOOST_MPL_AUX_MSVC_VALUE_WKND(C) BOOST_MPL_AUX_VALUE_WKND(C)
#else
# define BOOST_MPL_AUX_VALUE_WKND(C) C
# define BOOST_MPL_AUX_MSVC_VALUE_WKND(C) \
::boost::mpl::aux::value_wknd< C > \
/**/
#endif
#else // BOOST_MPL_CFG_BCC_INTEGRAL_CONSTANTS
# define BOOST_MPL_AUX_VALUE_WKND(C) C
# define BOOST_MPL_AUX_MSVC_VALUE_WKND(C) C
#endif
#if BOOST_WORKAROUND(__EDG_VERSION__, <= 238)
# define BOOST_MPL_AUX_NESTED_VALUE_WKND(T, C) \
BOOST_MPL_AUX_STATIC_CAST(T, C::value) \
/**/
#else
# define BOOST_MPL_AUX_NESTED_VALUE_WKND(T, C) \
BOOST_MPL_AUX_VALUE_WKND(C)::value \
/**/
#endif
namespace boost { namespace mpl { namespace aux {
template< typename T > struct value_type_wknd
{
typedef typename T::value_type type;
};
#if defined(BOOST_MPL_CFG_MSVC_ETI_BUG)
template<> struct value_type_wknd<int>
{
typedef int type;
};
#endif
}}}
#endif // BOOST_MPL_AUX_VALUE_WKND_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
]
| [
[
[
1,
89
]
]
]
|
8e769c0b21011a57d1f2173e9f38983a4ff7200f | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlIntpTrilinear3.h | fcf09dca9d55732c4e90e9400c0ad37d87baf216 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,678 | h | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifndef WMLINTPTRILINEAR3_H
#define WMLINTPTRILINEAR3_H
#include "WmlSystem.h"
namespace Wml
{
template <class Real>
class WML_ITEM IntpTrilinear3
{
public:
// Construction and destruction. IntpTrilinear3 does not accept
// responsibility for deleting the input array. The application must do
// so. The interpolator is for uniformly spaced (x,y,z)-values. The
// function values are assumed to be organized as f(x,y,z) = F[z][y][x].
IntpTrilinear3 (int iXBound, int iYBound, int iZBound, Real fXMin,
Real fXSpacing, Real fYMin, Real fYSpacing, Real fZMin,
Real fZSpacing, Real*** aaafF);
int GetXBound () const;
int GetYBound () const;
int GetZBound () const;
int GetQuantity () const;
Real*** GetF () const;
Real GetXMin () const;
Real GetXMax () const;
Real GetXSpacing () const;
Real GetYMin () const;
Real GetYMax () const;
Real GetYSpacing () const;
Real GetZMin () const;
Real GetZMax () const;
Real GetZSpacing () const;
// Evaluate the function and its derivatives. The application is
// responsible for ensuring that xmin <= x <= xmax, ymin <= y <= ymax,
// and zmin <= z <= zmax. If (x,y,z) is outside the extremes, the
// function returns MAXREAL. The first operator is for function
// evaluation. The second operator is for function or derivative
// evaluations. The uiXOrder argument is the order of the x-derivative,
// the uiYOrder argument is the order of the y-derivative, and the
// uiZOrder argument is the order of the z-derivative. All orders are
// zero to get the function value itself.
Real operator() (Real fX, Real fY, Real fZ) const;
Real operator() (int iXOrder, int iYOrder, int iZOrder, Real fX,
Real fY, Real fZ) const;
protected:
int m_iXBound, m_iYBound, m_iZBound, m_iQuantity;
Real m_fXMin, m_fXMax, m_fXSpacing, m_fInvXSpacing;
Real m_fYMin, m_fYMax, m_fYSpacing, m_fInvYSpacing;
Real m_fZMin, m_fZMax, m_fZSpacing, m_fInvZSpacing;
Real*** m_aaafF;
static const Real ms_aafBlend[2][2];
};
typedef IntpTrilinear3<float> IntpTrilinear3f;
typedef IntpTrilinear3<double> IntpTrilinear3d;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
76
]
]
]
|
555c1b47599271c55aa75c721dd48b1d1023392f | 9d52dd06680cf4618fc128c84b65408262740397 | /ID2204/assignment1/GecodeAssignment.cpp | 62af4f705de6224c1188b9fabc560a989228d2e2 | []
| no_license | Fercho1992/wangyuhere | bd43d57108d46cdf63c3496b68db016e7766ca23 | 088cff2286924b2c074f3665ae902522c054ac8a | refs/heads/master | 2016-08-12T23:17:23.067134 | 2010-10-10T11:44:26 | 2010-10-10T11:44:26 | 51,190,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,212 | cpp | // GecodeAssignment.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Sudoku.h"
#include "Queens.h"
#include <gecode/gist.hh>
using namespace Gecode;
void runSudoku(int i, IntConLevel option = ICL_DEF);
void runQueens(int n, IntVarBranch op = INT_VAR_SIZE_MIN);
void runQueensGist(int n);
int _tmain(int argc, _TCHAR* argv[])
{
const int size = sizeof(examples)/sizeof(examples[0]);
for(int i = 0; i < size; i++) {
std::cout<<"=====================================";
runSudoku(i);
}
std::cout<<"\n============Using ICL_DEF============";
runSudoku(5, ICL_DEF);
std::cout<<"\n============Using ICL_VAL============";
runSudoku(5, ICL_VAL);
std::cout<<"\n============Using ICL_BND============";
runSudoku(5, ICL_BND);
std::cout<<"\n============Using ICL_DOM============";
runSudoku(5, ICL_DOM);
std::cout<<"\n8 Queens solutions:\n";
runQueens(8);
std::cout<<"\n8 Queens using INT_VAR_SIZE_MAX\n";
runQueens(8, INT_VAR_SIZE_MAX);
runQueensGist(8);
system("PAUSE");
return 0;
}
void runSudoku(int i, IntConLevel option) {
std::cout<<"\nSudoku puzzle "<<i<<" :\n";
for(int j = 0; j < 9; j++)
{
for(int k = 0; k < 9; k++)
{
std::cout<<examples[i][j][k]<<" ";
}
std::cout<<std::endl;
}
std::cout<<"\nSudoku answer "<<i<<" :\n";
Sudoku* m = new Sudoku(&examples[i][0][0], option);
DFS<Sudoku> e(m);
delete m;
while (Sudoku* s = e.next()) {
std::cout<<"depth: "<<e.statistics().depth<<std::endl;
std::cout<<"memory: "<<e.statistics().memory<<std::endl;
std::cout<<"node: "<<e.statistics().node<<std::endl;
s->print(); delete s;
}
}
void runQueens(int n, IntVarBranch op) {
Queens* q = new Queens(n, op);
DFS<Queens> e(q);
delete q;
int i = 0;
while(Queens* qs = e.next()) {
i++;
std::cout<<"depth: "<<e.statistics().depth<<std::endl;
std::cout<<"memory: "<<e.statistics().memory<<std::endl;
std::cout<<"node: "<<e.statistics().node<<std::endl;
qs->print(std::cout);
delete qs;
}
std::cout<<"Number of solution "<<i<<std::endl;
}
void runQueensGist(int n)
{
Queens* q = new Queens(n);
Gist::dfs(q);
delete q;
} | [
"wangyuhere@d95a48d6-0e68-11df-9450-0db692d89755"
]
| [
[
[
1,
86
]
]
]
|
79a2b2d1faf72a9302159ad7001c4de3e7a008fd | 1092bd6dc9b728f3789ba96e37e51cdfb9e19301 | /loci/control/xml/parser.cpp | bfc0d67298097f9518bb4a7a6ff5b3dbed62e3ac | []
| 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 | 6,225 | cpp | #include "loci/control/xml/parser.h"
#include "loci/control/xml/detail/default_node_parsers.h"
#include "loci/anim/weight_mask.h"
#include "loci/control/actor_controller.h"
#include "loci/numeric/vector.h"
#include "loci/anim/nodes/sync.h"
namespace loci {
namespace control {
namespace xml
{
parser::parser()
{
set_seq_node_parser("sequence", detail::parse_sequence);
set_seq_node_parser("clip", detail::parse_clip);
set_seq_node_parser("trim", detail::parse_trim);
set_seq_node_parser("timeoffset", detail::parse_time_offset);
set_seq_node_parser("applyduration", detail::parse_apply_duration);
set_seq_node_parser("alterduration", detail::parse_alter_duration);
set_seq_node_parser("heading", detail::parse_fix_heading);
set_seq_node_parser("autoturn", detail::parse_follow_heading);
set_blend_node_parser("speedtransition", detail::parse_speed_transition);
set_blend_node_parser("add", detail::parse_additive_combine);
set_blend_node_parser("sub", detail::parse_additive_extract);
set_blend_node_parser("tempo", detail::parse_tempo);
set_blend_node_parser("sync", detail::parse_sync_blend);
}
void parser::parse_motions(const xml_parse_tree & xml)
{
BOOST_FOREACH(const xml_parse_tree::value_type & v, xml)
{
if (tag(v, "bvh"))
{
boost::shared_ptr<loci::anim::sync_warp> syncher;
loci::anim::sync_warp::sync_group group = 0;
BOOST_FOREACH(const xml_parse_tree::value_type & sv, v.second)
{
if (sv.first == "<xmlattr>") { continue; }
else if (tag(sv, "sync"))
{
if (!syncher) { syncher = boost::make_shared<loci::anim::sync_warp>(); }
std::istringstream iss(get_attr<std::string>(sv.second, "frames"));
anim::time_type frame;
while (iss >> frame)
{
syncher->add_frame(group, frame);
}
++group;
}
}
float yoffset = 0.0f;
try_get_attr(v.second, yoffset, "yoffset");
yoffset = -yoffset;
#ifdef LOCI_DEBUGGING
float r = 1.0;
float g = 1.0;
float b = 0.0;
std::string colours;
try_get_attr(v.second, colours, "colour");
if (!colours.empty())
{
std::istringstream iss(colours);
iss >> r >> g >> b;
r /= 255.0;
g /= 255.0;
b /= 255.0;
r = r < 0.0 ? 0.0 : r;
r = r > 1.0 ? 1.0 : r;
g = r < 0.0 ? 0.0 : g;
g = r > 1.0 ? 1.0 : g;
b = r < 0.0 ? 0.0 : b;
b = r > 1.0 ? 1.0 : b;
}
motions.add(
get_attr<std::string>(v.second, "id"),
get_attr<std::string>(v.second, "src"),
yoffset,
syncher,
r, g, b);
#else
motions.add(
get_attr<std::string>(v.second, "id"),
get_attr<std::string>(v.second, "src"),
yoffset,
syncher);
#endif
}
}
}
void parser::parse_masks(const xml_parse_tree & xml)
{
BOOST_FOREACH(const xml_parse_tree::value_type & v, xml)
{
if (tag(v, "region"))
{
anim::blend_info::weight_list & weights =
masks.insert(std::make_pair(get_attr<std::string>(v.second, "id"),
anim::blend_info::weight_list(motions.figure().structure()->size(), 0.0))).first->second;
BOOST_FOREACH(const xml_parse_tree::value_type & vb, v.second)
{
if (tag(vb, "branch"))
{
anim::weight_mask_branch(weights, *(motions.figure().name_bindings()), *(motions.figure().structure()),
get_attr<std::string>(vb.second, "parent"),
get_attr<unsigned int>(vb.second, "depth"),
get_attr<double>(vb.second, "startweight"),
get_attr<double>(vb.second, "endweight"));
}
}
}
}
}
void parser::parse_actions(const xml_parse_tree & xml)
{
std::string act_id;
BOOST_FOREACH(const xml_parse_tree::value_type & v, xml)
{
if (tag(v, "activity"))
{
get_attr(v.second, act_id, "id");
activities.insert(std::make_pair(act_id, activity(v.second)));
}
}
}
boost::shared_ptr<keyed_actor_controller> & parser::parse_actor(const xml_parse_tree & xml)
{
float x = 0.0f;
float z = 0.0f;
std::string at;
try_get_attr(xml, at, "at");
if (!at.empty())
{
std::istringstream iss(at);
iss >> x >> z;
}
final_speed = 1.0;
final_heading = 0.0;
try_get_attr(xml, final_speed, "speed");
try_get_attr(xml, final_heading, "heading");
speed_total = turn_total = accum_time = 0.0;
actor_control = boost::make_shared<keyed_actor_controller>(final_speed, final_heading);
actor_control->animation(
boost::make_shared<anim::anim_graph>(
boost::make_shared<anim::sync_blend>(parse_schedule(xml)),
motions.figure(), numeric::vector2f(x, z)) );
return actor_control;
}
}
}
} | [
"[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132"
]
| [
[
[
1,
170
]
]
]
|
d2804a1ad735df63bed663b5d2e0923469a5c8cf | 866d93e3842e0131c938d6d1648971382f75bb9a | /src/mBase64.cpp | 9929c5b54a7b738e77cbe0cc3224ff007aeec65e | []
| no_license | leoxiaofei/misslibrary | d010164a6776857c43375e89275cff1a1d772b0c | 2515e9a5f6b622fd74918bee18ecf874d0b654a3 | refs/heads/master | 2021-01-19T19:37:37.127542 | 2011-07-29T22:12:52 | 2011-07-29T22:12:52 | 32,333,477 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,171 | cpp | #ifndef MISS_HPP
#include <mBase64.h>
#endif
#include <iostream>
namespace Miss
{
static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static inline bool is_base64(unsigned char c)
{
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len)
{
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--)
{
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3)
{
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for (j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while ((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string)
{
int in_len = static_cast<int>(encoded_string.size());
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_]))
{
char_array_4[i++] = encoded_string[in_];
in_++;
if (i ==4)
{
for (i = 0; i <4; i++)
char_array_4[i] = (unsigned char)base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i)
{
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = (unsigned char)base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
}
| [
"[email protected]@a39b577b-92cc-c792-3b0c-ab9e68b69f99"
]
| [
[
[
1,
107
]
]
]
|
95ef3fed3e7320338c18b9869e5207809749eb92 | 465f130736402a22233b0148c1bd0fe7ab638e92 | /电路资料/磁场传感器/KMZ52/电子指南针芯片kmz52专用上位机输出程序/Compass1.h | afbd28e2064aeff970b8056cec59f3ce75e45f46 | []
| no_license | gilamada/minigpslog | 3a59cf4ea0e67463e006a655901ccac46994c60c | 342e311053ee5a43002a3f2968a0f0bd5ae49c90 | refs/heads/master | 2021-01-10T11:21:59.487362 | 2010-12-05T16:20:41 | 2010-12-05T16:20:41 | 36,965,174 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,378 | h | // Compass1.h : main header file for the COMPASS1 application
//
#if !defined(AFX_COMPASS1_H__DB879541_BFC3_43D6_9CD9_6973BCA47D3E__INCLUDED_)
#define AFX_COMPASS1_H__DB879541_BFC3_43D6_9CD9_6973BCA47D3E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CCompass1App:
// See Compass1.cpp for the implementation of this class
//
class CCompass1App : public CWinApp
{
public:
CCompass1App();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CCompass1App)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CCompass1App)
afx_msg void OnAppAbout();
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_COMPASS1_H__DB879541_BFC3_43D6_9CD9_6973BCA47D3E__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
49
]
]
]
|
76488b760475768aca19cdfd98c9be84cc461c10 | 20efb6a683bdf1ca771d33de75a372f0d971f990 | /KeyboardLock/KeyboardLock/KeyboardLock.h | 5f9f652c1557cc58c8f4d6f09378e7b20998f5cc | []
| no_license | minhkhanh/UofS-Cplus | c38cbe7e7b77635e1695bb7a43e83864ee8efb53 | 95c49f8beb9bd4e80277d77260520b07c71ef8ce | refs/heads/master | 2021-05-28T05:14:57.522467 | 2010-06-22T08:47:07 | 2010-06-22T08:47:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | h |
// KeyboardLock.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
#include "dllLink.h"
#include <fstream>
using namespace std;
// CKeyboardLockApp:
// See KeyboardLock.cpp for the implementation of this class
//
class CKeyboardLockApp : public CWinAppEx
{
public:
CKeyboardLockApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CKeyboardLockApp theApp; | [
"[email protected]@84b18ccf-10b6-9058-52df-92f566738495",
"[email protected]@84b18ccf-10b6-9058-52df-92f566738495"
]
| [
[
[
1,
11
],
[
15,
35
]
],
[
[
12,
14
]
]
]
|
c95673b326067db10083077707b44110ee764b6d | ec593cdbcb75afa0e1d49a9d5f992d929f5b131b | /MzCommon.h | d7ee70c3322590b9337b458d256912d0fe92bc21 | []
| no_license | jemyzhang/MzCommon_deprecated | 10873a31b4c240bcdb8d31f7cf7d546c193b59a7 | 99f44847355882edf40329bc17420a5414a59389 | refs/heads/master | 2016-09-01T17:09:08.785822 | 2010-01-18T02:09:09 | 2010-01-18T02:09:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 11,005 | h | #pragma once
// include the MZFC library header file
#include <mzfc_inc.h>
#include <list>
using std::list;
typedef enum TextEncode{
ttcAnsi,
ttcUnicode,
ttcUnicodeBigEndian,
ttcUtf8
}TEXTENCODE_t;
#define LOADIMAGE(nID) ImagingHelper::GetImageObject(ImgresHandle,nID)
#define LOADSTRING(uID) MzLoadString(uID,LangresHandle)
#define MZFC_WM_MESSAGE_QUIT MZFC_WM_MESSAGE+0x100
class MzCommonC
{
public:
//有长度限制的行字符串复制
static void newlinecpy(wchar_t** pdst, const wchar_t* src, size_t nsize = 0);
//新建并复制字符串
static void newstrcpy(wchar_t** pdst,const wchar_t* src, size_t nsize = 0);
//去除字符串中特定的字符
static wchar_t* removeSpecStr(wchar_t* sStr, wchar_t* dStr);
//remove LF to "\n"
static wchar_t* removeWrap(wchar_t* dst, wchar_t* src);
//restore "\n" "\r" to LF
static wchar_t* restoreWrap(wchar_t* dst, wchar_t* src);
static wchar_t* _wcstok(wchar_t* _Str, const wchar_t *_Delim){
static wchar_t* header;
wchar_t* retval;
if(_Str != NULL){
header = _Str;
}
if(header == NULL || _Delim == NULL){
return header;
}
int delimLen = lstrlen(_Delim);
if(delimLen == 0){
return header;
}
CMzString tmp = header;
int cnt = 0;
while(tmp.SubStr(cnt++,delimLen).Compare(_Delim) != 0){
if(cnt >= tmp.Length()){
retval = header;
header = NULL;
return retval;
}
}
retval = header;
header[cnt-1] = '\0';
header += (cnt-1 + delimLen);
return retval;
}
};
class MzCommonDateTime
{
public:
static void waitms(unsigned int ms){
DWORD s = GetTickCount();
DWORD e;
do{ //wait
//Do Events
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
e = GetTickCount();
}while(e < s + ms);
}
static void TimetToSystemTime( time_t t, LPSYSTEMTIME pst );
static void TimetToLocalTime( time_t t, LPSYSTEMTIME pst );
static void SystemTimeToTimet( SYSTEMTIME st, time_t *pt );
//获取当前日期
//返回值:当前系统日期,格式:2009-12-11
static SYSTEMTIME StrToDate(wchar_t* datestr,wchar_t* format = L"%04d-%02d-%02d") {
SYSTEMTIME sysDate;
sysDate.wYear = 0;
sysDate.wMonth = 0;
sysDate.wDay = 0;
if(datestr){
swscanf(datestr,format,&sysDate.wYear,&sysDate.wMonth,&sysDate.wDay);
}
return sysDate;
}
static CMzString Date() {
SYSTEMTIME sysTime;
GetLocalTime(&sysTime);
CMzString sDate(16);
wsprintf(sDate.C_Str(), L"%04d-%02d-%02d", sysTime.wYear, sysTime.wMonth, sysTime.wDay);
return sDate;
}
static void getDate(int *py = 0, int *pm = 0, int *pd = 0) {
SYSTEMTIME sysTime;
GetLocalTime(&sysTime);
if(py) *py = sysTime.wYear;
if(pm) *pm = sysTime.wMonth;
if(pd) *pd = sysTime.wDay;
return;
}
static void getPreDate(int &y, int &m) {
m--;
if(m <= 0){
m = 12;
y--;
}
}
static void getNextDate(int &y, int &m) {
m++;
if(m > 12){
m = 1;
y++;
}
}
static int getWeekDay(int year,int month, int day);
static bool isLeapyear(int year);
static void OneDayDate(SYSTEMTIME &date,bool isYesterday = false);
//获取当前时间
//返回值:当前系统时间,格式:12:12:15
static CMzString Time() {
SYSTEMTIME sysTime;
GetLocalTime(&sysTime);
CMzString sTime(16);
wsprintf(sTime.C_Str(), L"%02d:%02d:%02d", sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
return sTime;
}
//获取当前时间
static wchar_t* NowtoStr(){
static wchar_t nowstr[128];
SYSTEMTIME sysTime;
GetLocalTime(&sysTime);
wsprintf(nowstr, L"%04d%02d%02d%02d%02d%02d",
sysTime.wYear, sysTime.wMonth, sysTime.wDay,
sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
return nowstr;
}
static CMzString Now() {
CMzString sDateTime(32), sDate(16), sTime(16);
sDate = Date();
sTime = Time();
sDateTime = sDate + L" " + sTime;
return sDateTime;
}
//获取一个月的天数
static int getDays(int year, int month);
static int checkDate(int year,int month, int day);
static int compareDateTime(SYSTEMTIME tm1, SYSTEMTIME tm2){
int nRet = 0;
if(tm1.wYear > tm2.wYear){
nRet += 32;
}else if(tm1.wYear < tm2.wYear){
nRet -= 32;
}
if(tm1.wMonth > tm2.wMonth){
nRet += 16;
}else if(tm1.wMonth < tm2.wMonth){
nRet -= 16;
}
if(tm1.wDay > tm2.wDay){
nRet += 8;
}else if(tm1.wDay < tm2.wDay){
nRet -= 8;
}
if(tm1.wHour > tm2.wHour){
nRet += 4;
}else if(tm1.wHour < tm2.wHour){
nRet -= 4;
}
if(tm1.wMinute > tm2.wMinute){
nRet += 2;
}else if(tm1.wMinute < tm2.wMinute){
nRet -= 2;
}
if(tm1.wSecond > tm2.wSecond){
nRet += 1;
}else if(tm1.wYear < tm2.wYear){
nRet -= 1;
}
return nRet;
}
//0: equal 1: large -1: small
static int compareDate(SYSTEMTIME tm1, SYSTEMTIME tm2){
if(tm1.wYear > tm2.wYear) return 1;
if((tm1.wYear == tm2.wYear) &&
(tm1.wMonth > tm2.wMonth)){
return 1;
}
if((tm1.wYear == tm2.wYear) &&
(tm1.wMonth == tm2.wMonth) &&
(tm1.wDay > tm2.wDay)){
return 1;
}
if((tm1.wYear == tm2.wYear) &&
(tm1.wMonth == tm2.wMonth) &&
(tm1.wDay == tm2.wDay) &&
(tm1.wHour > tm2.wHour) ){
return 1;
}
if((tm1.wYear == tm2.wYear) &&
(tm1.wMonth == tm2.wMonth) &&
(tm1.wDay == tm2.wDay) &&
(tm1.wHour == tm2.wHour) &&
(tm1.wMinute > tm2.wMinute)){
return 1;
}
if((tm1.wYear == tm2.wYear) &&
(tm1.wMonth == tm2.wMonth) &&
(tm1.wDay == tm2.wDay) &&
(tm1.wHour == tm2.wHour) &&
(tm1.wMinute == tm2.wMinute) &&
(tm1.wSecond > tm2.wSecond) ){
return 1;
}
if((tm1.wYear == tm2.wYear) &&
(tm1.wMonth == tm2.wMonth) &&
(tm1.wDay == tm2.wDay) &&
(tm1.wHour == tm2.wHour) &&
(tm1.wMinute == tm2.wMinute) &&
(tm1.wSecond == tm2.wSecond) ){
return 0;
}
return -1;
}
};
//文件操作常用函数
class MzCommonFile{
public:
//检查文件夹是否存在,不存在则新建
static BOOL DirectoryExists_New(TCHAR* foldername){
if(FileExists(foldername)){
return true;
}
return CreateDirectory(foldername,NULL);
}
//以当前时间为名称创建文件夹
static CMzString CreateDirectoryByDate(TCHAR* parentdir,BOOL &result){
CMzString str = parentdir;
str = str + L"\\";
str = str + MzCommonDateTime::NowtoStr();
result = DirectoryExists_New(str.C_Str());
return str;
}
//列表所有文件夹
//无文件夹则返回0
static int ListDirectory(TCHAR* parentdir, list<CMzString> &s){
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
BOOL bFinished = true;
int ret = 0;
CMzString str = parentdir;
str = str + L"\\*.*";
s.clear(); //清空搜索结果
hFind = FindFirstFile(str.C_Str(), &FindFileData);
if(hFind != INVALID_HANDLE_VALUE){
while(bFinished){
if((FindFileData.dwFileAttributes & (~FILE_ATTRIBUTE_DIRECTORY)) == 0){ //is Directory
s.push_back(FindFileData.cFileName);
ret++;
}
bFinished = FindNextFile(hFind,&FindFileData);
}
FindClose(hFind);
}
return ret;
}
//备份所有文件
//当目标文件夹不存在是,自动新建
static bool BackupFiles(TCHAR* srcdir, TCHAR* destdir,list<CMzString> &files){
if(lstrcmp(srcdir,destdir) == 0){ //源文件夹与目标文件夹相同
return false;
}
if(!FileExists(srcdir)){ //源文件夹不存在
return false;
}
if(!DirectoryExists_New(destdir)){ //目标文件夹创建错误
return false;
}
list<CMzString>::iterator i = files.begin();
for(; i != files.end(); i++){
CMzString srcfile = srcdir;
srcfile = srcfile + L"\\" + *i;
CMzString destfile = destdir;
destfile = destfile + L"\\" + *i;
CopyFile(srcfile,destfile,false);
}
return true;
}
static BOOL DelFile(TCHAR* file){
BOOL ret = false;
if(FileExists(file)){
ret = DeleteFile(file);
}
return ret;
}
//遍历删除文件夹
static BOOL DelDirectory(TCHAR* foldername){
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
BOOL ret;
BOOL bFinished = true;
CMzString str = foldername;
str = str + L"\\*.*";
CMzString parentfolder = foldername;
parentfolder = parentfolder + L"\\";
hFind = FindFirstFile(str.C_Str(), &FindFileData);
if(hFind != INVALID_HANDLE_VALUE){
while(bFinished){
if((FindFileData.dwFileAttributes & (~FILE_ATTRIBUTE_DIRECTORY)) == 0){ //is Directory
CMzString folder = parentfolder + FindFileData.cFileName;
ret = DelDirectory(folder.C_Str());
}else{
CMzString file = parentfolder + FindFileData.cFileName;
ret = DeleteFile(file.C_Str());
}
bFinished = FindNextFile(hFind,&FindFileData);
}
FindClose(hFind);
}
return RemoveDirectory(parentfolder.C_Str());
}
//检查文件否存在
static bool FileExists(TCHAR* filename)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(filename, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
return false;
}
else
{
FindClose(hFind);
return true;
}
}
//获取应用程序目录
static bool GetCurrentPath(LPTSTR szPath)
{
HMODULE handle = GetModuleHandle(NULL);
DWORD dwRet = GetModuleFileName(handle, szPath, MAX_PATH);
if (dwRet == 0)
{
return false;
}
else
{
TCHAR* p = szPath;
while(*p)++p; //let p point to '\0'
while('\\' != *p)--p; //let p point to '\\'
++p;
*p = '\0'; //get the path
return true;
}
}
static TEXTENCODE_t getTextCode(TCHAR* filename);
static wchar_t* chr2wch(const char* buffer, wchar_t** wBuf);
};
//系统相关
typedef struct _PLATFORMVERSION
{
DWORD dwMajor;
DWORD dwMinor;
}PLATFORMVERSION;
#define SPI_GETPLATFORMVERSION 224
class MzCommonSystem{
public:
//获取版本号字符串
static wchar_t* getVersion();
//获取版本号数值
static BOOL getVersion(DWORD &Major,DWORD &Minor,DWORD &Major1,DWORD &Minor1);
//当系统版本号小于需求版本号时,返回false
static BOOL requireVersion(DWORD Major,DWORD Minor,DWORD Major1,DWORD Minor1);
private:
static wchar_t* sVersion;
};
namespace MzCommon {
class File : public MzCommonFile {};
class DateTime : public MzCommonDateTime {};
class C : public MzCommonC { };
class MzSystem : public MzCommonSystem { };
}; | [
"jemyzhang@53aff7d1-dc1e-0346-9cbd-63131b65f07d"
]
| [
[
[
1,
409
]
]
]
|
b7fb8cb836e6b33d72ea33d195b96c870f16b1d3 | 216ae2fd7cba505c3690eaae33f62882102bd14a | /utils/nxogre/include/NxOgreMemoryResource.h | f3b5810f22ce214fcfc4e1d91d2e338b3225eeb4 | []
| no_license | TimelineX/balyoz | c154d4de9129a8a366c1b8257169472dc02c5b19 | 5a0f2ee7402a827bbca210d7c7212a2eb698c109 | refs/heads/master | 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 11,150 | h | /** File: NxOgreMemoryResource.h
Created on: 17-Nov-08
Author: Robin Southern "betajaen"
SVN: $Id$
© Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org
This file is part of NxOgre.
NxOgre 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.
NxOgre 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 NxOgre. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NXOGRE_MEMORYRESOURCE_H
#define NXOGRE_MEMORYRESOURCE_H
#include "NxOgreStable.h"
#include "NxOgreCommon.h"
#include "NxOgreResource.h"
#include "NxOgrePointerClass.h"
namespace NxOgre_Namespace
{
/** \internal Do not use directly. Use Resource* and ResourceSystem::open
*/
class NxOgrePublicClass MemoryResource : public PointerClass<Classes::_MemoryResource>, public Resource
{
friend class MemoryArchive;
public:
/** \brief
*/
MemoryResource(const ArchiveResourceIdentifier&, Archive*);
/** \brief
*/
~MemoryResource(void);
/** \brief What is the resources status?
*/
Enums::ResourceStatus getStatus(void) const;
/** \brief Get the directionality of the resource
*/
Enums::ResourceDirectionality getDirectionality(void) const;
/** \brief Get the type of access of the resource
*/
Enums::ResourceAccess getAccess(void) const;
/** \brief Get the size (in bytes) of the resource, or Constants::ResourceSizeUnknown.
\note If the Directionality is sucessional or the status is anything but open then
the file size will be Constants::ResourceSizeUnknown.
*/
size_t getSize(void) const;
/** \brief Go somewhere into the resource from, this is relative to the ReadWrite pointer and not an absolute.
\note Depending on status, or directionality this will not be possible.
\return True if the seek did happen, or false if it did not.
*/
bool seek(size_t);
/** \brief Go to the beginning of the resource.
\note Depending on status, or directionality this will not be possible.
\return True if the seek did happen, or false if it did not.
*/
bool seekBeginning(void);
/** \brief Go to the end of the resource.
\note Depending on status, or directionality this will not be possible.
\return True if the seek did happen, or false if it did not.
*/
bool seekEnd(void);
/** \brief Is the ReadWrite pointer at the end of Resource?
*/
bool atBeginning(void) const;
/** \brief Is the ReadWrite pointer at the end of Resource, just like a standard "EOF" function.
*/
bool atEnd(void) const;
/** \brief Where the ReadWrite is from the beginning of the resource.
\note Constants::ResourceSizeUnknown will be returned if it is an unknown.
*/
size_t at(void) const;
/** \brief Write something to the buffer, with a size otherwise fail.
*/
bool write(const void* src, size_t src_size);
/** \brief Write a single null (0x00) to the resource otherwise fail.
*/
bool writeNull(void);
/** \brief Write a bool otherwise fail.
*/
bool writeBool(bool);
/** \brief Write a bool* array otherwise fail.
*/
bool writeBool(bool*, size_t length);
/** \brief Write a single unsigned char otherwise fail.
*/
bool writeUChar(unsigned char);
/** \brief Write a unsigned char* array otherwise fail.
*/
bool writeUChar(unsigned char*, size_t length);
/** \brief Write a single char otherwise fail.
*/
bool writeChar(char);
/** \brief Write a char* array otherwise fail.
*/
bool writeChar(char*, size_t length);
/** \brief Write a single unsigned short otherwise fail.
*/
bool writeUShort(unsigned short);
/** \brief Write a unsigned short* array otherwise fail.
*/
bool writeUShort(unsigned short*, size_t length);
/** \brief Write a single short otherwise fail.
*/
bool writeShort(short);
/** \brief Write a short* array otherwise fail.
*/
bool writeShort(short*, size_t length);
/** \brief Write a single unsigned int otherwise fail.
*/
bool writeUInt(unsigned int);
/** \brief Write a unsigned int* array otherwise fail.
*/
bool writeUInt(unsigned int*, size_t length);
/** \brief Write a single int otherwise fail.
*/
bool writeInt(int);
/** \brief Write a int* array otherwise fail.
*/
bool writeInt(int*, size_t length);
/** \brief Write a single float otherwise fail.
*/
bool writeFloat(float);
/** \brief Write a float* array otherwise fail.
*/
bool writeFloat(float*, size_t length);
/** \brief Write a single double otherwise fail.
*/
bool writeDouble(double);
/** \brief Write a double* array otherwise fail.
*/
bool writeDouble(double*, size_t length);
/** \brief Write a float or double otherwise fail
*/
bool writeReal(NxOgreRealType);
/** \brief Write a float or double array otherwise fail
*/
bool writeReal(NxOgreRealType*, size_t length);
/** \brief Write a single long otherwise fail.
*/
bool writeLong(long);
/** \brief Write a long* array otherwise fail.
*/
bool writeLong(long*, size_t length);
/** \brief Read a bool otherwise fail.
*/
bool readBool(void);
/** \brief Read a bool* array otherwise fail.
*/
void readBoolArray(bool*, size_t length);
/** \brief Read a single unsigned char otherwise fail.
*/
unsigned char readUChar(void);
/** \brief Read a unsigned char* array otherwise fail.
*/
void readUCharArray(unsigned char*, size_t length);
/** \brief Read a single char otherwise fail.
*/
char readChar(void);
/** \brief Read a char* array otherwise fail.
*/
void readCharArray(char*, size_t length);
/** \brief Read a single unsigned short otherwise fail.
*/
unsigned short readUShort(void);
/** \brief Read a unsigned short* array otherwise fail.
*/
void readUShortArray(unsigned short*, size_t length);
/** \brief Read a single short otherwise fail.
*/
short readShort(void);
/** \brief Read a short* array otherwise fail.
*/
void readShortArray(short*, size_t length);
/** \brief Read a single unsigned int otherwise fail.
*/
unsigned int readUInt(void);
/** \brief Read a unsigned int* array otherwise fail.
*/
void readUIntArray(unsigned int*, size_t length);
/** \brief Read a single int otherwise fail.
*/
int readInt(void);
/** \brief Read a int* array otherwise fail.
*/
void readIntArray(int*, size_t length);
/** \brief Read a single float otherwise fail.
*/
float readFloat(void);
/** \brief Read a float* array otherwise fail.
*/
void readFloatArray(float*, size_t length);
/** \brief Read a single double otherwise fail.
*/
double readDouble(void);
/** \brief Read a double* array otherwise fail.
*/
void readDouble(double*, size_t length);
/** \brief Read a float or double otherwise fail
*/
Real readReal(void);
/** \brief Read a float or double array otherwise fail
*/
void readRealArray(NxOgreRealType*, size_t length);
/** \brief Read a single long otherwise fail.
*/
long readLong(void);
/** \brief Read a long* array otherwise fail.
*/
void readLongArray(long*, size_t length);
/** \brief Flush function. Not applicable to memory
*/
void flush();
protected:
/** \brief Open the resource.
*/
void open();
/** \brief Close the resource.
*/
void close(void);
protected: // Variables
char* mStart;
char* mEnd;
char* mPointer;
}; // class MemoryResource
} // namespace NxOgre_Namespace
#endif
| [
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
]
| [
[
[
1,
319
]
]
]
|
ceb11545c2da56ce70f5f7c08f36221915e77211 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/luabind/detail/constructor.hpp | 2beb5cb1457c949770c6d800c5f6d227274c76e5 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,208 | hpp | // Copyright Daniel Wallin 2008. 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)
#if !BOOST_PP_IS_ITERATING
# ifndef LUABIND_DETAIL_CONSTRUCTOR_081018_HPP
# define LUABIND_DETAIL_CONSTRUCTOR_081018_HPP
# include <luabind/object.hpp>
# include <luabind/wrapper_base.hpp>
# include <boost/preprocessor/iteration/iterate.hpp>
# include <boost/preprocessor/iteration/local.hpp>
# include <boost/preprocessor/repetition/enum_params.hpp>
# include <boost/preprocessor/repetition/enum_binary_params.hpp>
namespace luabind { namespace detail {
inline void inject_backref(lua_State* L, void*, void*)
{}
template <class T>
void inject_backref(lua_State* L, T* p, wrap_base*)
{
weak_ref(L, 1).swap(wrap_access::ref(*p));
}
template <std::size_t Arity, class T, class Signature>
struct construct_aux;
template <class T, class Signature>
struct construct
: construct_aux<mpl::size<Signature>::value - 2, T, Signature>
{};
template <class T, class Signature>
struct construct_aux<0, T, Signature>
{
void operator()(argument const& self_) const
{
object_rep* self = touserdata<object_rep>(self_);
class_rep* cls = self->crep();
std::auto_ptr<T> instance(new T);
inject_backref(self_.interpreter(), instance.get(), instance.get());
if (cls->has_holder())
{
cls->construct_holder()(self->ptr(), instance.get());
}
else
{
self->set_object(instance.get());
}
self->set_destructor(cls->destructor());
instance.release();
}
};
# define BOOST_PP_ITERATION_PARAMS_1 \
(3, (1, LUABIND_MAX_ARITY, <luabind/detail/constructor.hpp>))
# include BOOST_PP_ITERATE()
}} // namespace luabind::detail
# endif // LUABIND_DETAIL_CONSTRUCTOR_081018_HPP
#else // !BOOST_PP_IS_ITERATING
# define N BOOST_PP_ITERATION()
template <class T, class Signature>
struct construct_aux<N, T, Signature>
{
typedef typename mpl::begin<Signature>::type first;
typedef typename mpl::next<first>::type iter0;
# define BOOST_PP_LOCAL_MACRO(n) \
typedef typename mpl::next< \
BOOST_PP_CAT(iter,BOOST_PP_DEC(n))>::type BOOST_PP_CAT(iter,n); \
typedef typename BOOST_PP_CAT(iter,n)::type BOOST_PP_CAT(a,BOOST_PP_DEC(n));
# define BOOST_PP_LOCAL_LIMITS (1,N)
# include BOOST_PP_LOCAL_ITERATE()
void operator()(argument const& self_, BOOST_PP_ENUM_BINARY_PARAMS(N,a,_)) const
{
object_rep* self = touserdata<object_rep>(self_);
class_rep* cls = self->crep();
std::auto_ptr<T> instance(new T(BOOST_PP_ENUM_PARAMS(N,_)));
inject_backref(self_.interpreter(), instance.get(), instance.get());
if (cls->has_holder())
{
cls->construct_holder()(self->ptr(), instance.get());
}
else
{
self->set_object(instance.get());
}
self->set_destructor(cls->destructor());
instance.release();
}
};
#endif
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
111
]
]
]
|
1112ca0583f44e15b6fbd392115b1a70baf36a28 | f2b4a9d938244916aa4377d4d15e0e2a6f65a345 | /Game/Dlg_Message.h | 4462c455a140853cc77d704914adda42dc9035e1 | [
"Apache-2.0"
]
| permissive | notpushkin/palm-heroes | d4523798c813b6d1f872be2c88282161cb9bee0b | 9313ea9a2948526eaed7a4d0c8ed2292a90a4966 | refs/heads/master | 2021-05-31T19:10:39.270939 | 2010-07-25T12:25:00 | 2010-07-25T12:25:00 | 62,046,865 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | h | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
#ifndef _HMM_GAME_MAPITEM_MESSAGE_DIALOG_H_
#define _HMM_GAME_MAPITEM_MESSAGE_DIALOG_H_
class iDlg_Message : public iTextDlg
{
public:
iDlg_Message(iViewMgr* pViewMgr, iHero* pHero, iMapItem* pMapItem);
// inlines
inline iMapItem* MapItem() { return m_pMapItem; }
inline iHero* Hero() { return m_pHero; }
private:
iMapItem* m_pMapItem;
iHero* m_pHero;
};
#endif //_HMM_GAME_MAPITEM_MESSAGE_DIALOG_H_
| [
"palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276"
]
| [
[
[
1,
39
]
]
]
|
7e178a6940af4e78af9ff22b11d631bcf9d4043c | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_client/src/iptv_client/TransmissionManager.cpp | 471295f32ea1d40dba1b4e75180fb82375c8954f | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,944 | cpp | #include "Transmission.h"
#include "TransmissionManager.h"
/** Destructor. Terminates all registered Transmissions.
*/
TransmissionManager::~TransmissionManager()
{
TerminateAllTransmissions();
}
/** Creates a new Transmission object.
* @param[in] mediaID Media ID.
* @param[in] userName User nickname. Default: wxEmptyString.
* @return Pointer to the newly-created Transmission object, or NULL if a Transmission object with
* the same Media ID already exists.
*/
Transmission *TransmissionManager::AddNewTransmission(unsigned long mediaID, const wxString &userName)
{
Transmission *transm = GetTransmissionByID(mediaID);
if(!transm)
{
transm = new Transmission(mediaID, userName);
m_list.push_back(transm);
return transm;
}
return NULL;
}
/** Removes a Transmission object. Terminates and deallocates.
* @param[in] mediaID Media ID of the transmission to remove.
* @remarks This method does nothing if there is no Transmissions with the given ID.
*/
void TransmissionManager::RemoveTransmission(unsigned long mediaID)
{
Transmission *transm = GetTransmissionByID(mediaID);
if(transm) // Don't attempt to remove a non-existent transmission.
{
m_list.remove(transm);
delete transm;
}
}
/** Search for a Transmission object with given media ID in the internal list.
* @param[in] mediaID The media ID to look for.
* @return Pointer to the associated Transmission object, or NULL if not found.
*/
Transmission *TransmissionManager::GetTransmissionByID(unsigned long mediaID)
{
TransmissionIterator it;
for(it = m_list.begin(); it != m_list.end(); it++)
{
if((*it)->GetMediaID() == mediaID)
return *it;
}
return NULL;
}
/** Search for a Transmission object with given user name in the internal list.
* @param[in] userName User name to look for.
* @return Pointer to the associated Transmission object, or NULL if not found.
*/
Transmission *TransmissionManager::GetTransmissionByName(const wxString &userName)
{
TransmissionIterator it;
for(it = m_list.begin(); it != m_list.end(); it++)
{
if((*it)->GetUserName() == userName)
return *it;
}
return NULL;
}
/** Gets the total number of Transmission objects.
* @return The object count.
*/
unsigned TransmissionManager::GetTransmissionCount() const
{
return (unsigned)m_list.size();
}
/** Gets the number of active Transmission objects.
* @return The object count.
*/
unsigned TransmissionManager::GetActiveTransmissionCount() const
{
unsigned count = 0;
TransmissionConstIterator it;
for(it = m_list.begin(); it != m_list.end(); it++)
{
if((*it)->IsActive())
count++;
}
return count;
}
/** Terminates all Transmissions. Clears the internal list.
*/
void TransmissionManager::TerminateAllTransmissions()
{
TransmissionIterator it;
for(it = m_list.begin(); it != m_list.end(); it++)
delete *it;
m_list.clear();
}
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
104
]
]
]
|
e35d4b79f6b3d6a479e1612a90fe9fcaf4bb6d64 | 0813282678cb6bb52cd0001a760cfbc24663cfca | /SCBuildOrderGUI.cpp | 22b8d4791177a1402b663bc23c07c9beda72a350 | []
| no_license | mannyzhou5/scbuildorder | e3850a86baaa33d1c549c7b89ddab7738b79b3c0 | 2396293ee483e40495590782b652320db8adf530 | refs/heads/master | 2020-04-29T01:01:04.504099 | 2011-04-12T10:00:54 | 2011-04-12T10:00:54 | 33,047,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,776 | cpp |
// SCBuildOrderGUI.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "afxwinappex.h"
#include "afxdialogex.h"
#include "SCBuildOrderGUI.h"
#include "MainFrm.h"
#include "ChildFrm.h"
#include "SCBuildOrderGUIDoc.h"
#include "SCBuildOrderGUIProtossView.h"
#include "SCBuildOrderGUIZergView.h"
#include "SCBuildOrderGUITerranView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CSCBuildOrderGUIApp
BEGIN_MESSAGE_MAP(CSCBuildOrderGUIApp, CWinAppEx)
ON_COMMAND(ID_APP_ABOUT, &CSCBuildOrderGUIApp::OnAppAbout)
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen)
END_MESSAGE_MAP()
// CSCBuildOrderGUIApp construction
CSCBuildOrderGUIApp::CSCBuildOrderGUIApp()
{
m_bHiColorIcons = TRUE;
// support Restart Manager
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS;
#ifdef _MANAGED
// If the application is built using Common Language Runtime support (/clr):
// 1) This additional setting is needed for Restart Manager support to work properly.
// 2) In your project, you must add a reference to System.Windows.Forms in order to build.
System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException);
#endif
// TODO: replace application ID string below with unique ID string; recommended
// format for string is CompanyName.ProductName.SubProduct.VersionInformation
SetAppID(_T("SCBuildOrderGUI.AppID.NoVersion"));
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CSCBuildOrderGUIApp object
CSCBuildOrderGUIApp theApp;
// CSCBuildOrderGUIApp initialization
BOOL CSCBuildOrderGUIApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance();
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
EnableTaskbarInteraction();
// AfxInitRichEdit2() is required to use RichEdit control
// AfxInitRichEdit2();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(4); // Load standard INI file options (including MRU)
InitContextMenuManager();
InitKeyboardManager();
InitTooltipManager();
CMFCToolTipInfo ttParams;
ttParams.m_bVislManagerTheme = TRUE;
theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL,
RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views
CMultiDocTemplate* pDocTemplate;
pDocTemplate = new CMultiDocTemplate(IDR_BUILDORDERTYPE_PROTOSS,
RUNTIME_CLASS(CSCBuildOrderGUIDoc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(CSCBuildOrderGUIProtossView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
pDocTemplate = new CMultiDocTemplate(IDR_BUILDORDERTYPE_ZERG,
RUNTIME_CLASS(CSCBuildOrderGUIDoc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(CSCBuildOrderGUIZergView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
pDocTemplate = new CMultiDocTemplate(IDR_BUILDORDERTYPE_TERRAN,
RUNTIME_CLASS(CSCBuildOrderGUIDoc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(CSCBuildOrderGUITerranView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
// create main MDI Frame window
CMainFrame* pMainFrame = new CMainFrame;
if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
{
delete pMainFrame;
return FALSE;
}
m_pMainWnd = pMainFrame;
// call DragAcceptFiles only if there's a suffix
// In an MDI app, this should occur immediately after setting m_pMainWnd
// Enable drag/drop open
m_pMainWnd->DragAcceptFiles();
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Enable DDE Execute open
EnableShellOpen();
RegisterShellFileTypes(TRUE);
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The main window has been initialized, so show and update it
pMainFrame->ShowWindow(SW_SHOWMAXIMIZED);
pMainFrame->UpdateWindow();
return TRUE;
}
int CSCBuildOrderGUIApp::ExitInstance()
{
//TODO: handle additional resources you may have added
AfxOleTerm(FALSE);
_CrtDumpMemoryLeaks();
return CWinAppEx::ExitInstance();
}
// CSCBuildOrderGUIApp message handlers
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// App command to run the dialog
void CSCBuildOrderGUIApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CSCBuildOrderGUIApp customization load/save methods
void CSCBuildOrderGUIApp::PreLoadState()
{
BOOL bNameValid;
CString strName;
bNameValid = strName.LoadString(IDS_EDIT_MENU);
ASSERT(bNameValid);
GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT);
}
void CSCBuildOrderGUIApp::LoadCustomState()
{
}
void CSCBuildOrderGUIApp::SaveCustomState()
{
}
// CSCBuildOrderGUIApp message handlers
| [
"[email protected]@a0245358-5b9e-171e-63e1-2316ddff5996",
"CarbonTwelve.Developer@a0245358-5b9e-171e-63e1-2316ddff5996"
]
| [
[
[
1,
12
],
[
16,
113
],
[
124,
125
],
[
127,
130
],
[
139,
176
],
[
179,
244
]
],
[
[
13,
15
],
[
114,
123
],
[
126,
126
],
[
131,
138
],
[
177,
178
]
]
]
|
b9b1a3c4005e25f93d00da3eb3e34956d6612c8e | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleCore/Wii/WiiThread.cpp | 89a471028f91181a60037c02b92fb28e7490c47a | []
| no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24 | cpp | #include "WiiThread.h"
| [
"[email protected]"
]
| [
[
[
1,
1
]
]
]
|
a4ef16aa94bdf46a572a7789d0815fe7891f8a5c | 4fdc157f7d6c5af784c3492909d848a0371e5877 | /code source/Debug.hpp | 6b3695bddd3ee3067ab3ffce88d9941bd5f2f2b9 | []
| no_license | moumen19/robotiquecartemere | d969e50aedc53844bb7c512ff15e6812b8b469de | 8333bb0b5c1b1396e1e99a870af2f60c9db149b0 | refs/heads/master | 2020-12-24T17:17:14.273869 | 2011-02-11T15:44:38 | 2011-02-11T15:44:38 | 34,446,411 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,840 | hpp | /*
*
* Bureau d'étude Robotique M2 ISEN 2010-2011
*
* DELBERGUE Julien
* JACQUEL Olivier
* PIETTE Ferdinand ([email protected])
*
* Fichier Debug.hpp
*
*/
#ifndef DEF_DEBUG
#define DEF_DEBUG
// Inclusion des bibliothèques
#include <iostream>
#include <vector>
#include <boost/thread/mutex.hpp>
#include <sstream>
//*************************************************************************************************
// Activation du mode debug
#define _DEBUG_MODE true
//*************************************************************************************************
/**
* Définition d'une macro ajoutant un message
* Cette macro définie le titre automatiquement (fichier + ligne)
* Les données sont automatiquement protégés ce qui permet de lancer la macro dans plusieurs threads en même temps
* @param message - Le message de Debug
* @param priority - Le niveau de priorité du message
* @see Debug_Priority
* @see addMessage()
*/
#define _DEBUG(message, priority) if(_DEBUG_MODE == true) \
{ \
std::ostringstream oss; \
oss << __FILE__ << " (" << __LINE__ << ")"; \
_DEBUG::lock(); \
_DEBUG::addMessage(oss.str(), message, priority); \
_DEBUG::unlock(); \
}
/**
* Définition d'une macro exécutant une méthode statique publique
* @param f - La méthode statique avec ses parametres
*/
#define _DEBUG_EXEC(f) if(_DEBUG_MODE == true) \
_DEBUG::f;
/**
* Definition d'une macro affichant un simple message dans la console
*/
#define _DISPLAY(message) { \
_DEBUG::lock(); \
std::cout << message; \
_DEBUG::unlock(); \
}
#define _CIN(message) { \
_DEBUG::lock(); \
std::cin >> message; \
_DEBUG::unlock(); \
}
/**
* Définition des constantes de configurations
*/
typedef int Debug_Configuration;
#define DISPLAY_NONE 0 // N'affiche aucun message
#define CONSOLE_DISPLAY 1 // Affiche les messages dans la console
#define FILE_DISPLAY 2 // Affiche les messages dans un fichier
#define SAVE_IN_MEMORY 4 // Enregistre les messages en memoire
/**
* Définition des constantes de priorités de messages
* @see _DEBUG()
* @see addMessage()
*/
enum Debug_Priority
{
FATAL,
WARNING,
INFORMATION
};
/**
* Structure d'un message
*/
struct Message
{
std::string title; // Titre du message
std::string content; // Contenu du message
Debug_Priority priority; // Priorité du message
bool isEmpty; // Définie si le message à un sens
} typedef Message;
/**
* Classe de débuggage
*/
class _DEBUG
{
public:
static void addMessage(std::string, std::string, Debug_Priority); // Ajoute un message
static void clearAllMessage(); // Efface tous les messages
static void configuration(Debug_Configuration, std::string filename = ""); // Configure le mode Debug
static Message getMessage(unsigned int); // Retourne un message
static Message getNextMessage(); // Retourne le message suivant
static int getNumMessages(); // Donne le nombre de message stocké
static void lock(); // Verouille un mutex
static void unlock(); // Deverouille le mutex
private:
static std::vector<Message> a_messages; // Stockage des messages
static unsigned int a_cursor; // Curseur indiquant quel sera le prochain message retourne par getNextMessage()
static Debug_Configuration a_configuration; // Configuration du mode Debug
static std::string a_filename; // Chemin du fichier de logs si existant
static boost::mutex a_mutex; // Mutex de protection
};
#endif
| [
"piette.ferdinand@308fe9b9-b635-520e-12eb-2ef3f824b1b6",
"ferdinand.piette@308fe9b9-b635-520e-12eb-2ef3f824b1b6"
]
| [
[
[
1,
15
],
[
21,
24
],
[
27,
30
],
[
125,
126
]
],
[
[
16,
20
],
[
25,
26
],
[
31,
124
],
[
127,
127
]
]
]
|
ab35ad141b3450ae033e1c3a3545a9ad0cb61b51 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/chrome/chrome/src/cpp/include/v8/src/stub-cache.h | c1029e3cd504d779cfe6049c6e3d80e378a2082c | [
"Apache-2.0"
]
| permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,374 | h | // Copyright 2006-2008 the V8 project authors. 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.
#ifndef V8_STUB_CACHE_H_
#define V8_STUB_CACHE_H_
#include "macro-assembler.h"
namespace v8 { namespace internal {
// The stub cache is used for megamorphic calls and property accesses.
// It maps (map, name, type)->Code*
// The design of the table uses the inline cache stubs used for
// mono-morphic calls. The beauty of this, we do not have to
// invalidate the cache whenever a prototype map is changed. The stub
// validates the map chain as in the mono-morphic case.
class SCTableReference;
class StubCache : public AllStatic {
public:
struct Entry {
String* key;
Code* value;
};
static void Initialize(bool create_heap_objects);
// Computes the right stub matching. Inserts the result in the
// cache before returning. This might compile a stub if needed.
static Object* ComputeLoadField(String* name,
JSObject* receiver,
JSObject* holder,
int field_index);
static Object* ComputeLoadCallback(String* name,
JSObject* receiver,
JSObject* holder,
AccessorInfo* callback);
static Object* ComputeLoadConstant(String* name,
JSObject* receiver,
JSObject* holder,
Object* value);
static Object* ComputeLoadInterceptor(String* name,
JSObject* receiver,
JSObject* holder);
static Object* ComputeLoadNormal(String* name, JSObject* receiver);
// ---
static Object* ComputeKeyedLoadField(String* name,
JSObject* receiver,
JSObject* holder,
int field_index);
static Object* ComputeKeyedLoadCallback(String* name,
JSObject* receiver,
JSObject* holder,
AccessorInfo* callback);
static Object* ComputeKeyedLoadConstant(String* name, JSObject* receiver,
JSObject* holder, Object* value);
static Object* ComputeKeyedLoadInterceptor(String* name,
JSObject* receiver,
JSObject* holder);
static Object* ComputeKeyedLoadArrayLength(String* name, JSArray* receiver);
static Object* ComputeKeyedLoadStringLength(String* name,
String* receiver);
static Object* ComputeKeyedLoadFunctionPrototype(String* name,
JSFunction* receiver);
// ---
static Object* ComputeStoreField(String* name,
JSObject* receiver,
int field_index,
Map* transition = NULL);
static Object* ComputeStoreCallback(String* name,
JSObject* receiver,
AccessorInfo* callback);
static Object* ComputeStoreInterceptor(String* name, JSObject* receiver);
// ---
static Object* ComputeKeyedStoreField(String* name,
JSObject* receiver,
int field_index,
Map* transition = NULL);
// ---
static Object* ComputeCallField(int argc,
String* name,
Object* object,
JSObject* holder,
int index);
static Object* ComputeCallConstant(int argc,
String* name,
Object* object,
JSObject* holder,
JSFunction* function);
static Object* ComputeCallNormal(int argc, String* name, JSObject* receiver);
static Object* ComputeCallInterceptor(int argc,
String* name,
Object* object,
JSObject* holder);
// ---
static Object* ComputeCallInitialize(int argc);
static Object* ComputeCallInitializeInLoop(int argc);
static Object* ComputeCallPreMonomorphic(int argc);
static Object* ComputeCallNormal(int argc);
static Object* ComputeCallMegamorphic(int argc);
static Object* ComputeCallMiss(int argc);
// Finds the Code object stored in the Heap::non_monomorphic_cache().
static Code* FindCallInitialize(int argc);
static Object* ComputeCallDebugBreak(int argc);
static Object* ComputeCallDebugPrepareStepIn(int argc);
static Object* ComputeLazyCompile(int argc);
// Update cache for entry hash(name, map).
static Code* Set(String* name, Map* map, Code* code);
// Clear the lookup table (@ mark compact collection).
static void Clear();
// Functions for generating stubs at startup.
static void GenerateMiss(MacroAssembler* masm);
// Generate code for probing the stub cache table.
static void GenerateProbe(MacroAssembler* masm,
Code::Flags flags,
Register receiver,
Register name,
Register scratch);
enum Table {
kPrimary,
kSecondary
};
private:
friend class SCTableReference;
static const int kPrimaryTableSize = 2048;
static const int kSecondaryTableSize = 512;
static Entry primary_[];
static Entry secondary_[];
// Computes the hashed offsets for primary and secondary caches.
static int PrimaryOffset(String* name, Code::Flags flags, Map* map) {
// This works well because the heap object tag size and the hash
// shift are equal. Shifting down the length field to get the
// hash code would effectively throw away two bits of the hash
// code.
ASSERT(kHeapObjectTagSize == String::kHashShift);
// Compute the hash of the name (use entire length field).
ASSERT(name->HasHashCode());
uint32_t field = name->length_field();
// Base the offset on a simple combination of name, flags, and map.
uint32_t key = (reinterpret_cast<uint32_t>(map) + field) ^ flags;
return key & ((kPrimaryTableSize - 1) << kHeapObjectTagSize);
}
static int SecondaryOffset(String* name, Code::Flags flags, int seed) {
// Use the seed from the primary cache in the secondary cache.
uint32_t key = seed - reinterpret_cast<uint32_t>(name) + flags;
return key & ((kSecondaryTableSize - 1) << kHeapObjectTagSize);
}
// Compute the entry for a given offset in exactly the same way as
// we done in generated code. This makes it a lot easier to avoid
// making mistakes in the hashed offset computations.
static Entry* entry(Entry* table, int offset) {
return reinterpret_cast<Entry*>(
reinterpret_cast<Address>(table) + (offset << 1));
}
};
class SCTableReference {
public:
static SCTableReference keyReference(StubCache::Table table) {
return SCTableReference(
reinterpret_cast<Address>(&first_entry(table)->key));
}
static SCTableReference valueReference(StubCache::Table table) {
return SCTableReference(
reinterpret_cast<Address>(&first_entry(table)->value));
}
Address address() const { return address_; }
private:
explicit SCTableReference(Address address) : address_(address) {}
static StubCache::Entry* first_entry(StubCache::Table table) {
switch (table) {
case StubCache::kPrimary: return StubCache::primary_;
case StubCache::kSecondary: return StubCache::secondary_;
}
UNREACHABLE();
return NULL;
}
Address address_;
};
// ------------------------------------------------------------------------
// Support functions for IC stubs for callbacks.
Object* LoadCallbackProperty(Arguments args);
Object* StoreCallbackProperty(Arguments args);
// Support functions for IC stubs for interceptors.
Object* LoadInterceptorProperty(Arguments args);
Object* StoreInterceptorProperty(Arguments args);
Object* CallInterceptorProperty(Arguments args);
// Support function for computing call IC miss stubs.
Handle<Code> ComputeCallMiss(int argc);
// The stub compiler compiles stubs for the stub cache.
class StubCompiler BASE_EMBEDDED {
public:
enum CheckType {
RECEIVER_MAP_CHECK,
STRING_CHECK,
NUMBER_CHECK,
BOOLEAN_CHECK,
JSARRAY_HAS_FAST_ELEMENTS_CHECK
};
StubCompiler() : masm_(NULL, 256) { }
Object* CompileCallInitialize(Code::Flags flags);
Object* CompileCallPreMonomorphic(Code::Flags flags);
Object* CompileCallNormal(Code::Flags flags);
Object* CompileCallMegamorphic(Code::Flags flags);
Object* CompileCallMiss(Code::Flags flags);
Object* CompileCallDebugBreak(Code::Flags flags);
Object* CompileCallDebugPrepareStepIn(Code::Flags flags);
Object* CompileLazyCompile(Code::Flags flags);
// Static functions for generating parts of stubs.
static void GenerateLoadGlobalFunctionPrototype(MacroAssembler* masm,
int index,
Register prototype);
static void GenerateFastPropertyLoad(MacroAssembler* masm,
Register dst, Register src,
JSObject* holder, int index);
static void GenerateLoadField(MacroAssembler* masm,
JSObject* object,
JSObject* holder,
Register receiver,
Register scratch1,
Register scratch2,
int index,
Label* miss_label);
static void GenerateLoadCallback(MacroAssembler* masm,
JSObject* object,
JSObject* holder,
Register receiver,
Register name,
Register scratch1,
Register scratch2,
AccessorInfo* callback,
Label* miss_label);
static void GenerateLoadConstant(MacroAssembler* masm,
JSObject* object,
JSObject* holder,
Register receiver,
Register scratch1,
Register scratch2,
Object* value,
Label* miss_label);
static void GenerateLoadInterceptor(MacroAssembler* masm,
JSObject* object,
JSObject* holder,
Register receiver,
Register name,
Register scratch1,
Register scratch2,
Label* miss_label);
static void GenerateLoadArrayLength(MacroAssembler* masm,
Register receiver,
Register scratch,
Label* miss_label);
static void GenerateLoadStringLength(MacroAssembler* masm,
Register receiver,
Register scratch,
Label* miss_label);
static void GenerateLoadStringLength2(MacroAssembler* masm,
Register receiver,
Register scratch1,
Register scratch2,
Label* miss_label);
static void GenerateLoadFunctionPrototype(MacroAssembler* masm,
Register receiver,
Register scratch1,
Register scratch2,
Label* miss_label);
static void GenerateStoreField(MacroAssembler* masm,
Builtins::Name storage_extend,
JSObject* object,
int index,
Map* transition,
Register receiver_reg,
Register name_reg,
Register scratch,
Label* miss_label);
static void GenerateLoadMiss(MacroAssembler* masm, Code::Kind kind);
protected:
Object* GetCodeWithFlags(Code::Flags flags);
MacroAssembler* masm() { return &masm_; }
private:
MacroAssembler masm_;
};
class LoadStubCompiler: public StubCompiler {
public:
Object* CompileLoadField(JSObject* object, JSObject* holder, int index);
Object* CompileLoadCallback(JSObject* object,
JSObject* holder,
AccessorInfo* callback);
Object* CompileLoadConstant(JSObject* object,
JSObject* holder,
Object* value);
Object* CompileLoadInterceptor(JSObject* object,
JSObject* holder,
String* name);
private:
Object* GetCode(PropertyType);
};
class KeyedLoadStubCompiler: public StubCompiler {
public:
Object* CompileLoadField(String* name,
JSObject* object,
JSObject* holder,
int index);
Object* CompileLoadCallback(String* name,
JSObject* object,
JSObject* holder,
AccessorInfo* callback);
Object* CompileLoadConstant(String* name,
JSObject* object,
JSObject* holder,
Object* value);
Object* CompileLoadInterceptor(JSObject* object,
JSObject* holder,
String* name);
Object* CompileLoadArrayLength(String* name);
Object* CompileLoadStringLength(String* name);
Object* CompileLoadFunctionPrototype(String* name);
private:
Object* GetCode(PropertyType);
};
class StoreStubCompiler: public StubCompiler {
public:
Object* CompileStoreField(JSObject* object,
int index,
Map* transition,
String* name);
Object* CompileStoreCallback(JSObject* object,
AccessorInfo* callbacks,
String* name);
Object* CompileStoreInterceptor(JSObject* object, String* name);
private:
Object* GetCode(PropertyType type);
};
class KeyedStoreStubCompiler: public StubCompiler {
public:
Object* CompileStoreField(JSObject* object,
int index,
Map* transition,
String* name);
private:
Object* GetCode(PropertyType type);
};
class CallStubCompiler: public StubCompiler {
public:
explicit CallStubCompiler(int argc) : arguments_(argc) { }
Object* CompileCallField(Object* object, JSObject* holder, int index);
Object* CompileCallConstant(Object* object,
JSObject* holder,
JSFunction* function,
CheckType check);
Object* CompileCallInterceptor(Object* object,
JSObject* holder,
String* name);
private:
const ParameterCount arguments_;
const ParameterCount& arguments() { return arguments_; }
Object* GetCode(PropertyType type);
};
} } // namespace v8::internal
#endif // V8_STUB_CACHE_H_
| [
"noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9"
]
| [
[
[
1,
470
]
]
]
|
273846a5a546c1f1b25a138e28779515f04bd3c0 | 8bbbcc2bd210d5608613c5c591a4c0025ac1f06b | /nes/mapper/090.cpp | 4737027a47d99d402284c1bef6326148d0d9575e | []
| no_license | PSP-Archive/NesterJ-takka | 140786083b1676aaf91d608882e5f3aaa4d2c53d | 41c90388a777c63c731beb185e924820ffd05f93 | refs/heads/master | 2023-04-16T11:36:56.127438 | 2008-12-07T01:39:17 | 2008-12-07T01:39:17 | 357,617,280 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,778 | cpp |
/////////////////////////////////////////////////////////////////////
// Mapper 90
void NES_mapper90_Init()
{
g_NESmapper.Reset = NES_mapper90_Reset;
g_NESmapper.MemoryReadLow = NES_mapper90_MemoryReadLow;
g_NESmapper.MemoryWriteLow = NES_mapper90_MemoryWriteLow;
g_NESmapper.MemoryWrite = NES_mapper90_MemoryWrite;
g_NESmapper.HSync = NES_mapper90_HSync;
}
void NES_mapper90_Reset()
{
uint8 i;
// set CPU bank pointers
g_NESmapper.set_CPU_bank4(g_NESmapper.num_8k_ROM_banks-4);
g_NESmapper.set_CPU_bank5(g_NESmapper.num_8k_ROM_banks-3);
g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-2);
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
// set PPU bank pointers
g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7);
g_NESmapper.Mapper90.irq_counter = 0;
g_NESmapper.Mapper90.irq_latch = 0;
g_NESmapper.Mapper90.irq_enabled = 0;
g_NESmapper.Mapper90.chr_bank_size=0;
g_NESmapper.Mapper90.prg_bank_size=0;
for(i = 0; i < 4; i++)
{
g_NESmapper.Mapper90.prg_reg[i] = g_NESmapper.num_8k_ROM_banks-4+i;
g_NESmapper.Mapper90.nam_low_reg[i] = 0;
g_NESmapper.Mapper90.nam_high_reg[i] = 0;
g_NESmapper.Mapper90.chr_low_reg[i] = i;
g_NESmapper.Mapper90.chr_high_reg[i] = 0;
g_NESmapper.Mapper90.chr_low_reg[i+4] = i+4;
g_NESmapper.Mapper90.chr_high_reg[i+4] = 0;
}
g_NESmapper.Mapper90.value1^=1;
g_NESmapper.Mapper90.mode = 0;
}
uint8 NES_mapper90_MemoryReadLow(uint32 addr)
{
#if 0
if(addr == 0x5000)
{
return (uint8)(g_NESmapper.Mapper90.value1*g_NESmapper.Mapper90.value2 & 0x00FF);
}
else
{
return (uint8)(addr >> 8);
}
#else
if(g_NESmapper.Mapper90.value1&1)
return 0xFF;
else
return 0;
#endif
}
void NES_mapper90_MemoryWriteLow(uint32 addr, uint8 data)
{
#if 0
if(addr == 0x5000)
{
g_NESmapper.Mapper90.value1 = data;
}
else if(addr == 0x5001)
{
g_NESmapper.Mapper90.value2 = data;
}
#endif
}
void NES_mapper90_MemoryWrite(uint32 addr, uint8 data)
{
switch(addr&0xF007)
{
case 0x8000:
case 0x8001:
case 0x8002:
case 0x8003:
{
g_NESmapper.Mapper90.prg_reg[addr & 0x03] = data;
NES_mapper90_Sync_Prg_Banks();
// LOG("W " << HEX(addr,4) << " " << HEX(data,2) << " " << HEX(g_NESmapper.Mapper90.prg_bank_size,2) << endl);
}
break;
case 0x9000:
case 0x9001:
case 0x9002:
case 0x9003:
case 0x9004:
case 0x9005:
case 0x9006:
case 0x9007:
{
g_NESmapper.Mapper90.chr_low_reg[addr & 0x07] = data;
NES_mapper90_Sync_Chr_Banks();
}
break;
case 0xA000:
case 0xA001:
case 0xA002:
case 0xA003:
case 0xA004:
case 0xA005:
case 0xA006:
case 0xA007:
{
g_NESmapper.Mapper90.chr_high_reg[addr & 0x07] = data;
NES_mapper90_Sync_Chr_Banks();
}
break;
case 0xB000:
case 0xB001:
case 0xB002:
case 0xB003:
{
g_NESmapper.Mapper90.nam_low_reg[addr & 0x03] = data;
NES_mapper90_Sync_Mirror();
}
break;
case 0xB004:
case 0xB005:
case 0xB006:
case 0xB007:
{
g_NESmapper.Mapper90.nam_high_reg[addr & 0x03] = data;
NES_mapper90_Sync_Mirror();
}
break;
case 0xC002:
{
g_NESmapper.Mapper90.irq_enabled = 0;
}
break;
case 0xC003:
case 0xC004:
{
if(g_NESmapper.Mapper90.irq_enabled == 0)
{
g_NESmapper.Mapper90.irq_enabled = 1;
g_NESmapper.Mapper90.irq_counter = g_NESmapper.Mapper90.irq_latch;
}
}
break;
case 0xC005:
{
g_NESmapper.Mapper90.irq_counter = data;
g_NESmapper.Mapper90.irq_latch = data;
}
break;
case 0xD000:
{
g_NESmapper.Mapper90.prg_bank_6000 = data & 0x80;
g_NESmapper.Mapper90.prg_bank_e000 = data & 0x04;
g_NESmapper.Mapper90.prg_bank_size = data & 0x03;
g_NESmapper.Mapper90.chr_bank_size = (data & 0x18) >> 3;
g_NESmapper.Mapper90.mirror_mode = data & 0x20;
NES_mapper90_Sync_Prg_Banks();
NES_mapper90_Sync_Chr_Banks();
NES_mapper90_Sync_Mirror();
g_NESmapper.Mapper90.mode = data;
}
break;
case 0xD001:
{
g_NESmapper.Mapper90.mirror_type = data & 0x03;
NES_mapper90_Sync_Mirror();
}
break;
case 0xD003:
{
// bank page
}
break;
}
// LOG("W " << HEX(addr,4) << " " << HEX(data,2) << " " << HEX(g_NESmapper.Mapper90.prg_bank_size,2) << endl);
}
void NES_mapper90_HSync(uint32 scanline)
{
if((scanline >= 0) && (scanline <= 239)) //239
{
if(NES_PPU_spr_enabled() || NES_PPU_bg_enabled())
{
if(--g_NESmapper.Mapper90.irq_counter == 0)
{
if(g_NESmapper.Mapper90.irq_enabled)
{
NES6502_DoIRQ();
}
// g_NESmapper.Mapper90.irq_counter = g_NESmapper.Mapper90.irq_latch;
// g_NESmapper.Mapper90.irq_latch = 0;
// g_NESmapper.Mapper90.irq_enabled = 0;
}
else
{
// g_NESmapper.Mapper90.irq_counter--;
}
}
}
}
void NES_mapper90_Sync_Mirror()
{
uint8 i;
uint32 nam_bank[4];
for(i = 0; i < 4; i++)
{
nam_bank[i] = ((uint32)g_NESmapper.Mapper90.nam_high_reg[i] << 8) | (uint32)g_NESmapper.Mapper90.nam_low_reg[i];
}
if(g_NESmapper.Mapper90.mirror_mode)
{
for(i = 0; i < 4; i++)
{
if(!g_NESmapper.Mapper90.nam_high_reg[i] && (g_NESmapper.Mapper90.nam_low_reg[i] == i))
{
g_NESmapper.Mapper90.mirror_mode = 0;
}
}
if(g_NESmapper.Mapper90.mirror_mode)
{
g_NESmapper.set_PPU_bank8(nam_bank[0]);
g_NESmapper.set_PPU_bank9(nam_bank[1]);
g_NESmapper.set_PPU_bank10(nam_bank[2]);
g_NESmapper.set_PPU_bank11(nam_bank[3]);
}
}
else
{
if(g_NESmapper.Mapper90.mirror_type == 0)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT);
}
else if(g_NESmapper.Mapper90.mirror_type == 1)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ);
}
else
{
g_NESmapper.set_mirroring(0,0,0,0);
}
}
}
void NES_mapper90_Sync_Chr_Banks()
{
uint8 i;
uint32 chr_bank[8];
for(i = 0; i < 8; i++)
{
chr_bank[i] = ((uint32)g_NESmapper.Mapper90.chr_high_reg[i] << 8) | (uint32)g_NESmapper.Mapper90.chr_low_reg[i];
}
if(g_NESmapper.Mapper90.chr_bank_size == 0)
{
g_NESmapper.set_PPU_bank0(chr_bank[0]*8+0);
g_NESmapper.set_PPU_bank1(chr_bank[0]*8+1);
g_NESmapper.set_PPU_bank2(chr_bank[0]*8+2);
g_NESmapper.set_PPU_bank3(chr_bank[0]*8+3);
g_NESmapper.set_PPU_bank4(chr_bank[0]*8+4);
g_NESmapper.set_PPU_bank5(chr_bank[0]*8+5);
g_NESmapper.set_PPU_bank6(chr_bank[0]*8+6);
g_NESmapper.set_PPU_bank7(chr_bank[0]*8+7);
}
else if(g_NESmapper.Mapper90.chr_bank_size == 1)
{
g_NESmapper.set_PPU_bank0(chr_bank[0]*4+0);
g_NESmapper.set_PPU_bank1(chr_bank[0]*4+1);
g_NESmapper.set_PPU_bank2(chr_bank[0]*4+2);
g_NESmapper.set_PPU_bank3(chr_bank[0]*4+3);
g_NESmapper.set_PPU_bank4(chr_bank[4]*4+0);
g_NESmapper.set_PPU_bank5(chr_bank[4]*4+1);
g_NESmapper.set_PPU_bank6(chr_bank[4]*4+2);
g_NESmapper.set_PPU_bank7(chr_bank[4]*4+3);
}
else if(g_NESmapper.Mapper90.chr_bank_size == 2)
{
g_NESmapper.set_PPU_bank0(chr_bank[0]*2+0);
g_NESmapper.set_PPU_bank1(chr_bank[0]*2+1);
g_NESmapper.set_PPU_bank2(chr_bank[2]*2+0);
g_NESmapper.set_PPU_bank3(chr_bank[2]*2+1);
g_NESmapper.set_PPU_bank4(chr_bank[4]*2+0);
g_NESmapper.set_PPU_bank5(chr_bank[4]*2+1);
g_NESmapper.set_PPU_bank6(chr_bank[6]*2+0);
g_NESmapper.set_PPU_bank7(chr_bank[6]*2+1);
}
else
{
g_NESmapper.set_PPU_bank0(chr_bank[0]);
g_NESmapper.set_PPU_bank1(chr_bank[1]);
g_NESmapper.set_PPU_bank2(chr_bank[2]);
g_NESmapper.set_PPU_bank3(chr_bank[3]);
g_NESmapper.set_PPU_bank4(chr_bank[4]);
g_NESmapper.set_PPU_bank5(chr_bank[5]);
g_NESmapper.set_PPU_bank6(chr_bank[6]);
g_NESmapper.set_PPU_bank7(chr_bank[7]);
}
}
void NES_mapper90_Sync_Prg_Banks()
{
#if 1
if(g_NESmapper.Mapper90.prg_bank_size == 0)
{
g_NESmapper.set_CPU_bank4(g_NESmapper.num_8k_ROM_banks-4);
g_NESmapper.set_CPU_bank5(g_NESmapper.num_8k_ROM_banks-3);
g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-2);
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
}
else if(g_NESmapper.Mapper90.prg_bank_size == 1)
{
g_NESmapper.set_CPU_bank4(g_NESmapper.Mapper90.prg_reg[1]*2);
g_NESmapper.set_CPU_bank5(g_NESmapper.Mapper90.prg_reg[1]*2+1);
g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-2);
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
}
else if(g_NESmapper.Mapper90.prg_bank_size == 2)
{
if(g_NESmapper.Mapper90.prg_bank_e000)
{
g_NESmapper.set_CPU_bank4(g_NESmapper.Mapper90.prg_reg[0]);
g_NESmapper.set_CPU_bank5(g_NESmapper.Mapper90.prg_reg[1]);
g_NESmapper.set_CPU_bank6(g_NESmapper.Mapper90.prg_reg[2]);
g_NESmapper.set_CPU_bank7(g_NESmapper.Mapper90.prg_reg[3]);
}
else
{
if(g_NESmapper.Mapper90.prg_bank_6000)
{
g_NESmapper.set_CPU_bank3(g_NESmapper.Mapper90.prg_reg[3]);
}
g_NESmapper.set_CPU_bank4(g_NESmapper.Mapper90.prg_reg[0]);
g_NESmapper.set_CPU_bank5(g_NESmapper.Mapper90.prg_reg[1]);
g_NESmapper.set_CPU_bank6(g_NESmapper.Mapper90.prg_reg[2]);
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
}
}
else
{
// 8k in reverse g_NESmapper.Mapper90.mode?
g_NESmapper.set_CPU_bank4(g_NESmapper.Mapper90.prg_reg[3]);
g_NESmapper.set_CPU_bank5(g_NESmapper.Mapper90.prg_reg[2]);
g_NESmapper.set_CPU_bank6(g_NESmapper.Mapper90.prg_reg[1]);
g_NESmapper.set_CPU_bank7(g_NESmapper.Mapper90.prg_reg[0]);
}
#else
switch(g_NESmapper.Mapper90.mode&3){
case 0:
if(g_NESmapper.Mapper90.mode&4){
uint32 bn = g_NESmapper.Mapper90.prg_reg[3]<<2;
g_NESmapper.set_CPU_banks(bn, bn+1, bn+2, bn+3);
}
else{
g_NESmapper.set_CPU_bank4(g_NESmapper.num_8k_ROM_banks-4);
g_NESmapper.set_CPU_bank5(g_NESmapper.num_8k_ROM_banks-3);
g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-2);
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
}
if(g_NESmapper.Mapper90.mode&0x80){
g_NESmapper.set_CPU_bank3((g_NESmapper.Mapper90.prg_reg[3]<<2)|3);
}
break;
case 1:
g_NESmapper.set_CPU_bank4(g_NESmapper.Mapper90.prg_reg[1]<<1);
g_NESmapper.set_CPU_bank5(g_NESmapper.Mapper90.prg_reg[1]<<1+1);
if(g_NESmapper.Mapper90.mode&4){
g_NESmapper.set_CPU_bank6(g_NESmapper.Mapper90.prg_reg[3]<<1);
g_NESmapper.set_CPU_bank7(g_NESmapper.Mapper90.prg_reg[3]<<1+1);
}
else{
g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-2);
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
}
if(g_NESmapper.Mapper90.mode&0x80){
g_NESmapper.set_CPU_bank3((g_NESmapper.Mapper90.prg_reg[3]<<1)|1);
}
break;
case 2:
g_NESmapper.set_CPU_bank4(g_NESmapper.Mapper90.prg_reg[0]);
g_NESmapper.set_CPU_bank5(g_NESmapper.Mapper90.prg_reg[1]);
g_NESmapper.set_CPU_bank6(g_NESmapper.Mapper90.prg_reg[2]);
if(g_NESmapper.Mapper90.mode & 0x04){
g_NESmapper.set_CPU_bank7(g_NESmapper.Mapper90.prg_reg[3]);
}
else{
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
}
if(g_NESmapper.Mapper90.mode & 0x80){
g_NESmapper.set_CPU_bank3(g_NESmapper.Mapper90.prg_reg[3]);
}
break;
case 3:
g_NESmapper.set_CPU_bank4(g_NESmapper.Mapper90.prg_reg[2]);
g_NESmapper.set_CPU_bank5(g_NESmapper.Mapper90.prg_reg[3]);
g_NESmapper.set_CPU_bank6(g_NESmapper.Mapper90.prg_reg[0]);
if(g_NESmapper.Mapper90.mode & 0x04){
g_NESmapper.set_CPU_bank7(g_NESmapper.Mapper90.prg_reg[1]);
}
else{
g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1);
}
if(g_NESmapper.Mapper90.mode & 0x80){
g_NESmapper.set_CPU_bank3(g_NESmapper.Mapper90.prg_reg[3]);
}
break;
break;
}
#endif
}
/////////////////////////////////////////////////////////////////////
| [
"takka@e750ed6d-7236-0410-a570-cc313d6b6496"
]
| [
[
[
1,
434
]
]
]
|
ece85565a78fdb6ed3644501a5ff47065e23d5cd | 89d2197ed4531892f005d7ee3804774202b1cb8d | /GWEN/include/Gwen/Controls/Modal.h | 639646a971b0bf133cf18aa943e2c9d3785d6ab1 | [
"MIT",
"Zlib"
]
| permissive | hpidcock/gbsfml | ef8172b6c62b1c17d71d59aec9a7ff2da0131d23 | e3aa990dff8c6b95aef92bab3e94affb978409f2 | refs/heads/master | 2020-05-30T15:01:19.182234 | 2010-09-29T06:53:53 | 2010-09-29T06:53:53 | 35,650,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | h |
#pragma once
#include "Gwen/Controls/Base.h"
#include "Gwen/Gwen.h"
#include "Gwen/Skin.h"
namespace Gwen
{
namespace ControlsInternal
{
class Modal : public Controls::Base
{
GWEN_CONTROL_INLINE( Modal, Controls::Base )
{
SetKeyboardInputEnabled( true );
SetMouseInputEnabled( true );
SetShouldDrawBackground( true );
}
virtual void Layout( Skin::Base* skin )
{
SetBounds( 0, 0, GetCanvas()->Width(), GetCanvas()->Height() );
}
virtual void Render( Skin::Base* skin )
{
if ( !ShouldDrawBackground() ) return;
skin->DrawModalControl( this );
}
};
}
} | [
"haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793"
]
| [
[
[
1,
35
]
]
]
|
8e0d1a702c2d9e19a039635b96aa84c5e7e89775 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Graphic/Main/BoundingBox.h | 99ab4105d73adf8a0f9ece84457aca5dbb0a667b | []
| no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,406 | h | #ifndef _BOUNDINGBOX_H_
#define _BOUNDINGBOX_H_
#include <Common/Prerequisites.h>
#include "BoundingVolume.h"
namespace Flagship
{
class _DLL_Export BoundingBox : public BoundingVolume
{
public:
BoundingBox();
BoundingBox( Box3f& rkBox );
BoundingBox( Vector3f& vCenter, Vector3f * avAxis = NULL, float * afExtent = NULL );
virtual ~BoundingBox();
// 重载等于
BoundingBox& operator = ( BoundingBox& rkBound );
// 设置中心
void SetCenter( Vector3f& rvCenter ) { m_kBox.Center = rvCenter; }
// 设置坐标
void SetAxis( Vector3f * avAxis );
// 设置扩展
void SetExtent( float * afExtent );
// 获取盒子
Box3f& GetBox() { return m_kBox; }
public:
// 扩大包容
virtual void GrowToContain( BoundingVolume * pBound );
// 判断位置
virtual bool IsInBound( Vector3f& vPos );
// 是否被剪裁
virtual bool IsCulled( Plane3f * pkPlane );
// 是否相交
virtual bool IsIntersect( BoundingVolume * pBound );
// 坐标变换
virtual void TransformBy( Matrix4f& rmatWorld, BoundingVolume * pkResultBound );
// 获取背面平面
virtual Plane3f * GetBackPlane( Vector3f& vPos );
protected:
// 盒子
Box3f m_kBox;
private:
};
}
#endif
| [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
]
| [
[
[
1,
59
]
]
]
|
b3bc99a78692db0fd8e81a2cb9a1f2a5c50e5d8d | 7e68ef369eff945f581e22595adecb6b3faccd0e | /code/linux/minifw/sockstream.h | a5579374e8d146f7607dfb8c7b524b7dc2919606 | []
| no_license | kimhmadsen/mini-framework | 700bb1052227ba18eee374504ff90f41e98738d2 | d1983a68c6b1d87e24ef55ca839814ed227b3956 | refs/heads/master | 2021-01-01T05:36:55.074091 | 2008-12-16T00:33:10 | 2008-12-16T00:33:10 | 32,415,758 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | h | #pragma once
#include <sys/socket.h>
#include <unistd.h>
typedef int SOCKET;
typedef int HANDLE;
typedef int ssize_t;
const int INVALID_HANDLE_VALUE = -1;
/**
Implement a Wrapper Facade for the socket data structure.
Responsibility:
- Encapsulates socket structures with a cohesive objectoriented abstraction.
Collaborator:
- HANDLE
*/
class SockStream
{
public:
SockStream(void);
SockStream(HANDLE h);
SockStream(const SockStream& ss );
~SockStream(void);
void SetHandle( HANDLE h );
HANDLE GetHandle(void);
ssize_t recv (void* buf, size_t len, int flags);
ssize_t send (const char* buf, size_t len, int flags);
//
ssize_t recv_n (void* buf, size_t len, int flags);
ssize_t send_n (const char* buf, size_t len, int flags);
void close(void);
private:
HANDLE handle;
//SOCKET handle;
};
| [
"mariasolercliment@77f6bdef-6155-0410-8b08-fdea0229669f"
]
| [
[
[
1,
39
]
]
]
|
3b1e90c36e526e9031a4d8c21f90a51c3df0acd8 | d7320c9c1f155e2499afa066d159bfa6aa94b432 | /ghostgproxy/game_base.h | b75cdb6dbf1ff703e6dd8044cca3b0f0bf186677 | []
| no_license | HOST-PYLOS/ghostnordicleague | c44c804cb1b912584db3dc4bb811f29f3761a458 | 9cb262d8005dda0150b75d34b95961d664b1b100 | refs/heads/master | 2016-09-05T10:06:54.279724 | 2011-02-23T08:02:50 | 2011-02-23T08:02:50 | 32,241,503 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,287 | h | /*
Copyright [2008] [Trevor Hogan]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#ifndef GAME_BASE_H
#define GAME_BASE_H
#include "gameslot.h"
//
// CBaseGame
//
class CTCPServer;
class CGameProtocol;
class CPotentialPlayer;
class CGamePlayer;
class CMap;
class CSaveGame;
class CReplay;
class CIncomingJoinPlayer;
class CIncomingAction;
class CIncomingChatPlayer;
class CIncomingMapSize;
class CCallableScoreCheck;
class CCallableGamePlayerSummaryCheck;
typedef pair<string,CCallableGamePlayerSummaryCheck *> PairedGPSCheck;
typedef pair<string,string> PairedPlayers;
typedef pair<unsigned char, double> BalancePlayerPair;
class CBaseGame
{
public:
CGHost *m_GHost;
protected:
CTCPServer *m_Socket; // listening socket
CGameProtocol *m_Protocol; // game protocol
vector<CGameSlot> m_Slots; // vector of slots
vector<CPotentialPlayer *> m_Potentials; // vector of potential players (connections that haven't sent a W3GS_REQJOIN packet yet)
vector<CGamePlayer *> m_Players; // vector of players
vector<CCallableScoreCheck *> m_ScoreChecks;
queue<CIncomingAction *> m_Actions; // queue of actions to be sent
vector<string> m_Reserved; // vector of player names with reserved slots (from the !hold command)
set<string> m_IgnoredNames; // set of player names to NOT print ban messages for when joining because they've already been printed
set<string> m_IPBlackList; // set of IP addresses to blacklist from joining (todotodo: convert to uint32's for efficiency)
vector<CGameSlot> m_EnforceSlots; // vector of slots to force players to use (used with saved games)
vector<PIDPlayer> m_EnforcePlayers; // vector of pids to force players to use (used with saved games)
CMap *m_Map; // map data
CSaveGame *m_SaveGame; // savegame data (this is a pointer to global data)
CReplay *m_Replay; // replay
bool m_Exiting; // set to true and this class will be deleted next update
bool m_Saving; // if we're currently saving game data to the database
uint16_t m_HostPort; // the port to host games on
unsigned char m_GameState; // game state, public or private
unsigned char m_VirtualHostPID; // virtual host's PID
unsigned char m_FakePlayerPID; // the fake player's PID (if present)
vector<unsigned char> m_FakePlayerPIDs; // multiple fakeplayers PIDS
unsigned char m_GProxyEmptyActions;
string m_GameName; // game name
string m_LastGameName; // last game name (the previous game name before it was rehosted)
string m_VirtualHostName; // virtual host's name
string m_OwnerName; // name of the player who owns this game (should be considered an admin)
string m_CreatorName; // name of the player who created this game
string m_CreatorServer; // battle.net server the player who created this game was on
string m_AnnounceMessage; // a message to be sent every m_AnnounceInterval seconds
string m_StatString; // the stat string when the game started (used when saving replays)
string m_KickVotePlayer; // the player to be kicked with the currently running kick vote
string m_HCLCommandString; // the "HostBot Command Library" command string, used to pass a limited amount of data to specially designed maps
uint32_t m_RandomSeed; // the random seed sent to the Warcraft III clients
uint32_t m_HostCounter; // a unique game number
uint32_t m_EntryKey; // random entry key for LAN, used to prove that a player is actually joining from LAN
uint32_t m_Latency; // the number of ms to wait between sending action packets (we queue any received during this time)
uint32_t m_SyncLimit; // the maximum number of packets a player can fall out of sync before starting the lag screen
uint32_t m_SyncCounter; // the number of actions sent so far (for determining if anyone is lagging)
uint32_t m_GameTicks; // ingame ticks
uint32_t m_CreationTime; // GetTime when the game was created
uint32_t m_LastPingTime; // GetTime when the last ping was sent
uint32_t m_LastRefreshTime; // GetTime when the last game refresh was sent
uint32_t m_LastDownloadTicks; // GetTicks when the last map download cycle was performed
uint32_t m_DownloadCounter; // # of map bytes downloaded in the last second
uint32_t m_LastDownloadCounterResetTicks; // GetTicks when the download counter was last reset
uint32_t m_LastAnnounceTime; // GetTime when the last announce message was sent
uint32_t m_AnnounceInterval; // how many seconds to wait between sending the m_AnnounceMessage
uint32_t m_LastAutoStartTime; // the last time we tried to auto start the game
uint32_t m_AutoStartPlayers; // auto start the game when there are this many players or more
uint32_t m_LastCountDownTicks; // GetTicks when the last countdown message was sent
int32_t m_CountDownCounter; // the countdown is finished when this reaches zero
uint32_t m_StartedLoadingTicks; // GetTicks when the game started loading
uint32_t m_StartPlayers; // number of players when the game started
uint32_t m_LastLagScreenResetTime; // GetTime when the "lag" screen was last reset
uint32_t m_LastActionSentTicks; // GetTicks when the last action packet was sent
uint32_t m_LastActionLateBy; // the number of ticks we were late sending the last action packet by
uint32_t m_StartedLaggingTime; // GetTime when the last lag screen started
uint32_t m_LastLagScreenTime; // GetTime when the last lag screen was active (continuously updated)
uint32_t m_LastReservedSeen; // GetTime when the last reserved player was seen in the lobby
uint32_t m_StartedKickVoteTime; // GetTime when the kick vote was started
uint32_t m_GameOverTime; // GetTime when the game was over
uint32_t m_LastPlayerLeaveTicks; // GetTicks when the most recent player left the game
double m_MinimumScore; // the minimum allowed score for matchmaking mode
double m_MaximumScore; // the maximum allowed score for matchmaking mode
bool m_SlotInfoChanged; // if the slot info has changed and hasn't been sent to the players yet (optimization)
bool m_Locked; // if the game owner is the only one allowed to run game commands or not
bool m_RefreshMessages; // if we should display "game refreshed..." messages or not
bool m_RefreshError; // if there was an error refreshing the game
bool m_RefreshRehosted; // if we just rehosted and are waiting for confirmation that it was successful
bool m_MuteAll; // if we should stop forwarding ingame chat messages targeted for all players or not
bool m_MuteLobby; // if we should stop forwarding lobby chat messages
bool m_CountDownStarted; // if the game start countdown has started or not
bool m_GameLoading; // if the game is currently loading or not
bool m_GameLoaded; // if the game has loaded or not
bool m_LoadInGame; // if the load-in-game feature is enabled or not
bool m_Lagging; // if the lag screen is active or not
bool m_AutoSave; // if we should auto save the game before someone disconnects
bool m_MatchMaking; // if matchmaking mode is enabled
bool m_LocalAdminMessages; // if local admin messages should be relayed or not
string m_SentinelCB;
string m_ScourgeCB;
/*
NordicLeague - @begin - Some added custom variables
*/
uint32_t m_StartedVoteEndTime; // GetTime when the end vote was started
bool m_VoteEndInProgress;
uint32_t m_LastGameInfoUpdateTime;
uint32_t m_LastGameInfoPlayers;
string m_LastGameInfoName;
uint32_t m_FFTeam;
uint32_t m_FFVotesNeeded;
uint32_t m_FFStartedTime;
bool m_FFSucceeded;
uint32_t m_ForfeitDelayTime;
uint32_t m_FFKickTime;
uint32_t m_LobbyTimeLimit; // Each game must have it's own lobby timelimit to prevent !autostart off from closing games
vector<PairedGPSCheck> m_PairedSafeGameChecks; // vector of paired threaded database game player summary checks in progress for safegames
vector<PairedGPSCheck> m_PairedReliabilityChecks; // vector of paired threaded database game player summary checks in progress
uint32_t m_BalanceSlotsTime; // timer for delaying balancing of slots.
bool m_GameIsInHouse; // inhouse game.
vector<PairedPlayers> m_PairedLinkedPlayers;
vector<string> m_ChatLog;
uint32_t m_StartTime;
uint32_t m_AutoCloseTime;
bool m_AutoClose;
uint32_t m_AutoStartPlayersTime;
uint32_t m_LobbyJokeTime;
/*
NordicLeague - @end - Some added custom variables
*/
public:
CBaseGame( CGHost *nGHost, CMap *nMap, CSaveGame *nSaveGame, uint16_t nHostPort, unsigned char nGameState, string nGameName, string nOwnerName, string nCreatorName, string nCreatorServer );
virtual ~CBaseGame( );
virtual vector<CGameSlot> GetEnforceSlots( ) { return m_EnforceSlots; }
virtual vector<PIDPlayer> GetEnforcePlayers( ) { return m_EnforcePlayers; }
virtual CSaveGame *GetSaveGame( ) { return m_SaveGame; }
virtual uint16_t GetHostPort( ) { return m_HostPort; }
virtual unsigned char GetGameState( ) { return m_GameState; }
virtual unsigned char GetGProxyEmptyActions( ) { return m_GProxyEmptyActions; }
virtual string GetGameName( ) { return m_GameName; }
virtual string GetLastGameName( ) { return m_LastGameName; }
virtual string GetVirtualHostName( ) { return m_VirtualHostName; }
virtual string GetOwnerName( ) { return m_OwnerName; }
virtual string GetCreatorName( ) { return m_CreatorName; }
virtual string GetCreatorServer( ) { return m_CreatorServer; }
virtual uint32_t GetHostCounter( ) { return m_HostCounter; }
virtual uint32_t GetLastLagScreenTime( ) { return m_LastLagScreenTime; }
virtual bool GetLocked( ) { return m_Locked; }
virtual bool GetRefreshMessages( ) { return m_RefreshMessages; }
virtual bool GetCountDownStarted( ) { return m_CountDownStarted; }
virtual bool GetGameLoading( ) { return m_GameLoading; }
virtual bool GetGameLoaded( ) { return m_GameLoaded; }
virtual bool GetLagging( ) { return m_Lagging; }
virtual void SetEnforceSlots( vector<CGameSlot> nEnforceSlots ) { m_EnforceSlots = nEnforceSlots; }
virtual void SetEnforcePlayers( vector<PIDPlayer> nEnforcePlayers ) { m_EnforcePlayers = nEnforcePlayers; }
virtual void SetExiting( bool nExiting ) { m_Exiting = nExiting; }
virtual void SetAutoStartPlayers( uint32_t nAutoStartPlayers ) { m_AutoStartPlayers = nAutoStartPlayers; }
virtual void SetMinimumScore( double nMinimumScore ) { m_MinimumScore = nMinimumScore; }
virtual void SetMaximumScore( double nMaximumScore ) { m_MaximumScore = nMaximumScore; }
virtual void SetRefreshError( bool nRefreshError ) { m_RefreshError = nRefreshError; }
virtual void SetMatchMaking( bool nMatchMaking ) { m_MatchMaking = nMatchMaking; }
virtual void SetForfeitDelayTime( uint32_t nTime ) { m_ForfeitDelayTime = nTime; }
virtual void SetInhouse( bool nInhouse ) { m_GameIsInHouse = nInhouse; }
virtual void SetHCLMode( string nHCL ) { m_HCLCommandString = nHCL; }
virtual void AddLinkedPlayers( PairedPlayers Linked ) { m_PairedLinkedPlayers.push_back(Linked); }
virtual void RemoveLinkedPlayers( string player );
virtual void RemoveAllLinkedPlayers( );
virtual bool IsLinked( string player, string player2 );
virtual void UpdateGameInfo(uint32_t players);
virtual uint32_t GetNextTimedActionTicks( );
virtual uint32_t GetSlotsOccupied( );
virtual uint32_t GetSlotsOpen( );
virtual uint32_t GetNumPlayers( );
virtual uint32_t GetNumHumanPlayers( );
virtual string GetDescription( );
virtual void SetAnnounce( uint32_t interval, string message );
// processing functions
virtual unsigned int SetFD( void *fd, void *send_fd, int *nfds );
virtual bool Update( void *fd, void *send_fd );
virtual void UpdatePost( void *send_fd );
// generic functions to send packets to players
virtual void Send( CGamePlayer *player, BYTEARRAY data );
virtual void Send( unsigned char PID, BYTEARRAY data );
virtual void Send( BYTEARRAY PIDs, BYTEARRAY data );
virtual void SendAll( BYTEARRAY data );
// functions to send packets to players
virtual void SendChat( unsigned char fromPID, CGamePlayer *player, string message );
virtual void SendChat( unsigned char fromPID, unsigned char toPID, string message );
virtual void SendChat( CGamePlayer *player, string message );
virtual void SendChat( unsigned char toPID, string message );
virtual void SendAllChat( unsigned char fromPID, string message );
virtual void SendAllChat( string message );
virtual void SendLocalAdminChat( string message );
virtual void SendAllSlotInfo( );
virtual void SendVirtualHostPlayerInfo( CGamePlayer *player );
virtual void SendFakePlayerInfo( CGamePlayer *player );
virtual void SendAllActions( );
virtual void SendWelcomeMessage( CGamePlayer *player );
virtual void SendEndMessage( );
// events
// note: these are only called while iterating through the m_Potentials or m_Players vectors
// therefore you can't modify those vectors and must use the player's m_DeleteMe member to flag for deletion
virtual void EventPlayerDeleted( CGamePlayer *player );
virtual void EventPlayerDisconnectTimedOut( CGamePlayer *player );
virtual void EventPlayerDisconnectPlayerError( CGamePlayer *player );
virtual void EventPlayerDisconnectSocketError( CGamePlayer *player );
virtual void EventPlayerDisconnectConnectionClosed( CGamePlayer *player );
virtual void EventPlayerJoined( CPotentialPlayer *potential, CIncomingJoinPlayer *joinPlayer );
virtual void EventPlayerJoinedWithScore( CPotentialPlayer *potential, CIncomingJoinPlayer *joinPlayer, double score, uint32_t games = 0, uint32_t staypercent = 0, bool vouched = false, string alias = string());
virtual void EventPlayerLeft( CGamePlayer *player, uint32_t reason );
virtual void EventPlayerLoaded( CGamePlayer *player );
virtual void EventPlayerAction( CGamePlayer *player, CIncomingAction *action );
virtual void EventPlayerKeepAlive( CGamePlayer *player, uint32_t checkSum );
virtual void EventPlayerChatToHost( CGamePlayer *player, CIncomingChatPlayer *chatPlayer );
virtual bool EventPlayerBotCommand( CGamePlayer *player, string command, string payload );
virtual void EventPlayerChangeTeam( CGamePlayer *player, unsigned char team );
virtual void EventPlayerChangeColour( CGamePlayer *player, unsigned char colour );
virtual void EventPlayerChangeRace( CGamePlayer *player, unsigned char race );
virtual void EventPlayerChangeHandicap( CGamePlayer *player, unsigned char handicap );
virtual void EventPlayerDropRequest( CGamePlayer *player );
virtual void EventPlayerMapSize( CGamePlayer *player, CIncomingMapSize *mapSize );
virtual void EventPlayerPongToHost( CGamePlayer *player, uint32_t pong );
// these events are called outside of any iterations
virtual void EventGameRefreshed( string server );
virtual void EventGameStarted( );
virtual void EventGameLoaded( );
// other functions
virtual unsigned char GetSIDFromPID( unsigned char PID );
virtual CGamePlayer *GetPlayerFromPID( unsigned char PID );
virtual CGamePlayer *GetPlayerFromSID( unsigned char SID );
virtual CGamePlayer *GetPlayerFromName( string name, bool sensitive );
virtual uint32_t GetPlayerFromNamePartial( string name, CGamePlayer **player );
virtual CGamePlayer *GetPlayerFromColour( unsigned char colour );
virtual unsigned char GetNewPID( );
virtual unsigned char GetNewColour( );
virtual BYTEARRAY GetPIDs( );
virtual BYTEARRAY GetPIDs( unsigned char excludePID );
virtual unsigned char GetHostPID( );
virtual unsigned char GetEmptySlot( bool reserved, string name = string() );
virtual unsigned char GetEmptySlot( unsigned char team, unsigned char PID );
virtual void SwapSlots( unsigned char SID1, unsigned char SID2 );
virtual void OpenSlot( unsigned char SID, bool kick );
virtual void CloseSlot( unsigned char SID, bool kick );
virtual void ComputerSlot( unsigned char SID, unsigned char skill, bool kick );
virtual void ColourSlot( unsigned char SID, unsigned char colour );
virtual void OpenAllSlots( );
virtual void CloseAllSlots( );
virtual void ShuffleSlots( );
virtual vector<unsigned char> BalanceSlotsRecursive( vector<unsigned char> PlayerIDs, unsigned char *TeamSizes, double *PlayerScores, unsigned char StartTeam );
virtual vector<unsigned char> BalanceSlotsRecursive2( vector<unsigned char> PlayerIDs, unsigned char *TeamSizes, double *PlayerScores, unsigned char *PlayerLinks );
virtual void BalanceSlotsLinked(vector<BalancePlayerPair> Players);
virtual void BalanceSlots( );
virtual void AddToSpoofed( string server, string name, bool sendMessage );
virtual void AddToReserved( string name );
virtual bool IsOwner( string name );
virtual bool IsReserved( string name );
virtual bool IsDownloading( );
virtual bool IsGameDataSaved( );
virtual void SaveGameData( );
virtual void StartCountDown( bool force );
virtual void StartCountDownAuto( bool requireSpoofChecks );
virtual void StopPlayers( string reason );
virtual void StopLaggers( string reason );
virtual void CreateVirtualHost( );
virtual void DeleteVirtualHost( );
virtual void CreateFakePlayer( string name = "" );
virtual void DeleteFakePlayer( );
};
#endif
| [
"fredrik.sigillet@4a4c9648-eef2-11de-9456-cf00f3bddd4e",
"[email protected]@4a4c9648-eef2-11de-9456-cf00f3bddd4e"
]
| [
[
[
1,
169
],
[
173,
267
],
[
269,
334
]
],
[
[
170,
172
],
[
268,
268
]
]
]
|
88cbb8a72497dab47ddb5ba5b40896112642cef9 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /SysLibs/ECom/InterfaceClient/InterfaceClient.h | a4beb748d816ae9fc15030384cb1f7ef51dc32a3 | []
| 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 | 652 | h | // InterfaceClient.h
//
// Copyright (c) 2001 Symbian Ltd. All rights reserved.
#ifndef __CINTERFACECLIENT_H
#define __CINTERFACECLIENT_H
#include <Interface.h>
// Example ECOM client that uses the InterfaceImplementation plug-ins
// through the InterfaceDefinition (CExampleInterface) interface
class TInterfaceClient
{
public:
// Gets the default implementation of CExampleInterface
void GetDefaultL();
// Gets a CExampleInterface implementation by requesting
// a specific types of capability
void GetBySpecificationL();
// Gets all the CExampleInterface implementations
void GetByDiscoveryL();
};
#endif
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
]
| [
[
[
1,
27
]
]
]
|
8e5de6a59b905d879f1a1a5d3d56458c9213d714 | eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5 | /WinEditionWithJRE/browser-lcc/jscc/src/v8/v8/src/spaces-inl.h | be1a1156b913a0cc1f7bdc1dd2e8d36bad08bf26 | [
"BSD-3-Clause",
"bzip2-1.0.6",
"Artistic-1.0",
"LicenseRef-scancode-public-domain",
"Artistic-2.0"
]
| permissive | baxtree/OKBuzzer | c46c7f271a26be13adcf874d77a7a6762a8dc6be | a16e2baad145f5c65052cdc7c767e78cdfee1181 | refs/heads/master | 2021-01-02T22:17:34.168564 | 2011-06-15T02:29:56 | 2011-06-15T02:29:56 | 1,790,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,428 | h | // Copyright 2006-2010 the V8 project authors. 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.
#ifndef V8_SPACES_INL_H_
#define V8_SPACES_INL_H_
#include "isolate.h"
#include "spaces.h"
#include "v8memory.h"
namespace v8 {
namespace internal {
// -----------------------------------------------------------------------------
// PageIterator
bool PageIterator::has_next() {
return prev_page_ != stop_page_;
}
Page* PageIterator::next() {
ASSERT(has_next());
prev_page_ = (prev_page_ == NULL)
? space_->first_page_
: prev_page_->next_page();
return prev_page_;
}
// -----------------------------------------------------------------------------
// Page
Page* Page::next_page() {
return heap_->isolate()->memory_allocator()->GetNextPage(this);
}
Address Page::AllocationTop() {
PagedSpace* owner = heap_->isolate()->memory_allocator()->PageOwner(this);
return owner->PageAllocationTop(this);
}
Address Page::AllocationWatermark() {
PagedSpace* owner = heap_->isolate()->memory_allocator()->PageOwner(this);
if (this == owner->AllocationTopPage()) {
return owner->top();
}
return address() + AllocationWatermarkOffset();
}
uint32_t Page::AllocationWatermarkOffset() {
return static_cast<uint32_t>((flags_ & kAllocationWatermarkOffsetMask) >>
kAllocationWatermarkOffsetShift);
}
void Page::SetAllocationWatermark(Address allocation_watermark) {
if ((heap_->gc_state() == Heap::SCAVENGE) && IsWatermarkValid()) {
// When iterating intergenerational references during scavenge
// we might decide to promote an encountered young object.
// We will allocate a space for such an object and put it
// into the promotion queue to process it later.
// If space for object was allocated somewhere beyond allocation
// watermark this might cause garbage pointers to appear under allocation
// watermark. To avoid visiting them during dirty regions iteration
// which might be still in progress we store a valid allocation watermark
// value and mark this page as having an invalid watermark.
SetCachedAllocationWatermark(AllocationWatermark());
InvalidateWatermark(true);
}
flags_ = (flags_ & kFlagsMask) |
Offset(allocation_watermark) << kAllocationWatermarkOffsetShift;
ASSERT(AllocationWatermarkOffset()
== static_cast<uint32_t>(Offset(allocation_watermark)));
}
void Page::SetCachedAllocationWatermark(Address allocation_watermark) {
mc_first_forwarded = allocation_watermark;
}
Address Page::CachedAllocationWatermark() {
return mc_first_forwarded;
}
uint32_t Page::GetRegionMarks() {
return dirty_regions_;
}
void Page::SetRegionMarks(uint32_t marks) {
dirty_regions_ = marks;
}
int Page::GetRegionNumberForAddress(Address addr) {
// Each page is divided into 256 byte regions. Each region has a corresponding
// dirty mark bit in the page header. Region can contain intergenerational
// references iff its dirty mark is set.
// A normal 8K page contains exactly 32 regions so all region marks fit
// into 32-bit integer field. To calculate a region number we just divide
// offset inside page by region size.
// A large page can contain more then 32 regions. But we want to avoid
// additional write barrier code for distinguishing between large and normal
// pages so we just ignore the fact that addr points into a large page and
// calculate region number as if addr pointed into a normal 8K page. This way
// we get a region number modulo 32 so for large pages several regions might
// be mapped to a single dirty mark.
ASSERT_PAGE_ALIGNED(this->address());
STATIC_ASSERT((kPageAlignmentMask >> kRegionSizeLog2) < kBitsPerInt);
// We are using masking with kPageAlignmentMask instead of Page::Offset()
// to get an offset to the beginning of 8K page containing addr not to the
// beginning of actual page which can be bigger then 8K.
intptr_t offset_inside_normal_page = OffsetFrom(addr) & kPageAlignmentMask;
return static_cast<int>(offset_inside_normal_page >> kRegionSizeLog2);
}
uint32_t Page::GetRegionMaskForAddress(Address addr) {
return 1 << GetRegionNumberForAddress(addr);
}
uint32_t Page::GetRegionMaskForSpan(Address start, int length_in_bytes) {
uint32_t result = 0;
if (length_in_bytes >= kPageSize) {
result = kAllRegionsDirtyMarks;
} else if (length_in_bytes > 0) {
int start_region = GetRegionNumberForAddress(start);
int end_region =
GetRegionNumberForAddress(start + length_in_bytes - kPointerSize);
uint32_t start_mask = (~0) << start_region;
uint32_t end_mask = ~((~1) << end_region);
result = start_mask & end_mask;
// if end_region < start_region, the mask is ored.
if (result == 0) result = start_mask | end_mask;
}
#ifdef DEBUG
if (FLAG_enable_slow_asserts) {
uint32_t expected = 0;
for (Address a = start; a < start + length_in_bytes; a += kPointerSize) {
expected |= GetRegionMaskForAddress(a);
}
ASSERT(expected == result);
}
#endif
return result;
}
void Page::MarkRegionDirty(Address address) {
SetRegionMarks(GetRegionMarks() | GetRegionMaskForAddress(address));
}
bool Page::IsRegionDirty(Address address) {
return GetRegionMarks() & GetRegionMaskForAddress(address);
}
void Page::ClearRegionMarks(Address start, Address end, bool reaches_limit) {
int rstart = GetRegionNumberForAddress(start);
int rend = GetRegionNumberForAddress(end);
if (reaches_limit) {
end += 1;
}
if ((rend - rstart) == 0) {
return;
}
uint32_t bitmask = 0;
if ((OffsetFrom(start) & kRegionAlignmentMask) == 0
|| (start == ObjectAreaStart())) {
// First region is fully covered
bitmask = 1 << rstart;
}
while (++rstart < rend) {
bitmask |= 1 << rstart;
}
if (bitmask) {
SetRegionMarks(GetRegionMarks() & ~bitmask);
}
}
void Page::FlipMeaningOfInvalidatedWatermarkFlag(Heap* heap) {
heap->page_watermark_invalidated_mark_ ^= 1 << WATERMARK_INVALIDATED;
}
bool Page::IsWatermarkValid() {
return (flags_ & (1 << WATERMARK_INVALIDATED)) !=
heap_->page_watermark_invalidated_mark_;
}
void Page::InvalidateWatermark(bool value) {
if (value) {
flags_ = (flags_ & ~(1 << WATERMARK_INVALIDATED)) |
heap_->page_watermark_invalidated_mark_;
} else {
flags_ =
(flags_ & ~(1 << WATERMARK_INVALIDATED)) |
(heap_->page_watermark_invalidated_mark_ ^
(1 << WATERMARK_INVALIDATED));
}
ASSERT(IsWatermarkValid() == !value);
}
bool Page::GetPageFlag(PageFlag flag) {
return (flags_ & static_cast<intptr_t>(1 << flag)) != 0;
}
void Page::SetPageFlag(PageFlag flag, bool value) {
if (value) {
flags_ |= static_cast<intptr_t>(1 << flag);
} else {
flags_ &= ~static_cast<intptr_t>(1 << flag);
}
}
void Page::ClearPageFlags() {
flags_ = 0;
}
void Page::ClearGCFields() {
InvalidateWatermark(true);
SetAllocationWatermark(ObjectAreaStart());
if (heap_->gc_state() == Heap::SCAVENGE) {
SetCachedAllocationWatermark(ObjectAreaStart());
}
SetRegionMarks(kAllRegionsCleanMarks);
}
bool Page::WasInUseBeforeMC() {
return GetPageFlag(WAS_IN_USE_BEFORE_MC);
}
void Page::SetWasInUseBeforeMC(bool was_in_use) {
SetPageFlag(WAS_IN_USE_BEFORE_MC, was_in_use);
}
bool Page::IsLargeObjectPage() {
return !GetPageFlag(IS_NORMAL_PAGE);
}
void Page::SetIsLargeObjectPage(bool is_large_object_page) {
SetPageFlag(IS_NORMAL_PAGE, !is_large_object_page);
}
bool Page::IsPageExecutable() {
return GetPageFlag(IS_EXECUTABLE);
}
void Page::SetIsPageExecutable(bool is_page_executable) {
SetPageFlag(IS_EXECUTABLE, is_page_executable);
}
// -----------------------------------------------------------------------------
// MemoryAllocator
void MemoryAllocator::ChunkInfo::init(Address a, size_t s, PagedSpace* o) {
address_ = a;
size_ = s;
owner_ = o;
executable_ = (o == NULL) ? NOT_EXECUTABLE : o->executable();
owner_identity_ = (o == NULL) ? FIRST_SPACE : o->identity();
}
bool MemoryAllocator::IsValidChunk(int chunk_id) {
if (!IsValidChunkId(chunk_id)) return false;
ChunkInfo& c = chunks_[chunk_id];
return (c.address() != NULL) && (c.size() != 0) && (c.owner() != NULL);
}
bool MemoryAllocator::IsValidChunkId(int chunk_id) {
return (0 <= chunk_id) && (chunk_id < max_nof_chunks_);
}
bool MemoryAllocator::IsPageInSpace(Page* p, PagedSpace* space) {
ASSERT(p->is_valid());
int chunk_id = GetChunkId(p);
if (!IsValidChunkId(chunk_id)) return false;
ChunkInfo& c = chunks_[chunk_id];
return (c.address() <= p->address()) &&
(p->address() < c.address() + c.size()) &&
(space == c.owner());
}
Page* MemoryAllocator::GetNextPage(Page* p) {
ASSERT(p->is_valid());
intptr_t raw_addr = p->opaque_header & ~Page::kPageAlignmentMask;
return Page::FromAddress(AddressFrom<Address>(raw_addr));
}
int MemoryAllocator::GetChunkId(Page* p) {
ASSERT(p->is_valid());
return static_cast<int>(p->opaque_header & Page::kPageAlignmentMask);
}
void MemoryAllocator::SetNextPage(Page* prev, Page* next) {
ASSERT(prev->is_valid());
int chunk_id = GetChunkId(prev);
ASSERT_PAGE_ALIGNED(next->address());
prev->opaque_header = OffsetFrom(next->address()) | chunk_id;
}
PagedSpace* MemoryAllocator::PageOwner(Page* page) {
int chunk_id = GetChunkId(page);
ASSERT(IsValidChunk(chunk_id));
return chunks_[chunk_id].owner();
}
bool MemoryAllocator::InInitialChunk(Address address) {
if (initial_chunk_ == NULL) return false;
Address start = static_cast<Address>(initial_chunk_->address());
return (start <= address) && (address < start + initial_chunk_->size());
}
#ifdef ENABLE_HEAP_PROTECTION
void MemoryAllocator::Protect(Address start, size_t size) {
OS::Protect(start, size);
}
void MemoryAllocator::Unprotect(Address start,
size_t size,
Executability executable) {
OS::Unprotect(start, size, executable);
}
void MemoryAllocator::ProtectChunkFromPage(Page* page) {
int id = GetChunkId(page);
OS::Protect(chunks_[id].address(), chunks_[id].size());
}
void MemoryAllocator::UnprotectChunkFromPage(Page* page) {
int id = GetChunkId(page);
OS::Unprotect(chunks_[id].address(), chunks_[id].size(),
chunks_[id].owner()->executable() == EXECUTABLE);
}
#endif
// --------------------------------------------------------------------------
// PagedSpace
bool PagedSpace::Contains(Address addr) {
Page* p = Page::FromAddress(addr);
if (!p->is_valid()) return false;
return heap()->isolate()->memory_allocator()->IsPageInSpace(p, this);
}
// Try linear allocation in the page of alloc_info's allocation top. Does
// not contain slow case logic (eg, move to the next page or try free list
// allocation) so it can be used by all the allocation functions and for all
// the paged spaces.
HeapObject* PagedSpace::AllocateLinearly(AllocationInfo* alloc_info,
int size_in_bytes) {
Address current_top = alloc_info->top;
Address new_top = current_top + size_in_bytes;
if (new_top > alloc_info->limit) return NULL;
alloc_info->top = new_top;
ASSERT(alloc_info->VerifyPagedAllocation());
accounting_stats_.AllocateBytes(size_in_bytes);
return HeapObject::FromAddress(current_top);
}
// Raw allocation.
MaybeObject* PagedSpace::AllocateRaw(int size_in_bytes) {
ASSERT(HasBeenSetup());
ASSERT_OBJECT_SIZE(size_in_bytes);
HeapObject* object = AllocateLinearly(&allocation_info_, size_in_bytes);
if (object != NULL) return object;
object = SlowAllocateRaw(size_in_bytes);
if (object != NULL) return object;
return Failure::RetryAfterGC(identity());
}
// Reallocating (and promoting) objects during a compacting collection.
MaybeObject* PagedSpace::MCAllocateRaw(int size_in_bytes) {
ASSERT(HasBeenSetup());
ASSERT_OBJECT_SIZE(size_in_bytes);
HeapObject* object = AllocateLinearly(&mc_forwarding_info_, size_in_bytes);
if (object != NULL) return object;
object = SlowMCAllocateRaw(size_in_bytes);
if (object != NULL) return object;
return Failure::RetryAfterGC(identity());
}
// -----------------------------------------------------------------------------
// LargeObjectChunk
Address LargeObjectChunk::GetStartAddress() {
// Round the chunk address up to the nearest page-aligned address
// and return the heap object in that page.
Page* page = Page::FromAddress(RoundUp(address(), Page::kPageSize));
return page->ObjectAreaStart();
}
void LargeObjectChunk::Free(Executability executable) {
Isolate* isolate =
Page::FromAddress(RoundUp(address(), Page::kPageSize))->heap_->isolate();
isolate->memory_allocator()->FreeRawMemory(address(), size(), executable);
}
// -----------------------------------------------------------------------------
// NewSpace
MaybeObject* NewSpace::AllocateRawInternal(int size_in_bytes,
AllocationInfo* alloc_info) {
Address new_top = alloc_info->top + size_in_bytes;
if (new_top > alloc_info->limit) return Failure::RetryAfterGC();
Object* obj = HeapObject::FromAddress(alloc_info->top);
alloc_info->top = new_top;
#ifdef DEBUG
SemiSpace* space =
(alloc_info == &allocation_info_) ? &to_space_ : &from_space_;
ASSERT(space->low() <= alloc_info->top
&& alloc_info->top <= space->high()
&& alloc_info->limit == space->high());
#endif
return obj;
}
intptr_t LargeObjectSpace::Available() {
return LargeObjectChunk::ObjectSizeFor(
heap()->isolate()->memory_allocator()->Available());
}
template <typename StringType>
void NewSpace::ShrinkStringAtAllocationBoundary(String* string, int length) {
ASSERT(length <= string->length());
ASSERT(string->IsSeqString());
ASSERT(string->address() + StringType::SizeFor(string->length()) ==
allocation_info_.top);
allocation_info_.top =
string->address() + StringType::SizeFor(length);
string->set_length(length);
}
bool FreeListNode::IsFreeListNode(HeapObject* object) {
return object->map() == HEAP->raw_unchecked_byte_array_map()
|| object->map() == HEAP->raw_unchecked_one_pointer_filler_map()
|| object->map() == HEAP->raw_unchecked_two_pointer_filler_map();
}
} } // namespace v8::internal
#endif // V8_SPACES_INL_H_
| [
"[email protected]"
]
| [
[
[
1,
529
]
]
]
|
a33cdbbe108bc09c6a85579daf3cb6c70f2672fc | 22b6d8a368ecfa96cb182437b7b391e408ba8730 | /engine/include/qvCommandArgs.h | a2e88b0bfc37fa30d6c577fe01ad76bf24960a43 | [
"MIT"
]
| permissive | drr00t/quanticvortex | 2d69a3e62d1850b8d3074ec97232e08c349e23c2 | b780b0f547cf19bd48198dc43329588d023a9ad9 | refs/heads/master | 2021-01-22T22:16:50.370688 | 2010-12-18T12:06:33 | 2010-12-18T12:06:33 | 85,525,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,336 | h | /**************************************************************************************************
//This code is part of QuanticVortex for latest information, see http://www.quanticvortex.org
//
//Copyright (c) 2009-2010 QuanticMinds Software Ltda.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
**************************************************************************************************/
#ifndef __COMMAND_ARGS_H_
#define __COMMAND_ARGS_H_
#include <vector>
#include "qvCommandTypes.h"
namespace qv
{
class CommandArgs
{
public:
CommandArgs( const qv::CT_COMMAND_TYPE& commandType)
: mCommandType(commandType)
/// create a event argument with type
{}
virtual ~CommandArgs()
{}
const qv::CT_COMMAND_TYPE& getType() const;
/// event argument type
private:
CommandArgs(const CommandArgs&); // to avoid copy of command args
CommandArgs& operator = (const CommandArgs&); // to avoid copy of command args
const qv::CT_COMMAND_TYPE& mCommandType; // event arguments type
};
typedef std::vector<qv::CommandArgs*> CommandArgsArray;
/// array of CommandArgs
//inlines
inline const qv::CT_COMMAND_TYPE& qv::CommandArgs::getType() const
{
return mCommandType;
}
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
72
]
]
]
|
231b32dd53265c95da90e2099170efcdafabf61f | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Utilities/Destruction/BreakOffParts/hkpBreakOffPartsUtil.inl | 9fbdc4de3034548f9eff64782282fb26acf4d401 | []
| no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,004 | inl | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
void hkpBreakOffPartsUtil::LimitContactImpulseUtil::setMaxImpulseForShapeKey ( const hkpShapeKey key, hkUint8 max_impulse )
{
HK_ASSERT2(0xdbc48575, key != HK_INVALID_SHAPE_KEY, "Cannot associate an impulse with an invalid shape key");
m_shapeKeyToMaxImpulse.insert( key, max_impulse);
}
hkUint8 hkpBreakOffPartsUtil::LimitContactImpulseUtil::getMaxImpulseForKey ( const hkpShapeKey key ) const
{
HK_ASSERT2(0xdbc48575, key != HK_INVALID_SHAPE_KEY, "Cannot associate an impulse with an invalid shape key");
return m_shapeKeyToMaxImpulse.getWithDefault( key, 0 );
}
void hkpBreakOffPartsUtil::LimitContactImpulseUtil::removeKey ( const hkpShapeKey key )
{
HK_ASSERT2(0xdbc48575, key != HK_INVALID_SHAPE_KEY, "Cannot associate an impulse with an invalid shape key");
m_shapeKeyToMaxImpulse.remove(key);
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
43
]
]
]
|
f7ba464003e03b4d1471e82a4dd7974264459063 | c58b7487c69d596d08dafba52361aab43ed25ed3 | /json_test/json_spirit_writer_test.cpp | e87ef4a92c6e769785bec8d8b943186b47c720de | [
"MIT"
]
| permissive | deweerdt/JSON-Spirit | a2508d6272aa058ff9902c2c6494b7f1d70dec09 | 7dd32ece9c700c3e4a51e6c466cddcefd1054766 | refs/heads/master | 2020-04-04T13:14:06.281332 | 2009-12-07T16:13:55 | 2009-12-07T16:13:55 | 403,942 | 4 | 2 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 19,412 | cpp | // Copyright John W. Wilkinson 2007 - 2009.
// Distributed under the MIT License, see accompanying file LICENSE.txt
// json spirit version 4.02
#include "json_spirit_writer_test.h"
#include "json_spirit_writer.h"
#include "json_spirit_value.h"
#include "utils_test.h"
#include <sstream>
#include <boost/integer_traits.hpp>
using namespace json_spirit;
using namespace std;
using namespace boost;
namespace
{
const int64_t max_int64 = integer_traits< int64_t >::max();
const uint64_t max_uint64 = integer_traits< uint64_t >::max();
template< class Config_type >
struct Test_runner
{
typedef typename Config_type::String_type String_type;
typedef typename Config_type::Object_type Object_type;
typedef typename Config_type::Array_type Array_type;
typedef typename Config_type::Value_type Value_type;
typedef typename String_type::value_type Char_type;
typedef typename String_type::const_iterator Iter_type;
typedef std::basic_ostream< Char_type > Ostream_type;
String_type to_str( const char* c_str )
{
return ::to_str< String_type >( c_str );
}
void add_value( Object_type& obj, const char* c_name, const Value_type& value )
{
Config_type::add( obj, to_str( c_name ), value );
}
void add_c_str( Object_type& obj, const char* c_name, const char* c_value )
{
add_value( obj, c_name, to_str( c_value ) );
}
void check_eq( const Value_type& value, const char* expected_result )
{
assert_eq( write( value ), to_str( expected_result ) );
}
void check_eq_pretty( const Value_type& value, const char* expected_result )
{
assert_eq( write_formatted( value ), to_str( expected_result ) );
}
void test_empty_obj()
{
check_eq( Object_type(), "{}" );
check_eq_pretty( Object_type(), "{\n"
"}" );
}
void test_obj_with_one_member()
{
Object_type obj;
add_c_str( obj, "name", "value" );
check_eq ( obj, "{\"name\":\"value\"}" );
check_eq_pretty( obj, "{\n"
" \"name\" : \"value\"\n"
"}" );
}
void test_obj_with_two_members()
{
Object_type obj;
add_c_str( obj, "name_1", "value_1" );
add_c_str( obj, "name_2", "value_2" );
check_eq( obj, "{\"name_1\":\"value_1\",\"name_2\":\"value_2\"}" );
check_eq_pretty( obj, "{\n"
" \"name_1\" : \"value_1\",\n"
" \"name_2\" : \"value_2\"\n"
"}" );
}
void test_obj_with_three_members()
{
Object_type obj;
add_c_str( obj, "name_1", "value_1" );
add_c_str( obj, "name_2", "value_2" );
add_c_str( obj, "name_3", "value_3" );
check_eq( obj, "{\"name_1\":\"value_1\",\"name_2\":\"value_2\",\"name_3\":\"value_3\"}" );
check_eq_pretty( obj, "{\n"
" \"name_1\" : \"value_1\",\n"
" \"name_2\" : \"value_2\",\n"
" \"name_3\" : \"value_3\"\n"
"}" );
}
void test_obj_with_one_empty_child_obj()
{
Object_type child;
Object_type root;
add_value( root, "child", child );
check_eq( root, "{\"child\":{}}" );
check_eq_pretty( root, "{\n"
" \"child\" : {\n"
" }\n"
"}" );
}
void test_obj_with_one_child_obj()
{
Object_type child;
add_c_str( child, "name_2", "value_2" );
Object_type root;
add_value( root, "child", child );
add_c_str( root, "name_1", "value_1" );
check_eq( root, "{\"child\":{\"name_2\":\"value_2\"},\"name_1\":\"value_1\"}" );
check_eq_pretty( root, "{\n"
" \"child\" : {\n"
" \"name_2\" : \"value_2\"\n"
" },\n"
" \"name_1\" : \"value_1\"\n"
"}" );
}
void test_obj_with_grandchild_obj()
{
Object_type child_1; add_c_str( child_1, "name_1", "value_1" );
Object_type child_2;
Object_type child_3; add_c_str( child_3, "name_3", "value_3" );
add_value( child_2, "grandchild", child_3 );
add_c_str( child_2, "name_2", "value_2" );
Object_type root;
add_value( root, "child_1", child_1 );
add_value( root, "child_2", child_2 );
add_c_str( root, "name_a", "value_a" );
add_c_str( root, "name_b", "value_b" );
check_eq( root, "{\"child_1\":{\"name_1\":\"value_1\"},"
"\"child_2\":{\"grandchild\":{\"name_3\":\"value_3\"},\"name_2\":\"value_2\"},"
"\"name_a\":\"value_a\","
"\"name_b\":\"value_b\"}" );
check_eq_pretty( root, "{\n"
" \"child_1\" : {\n"
" \"name_1\" : \"value_1\"\n"
" },\n"
" \"child_2\" : {\n"
" \"grandchild\" : {\n"
" \"name_3\" : \"value_3\"\n"
" },\n"
" \"name_2\" : \"value_2\"\n"
" },\n"
" \"name_a\" : \"value_a\",\n"
" \"name_b\" : \"value_b\"\n"
"}" );
}
void test_objs_with_bool_pairs()
{
Object_type obj;
add_value( obj, "name_1", true );
add_value( obj, "name_2", false );
add_value( obj, "name_3", true );
check_eq( obj, "{\"name_1\":true,\"name_2\":false,\"name_3\":true}" );
}
void test_objs_with_int_pairs()
{
Object_type obj;
add_value( obj, "name_1", 11 );
add_value( obj, "name_2", INT_MAX );
add_value( obj, "name_3", max_int64 );
ostringstream os;
os << "{\"name_1\":11,\"name_2\":" << INT_MAX << ",\"name_3\":" << max_int64 << "}";
check_eq( obj, os.str().c_str() );
}
void test_objs_with_real_pairs()
{
Object_type obj;
add_value( obj, "name_1", 1.0 );
add_value( obj, "name_2", 1.234567890123456e-108 );
add_value( obj, "name_3", -1234567890.123456 );
add_value( obj, "name_4", -1.2e-126 );
check_eq( obj, "{\"name_1\":1.000000000000000,"
"\"name_2\":1.234567890123456e-108,"
"\"name_3\":-1234567890.123456,"
"\"name_4\":-1.200000000000000e-126}" );
}
void test_objs_with_null_pairs()
{
Object_type obj;
add_value( obj, "name_1", Value_type::null );
add_value( obj, "name_2", Value_type::null );
add_value( obj, "name_3", Value_type::null );
check_eq( obj, "{\"name_1\":null,\"name_2\":null,\"name_3\":null}" );
}
void test_empty_array()
{
check_eq( Array_type(), "[]" );
check_eq_pretty( Array_type(), "[\n"
"]" );
}
void test_array_with_one_member()
{
Array_type arr;
arr.push_back( to_str( "value" ) );
check_eq ( arr, "[\"value\"]" );
check_eq_pretty( arr, "[\n"
" \"value\"\n"
"]" );
}
void test_array_with_two_members()
{
Array_type arr;
arr.push_back( to_str( "value_1" ) );
arr.push_back( 1 );
check_eq ( arr, "[\"value_1\",1]" );
check_eq_pretty( arr, "[\n"
" \"value_1\",\n"
" 1\n"
"]" );
}
void test_array_with_n_members()
{
Array_type arr;
arr.push_back( to_str( "value_1" ) );
arr.push_back( 123 );
arr.push_back( 123.456 );
arr.push_back( true );
arr.push_back( false );
arr.push_back( Value_type() );
check_eq ( arr, "[\"value_1\",123,123.4560000000000,true,false,null]" );
check_eq_pretty( arr, "[\n"
" \"value_1\",\n"
" 123,\n"
" 123.4560000000000,\n"
" true,\n"
" false,\n"
" null\n"
"]" );
}
void test_array_with_one_empty_child_array()
{
Array_type arr;
arr.push_back( Array_type() );
check_eq ( arr, "[[]]" );
check_eq_pretty( arr, "[\n"
" [\n"
" ]\n"
"]" );
}
void test_array_with_one_child_array()
{
Array_type child;
child.push_back( 2 );
Array_type root;
root.push_back( 1 );
root.push_back( child );
check_eq ( root, "[1,[2]]" );
check_eq_pretty( root, "[\n"
" 1,\n"
" [\n"
" 2\n"
" ]\n"
"]" );
}
void test_array_with_grandchild_array()
{
Array_type child_1; child_1.push_back( 11 );
Array_type child_2; child_2.push_back( 22 );
Array_type child_3; child_3.push_back( 33 );
child_2.push_back( child_3 );
Array_type root;
root.push_back( 1);
root.push_back( child_1 );
root.push_back( child_2 );
root.push_back( 2 );
check_eq ( root, "[1,[11],[22,[33]],2]" );
check_eq_pretty( root, "[\n"
" 1,\n"
" [\n"
" 11\n"
" ],\n"
" [\n"
" 22,\n"
" [\n"
" 33\n"
" ]\n"
" ],\n"
" 2\n"
"]" );
}
void test_array_and_objs()
{
Array_type a;
a.push_back( 11 );
Object_type obj;
add_value( obj, "a", 1 );
a.push_back( obj );
check_eq ( a, "[11,{\"a\":1}]" );
check_eq_pretty( a, "[\n"
" 11,\n"
" {\n"
" \"a\" : 1\n"
" }\n"
"]" );
add_value( obj, "b", 2 );
a.push_back( 22 );
a.push_back( 33 );
a.push_back( obj );
check_eq ( a, "[11,{\"a\":1},22,33,{\"a\":1,\"b\":2}]" );
check_eq_pretty( a, "[\n"
" 11,\n"
" {\n"
" \"a\" : 1\n"
" },\n"
" 22,\n"
" 33,\n"
" {\n"
" \"a\" : 1,\n"
" \"b\" : 2\n"
" }\n"
"]" );
}
void test_obj_and_arrays()
{
Object_type obj;
add_value( obj, "a", 1 );
Array_type a;
a.push_back( 11 );
add_value( obj, "b", a );
check_eq ( obj, "{\"a\":1,\"b\":[11]}" );
check_eq_pretty( obj, "{\n"
" \"a\" : 1,\n"
" \"b\" : [\n"
" 11\n"
" ]\n"
"}" );
a.push_back( obj );
add_value( obj, "c", a );
check_eq ( obj, "{\"a\":1,\"b\":[11],\"c\":[11,{\"a\":1,\"b\":[11]}]}" );
check_eq_pretty( obj, "{\n"
" \"a\" : 1,\n"
" \"b\" : [\n"
" 11\n"
" ],\n"
" \"c\" : [\n"
" 11,\n"
" {\n"
" \"a\" : 1,\n"
" \"b\" : [\n"
" 11\n"
" ]\n"
" }\n"
" ]\n"
"}" );
}
void test_escape_char( const char* esc_str_in, const char* esc_str_out )
{
Object_type obj;
const string name_str( string( esc_str_in ) + "name" );
add_value( obj, name_str.c_str(), to_str( "value" ) + to_str( esc_str_in ) );
const string out_str( string( "{\"" ) + esc_str_out + "name\":\"value" + esc_str_out + "\"}" );
check_eq( obj, out_str.c_str() );
}
void test_escape_chars()
{
test_escape_char( "\r", "\\r" );
test_escape_char( "\n", "\\n" );
test_escape_char( "\t", "\\t" );
test_escape_char( "\f", "\\f" );
test_escape_char( "\b", "\\b" );
test_escape_char( "\"", "\\\"" );
test_escape_char( "\\", "\\\\" );
test_escape_char( "\x01", "\\u0001" );
test_escape_char( "\x12", "\\u0012" );
test_escape_char( "\x7F", "\\u007F" );
}
void test_to_stream()
{
basic_ostringstream< Char_type > os;
Array_type arr;
arr.push_back( 1 );
arr.push_back( 2 );
write( arr, os );
assert_eq( os.str(), to_str( "[1,2]" ) );
}
void test_values()
{
check_eq( 123, "123" );
check_eq( 1.234, "1.234000000000000" );
check_eq( to_str( "abc" ), "\"abc\"" );
check_eq( false, "false" );
check_eq( Value_type::null, "null" );
}
void test_uint64()
{
check_eq( Value_type( 0 ), "0" );
check_eq( Value_type( int64_t( 0 ) ), "0" );
check_eq( Value_type( uint64_t( 0 ) ), "0" );
check_eq( Value_type( 1 ), "1" );
check_eq( Value_type( int64_t( 1 ) ), "1" );
check_eq( Value_type( uint64_t( 1 ) ), "1" );
check_eq( Value_type( -1 ), "-1" );
check_eq( Value_type( int64_t( -1 ) ), "-1" );
check_eq( Value_type( max_int64 ), "9223372036854775807" );
check_eq( Value_type( uint64_t( max_int64 ) ), "9223372036854775807" );
check_eq( Value_type( max_uint64 ), "18446744073709551615" );
}
void run_tests()
{
test_empty_obj();
test_obj_with_one_member();
test_obj_with_two_members();
test_obj_with_three_members();
test_obj_with_one_empty_child_obj();
test_obj_with_one_child_obj();
test_obj_with_grandchild_obj();
test_objs_with_bool_pairs();
test_objs_with_int_pairs();
test_objs_with_real_pairs();
test_objs_with_null_pairs();
test_empty_array();
test_array_with_one_member();
test_array_with_two_members();
test_array_with_n_members();
test_array_with_one_empty_child_array();
test_array_with_one_child_array();
test_array_with_grandchild_array();
test_array_and_objs();
test_obj_and_arrays();
test_escape_chars();
test_to_stream();
test_values();
test_uint64();
}
};
#ifndef BOOST_NO_STD_WSTRING
void test_wide_esc_u( wchar_t c, const wstring& result)
{
const wstring s( 1, c );
wArray arr( 1, s );
assert_eq( write( arr ), L"[\"\\u" + result + L"\"]" );
}
void test_wide_esc_u()
{
test_wide_esc_u( 0xABCD, L"ABCD" );
test_wide_esc_u( 0xFFFF, L"FFFF" );
}
#endif
bool is_printable( char c )
{
const wint_t unsigned_c( ( c >= 0 ) ? c : 256 + c );
return iswprint( unsigned_c ) != 0;
}
void test_extended_ascii()
{
const string expeced_result( is_printable( 'ä' ) ? "[\"äöüß\"]" : "[\"\\u00E4\\u00F6\\u00FC\\u00DF\"]" );
assert_eq( write( Array( 1, "äöüß" ) ), expeced_result );
}
}
void json_spirit::test_writer()
{
Test_runner< Config >().run_tests();
Test_runner< mConfig >().run_tests();
#ifndef BOOST_NO_STD_WSTRING
Test_runner< wConfig >().run_tests();
Test_runner< wmConfig >().run_tests();
test_wide_esc_u();
#endif
test_extended_ascii();
}
| [
"[email protected]"
]
| [
[
[
1,
579
]
]
]
|
adc257b31a8ee75e66409ff1cbb317412086c2e7 | 457f3762b71be7573ec4a4ac27f7da66191ef68a | /ext/ResizableLib/ResizableVersion.cpp | 68846ef751d5f39928bd7966737ca92f5b4c6ccd | [
"Artistic-1.0"
]
| permissive | jrk/tortoisegit | 7a88b097a0d5ac48d3be5c183c97b528864e4a6d | 3943dc12e10fe923998e3367f83d9b8e709eb271 | refs/heads/master | 2021-01-19T17:42:18.472204 | 2009-02-27T03:36:58 | 2009-02-27T03:36:58 | 138,746 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,790 | cpp | // ResizableVersion.cpp: implementation of the CResizableVersion class.
//
/////////////////////////////////////////////////////////////////////////////
//
// This file is part of ResizableLib
// http://sourceforge.net/projects/resizablelib
//
// Copyright (C) 2000-2004 by Paolo Messina
// http://www.geocities.com/ppescher - mailto:[email protected]
//
// The contents of this file are subject to the Artistic License (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.opensource.org/licenses/artistic-license.html
//
// If you find this code useful, credits would be nice!
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ResizableVersion.h"
//////////////////////////////////////////////////////////////////////
// Static initializer object (with macros to hide in ClassView)
// static intializer must be called before user code
#pragma warning(disable:4073)
#pragma init_seg(lib)
#ifdef _UNDEFINED_
#define BEGIN_HIDDEN {
#define END_HIDDEN }
#else
#define BEGIN_HIDDEN
#define END_HIDDEN
#endif
BEGIN_HIDDEN
struct _VersionInitializer
{
_VersionInitializer()
{
InitRealVersions();
};
};
END_HIDDEN
// The one and only version-check object
static _VersionInitializer g_version;
//////////////////////////////////////////////////////////////////////
// Private implementation
// DLL Version support
#include <shlwapi.h>
static DLLVERSIONINFO g_dviCommCtrls;
static OSVERSIONINFOEX g_osviWindows;
static void CheckOsVersion()
{
// Try calling GetVersionEx using the OSVERSIONINFOEX structure.
SecureZeroMemory(&g_osviWindows, sizeof(OSVERSIONINFOEX));
g_osviWindows.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (GetVersionEx((LPOSVERSIONINFO)&g_osviWindows))
return;
// If that fails, try using the OSVERSIONINFO structure.
g_osviWindows.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
if (GetVersionEx((LPOSVERSIONINFO)&g_osviWindows))
return;
// When all the above fails, set values for the worst case
g_osviWindows.dwMajorVersion = 4;
g_osviWindows.dwMinorVersion = 0;
g_osviWindows.dwBuildNumber = 0;
g_osviWindows.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;
g_osviWindows.szCSDVersion[0] = TEXT('\0');
}
static void CheckCommCtrlsVersion()
{
// Check Common Controls version
SecureZeroMemory(&g_dviCommCtrls, sizeof(DLLVERSIONINFO));
HMODULE hMod = ::LoadLibrary(_T("comctl32.dll"));
if (hMod != NULL)
{
// Get the version function
DLLGETVERSIONPROC pfnDllGetVersion;
pfnDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hMod, "DllGetVersion");
if (pfnDllGetVersion != NULL)
{
// Obtain version information
g_dviCommCtrls.cbSize = sizeof(DLLVERSIONINFO);
if (SUCCEEDED(pfnDllGetVersion(&g_dviCommCtrls)))
{
::FreeLibrary(hMod);
return;
}
}
::FreeLibrary(hMod);
}
// Set values for the worst case
g_dviCommCtrls.dwMajorVersion = 4;
g_dviCommCtrls.dwMinorVersion = 0;
g_dviCommCtrls.dwBuildNumber = 0;
g_dviCommCtrls.dwPlatformID = DLLVER_PLATFORM_WINDOWS;
}
//////////////////////////////////////////////////////////////////////
// Exported global symbols
DWORD realWINVER = 0;
#ifdef _WIN32_WINDOWS
DWORD real_WIN32_WINDOWS = 0;
#endif
#ifdef _WIN32_WINNT
DWORD real_WIN32_WINNT = 0;
#endif
#ifdef _WIN32_IE
DWORD real_WIN32_IE = 0;
#endif
// macro to convert version numbers to hex format
#define CNV_OS_VER(x) ((BYTE)(((BYTE)(x) / 10 * 16) | ((BYTE)(x) % 10)))
void InitRealVersions()
{
CheckCommCtrlsVersion();
CheckOsVersion();
// set real version values
realWINVER = MAKEWORD(CNV_OS_VER(g_osviWindows.dwMinorVersion),
CNV_OS_VER(g_osviWindows.dwMajorVersion));
#ifdef _WIN32_WINDOWS
if (g_osviWindows.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
real_WIN32_WINDOWS = realWINVER;
else
real_WIN32_WINDOWS = 0;
#endif
#ifdef _WIN32_WINNT
if (g_osviWindows.dwPlatformId == VER_PLATFORM_WIN32_NT)
real_WIN32_WINNT = realWINVER;
else
real_WIN32_WINNT = 0;
#endif
#ifdef _WIN32_IE
switch (g_dviCommCtrls.dwMajorVersion)
{
case 4:
switch (g_dviCommCtrls.dwMinorVersion)
{
case 70:
real_WIN32_IE = 0x0300;
break;
case 71:
real_WIN32_IE = 0x0400;
break;
case 72:
real_WIN32_IE = 0x0401;
break;
default:
real_WIN32_IE = 0x0200;
}
break;
case 5:
if (g_dviCommCtrls.dwMinorVersion > 80)
real_WIN32_IE = 0x0501;
else
real_WIN32_IE = 0x0500;
break;
case 6:
real_WIN32_IE = 0x0600; // includes checks for 0x0560 (IE6)
break;
default:
real_WIN32_IE = 0;
}
#endif
}
| [
"[email protected]"
]
| [
[
[
1,
190
]
]
]
|
c03706ce93eaefe94ec8d13fd4bb19c4c3faa69e | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/uavobjectbrowser/browseritemdelegate.cpp | 2ee84e1f517929e41651c689eb5075d2165fa6ab | []
| 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 | 2,829 | cpp | /**
******************************************************************************
*
* @file browseritemdelegate.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 "browseritemdelegate.h"
#include "fieldtreeitem.h"
BrowserItemDelegate::BrowserItemDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
}
QWidget *BrowserItemDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem & option ,
const QModelIndex & index ) const
{
FieldTreeItem *item = static_cast<FieldTreeItem*>(index.internalPointer());
QWidget *editor = item->createEditor(parent);
Q_ASSERT(editor);
return editor;
}
void BrowserItemDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
FieldTreeItem *item = static_cast<FieldTreeItem*>(index.internalPointer());
QVariant value = index.model()->data(index, Qt::EditRole);
item->setEditorValue(editor, value);
}
void BrowserItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
FieldTreeItem *item = static_cast<FieldTreeItem*>(index.internalPointer());
QVariant value = item->getEditorValue(editor);
model->setData(index, value, Qt::EditRole);
}
void BrowserItemDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
QSize BrowserItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex &index) const
{
return QSpinBox().sizeHint();
}
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
]
| [
[
[
1,
72
]
]
]
|
30bf230c2d5ab6682e1ccc588b713d16924f1130 | 8776961f3465f885d140dd366bfe90119e49178d | /trunk/include/iccNumberDateTime.h | 04b85b7c477afb373a12134de752778e130439e7 | []
| no_license | BackupTheBerlios/icclibplusplus-svn | 7b3bc3ca2c23cbaaed2c9d45ce0e7e6c417b27c8 | 3a61ea5be2a4e725986b8586d0d63d14ef7af114 | refs/heads/master | 2021-01-19T19:39:43.301240 | 2005-02-05T10:42:08 | 2005-02-05T10:42:08 | 40,802,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,517 | h | #ifndef _H_iccNumberDateTime_H_
#define _H_iccNumberDateTime_H_
#include "iccObject.h"
#include "iccBasicNumericTypes.h"
#include <istream>
#include <ostream>
ICC_LIB_NAMESPACE_START
// Date shall be in Coordinated Universal Time (UTC)
class iccNumberDateTime: public iccObject
{
public:
iccNumberDateTime(void)
: m_year(0),m_month(0),m_day(0),
m_hours(0),m_minutes(0),m_seconds(0)
{}
friend void operator>>(std::istream& inStream,iccNumberDateTime& outNumber);
friend std::ostream& operator<<(std::ostream& outStream,const iccNumberDateTime& inNumber);
iccNumberDateTime& operator=(const iccNumberDateTime &inNumber)
{
if(this != &inNumber)
{
m_year = inNumber.m_year;
m_month = inNumber.m_month;
m_day = inNumber.m_day;
m_hours = inNumber.m_hours;
m_minutes = inNumber.m_minutes;
m_seconds = inNumber.m_seconds;
}
return *this;
}
unsigned long GetSize(void) const
{
return sizeof m_year
+ sizeof m_month
+ sizeof m_day
+ sizeof m_hours
+ sizeof m_minutes
+ sizeof m_seconds;
}
bool IsValid(void) const
{
if(m_month < 1 || 12 < m_month)
return false;
if(m_day < 1 || 31 < m_day)
return false;
else
if(
(m_month==4 || m_month==6 || m_month==9 || m_month==11)
&& 30 < m_day
)
return false;
else
if(m_month == 2 && 28 < m_day)
return false;
#pragma message("TO DO: leap years")
if(23 < m_hours)
return false;
if(59 < m_minutes)
return false;
if(59 < m_seconds)
return false;
return true;
}
void AutoCorrect(void)
{
if(m_month < 1 || 12 < m_month)
m_month = 1;
if(
(m_month==4 || m_month==6 || m_month==9 || m_month==11)
&& 30 < m_day
)
m_day = 1;
else
if(m_month == 2 && 28 < m_day)
m_day = 1;
else
if(31 < m_day)
m_day = 1;
#pragma message("TO DO: leap years")
if(23 < m_hours)
m_hours = 0;
if(59 < m_minutes)
m_minutes = 0;
if(59 < m_seconds)
m_seconds = 0;
}
private:
iccNumberUInt16 m_year;
iccNumberUInt16 m_month;
iccNumberUInt16 m_day;
iccNumberUInt16 m_hours;
iccNumberUInt16 m_minutes;
iccNumberUInt16 m_seconds;
};
#pragma message("TO DO: write conversion methods to/from local time to UTC")
//--------------------------------------------------------------------
void operator>>(std::istream& inStream,iccNumberDateTime& outNumber)
{
inStream >> outNumber.m_year;
inStream >> outNumber.m_month;
inStream >> outNumber.m_day;
inStream >> outNumber.m_hours;
inStream >> outNumber.m_minutes;
inStream >> outNumber.m_seconds;
}
//--------------------------------------------------------------------
std::ostream& operator<<(std::ostream& outStream,const iccNumberDateTime& inNumber)
{
outStream << inNumber.m_year;
outStream << inNumber.m_month;
outStream << inNumber.m_day;
outStream << inNumber.m_hours;
outStream << inNumber.m_minutes;
outStream << inNumber.m_seconds;
return outStream;
}
ICC_LIB_NAMESPACE_END
#endif//_H_iccNumberDateTime_H_
| [
"ivan_laurette@98e260e7-36eb-0310-bdc2-d94bb0a282ea"
]
| [
[
[
1,
134
]
]
]
|
08a607c0b5d98f8a6606c4e5d6d3447cfe5bc8c8 | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/framework/movie/mediatimer.cpp | 222af31d1e8a15872a6b80e0b54e82a213b30f10 | []
| no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp | #include"mediatimer.h"
#include"../../auxiliary/debug/warning.h"
static const unt TIMESTOP = ~0;
namespace Maid
{
MediaTimer::MediaTimer()
:m_StartTime(TIMESTOP)
,m_Offset(0)
{
}
void MediaTimer::Start()
{
m_StartTime = m_Timer.Get();
}
void MediaTimer::Stop()
{
if( m_StartTime==TIMESTOP ) { return ; }
const double now = Get();
m_StartTime = TIMESTOP;
m_Offset = now; // 再開用にとっておく
}
double MediaTimer::Get() const
{
if( m_StartTime==TIMESTOP ) { return m_Offset; }
const double time = double(m_Timer.Get() - m_StartTime) / 1000.0;
return time + m_Offset;
}
void MediaTimer::SetOffset( double time )
{
m_Offset = time;
}
} | [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
17f74e9bf2ad7b4b488059b3af8f26ae4a12f4f6 | 65eb241d4016d565d18e2aa9d889d13eab68fbf5 | /linucom2.2.0/qextserialport.h | 0a36272dad80efaacaa2069f33096cf71f509edf | []
| no_license | openlinux/MyApp | 3c5ac925a58bca1e8bb563d4386ed77de10c0500 | bc86b85b3d315455c1a19e779b10f5dffb4864fe | refs/heads/master | 2021-01-10T20:11:13.555628 | 2011-08-09T02:49:49 | 2011-08-09T02:49:49 | 1,699,362 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 908 | h | #ifndef _QEXTSERIALPORT_H_
#define _QEXTSERIALPORT_H_
//by hqw
#define _TTY_POSIX_
//end by
/*POSIX CODE*/
#ifdef _TTY_POSIX_
#include "posix_qextserialport.h"
#define QextBaseType Posix_QextSerialPort
/*MS WINDOWS CODE*/
#else
#include "win_qextserialport.h"
#define QextBaseType Win_QextSerialPort
#endif
class QextSerialPort: public QextBaseType
{
Q_OBJECT
public:
typedef QextSerialBase::QueryMode QueryMode;
QextSerialPort();
QextSerialPort(const QString & name, QueryMode mode = QextSerialPort::Polling);
QextSerialPort(PortSettings const& s, QueryMode mode = QextSerialPort::Polling);
QextSerialPort(const QString & name, PortSettings const& s, QueryMode mode = QextSerialPort::Polling);
QextSerialPort(const QextSerialPort& s);
QextSerialPort& operator=(const QextSerialPort&);
virtual ~QextSerialPort();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
29203ede07e8e20f6677d50ee0766d6807e342c4 | 68158fb8077a73ee2f294fd098c65f3c14995604 | /progii_01/hello.cpp | eeb66807e4de5be9396cc2afdc8983ea417b2864 | []
| no_license | tomoskozi/programozasii2010 | 6ae0f121875ba33028870907373d9be83346dff7 | 53b9908186074cf2d0248d6c6081008d8f2b7095 | refs/heads/master | 2021-01-15T13:48:25.706731 | 2010-09-13T22:28:01 | 2010-09-13T22:28:01 | 33,947,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 253 | cpp | // gyakorlatilag az stdio C++-os megfelelője
#include <iostream>
// no comment
int main()
{
// standard kimeneti stream
std::cout << "Hello World!" << std::endl;
// rendszer parancs várakoztatáshoz
system("PAUSE");
return 0;
} | [
"[email protected]@0a3ff402-c372-f730-fa5b-f08b189355ce"
]
| [
[
[
1,
14
]
]
]
|
c22e726e35b2ee5ef344b3e8d995aa98f454a1ee | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/gui_core/gui_core_kernel_1.h | f59bac112afcd50053bacdf051d5761721474e4a | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
]
| permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,412 | h | // Copyright (C) 2005 Davis E. King ([email protected]), Keita Mochizuki
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_GUI_CORE_KERNEl_1_
#define DLIB_GUI_CORE_KERNEl_1_
#ifdef DLIB_ISO_CPP_ONLY
#error "DLIB_ISO_CPP_ONLY is defined so you can't use this OS dependent code. Turn DLIB_ISO_CPP_ONLY off if you want to use it."
#endif
#ifdef DLIB_NO_GUI_SUPPORT
#error "DLIB_NO_GUI_SUPPORT is defined so you can't use the GUI code. Turn DLIB_NO_GUI_SUPPORT off if you want to use it."
#endif
#include <string>
#include "../windows_magic.h"
#include <windows.h>
#include <winuser.h>
#include <windowsx.h>
#include <commctrl.h>
#include "gui_core_kernel_abstract.h"
#ifdef _MSC_VER
// Disable the following warnings for Visual Studio
//
// These two warnings have to do with converting points to and from the LONG
// type. But both these types are 32 bits in windows so it is fine.
#pragma warning(disable: 4244; disable: 4312)
#endif
#include "../algs.h"
#include "../sync_extension.h"
#include "../binary_search_tree.h"
#include "../threads.h"
#include "../geometry/rectangle.h"
#include "../assert.h"
#include "../queue.h"
#include "../pixel.h"
#include "../unicode.h"
#include "../smart_pointers_thread_safe.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class base_window;
namespace gui_core_kernel_1_globals
{
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);
class event_handler_thread;
}
// ----------------------------------------------------------------------------------------
class canvas : public rectangle
{
public:
struct pixel
{
unsigned char blue;
unsigned char green;
unsigned char red;
};
~canvas() { }
inline pixel* operator[] (
unsigned long row
) const
{
DLIB_ASSERT(row < height(),
"\tpixel* canvas::operator[]"
<< "\n\tyou have to give a row that is less than the height()"
<< "\n\tthis: " << this
<< "\n\trow: " << row
<< "\n\theight(): " << height()
);
unsigned char* temp = bits + row_width*row;
return reinterpret_cast<pixel*>(temp);
}
void fill (
unsigned char red_,
unsigned char green_,
unsigned char blue_
) const;
private:
friend LRESULT CALLBACK gui_core_kernel_1_globals::WndProc (HWND, UINT, WPARAM, LPARAM);
canvas (
unsigned char* bits__,
unsigned long padding__,
unsigned long left__,
unsigned long top__,
unsigned long right__,
unsigned long bottom__
) :
rectangle(left__,top__,right__,bottom__),
bits(bits__),
width_(width()),
height_(height()),
row_width(width_*3+padding__)
{}
// restricted functions
canvas(); // normal constructor
canvas(canvas&); // copy constructor
canvas& operator=(canvas&); // assignment operator
unsigned char* const bits;
const unsigned long width_;
const unsigned long height_;
const unsigned long row_width;
};
template <>
struct pixel_traits<canvas::pixel>
{
const static bool rgb = true;
const static bool rgb_alpha = false;
const static bool grayscale = false;
const static bool hsi = false;
const static long num = 3;
static unsigned long max() { return 255;}
const static bool has_alpha = false;
};
// ----------------------------------------------------------------------------------------
void put_on_clipboard (
const std::string& str
);
void put_on_clipboard (
const std::wstring& str
);
void put_on_clipboard (
const dlib::ustring& str
);
// ----------------------------------------------------------------------------------------
void get_from_clipboard (
std::string& str
);
void get_from_clipboard (
std::wstring& str
);
void get_from_clipboard (
dlib::ustring& str
);
// ----------------------------------------------------------------------------------------
class base_window
{
friend LRESULT CALLBACK gui_core_kernel_1_globals::WndProc (HWND, UINT, WPARAM, LPARAM);
shared_ptr_thread_safe<gui_core_kernel_1_globals::event_handler_thread> globals;
HWND hwnd;
DWORD style;
bool has_been_destroyed;
// This is true if the mouse is in this window. false otherwise.
// also note that this variable is only accessed from the event handling thread
// (except for being initialized below in the constructor, but that is inside
// the window_table mutex so it doesn't matter).
bool mouse_in;
// this is a copy of the last inputs we sent to the on_mouse_move() event.
long prevx;
long prevy;
unsigned long prev_state;
protected:
const rmutex& wm;
public:
base_window (
bool resizable = true,
bool undecorated = false
);
virtual ~base_window (
);
void close_window (
);
bool is_closed (
) const;
void set_title (
const std::string& title
);
void set_title (
const std::wstring& title
);
void set_title (
const ustring& title
);
virtual void show (
);
virtual void hide(
);
void set_size (
int width_,
int height_
);
void set_pos (
long x_,
long y_
);
void get_pos (
long& x_,
long& y_
);
void get_size (
unsigned long& width,
unsigned long& height
) const;
void get_display_size (
unsigned long& width,
unsigned long& height
) const;
void invalidate_rectangle (
const rectangle& rect
);
void trigger_user_event (
void* p,
int i
);
void wait_until_closed (
) const;
void set_im_pos (
long x_,
long y_
);
enum on_close_return_code
{
DO_NOT_CLOSE_WINDOW,
CLOSE_WINDOW
};
enum mouse_state_masks
{
NONE = 0,
LEFT = 1,
RIGHT = 2,
MIDDLE = 4,
SHIFT = 8,
CONTROL = 16
};
enum keyboard_state_masks
{
KBD_MOD_NONE = 0,
KBD_MOD_SHIFT = 1,
KBD_MOD_CONTROL = 2,
KBD_MOD_ALT = 4,
KBD_MOD_META = 8,
KBD_MOD_CAPS_LOCK = 16,
KBD_MOD_NUM_LOCK = 32,
KBD_MOD_SCROLL_LOCK = 64
};
enum non_printable_keyboard_keys
{
KEY_BACKSPACE,
KEY_SHIFT,
KEY_CTRL,
KEY_ALT,
KEY_PAUSE,
KEY_CAPS_LOCK,
KEY_ESC,
KEY_PAGE_UP,
KEY_PAGE_DOWN,
KEY_END,
KEY_HOME,
KEY_LEFT, // This is the left arrow key
KEY_RIGHT, // This is the right arrow key
KEY_UP, // This is the up arrow key
KEY_DOWN, // This is the down arrow key
KEY_INSERT,
KEY_DELETE,
KEY_SCROLL_LOCK,
// Function Keys
KEY_F1,
KEY_F2,
KEY_F3,
KEY_F4,
KEY_F5,
KEY_F6,
KEY_F7,
KEY_F8,
KEY_F9,
KEY_F10,
KEY_F11,
KEY_F12
};
protected:
virtual on_close_return_code on_window_close(
){return CLOSE_WINDOW;}
virtual void on_user_event (
void* p,
int i
){}
virtual void on_window_resized(
){}
virtual void on_window_moved(
){}
virtual void on_mouse_down (
unsigned long btn,
unsigned long state,
long x,
long y,
bool is_double_click
){}
virtual void on_mouse_up (
unsigned long btn,
unsigned long state,
long x,
long y
){}
virtual void on_mouse_move (
unsigned long state,
long x,
long y
){}
virtual void on_mouse_leave (
){}
virtual void on_mouse_enter (
){}
virtual void on_wheel_up (
unsigned long state
){}
virtual void on_wheel_down (
unsigned long state
){}
virtual void on_focus_gained (
){}
virtual void on_focus_lost (
){}
virtual void on_keydown (
unsigned long key,
bool is_printable,
unsigned long state
){}
virtual void on_string_put (
const std::wstring &str
){}
private:
virtual void paint (
const canvas& c
) =0;
base_window(base_window&); // copy constructor
base_window& operator=(base_window&); // assignment operator
};
// ----------------------------------------------------------------------------------------
}
#ifdef NO_MAKEFILE
#include "gui_core_kernel_1.cpp"
#endif
#endif // DLIB_GUI_CORE_KERNEl_1_
| [
"jimmy@DGJ3X3B1.(none)"
]
| [
[
[
1,
417
]
]
]
|
fb3995971e03f820b4967944e1501778dbf35d99 | be0db8bf2276da4b71a67723bbe8fb75e689bacb | /Src/App/app.cpp | d7a2402d90cd04a84229bc77c375840799216c26 | []
| no_license | jy02140486/cellwarfare | 21a8eb793b94b8472905d793f4b806041baf57bb | 85f026efd03f12dd828817159b9821eff4e4aff0 | refs/heads/master | 2020-12-24T15:22:58.595707 | 2011-07-24T12:36:45 | 2011-07-24T12:36:45 | 32,970,508 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,962 | cpp | #include "app.h"
#include "../libs/querryback.h"
#include "../Libs/Converter.h"
#include <time.h>
#define FPS 44
T_App::T_App()
{
/* code */
}
int T_App::start()
{
srand (time(NULL));
if (init() == false)
{
return -1;
}
global_state=STRATGY;
int fps=FPS;
mrk=GetTickCount();
while (!mQuit)
{
if (GetTickCount()-mrk>1000/fps)
{
mGui.exec(false);
loop();
mrk=GetTickCount();
}
else Sleep(1000.0/fps-(GetTickCount()-mrk));
}
return 0;
}
void T_App::onMouseUp(const CL_InputEvent &, const CL_InputState &)
{
switch(global_state)
{
case TATICAL:
{
bf* tbf=entites->curBF;
if(tbf->SOselected==NULL||tbf->datas->ImmunityPoints<=0)
{
tbf->SOselected=NULL;
return;
}
CL_Vec2i cannon(tbf->SOselected->pos->x,tbf->SOselected->pos->y);
CL_Vec2i mouse=mMouse.get_position();
b2Vec2 b2cannon=Converter::Vec2from_c_to_b(cannon);
b2Vec2 b2mouse=Converter::Vec2from_c_to_b(mouse);
b2Vec2 dir=b2mouse-b2cannon;
switch(tbf->SOselected->ObjState)
{
case ScrObj::LYMPH:
tbf->launchTC(dir);
break;
case ScrObj::CANNON:
tbf->launchWC(dir);
break;
}
tbf->datas->ImmunityPoints--;
tbf->SOselected=NULL;
}break;
}
}
void T_App::onMouseDown(const CL_InputEvent &, const CL_InputState &)
{
switch(global_state)
{
case STRATGY:
{
if (mpComWindow->get_client_area().contains(mMouse.get_position()))
{
return;
}
;
ScrObj*temp=entites->ScrObjTraversal();
if (temp!=NULL)
{
// if(entites->SOselected!=NULL)
// if (intruders==0)
// entites->SOselected->ObjState=ScrObj::NORMAL;
// else entites->SOselected->ObjState=ScrObj::INTRUDED;
entites->SOselected=temp;
ScrObjSelect();
}else
{
//entites->SOselected=NULL;
infoBF->set_visible(false);
}break;
}
case TATICAL:
bf* tbf=entites->curBF;
ScrObj*temp=entites->ScrObjTraversal(tbf->head);
if (temp!=NULL)
tbf->SOselected=temp;
break;
//default:temp;
}
}
void T_App::onMouseMove(const CL_InputEvent &, const CL_InputState &)
{
mx->set_text(mMouse.get_x());
my->set_text(mMouse.get_y());
}
int T_App::eventInit()
{
//ÅäÖÃʼþ²å²Û
slotMouseMove = mMouse.sig_pointer_move().connect(this,
&T_App::onMouseMove);
slotMouseDown = mMouse.sig_key_down().connect(this,
&T_App::onMouseDown);
slotMouseUp=mMouse.sig_key_up().connect(this,
&T_App::onMouseUp);
slotKeyboardUp=mKeyboard.sig_key_up().connect(this,
&T_App::onKeyboardUp);
return 0;
}
void T_App::onKeyboardUp(const CL_InputEvent &key,
const CL_InputState &state)
{
}
void T_App::StateSwitching(GLOBAL_STATE newstate)
{
switch(global_state)
{
case STRATGY:
//mpComWindow->set_visible(false);
cirfirm->set_text("Quit");
infoBF->set_visible(false);
TaticalBoard->set_visible(true);
break;
case TATICAL:
cirfirm->set_text("Enter");
infoBF->set_visible(true);
// TaticalBoard->set_visible(false);
break;
}
global_state=newstate;
switch(global_state)
{
case TATICAL:
break;
}
}
void T_App::ButtonClick()
{
//
switch(global_state)
{
case STRATGY:
if (entites->SOselected!=NULL)
{
entites->setcurBF(entites->SOselected->datas);
char *temp=new char(10);
sprintf(temp,"%d",entites->SOselected->datas->ImmunityPoints);
CL_StringRef str=temp;
Tcellsdeployed->set_text(temp);
StateSwitching(TATICAL);
}
break;
case TATICAL:
StateSwitching(STRATGY);
// entites->curBF->DataSynchronize(entites->SOselected->datas);
entites->retreat();
entites->SOselected->ObjState=ScrObj::NORMAL;
entites->curBF->~bf();
// delete entites->curBF;
break;
default:;
}
}
void T_App::ScrObjSelect()
{
ScrObj*temp=entites->SOselected;
cellsdeployed->set_value(temp->datas->ImmunityPoints);
intruders->set_value(temp->datas->intruder);
if (temp->timer!=NULL)
{
// timeleft->set_max(temp->timer->length);
timeleft->set_position(entites->SOselected->timer->length-entites->SOselected->timer->get_curSec());
}
infoBF->set_visible(true);
char tempt[10];
sprintf(tempt,"%d",entites->SOselected->datas->intruder);
CL_StringRef str=tempt;
Tintruders->set_text(tempt);
}
void T_App::invading_LogicLayer_Failure()
{
if (global_state==STRATGY)
{
int i=RandomVal::int_from_to(0,3);
int ti=RandomVal::int_from_to(10,28);
ScrObj*temp=entites->head;
for(int j=0;j<i;j++)
{
temp=temp->next;
}
if (temp->ObjState!=ScrObj::INTRUDED)
{
timingtarget=entites->curLV;
entites->curLV->defbfs[i].intruder=ti;
intruders->set_value(ti);
temp->ObjState=ScrObj::INTRUDED;
temp->timer=new Timer();
Timer* tt=temp->timer;
int ttime=ti+8;
tt->init(ttime,false);
temp->datas->timeleft=ttime;
tt->begin(false);
tt->func_expired().set(this,&T_App::Ttimesup);
CL_Console::write_line("aa");
}
}
}
void T_App::Ttimesup()
{
CL_Console::write_line("call");
//entites->hero->HP->minus();
for(ScrObj* temp=entites->head;temp!=NULL;temp=temp->next)
{
if(temp->timer!=NULL)
if(timingtarget==entites->curLV)
if (temp->timer->get_curSec()<=0)
{
entites->hero->HP->minus(temp->datas->intruder);
temp->ObjState=ScrObj::NORMAL;
break;
}
}
}
void T_App::updateBoard()
{
char *temp=new char(10);
sprintf(temp,"%d",entites->SOselected->datas->ImmunityPoints);
CL_StringRef str=temp;
Tcellsdeployed->set_text(temp);
}
void T_App::takePill()
{
if (!entites->hero->painkiller->minusable(1))
{
return;
}
for(ScrObj*temp=entites->head;temp!=NULL;temp=temp->next)
{
temp->ObjState=ScrObj::NORMAL;
temp->datas->intruder=0;
}
entites->hero->painkiller->minus(1);
entites->hero->HP->minus(20);
} | [
"[email protected]@7e182df5-b8f1-272d-db4e-b61a9d634eb1"
]
| [
[
[
1,
294
]
]
]
|
c33a56b675181bb8b9eb470c02e7f3da5a503c92 | 9ad9345e116ead00be7b3bd147a0f43144a2e402 | /Integration_WAH_&_Extraction/SMDataExtraction/SMDataExtraction/EncodedMultiCatAttribute.h | 4bb0b04e5592155638f1fcafca0d37664bbd134d | []
| no_license | asankaf/scalable-data-mining-framework | e46999670a2317ee8d7814a4bd21f62d8f9f5c8f | 811fddd97f52a203fdacd14c5753c3923d3a6498 | refs/heads/master | 2020-04-02T08:14:39.589079 | 2010-07-18T16:44:56 | 2010-07-18T16:44:56 | 33,870,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,734 | h | #pragma once
#include "VBitStream.h"
#include "AttributeType.h"
#include "EncodedAttributeInfo.h"
#include "StringSpecAssignVals.h"
#include "boost/dynamic_bitset.hpp";
#include "SEEDMinerExceptions.h"
#include <vector>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <algorithm>
using namespace boost;
using namespace std;
/************************************************************************/
/* Class :EncodedMultiCatAttribute.h
/* Started:25.02.2010 21:45:12
/* Updated:22.04.2010 06:13:19
/* Author :SEEDMiner
/* Subj :An Attribute class that is inheriting from the Attribute.h
/* class, this particular class stores whatever the specific
/* behaviours and attributes in String data type.
/* Version:
/************************************************************************/
class EncodedMultiCatAttribute : public EncodedAttributeInfo
{
public:
#pragma region Constructors & Destructor
__declspec(dllexport) EncodedMultiCatAttribute(void);
__declspec(dllexport) ~EncodedMultiCatAttribute(void);
#pragma endregion Constructors & Destructor
#pragma region Getters & Setters
__declspec(dllexport) void setMappedValList(vector<dynamic_bitset<>> & _mapped_vals);
__declspec(dllexport) vector<dynamic_bitset<>> mappedValList();
__declspec(dllexport) vector<string> uniqueValList();
__declspec(dllexport) void setUniqueValList(vector<string> uniques){this->_uniqueValList = uniques;this->_noOfUniqueVals = uniques.size();}
__declspec(dllexport) int* getMappedIntVals();
__declspec(dllexport) int noOfUniqueValues();
#pragma endregion Getters & Setters
/** Concrete implementation of the Decoding the tuple according to the string attribute type*/
__declspec(dllexport) string decodeTheTuple(int tupleID) throw(error_vector_out_of_range);
/** Method to map string data to integer values according to the positioning of those values in*/
/** the unique value list*/
__declspec(dllexport) dynamic_bitset<>* mapStringDataToCategories(vector<string> _valueList,std::set<string> _uniqueValList,int noOfRows);
/** Binary Search Implementation to find a particular value from the unique value list*/
int binarySearch(vector<string> arr, string value, int left, int right);
/** Initialization method to instantiate instance variables*/
void Init();
/** Keeping unique value list as a map to access more efficiently*/
void setUniqueMap();
private:
int* _mappedIntVals;
vector<dynamic_bitset<>> _mappedValList;
dynamic_bitset<> *_mappedVals;
vector<string> _uniqueValList;
map<string,int> _uniqueValueMap;
map<string,int>::iterator _it;
int _noOfUniqueVals;
};
| [
"jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1",
"samfernandopulle@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
]
| [
[
[
1,
1
],
[
3,
7
],
[
9,
9
],
[
17,
19
],
[
31,
33
],
[
37,
38
],
[
44,
46
],
[
48,
49
],
[
58,
58
],
[
61,
61
],
[
64,
64
],
[
67,
77
]
],
[
[
2,
2
],
[
8,
8
],
[
10,
16
],
[
20,
30
],
[
34,
36
],
[
39,
43
],
[
47,
47
],
[
50,
57
],
[
59,
60
],
[
62,
63
],
[
65,
66
]
]
]
|
b5041171b8e69c77bed5a05d6fa8d5884caae01f | 640a36607eb5b185eceb733643dda918221a40a4 | /Sever/lib/IOCPFramework/BehaviorCreateMainThread.cpp | 6df00e4bb2f587bd3bbe4de15acb2b1880fc2ab5 | []
| no_license | degravata/simple-flash-mmorpg | 13cc97665e89dc8a0c6218a9a6ebc5c44217fc7d | 71138defc786ce757eae8d6fc6bd53d16bf44e63 | refs/heads/master | 2016-09-12T10:38:44.046533 | 2011-01-25T07:51:25 | 2011-01-25T07:51:25 | 56,880,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,373 | cpp | #include "BehaviorCreateMainThread.h"
namespace SevenSmile{
namespace Net{
namespace IOCPFramework{
namespace Behavior{
BehaviorCreateMainThread::BehaviorCreateMainThread(void)
{
this->_lpBaseBehaviorMsgDeal=0;
//this->_lpIBMsgDealManage=0;
_hMainThread=NULL;
//_dwMainThreadId=NULL;
_hEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
_initRes=0;
Init();
strcpy_s(ADDR,"127.0.0.1");
PORT=5555;
SYSTEM_INFO sys_info;
GetSystemInfo( &sys_info );
_intMaxExecuteThreadNum =
sys_info.dwNumberOfProcessors > MAXTHREAD_COUNT ? MAXTHREAD_COUNT : sys_info.dwNumberOfProcessors;
//_intPostNum=POST_NUMBER;
//创建主线程
_hMainThread = CreateThread(
NULL,
0,
&ServerRoutine,
(LPVOID)this,
CREATE_SUSPENDED,
//&_dwMainThreadId
NULL
);
}
BehaviorCreateMainThread::BehaviorCreateMainThread(
char* i_lpCharIpAddr,
int i_intPort,
int i_intExecuteThreadNum)
{
Init();
strcpy_s(ADDR,i_lpCharIpAddr);
PORT =i_intPort;
_intMaxExecuteThreadNum=i_intExecuteThreadNum;
//创建主线程
_hMainThread = CreateThread(
NULL,
0,
&ServerRoutine,
(LPVOID)this,
CREATE_SUSPENDED,
//&_dwMainThreadId
NULL
);
}
void BehaviorCreateMainThread::Init(void){
_lpBaseBehaviorMsgDeal=NULL;
_lpMainListenIOCPKey=NULL;
_lpBehaviorMsgSend=NULL;
}
BehaviorCreateMainThread::~BehaviorCreateMainThread(void)
{
//关闭线程,这里要换用让线程退出的方法。
if(NULL!=this->_hArrThread){
for (int i=0;i<this->_intMaxExecuteThreadNum;i++)
{
if(NULL!=_hArrThread[i]){
TerminateThread(_hArrThread[i],NULL);
CloseHandle(_hArrThread[i]);
}
}
delete[] _hArrThread;
_hArrThread=NULL;
}
TerminateThread(_hMainThread,NULL);
if (NULL!=this->_lpMainListenIOCPKey){
delete _lpMainListenIOCPKey;
_lpMainListenIOCPKey=NULL;
}
if (NULL!=_lpMainListenIOCPKey){
delete _lpMainListenIOCPKey;
_lpMainListenIOCPKey=NULL;
}
if (NULL!=_lpBehaviorMsgSend){
delete _lpBehaviorMsgSend;
_lpBehaviorMsgSend=NULL;
}
}
void BehaviorCreateMainThread::SetListenSoketIPAddr(const char* i_lpChar){
strcpy_s(ADDR,i_lpChar);
}
void BehaviorCreateMainThread::SetListenSoketPort(int i_intPort){
//strcpy_s(ADDR,i_lpChar);
PORT=i_intPort;
}
void BehaviorCreateMainThread::SetExecuteThreadNum(int i_intThreadNum){
this->_intMaxExecuteThreadNum=i_intThreadNum;
}
//void SetPostNum(int i_intPostNum);
/*-------------------------------------------------------------------------------------------
函数功能:主循环
函数说明:
函数返回:成功,TRUE;失败,FALSE
-------------------------------------------------------------------------------------------*/
bool BehaviorCreateMainThread::MainLoop(void)
{
DWORD dwRet;
while(1)
{
dwRet = WaitForSingleObject(_hAcceptEvent,1000);
switch( dwRet )
{
case WAIT_FAILED:
{
PostQueuedCompletionStatus(_hIOCP,0,0,NULL);
return FALSE;
}
break;
case WAIT_TIMEOUT:
{
//CheckForInvalidConnection();
}
break;
case WAIT_OBJECT_0: //接收到了所有发出的连接都用光了的消息,再次发出连接
{
if( !PostAcceptEx() )
{
PostQueuedCompletionStatus(_hIOCP,0,0,NULL);
return FALSE;
}
}
break;
}
}
return TRUE;
}
DWORD BehaviorCreateMainThread::ServerRoutine(LPVOID lp){
//这里运行主线程初始化工作
BehaviorCreateMainThread* lpBehaviorCreateMainThread=(BehaviorCreateMainThread*) lp;
lpBehaviorCreateMainThread->_initRes = lpBehaviorCreateMainThread->InitIOCP();
SetEvent(lpBehaviorCreateMainThread->_hEvent);
if(lpBehaviorCreateMainThread->_initRes==0){
lpBehaviorCreateMainThread->MainLoop();
}
return 0;
}
int BehaviorCreateMainThread::Start(int i_intStartSeconds){
ResumeThread(_hMainThread);
WaitForSingleObject(_hEvent,INFINITE);
return _initRes;
}
int BehaviorCreateMainThread::InitIOCP(){
WSAData data;
if(WSAStartup( MAKEWORD(2,2),&data)){
//throw "WSAStartup fail!";
return 1;
}
_lpBehaviorMsgSend=new BaseBehavior::BaseBehaviorMsgSend();
this->_lpBaseBehaviorMsgDeal->SetBehaviorMsgSend(this->_lpBehaviorMsgSend);
_hIOCP=CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,NULL,0);
if( NULL == _hIOCP ){
return 2;
}
if( !InitSocket() ){
PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
//AddMessage("Init sociket fail!");
CloseHandle( _hIOCP );
return 3;
}
//启动处理线程
if( !StartThread() ){
//AddMessage("start thread fail!");
PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
CloseHandle( _hIOCP );
return 4;
}
if( !BindAndListenSocket() ){
PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
CloseHandle( _hIOCP );
closesocket( _soketMainListenSoket );
return 5;
}
//函数指针化
if( !GetFunPointer() ){
//cout<<"GetFunPointer fail!"<<endl;
PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
CloseHandle( _hIOCP );
closesocket( _soketMainListenSoket );
return 6;
}
//发送acceptEx
if( !PostAcceptEx() ){
PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
//cout<<"PostAcceptEx fail!"<<endl;
CloseHandle( _hIOCP );
closesocket( _soketMainListenSoket );
return 7;
}
//注册事件
if( !RegAcceptEvent() ){
PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
//cout<<"RegAcceptEvent fail!"<<endl;
CloseHandle( _hIOCP );
closesocket( _soketMainListenSoket );
return 8;
}
return 0;
}
/*-------------------------------------------------------------------------------------------
函数功能:初始化侦听SOCKET端口,并和完成端口连接起来。
函数说明:
函数返回:成功,TRUE;失败,FALSE
-------------------------------------------------------------------------------------------*/
bool BehaviorCreateMainThread::InitSocket(){
_soketMainListenSoket = WSASocket(
AF_INET,
SOCK_STREAM,
IPPROTO_TCP,
NULL,
0,
WSA_FLAG_OVERLAPPED
);
if( INVALID_SOCKET == _soketMainListenSoket ){
return FALSE;
}
//IOCP_KEY_PTR lp_key = m_key_group.GetBlank();
_lpMainListenIOCPKey = new IOCP_KEY();
_lpMainListenIOCPKey->socket = _soketMainListenSoket;
HANDLE hRet = CreateIoCompletionPort(
(HANDLE)_soketMainListenSoket,
_hIOCP,
(DWORD)_lpMainListenIOCPKey,
0
);
if(hRet == NULL){
closesocket( _soketMainListenSoket );
//m_key_group.RemoveAt( lp_key );
return FALSE;
}
return TRUE;
}
/*-------------------------------------------------------------------------------------------
函数功能:将侦听端口和自己的IP,PORT绑定,并开始侦听
函数说明:
函数返回:成功,TRUE;失败,FALSE
-------------------------------------------------------------------------------------------*/
bool BehaviorCreateMainThread::BindAndListenSocket(){
SOCKADDR_IN addr;
memset( &addr, 0, sizeof(SOCKADDR_IN) );
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr( ADDR );
addr.sin_port = htons( PORT );
int nRet;
nRet = bind( _soketMainListenSoket, (SOCKADDR*)&addr, sizeof( SOCKADDR ) );
if( SOCKET_ERROR == nRet ){
return FALSE;
}
nRet = listen( _soketMainListenSoket, 20 );
if( SOCKET_ERROR == nRet ){
return FALSE;
}
return TRUE;
}
/*-------------------------------------------------------------------------------------------
函数功能:根据CPU的数目,启动相应数量的数据处理线程
函数说明:
函数返回:成功,TRUE;失败,FALSE
-------------------------------------------------------------------------------------------*/
bool BehaviorCreateMainThread::StartThread()
{
int i;
//SYSTEM_INFO sys_info;
//GetSystemInfo( &sys_info );
//int intThreadCount = sys_info.dwNumberOfProcessors > MAXTHREAD_COUNT ? MAXTHREAD_COUNT : sys_info.dwNumberOfProcessors;
int intThreadCount = this->_intMaxExecuteThreadNum;
_hArrThread=new HANDLE[intThreadCount];
//_dwArrThreadIds=new DWORD[intThreadCount];
for( i = 0; i < intThreadCount; i++ )
{
_hArrThread[i] = CreateThread(
NULL,
0,
CompletionRoutine,
(LPVOID)this,
0,
//&(_dwArrThreadIdsl[i])
NULL
);
if( NULL == _hArrThread[i] ){
CloseThreadHandle( i );
CloseHandle( _hIOCP );
return FALSE;
}
}
return TRUE;
}
//执行线程的回调函数
DWORD BehaviorCreateMainThread::CompletionRoutine(LPVOID lp_param){
BehaviorCreateMainThread* lp_this = (BehaviorCreateMainThread*)lp_param;
int nRet;
BOOL bRet;
DWORD dwBytes = 0;
HANDLE hRet;
IOCP_KEY* lp_key = NULL;
IOCP_IO* lp_io = NULL;
LPWSAOVERLAPPED lp_ov = NULL;
IOCP_KEY* lp_new_key = NULL;
while(1)
{
bRet = GetQueuedCompletionStatus(
lp_this->_hIOCP,
&dwBytes,
(LPDWORD)&lp_key,
&lp_ov,
INFINITE
);
lp_io = (IOCP_IO*)lp_ov;
if(lp_io->operation==0){
}else if(lp_io->operation==1){
//lp_this->AddMessage(lp_io->buf);
}else if(lp_io->operation==2){
}
if( FALSE == bRet )
{
//cout << "GetQueuedCompletionStatus() failed: " << GetLastError() << endl;
lp_this->Remove(lp_io,lp_key);
continue;
}
if( NULL == lp_key )
{
return 0;
}
if( lp_io == NULL )
{
//cout<<"recv a null CIoContext!"<<endl;
continue;
}
if( ( IOCP_ACCEPT != lp_io->operation ) && ( 0 == dwBytes ) )
{
closesocket( lp_io->socket );
lp_this->_lpBaseBehaviorMsgDeal->MsgQuit(lp_io);
//lp_this->_lpBaseBehaviorMsgDeal->MsgQuit(lp_io->socket);
lp_this->Remove(lp_io,lp_key);
continue;
}
switch( lp_io->operation )
{
case IOCP_ACCEPT:
{
// cout<<"接收到一个连接"<<endl;
//lp_this->GetAddrAndPort(lp_io);
lp_io->state = SOCKET_STATE_CONNECT;
if( dwBytes > 0 )
{
lp_io->state = SOCKET_STATE_CONNECT_AND_READ;
//cout<<"读取到一条数据"<<endl;
}
nRet = setsockopt(
lp_io->socket,
SOL_SOCKET,
SO_UPDATE_ACCEPT_CONTEXT,
( char* )&lp_this->_soketMainListenSoket,
sizeof( lp_this->_soketMainListenSoket ) );
if( SOCKET_ERROR == nRet ){
closesocket( lp_io->socket );
lp_this->_lpBaseBehaviorMsgDeal->MsgQuit(lp_io);
lp_this->_ioGroup.RemoveAt( lp_io );
//cout<<"update socket fail!"<<WSAGetLastError()<<endl;
continue;
}
lp_new_key = lp_this->_keyGroup.GetBlank();
if( lp_new_key == NULL ){
closesocket( lp_io->socket );
lp_this->_ioGroup.RemoveAt( lp_io );
//cout<<"get a handle fail!"<<GetLastError()<<endl;
continue;
}
lp_new_key->socket = lp_io->socket;
//将新建立的SOCKET同完成端口关联起来。
hRet = CreateIoCompletionPort(
( HANDLE )lp_io->socket,
lp_this->_hIOCP,
(DWORD)lp_new_key,0 );
if( NULL == hRet ){
closesocket( lp_io->socket );
lp_this->_keyGroup.RemoveAt( lp_new_key );
lp_this->_ioGroup.RemoveAt( lp_io );
//cout<<"link to iocp fail!"<<WSAGetLastError()<<endl;
continue;
}
//处理读取到的数据
if( dwBytes > 0 ){
//lp_io->wsaBuf.len = dwBytes;
//lp_this->HandleData( lp_io, IOCP_COMPLETE_ACCEPT_READ );
//bRet = lp_this->DataAction( lp_io, lp_new_key );
//if( FALSE == bRet )
//{
// continue;
//}
}
else{
//lp_this->HandleData( lp_io, IOCP_COMPLETE_ACCEPT );
//bRet = lp_this->DataAction( lp_io, lp_new_key );
lp_this->InitIoContext( lp_io );
lp_io->operation = IOCP_READ;
lp_this->ContinueRecv(lp_io, lp_new_key);
if( FALSE == bRet ){
continue;
}
}
}
break;
case IOCP_READ:
{
if( SOCKET_STATE_CONNECT_AND_READ != lp_io->state )
{
lp_io->state = SOCKET_STATE_CONNECT_AND_READ;
}
lp_io->wsaBuf.len = dwBytes;
//处理用户发送的信息
//lp_this->otherClass.translateMsg(lp_io->socket,lp_io->buf,len);
//发送给用户信息
//lp_this->_lpBaseBehaviorMsgDeal->
//if (lp_this->MsgSend(lp_io->socket,"12345678",3)==FALSE){
//这里是游戏逻辑处理。
//if (lp_this->_lpBaseBehaviorMsgDeal->MsgDeal(lp_io,lp_io->buf,dwBytes)==FALSE)
//if (lp_this->_lpIBMsgDealManage->MsgDealManage(
// &BaseBehavior::BaseBehaviorMsgDeal::MsgDeal,
// lp_io,
// lp_io->buf,
// dwBytes
// )==FALSE)
if (lp_this->_lpIBMsgDealManage->MsgDealManage(lp_this,lp_io,lp_io->buf,dwBytes)==FALSE)
{
lp_this->_lpBaseBehaviorMsgDeal->MsgQuit(lp_io);
closesocket( lp_io->socket );
lp_this->_ioGroup.RemoveAt( lp_io );
lp_this->_keyGroup.RemoveAt(lp_key);
continue;
}
else{
lp_this->ContinueRecv(lp_io,lp_key);
}
}
break;
case IOCP_WRITE:
{
//lp_this->_lpBaseBehaviorMsgDeal->RemoveSendObj(sendObj);
lp_this->_lpBehaviorMsgSend->Remove(lp_io);
//cout<<lp_io->buf<<endl;
//lp_this->_ioSendGroup.RemoveAt( lp_io );
/*lp_this->HandleData( lp_io, IOCP_COMPLETE_WRITE );
bRet = lp_this->DataAction( lp_io, lp_key );
continue;
if( FALSE == bRet )
{
continue;
}*/
//lp_this->ContinueRecv(lp_io,lp_key);
}
break;
default:
{
continue;
}
break;
}
}
//lp_this->AddMessage("io over");
return 0;
}
//bool BehaviorCreateMainThread::MsgSend(SOCKET s,char* buf,int len)
//{
// DWORD dwBytes;
// int nRet;
//
// //IOCP_IO io;
// ////WSABUF wsaBuf;
// ////WSAOVERLAPPED ol;
// //io.operation=IOCP_WRITE;
// //memset( &io.ol, 0, sizeof( WSAOVERLAPPED ) );
// //char msg[BUFFER_SIZE];
// //memset( &msg, 0, BUFFER_SIZE );
// //io.wsaBuf.buf = msg;
// //io.wsaBuf.len = BUFFER_SIZE;
// ////SOCKET socket;
// //io.socket=s;
// //
// //memcpy(msg,buf,len);
// //io.wsaBuf.buf =msg;
// //io.wsaBuf.len=len;
// //nRet = WSASend(
// // io.socket,
// // &io.wsaBuf,
// // 1,
// // &dwBytes,
// // 0,
// // &io.ol,NULL);
//
// WSABUF wsaBuf;
// WSAOVERLAPPED ol;
//
// memset( &ol, 0, sizeof( WSAOVERLAPPED ) );
// char msg[BUFFER_SIZE];
// memset( &msg, 0, BUFFER_SIZE );
// wsaBuf.buf = msg;
// wsaBuf.len = BUFFER_SIZE;
// SOCKET socket;
// socket=s;
// memcpy(msg,buf,len);
// wsaBuf.buf =msg;
// wsaBuf.len=len;
// nRet = WSASend(
// socket,
// &wsaBuf,
// 1,
// &dwBytes,
// 0,
// &ol,NULL);
// if( ( nRet == SOCKET_ERROR ) && ( WSAGetLastError() != WSA_IO_PENDING ) )
// {
// return FALSE;
// }
// return TRUE;
//}
//bool BehaviorCreateMainThread::MsgSend()
//{
// return TRUE;
//}
bool BehaviorCreateMainThread::ContinueRecv(IOCP_IO* lp_io,IOCP_KEY* lp_key)
{
DWORD dwBytes;
int nRet;
DWORD dwFlags;
InitIoContext( lp_io );
lp_io->operation = IOCP_READ;
dwFlags = 0;
nRet = WSARecv(
lp_io->socket,
&lp_io->wsaBuf,
1,
&dwBytes,
&dwFlags,
&lp_io->ol,NULL);
if((nRet==SOCKET_ERROR ) && ( WSAGetLastError() != WSA_IO_PENDING ) )
{
_lpBaseBehaviorMsgDeal->MsgQuit(lp_io);
closesocket( lp_io->socket );
_ioGroup.RemoveAt( lp_io );
_keyGroup.RemoveAt( lp_key );
return FALSE;
}
return TRUE;
}
void BehaviorCreateMainThread::Remove(IOCP_IO* lp_io,IOCP_KEY* lp_key)
{
_ioGroup.RemoveAt( lp_io );
//if(lp_key!=NULL){
_keyGroup.RemoveAt( lp_key );
//}
//UpdPlayerList();
}
///*-------------------------------------------------------------------------------------------
//函数功能:得到连接上来的客户端IP和PORT
//函数说明:
//函数返回:成功,TRUE;失败,FALSE
//-------------------------------------------------------------------------------------------*/
//bool BehaviorCreateMainThread::GetAddrAndPort(IOCP_IO* lp_io)
//{
// int nLocalLen, nRmoteLen;
// SOCKADDR_IN *pLocalAddr, *pRemoteAddr;
// lpGetAcceptExSockaddrs(lp_io->buf,
// 0,
// sizeof(SOCKADDR_IN) + 16, //同上
// sizeof(SOCKADDR_IN) + 16, //同上
// (SOCKADDR **)&pLocalAddr,
// &nLocalLen,
// (SOCKADDR **)&pRemoteAddr,
// &nRmoteLen);
// lp_io->ip=inet_ntoa(pRemoteAddr->sin_addr);
// lp_io->port=ntohs(pRemoteAddr->sin_port);
// return TRUE;
//}
///*-------------------------------------------------------------------------------------------
//函数功能:处理数据函数
//函数说明:
//函数返回:成功,TRUE;失败,FALSE
//-------------------------------------------------------------------------------------------*/
//bool BehaviorCreateMainThread::HandleData(IOCP_IO* lp_io, int nFlags)
//{
// switch( nFlags )
// {
// case IOCP_COMPLETE_ACCEPT:
// {
// //cout<<"Accept a link!*****************************"<<endl;
// InitIoContext( lp_io );
// lp_io->operation = IOCP_READ;
// }
// break;
// case IOCP_COMPLETE_ACCEPT_READ:
// {
// //cout<<"read a data!*******************************data length is:"<<endl;
// lp_io->operation = IOCP_WRITE;
// memset( &lp_io->ol, 0, sizeof(lp_io->ol) );
// }
// break;
// case IOCP_COMPLETE_READ:
// {
// //cout<<"IOCP_COMPLETE_READ!*******************************"<<endl;
// lp_io->operation = IOCP_WRITE;
// memset( &lp_io->ol, 0, sizeof(lp_io->ol) );
// }
// break;
// case IOCP_COMPLETE_WRITE:
// {
// //cout<<"IOCP_COMPLETE_WRITE!******************************"<<endl;
// InitIoContext( lp_io );
// lp_io->operation = IOCP_READ;
// }
// break;
// default:
// {
// //cout<<"handleData do nothing!*********************"<<endl;
// return FALSE;
// }
// }
// return TRUE;
//}
/*-------------------------------------------------------------------------------------------
函数功能:关闭所有线程
函数说明:
函数返回:
-------------------------------------------------------------------------------------------*/
void BehaviorCreateMainThread::CloseThreadHandle(int count)
{
if( count <= 0 )
{
return;
}
for( int i= 0; i < count; i++ )
{
CloseHandle( _hArrThread[i] );
_hArrThread[i] = INVALID_HANDLE_VALUE;
}
}
/*-------------------------------------------------------------------------------------------
函数功能:得到MS封装的SOCKET函数指针,这样可以提高速度
函数说明:
函数返回:成功,TRUE;失败,FALSE
-------------------------------------------------------------------------------------------*/
bool BehaviorCreateMainThread::GetFunPointer()
{
DWORD dwRet,nRet;
nRet = WSAIoctl(
_soketMainListenSoket,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&g_GUIDAcceptEx,
sizeof(g_GUIDAcceptEx),
&lpAcceptEx,
sizeof(lpAcceptEx),
&dwRet,NULL,NULL);
if( SOCKET_ERROR == nRet )
{
closesocket( _soketMainListenSoket );
//AddMessage("get acceptex fail!");
return FALSE;
}
//nRet = WSAIoctl(
// m_listen_socket,
// SIO_GET_EXTENSION_FUNCTION_POINTER,
// &g_GUIDTransmitFile,
// sizeof(g_GUIDTransmitFile),
// &lpTransmitFile,
// sizeof(lpTransmitFile),
// &dwRet,NULL,NULL);
//if(nRet == SOCKET_ERROR )
//{
// closesocket( m_listen_socket );
// AddMessage("get transmitfile fail!");
// return FALSE;
//}
//nRet = WSAIoctl(
// m_listen_socket,
// SIO_GET_EXTENSION_FUNCTION_POINTER,
// &g_GUIDGetAcceptExSockaddrs,
// sizeof(g_GUIDGetAcceptExSockaddrs),
// &lpGetAcceptExSockaddrs,
// sizeof(lpGetAcceptExSockaddrs),
// &dwRet,NULL,NULL);
return TRUE;
}
/*-------------------------------------------------------------------------------------------
函数功能:发出一定数量的连接
函数说明:
函数返回:成功,TRUE;失败,FALSE
-------------------------------------------------------------------------------------------*/
bool BehaviorCreateMainThread::PostAcceptEx()
{
int count = POST_NUMBER;
DWORD dwBytes;
BOOL bRet;
for( int i = 0; i < count; i++ )
{
SOCKET socket = WSASocket(
AF_INET,
SOCK_STREAM,
IPPROTO_TCP,
NULL,
0,
WSA_FLAG_OVERLAPPED);
if( INVALID_SOCKET == socket )
{
continue;
}
IOCP_IO* lp_io = _ioGroup.GetBlank();
InitIoContext( lp_io );
lp_io->socket = socket;
lp_io->operation = IOCP_ACCEPT;
lp_io->state = SOCKET_STATE_NOT_CONNECT;
/////////////////////////////////////////////////
bRet = lpAcceptEx(
_soketMainListenSoket,
lp_io->socket,
lp_io->buf,
// lp_io->wsaBuf.len - ((sizeof(SOCKADDR_IN) + 16) * 2),
0,
sizeof(SOCKADDR_IN) + 16,
sizeof(SOCKADDR_IN) + 16,
&dwBytes,&lp_io->ol);
if( ( bRet == FALSE ) && ( WSA_IO_PENDING != WSAGetLastError() ) )
{
closesocket( socket );
_ioGroup.RemoveAt( lp_io );
//AddMessage("post acceptex fail:");
continue;
}
}
return TRUE;
}
/*-------------------------------------------------------------------------------------------
函数功能:初始化IO结点
函数说明:
函数返回:
-------------------------------------------------------------------------------------------*/
void BehaviorCreateMainThread::InitIoContext(IOCP_IO* lp_io)
{
memset( &lp_io->ol, 0, sizeof( WSAOVERLAPPED ) );
memset( &lp_io->buf, 0, BUFFER_SIZE );
lp_io->wsaBuf.buf = lp_io->buf;
lp_io->wsaBuf.len = BUFFER_SIZE;
}
/*-------------------------------------------------------------------------------------------
函数功能:注册FD_ACCEPTG事件到m_h_accept_event事件,以便所有发出去的连接耗耗尽时,得到通知。
函数说明:
函数返回:成功,TRUE;失败,FALSE
-------------------------------------------------------------------------------------------*/
bool BehaviorCreateMainThread::RegAcceptEvent()
{
int nRet;
_hAcceptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
if( NULL == _hAcceptEvent )
{
return FALSE;
}
nRet = WSAEventSelect( _soketMainListenSoket, _hAcceptEvent, FD_ACCEPT );
if( nRet != 0 )
{
CloseHandle( _hAcceptEvent );
return FALSE;
}
return TRUE;
}
void BehaviorCreateMainThread::SetBehaviorMsgDeal(BaseBehavior::BaseBehaviorMsgDeal* i_lpBaseBehaviorMsgDeal){
this->_lpBaseBehaviorMsgDeal=i_lpBaseBehaviorMsgDeal;
}
void BehaviorCreateMainThread::SetIBMsgDealManage( BaseBehavior::IBMsgDealManage* i_lpIBMsgDealManage )
{
this->_lpIBMsgDealManage=i_lpIBMsgDealManage;
}
//void BehaviorCreateMainThread::SetBehaviorMsgSend(BaseBehavior::BaseBehaviorMsgSend* i_lpBaseBehaviorMsgSend){
// //this->_lpBaseBehaviorMsgSend=i_lpBaseBehaviorMsgSend;
// //this->_lpBaseBehaviorMsgSend=i_lpBaseBehaviorMsgSend;
//}
//void BehaviorCreateMainThread::SetBehaviorQuit(BaseBehavior::BaseBehaviorQuit* i_lpBaseBehaviorBehaviorQuit){
// this->_lpBaseBehaviorQuit=i_lpBaseBehaviorBehaviorQuit;
//}
//void BehaviorCreateMainThread::SetBehaviorMsgSend(SOCKET s,char* buf,int len){
// this->_lpBaseBehaviorMsgDeal=i_lpBaseBehaviorMsgDeal;
//}
//void BehaviorCreateMainThread::SetBehaviorQuit(){
//}
}
}
}
} | [
"fangtong8752@60e69123-55e6-9807-5f38-cd17b4386222"
]
| [
[
[
1,
973
]
]
]
|
c4dc1f52c83b98d0560e4b03e3b7f2c90080553e | 672d939ad74ccb32afe7ec11b6b99a89c64a6020 | /FileSystem/fswizard/FSWizard.cpp | f19de564831f92cbeb4273da9584d0b22c8c2b89 | []
| no_license | cloudlander/legacy | a073013c69e399744de09d649aaac012e17da325 | 89acf51531165a29b35e36f360220eeca3b0c1f6 | refs/heads/master | 2022-04-22T14:55:37.354762 | 2009-04-11T13:51:56 | 2009-04-11T13:51:56 | 256,939,313 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,182 | cpp | // FSWizard.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "FSWizard.h"
#include "FSWizardDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CFSWizardApp
BEGIN_MESSAGE_MAP(CFSWizardApp, CWinApp)
//{{AFX_MSG_MAP(CFSWizardApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CFSWizardApp construction
CFSWizardApp::CFSWizardApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CFSWizardApp object
CFSWizardApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CFSWizardApp initialization
BOOL CFSWizardApp::InitInstance()
{
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CFSWizardDlg dlg;
m_pSplash = new CAlphaSplashDlg;
// m_pSplash->Create(this);
m_pSplash->DoModal();
// m_pSplash->OnInitSplash();
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"xmzhang@5428276e-be0b-f542-9301-ee418ed919ad"
]
| [
[
[
1,
77
]
]
]
|
ef072e7cd283d2827113f8b52c89544ee2b0d2b8 | 21868e763ab7ee92486a16164ccf907328123c00 | /syntaxhighlighter.cpp | 0047c23dd399cbd93d3f06cfa3da1e37c346a670 | []
| no_license | nodesman/flare | 73aacd54b5b59480901164f83905cf6cc77fe2bb | ba95fbfdeec1d557056054cbf007bf485c8144a6 | refs/heads/master | 2020-05-09T11:17:15.929029 | 2011-11-26T16:54:07 | 2011-11-26T16:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,120 | cpp | #include "syntaxhighlighter.h"
#include "settings.h"
#include <QtGui>
#include "syntaxhighlighter.h"
SyntaxHighlighter::SyntaxHighlighter(QString theType, QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
keywordFormat.setForeground(Qt::darkBlue);
keywordFormat.setFontWeight(QFont::Bold);
if (theType == "Flex")
this->flexrules();
else if (theType == "HTML")
this->htmlrules();
else if (theType == "PHP")
this->phprules();
else if (theType == "JS")
this->jsrules();
else if (theType == "CSS")
this->cssrules();
classFormat.setFontWeight(QFont::Bold);
classFormat.setForeground(Qt::darkMagenta);
rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b");
rule.format = classFormat;
highlightingRules.append(rule);
singleLineCommentFormat.setForeground(Qt::red);
rule.pattern = QRegExp("//[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
multiLineCommentFormat.setForeground(Qt::red);
quotationFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("\".*\"");
rule.format = quotationFormat;
highlightingRules.append(rule);
functionFormat.setFontItalic(true);
functionFormat.setForeground(Qt::blue);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rule.format = functionFormat;
highlightingRules.append(rule);
commentStartExpression = QRegExp("/\\*");
commentEndExpression = QRegExp("\\*/");
}
void SyntaxHighlighter::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules) {
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = commentStartExpression.indexIn(text);
while (startIndex >= 0) {
int endIndex = commentEndExpression.indexIn(text, startIndex);
int commentLength;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex
+ commentEndExpression.matchedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = commentStartExpression.indexIn(text, startIndex + commentLength);
}
}
void SyntaxHighlighter::flexrules()
{
HighlightingRule rule;
QStringList keywordPatterns;
keywordPatterns << ">" << "mx:[a-zA-Z]+";
keywordFormat.setForeground(Qt::darkGreen);
keywordFormat.setFontWeight(QFont::Bold);
foreach (const QString &pattern, keywordPatterns) {
rule.pattern = QRegExp(pattern);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
}
void SyntaxHighlighter::cssrules()
{
HighlightingRule rule;
QStringList keywordPatterns;
QFile cssrulefile("./settings/cssrules.rul");
cssrulefile.open(QIODevice::ReadOnly);
QTextStream reader(&cssrulefile);
while (!reader.atEnd())
{
QString theLine = reader.readLine();
keywordPatterns.append(theLine);
}
//keywordPatterns << ">" << "mx:[a-zA-Z]+";
keywordFormat.setForeground(Qt::darkGreen);
keywordFormat.setFontWeight(QFont::Bold);
foreach (const QString &pattern, keywordPatterns) {
rule.pattern = QRegExp(pattern);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
}
void SyntaxHighlighter::phprules()
{
}
void SyntaxHighlighter::jsrules()
{
}
void SyntaxHighlighter::htmlrules()
{
}
| [
"[email protected]"
]
| [
[
[
1,
137
]
]
]
|
2471c87f32fc8856cd2dfadfe06bffe2c23d1890 | 555ce7f1e44349316e240485dca6f7cd4496ea9c | /DirectShowFilters/TsReader/source/TsDuration.cpp | 32d1ec95997e7bef5c2a64bda399e2f57a8b75dc | []
| 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 | 8,840 | cpp | /*
* Copyright (C) 2005 Team MediaPortal
* http://www.team-mediaportal.com
*
* 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, 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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include <afx.h>
#include <afxwin.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <streams.h>
#include "TsDuration.h"
#include "..\..\shared\AdaptionField.h"
extern void LogDebug(const char *fmt, ...) ;
CTsDuration::CTsDuration()
{
m_videoPid=-1;
}
CTsDuration::~CTsDuration(void)
{
}
void CTsDuration::SetFileReader(FileReader* reader)
{
m_reader=reader;
}
void CTsDuration::Set(CPcr& startPcr, CPcr& endPcr, CPcr& maxPcr)
{
m_startPcr=startPcr;
m_endPcr=endPcr;
m_maxPcr=maxPcr;
if (!m_firstStartPcr.IsValid)
{
m_firstStartPcr=m_startPcr;
}
}
void CTsDuration::SetVideoPid(int pid)
{
m_videoPid=pid;
}
int CTsDuration::GetPid()
{
if (m_videoPid>0) return m_videoPid;
return m_pid;
}
//*********************************************************
// Determines the total duration of the file (or timeshifting files)
//
//
void CTsDuration::UpdateDuration()
{
byte buffer[32712];
DWORD dwBytesRead;
int Loop=5 ;
do
{
m_bSearchStart=true;
m_bSearchEnd=false;
m_bSearchMax=false;
m_startPcr.Reset();
m_maxPcr.Reset();
m_reader->SetFilePointer(0,FILE_BEGIN);
Reset() ; // Reset internal "PacketSync" buffer
//find the first pcr in the file
while (!m_startPcr.IsValid)
{
if (!SUCCEEDED(m_reader->Read(buffer,sizeof(buffer),&dwBytesRead)))
{
//park filepointer at end of file
m_reader->SetFilePointer(-1,FILE_END);
m_reader->Read(buffer,1,&dwBytesRead);
return;
}
if (dwBytesRead==0)
{
//park filepointer at end of file
m_reader->SetFilePointer(-1,FILE_END);
m_reader->Read(buffer,1,&dwBytesRead);
return;
}
OnRawData(buffer,dwBytesRead);
}
//find the last pcr in the file
m_bSearchEnd=true;
m_bSearchStart=false;
m_endPcr.Reset();
__int64 offset=sizeof(buffer);
__int64 fileSize=m_reader->GetFileSize();
while (!m_endPcr.IsValid)
{
DWORD dwBytesRead;
m_reader->SetFilePointer(-offset,FILE_END);
if (!SUCCEEDED(m_reader->Read(buffer,sizeof(buffer),&dwBytesRead)))
{
break;
}
if (dwBytesRead==0)
{
break;
}
Reset() ; // Reset internal "PacketSync" buffer
OnRawData(buffer,dwBytesRead);
offset+=sizeof(buffer);
}
Loop-- ;
if(m_endPcr.PcrReferenceBase < m_startPcr.PcrReferenceBase)
{
if (Loop < 4) // Show log on 2nd wrong detection.
LogDebug("Abnormal start PCR, endPcr %I64d, startPcr %I64d",m_endPcr.PcrReferenceBase, m_startPcr.PcrReferenceBase);
Sleep(20) ;
}
}
while ((m_endPcr.PcrReferenceBase < m_startPcr.PcrReferenceBase) && Loop) ;
// When startPcr > endPcr, it could be a result of wrong file used to find "startPcr".
// If this file is just reused by TsWriter, and list buffer not updated yet, the search will operate
// in the latest ts packets received causing the start higher the end ( readed in the previous buffer )
// The only thing to do to discriminate an error and a real rollover is to re-search startPcr.
// Entering the following code with erroneous startPcr > endPcr makes an endless loop !!
// The startPcr read can also failed when it occurs between deleting and reusing the ts buffer.
// This abort the method. Duration will be updated on next call.
if (Loop==0)
LogDebug("PCR rollover normally found ! endPcr %I64d, startPcr %I64d",m_endPcr.PcrReferenceBase, m_startPcr.PcrReferenceBase);
else
{
if(Loop<3) // 1 failed + 1 succeded is quasi-normal, more is a bit suspicious ( disk drive too slow or problem ? )
LogDebug("Recovered wrong start PCR, seek to 'begin' on reused file ! ( Retried %d times )",4-Loop) ;
}
//When the last pcr < first pcr then a pcr roll over occured
//find where in the file this rollover happened
//and fill maxPcr
if (m_endPcr.PcrReferenceBase < m_startPcr.PcrReferenceBase)
{
//PCR rollover
m_bSearchMax=true;
m_bSearchEnd=false;
__int64 offset=sizeof(buffer);
while (!m_maxPcr.IsValid)
{
DWORD dwBytesRead;
m_reader->SetFilePointer(-offset,FILE_END);
if (!SUCCEEDED(m_reader->Read(buffer,sizeof(buffer),&dwBytesRead)))
{
break;
}
if (dwBytesRead==0)
{
break;
}
Reset() ; // Reset internal "PacketSync" buffer
OnRawData(buffer,dwBytesRead);
offset+=sizeof(buffer);
}
}
//park filepointer at end of file
m_reader->SetFilePointer(-1,FILE_END);
m_reader->Read(buffer,1,&dwBytesRead);
}
void CTsDuration::OnTsPacket(byte* tsPacket)
{
CTsHeader header(tsPacket);
CAdaptionField field;
field.Decode(header,tsPacket);
if (field.Pcr.IsValid)
{
if (m_bSearchStart)
{
if ( (m_videoPid>0 && header.Pid==m_videoPid) || m_videoPid<0)
{
m_pid=header.Pid;
m_startPcr=field.Pcr;
m_bSearchStart=false;
if (!m_firstStartPcr.IsValid)
{
m_firstStartPcr=m_startPcr;
}
}
}
if (m_bSearchEnd && m_pid==header.Pid)
{
m_endPcr=field.Pcr;
}
if (m_bSearchMax && m_pid==header.Pid)
{
if (field.Pcr.ToClock() > m_startPcr.ToClock())
{
m_maxPcr=field.Pcr;
}
}
}
}
//*********************************************************
// returns the duration in REFERENCE_TIME
// of the file (or timeshifting files)
CRefTime CTsDuration::Duration()
{
if (m_maxPcr.IsValid)
{
double duration= m_endPcr.ToClock() + (m_maxPcr.ToClock()- m_startPcr.ToClock());
CPcr pcr;
pcr.FromClock(duration);
//LogDebug("Duration:%f %s", duration, pcr.ToString());
CRefTime refTime((LONG)(duration*1000.0f));
return refTime;
}
else
{
double duration= m_endPcr.ToClock() - m_startPcr.ToClock();
CPcr pcr;
pcr.FromClock(duration);
//LogDebug("Duration:%f %s", duration, pcr.ToString());
CRefTime refTime((LONG)(duration*1000.0f));
return refTime;
}
}
//*********************************************************
// returns the total duration in REFERENCE_TIME
// of the file (or timeshifting files) since start of playback
// The TotalDuration() >= Duration() since the timeshifting files may have been
// wrapped and reused.
CRefTime CTsDuration::TotalDuration()
{
if (m_maxPcr.IsValid)
{
double duration= m_endPcr.ToClock() + (m_maxPcr.ToClock()- m_firstStartPcr.ToClock());
CPcr pcr;
pcr.FromClock(duration);
//LogDebug("Duration:%f %s", duration, pcr.ToString());
CRefTime refTime((LONG)(duration*1000.0f));
return refTime;
}
else
{
double duration= m_endPcr.ToClock() - m_firstStartPcr.ToClock();
CPcr pcr;
pcr.FromClock(duration);
//LogDebug("Duration:%f %s", duration, pcr.ToString());
CRefTime refTime((LONG)(duration*1000.0f));
return refTime;
}
}
///*********************************************************
///returns the earliest pcr we've encountered since we started playback
///Needed for timeshifting files since when
///timeshifting files are wrapped and being re-used, we 'loose' the first pcr
CPcr CTsDuration::FirstStartPcr()
{
return m_firstStartPcr;
}
///*********************************************************
///returns the earliest pcr currently available in the file/timeshifting files
CPcr CTsDuration::StartPcr()
{
return m_startPcr;
}
///*********************************************************
///returns the latest pcr
CPcr CTsDuration::EndPcr()
{
return m_endPcr;
}
///*********************************************************
///returns the pcr after which the pcr roll over happened
CPcr CTsDuration::MaxPcr()
{
return m_maxPcr;
}
| [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
20
],
[
26,
27
],
[
29,
73
],
[
75,
76
],
[
78,
78
],
[
80,
80
],
[
92,
92
],
[
109,
109
],
[
116,
116
],
[
118,
118
],
[
132,
132
],
[
156,
165
],
[
167,
178
],
[
180,
303
]
],
[
[
21,
23
]
],
[
[
24,
25
]
],
[
[
28,
28
]
],
[
[
74,
74
],
[
77,
77
],
[
79,
79
],
[
81,
91
],
[
93,
108
],
[
110,
115
],
[
117,
117
],
[
119,
131
],
[
133,
155
],
[
166,
166
],
[
179,
179
],
[
304,
304
]
]
]
|
80e6258243a1f311ae0da139d162dd8db9ce3f80 | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/core/Query/PlaylistSave.cpp | 857d2f658f578834ee617ce9cc173845de76416d | [
"BSD-3-Clause"
]
| permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | ISO-8859-9 | C++ | false | false | 4,597 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright © 2008, Daniel Önnerby
//
// 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 author nor the names of other 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 "../pch.hpp"
#include <core/Query/PlaylistSave.h>
#include <core/Library/Base.h>
#include <core/LibraryTrack.h>
using namespace musik::core;
//////////////////////////////////////////
///\brief
///Constructor
//////////////////////////////////////////
Query::PlaylistSave::PlaylistSave(void){
}
//////////////////////////////////////////
///\brief
///Destructor
//////////////////////////////////////////
Query::PlaylistSave::~PlaylistSave(void){
}
void Query::PlaylistSave::SavePlaylist(const utfstring playlistName,int playlistId,musik::core::tracklist::IRandomAccess *tracklist){
this->playlistId = playlistId;
this->playlistName = playlistName;
this->tracks.clear();
if(tracklist){
for(int i(0);i<tracklist->Size();++i){
// LibraryTrack *t = (LibraryTrack*)(*tracklist)[i].get();
this->tracks.push_back( (*tracklist)[i]->Id() );
}
}
}
bool Query::PlaylistSave::ParseQuery(Library::Base *library,db::Connection &db){
db::ScopedTransaction transaction(db);
{
db::Statement updatePlaylist("INSERT OR REPLACE INTO playlists (id,name,user_id) VALUES (?,?,?)",db);
if(this->playlistId!=0){
updatePlaylist.BindInt(0,this->playlistId);
}
updatePlaylist.BindTextUTF(1,this->playlistName);
updatePlaylist.BindInt(2,library->userId);
if( updatePlaylist.Step()==db::Done ){
if(this->playlistId==0){
this->playlistId = db.LastInsertedId();
}
}
}
{
db::Statement deleteTracks("DELETE FROM playlist_tracks WHERE playlist_id=?",db);
deleteTracks.BindInt(0,this->playlistId);
deleteTracks.Step();
}
db::Statement insertTracks("INSERT INTO playlist_tracks (track_id,playlist_id,sort_order) VALUES (?,?,?)",db);
for(int i(0);i<this->tracks.size();++i){
insertTracks.BindInt(0,this->tracks[i]);
insertTracks.BindInt(1,this->playlistId);
insertTracks.BindInt(2,i);
insertTracks.Step();
insertTracks.Reset();
}
return true;
}
//////////////////////////////////////////
///\brief
///Copy a query
///
///\returns
///A shared_ptr to the Query::Base
//////////////////////////////////////////
Query::Ptr Query::PlaylistSave::copy() const{
return Query::Ptr(new Query::PlaylistSave(*this));
}
bool Query::PlaylistSave::RunCallbacks(Library::Base *library){
bool callCallbacks(false);
{
boost::mutex::scoped_lock lock(library->libraryMutex);
if( (this->status & Status::Ended)!=0){
callCallbacks = true;
}
}
if(callCallbacks){
this->PlaylistSaved(this->playlistId);
}
return callCallbacks;
}
| [
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e",
"Urioxis@6a861d04-ae47-0410-a6da-2d49beace72e",
"[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e"
]
| [
[
[
1,
36
],
[
38,
39
],
[
41,
66
],
[
69,
136
]
],
[
[
37,
37
]
],
[
[
40,
40
],
[
67,
68
]
]
]
|
ef6f020c28e3c439527bea54b31f0b6a8c792bc4 | 9f2d447c69e3e86ea8fd8f26842f8402ee456fb7 | /shooting2011/shooting2011/movePattern.h | d138f0a14f70625576cebd5797a8bdb380b9a085 | []
| no_license | nakao5924/projectShooting2011 | f086e7efba757954e785179af76503a73e59d6aa | cad0949632cff782f37fe953c149f2b53abd706d | refs/heads/master | 2021-01-01T18:41:44.855790 | 2011-11-07T11:33:44 | 2011-11-07T11:33:44 | 2,490,410 | 0 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,205 | h |
#ifndef __MOVEPATTERN_H__
#define __MOVEPATTERN_H__
#include "movingObject.h"
class MovingObject;
class MovePattern{
public:
virtual void action(MovingObject *) {};
virtual ~MovePattern() {};
//virtual void vanishAction(MovingObject *)=0;
int frame;
};
class MovePatternUniformlyAcceleratedLinearMotion : public MovePattern{
public:
double vx,vy,v,theta,ax,ay;
MovePatternUniformlyAcceleratedLinearMotion(double vx,double vy,double a = 0);
void action(MovingObject *);
};
typedef MovePatternUniformlyAcceleratedLinearMotion MovePatternStraight; //nakao
class MovePatternLissajous : public MovePattern{
public:
double ampx,freqx,deltax;
double ampy,freqy,deltay;
//中心の位置
double posx,posy;
MovePatternLissajous(double,double,double,double,double,double,double,double);
void action(MovingObject *);
};
class MovePatternHero : public MovePattern{
public:
int heroId;
MovePatternHero(int _heroId);
void action(MovingObject *);
};
class MovePatternCircle : public MovePattern{
double theta,v,omega;
public:
MovePatternCircle(double theta,double r,double omega);
void action(MovingObject *);
~MovePatternCircle();
};
#endif | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
10
],
[
15,
18
],
[
22,
27
],
[
34,
37
],
[
39,
39
],
[
49,
49
]
],
[
[
11,
14
],
[
19,
21
],
[
28,
33
],
[
38,
38
],
[
40,
48
],
[
50,
50
]
]
]
|
1156b503425d13df3a4d262456593871c6040594 | b6c9433cefda8cfe76c8cb6550bf92dde38e68a8 | /epoc32/include/tools/stlport/stl/_stdexcept_base.h | a0f0a640bf225d066b227f0f093bc53ad060dcf7 | []
| no_license | fedor4ever/public-headers | 667f8b9d0dc70aa3d52d553fd4cbd5b0a532835f | 3666a83565a8de1b070f5ac0b22cc0cbd59117a4 | refs/heads/master | 2021-01-01T05:51:44.592006 | 2010-03-31T11:33:34 | 2010-03-31T11:33:34 | 33,378,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,391 | h | /*
* Copyright (c) 1996,1997
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef _STLP_INTERNAL_STDEXCEPT_BASE
#define _STLP_INTERNAL_STDEXCEPT_BASE
#if !defined (_STLP_USE_NATIVE_STDEXCEPT) || defined (_STLP_USE_OWN_NAMESPACE)
# ifndef _STLP_INTERNAL_EXCEPTION
# include <stl/_exception.h>
# endif
# if defined(_STLP_USE_EXCEPTIONS) || \
!(defined(_MIPS_SIM) && defined(_ABIO32) && (_MIPS_SIM == _ABIO32))
# ifndef _STLP_INTERNAL_CSTRING
# include <stl/_cstring.h>
# endif
# ifndef _STLP_STRING_FWD_H
# include <stl/_string_fwd.h>
# endif
# ifndef _STLP_USE_NO_IOSTREAMS
# define _STLP_OWN_STDEXCEPT 1
# endif
_STLP_BEGIN_NAMESPACE
/* We disable the 4275 warning for
* - WinCE where there are only static version of the native C++ runtime.
* - The MSVC compilers when the STLport user wants to make an STLport dll linked to
* the static C++ native runtime. In this case the std::exception base class is no more
* exported from native dll but is used as a base class for the exported __Named_exception
* class.
*/
# if defined (_STLP_WCE_NET) || \
defined (_STLP_USE_DYNAMIC_LIB) && defined (_STLP_USING_CROSS_NATIVE_RUNTIME_LIB)
# define _STLP_DO_WARNING_POP
# pragma warning (push)
# pragma warning (disable: 4275) // Non dll interface class 'exception' used as base
// for dll-interface class '__Named_exception'
# endif
# if !defined (_STLP_NO_EXCEPTION_HEADER)
# if !defined (_STLP_EXCEPTION_BASE) && !defined (_STLP_BROKEN_EXCEPTION_CLASS) && \
defined (_STLP_USE_NAMESPACES) && defined (_STLP_USE_OWN_NAMESPACE)
using _STLP_VENDOR_EXCEPT_STD::exception;
# endif
# endif
# define _STLP_EXCEPTION_BASE exception
class _STLP_CLASS_DECLSPEC __Named_exception : public _STLP_EXCEPTION_BASE {
public:
__Named_exception(const string& __str)
# ifndef _STLP_USE_NO_IOSTREAMS
;
const char* what() const _STLP_NOTHROW_INHERENTLY;
~__Named_exception() _STLP_NOTHROW_INHERENTLY;
# else
{
# if !defined (_STLP_USE_SAFE_STRING_FUNCTIONS)
strncpy(_M_name, _STLP_PRIV __get_c_string(__str), _S_bufsize);
# else
strncpy_s(_STLP_ARRAY_AND_SIZE(_M_name), _STLP_PRIV __get_c_string(__str), _S_bufsize);
# endif
_M_name[_S_bufsize - 1] = '\0';
}
const char* what() const _STLP_NOTHROW_INHERENTLY { return _M_name; }
# endif
private:
enum { _S_bufsize = 256 };
char _M_name[_S_bufsize];
};
# if defined (_STLP_DO_WARNING_POP)
# pragma warning (pop)
# undef _STLP_DO_WARNING_POP
# endif
_STLP_END_NAMESPACE
# endif /* Not o32, and no exceptions */
#endif /* _STLP_STDEXCEPT_SEEN */
#endif /* _STLP_INTERNAL_STDEXCEPT_BASE */
| [
"[email protected]"
]
| [
[
[
1,
102
]
]
]
|
586512510a371a267e7e1f5bf6fd06fb4861b196 | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/CryEngine/CryCommon/CREPolyMesh.h | 75f9254028737bd07956d0912c75a4a15742d54d | []
| no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,438 | h |
#ifndef __CREPOLYMESH_H__
#define __CREPOLYMESH_H__
//=============================================================
struct SPolyStat
{
int NumOccPolys;
int NumRendPolys;
int NumDetails;
int NumRendDetails;
int NumVerts;
int NumIndices;
};
class CREFlareGeom;
struct SMTriVert
{
Vec3 vert;
float dTC[2];
float lmTC[2];
UCol color;
};
class CREPolyMesh : public CRendElementBase
{
private:
public:
Plane m_Plane;
void *Srf;
int NumVerts;
int NumIndices;
SMTriVert *TriVerts;
bool *bNoDeform;
uint16 *Indices;
int NumLightRE;
int mFrameBr;
static SPolyStat mRS;
static void mfPrintStat();
public:
CREPolyMesh()
{
mfSetType(eDATA_Mesh);
mfSetFlags(FCEF_TRANSFORM | FCEF_NEEDFILLBUF);
NumLightRE = 0;
bNoDeform = NULL;
TriVerts = NULL;
Indices = NULL;
}
virtual ~CREPolyMesh();
void mfCheckSun(CShader *ef);
bool mfCullFace(ECull cl);
virtual CRendElementBase *mfCopyConstruct(void);
virtual void mfCenter(Vec3& centr, CRenderObject*pObj);
virtual int mfTransform(Matrix44& ViewMatr, Matrix44& ProjMatr, vec4_t *verts, vec4_t *vertsp, int Num);
virtual void mfPrepare(bool bCheckOverflow);
virtual void mfGetPlane(Plane& pl);
virtual void GetMemoryUsage(ICrySizer *pSizer) const
{
pSizer->AddObject(this, sizeof(*this));
}
};
#endif // __CREPOLYMESH_H__
| [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
8bd750d061c23cf2e6c954cc159aae9680fa584d | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Interface/WndTitle.cpp | 95170a2b64a67b395d4feba1f235513155ab62da | []
| no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UHC | C++ | false | false | 95,434 | cpp | // WndArcane.cpp: implementation of the CWndNeuz class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "defineObj.h"
#include "defineText.h"
#include "AppDefine.h"
#include "DPLoginClient.h"
#include "DPClient.h"
#include "dpCertified.h"
#include "wndCredit.h"
#include "..\_Common\Debug.h"
#include "webbox.h"
#include "WndManager.h"
#include "Network.h"
extern CDPLoginClient g_dpLoginClient;
extern CDPClient g_DPlay;
extern CDPCertified g_dpCertified;
#include "NPGameLib4.h"
extern CNPGameLib* GetNProtect();
extern BYTE nMaleHairColor[10][3];
extern BYTE nFeMaleHairColor[10][3];
#ifdef __CERTIFIER_COLLECTING_SYSTEM
#include "DPCollectClient.h"
#endif // __CERTIFIER_COLLECTING_SYSTEM
BOOL GetIePath( LPSTR lpPath )
{
LONG result;
HKEY hKey;
DWORD dwType;
char data[MAX_PATH];
DWORD dataSize = MAX_PATH+1;
result = ::RegOpenKeyEx ( HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\IEXPLORE.EXE", 0, KEY_QUERY_VALUE, &hKey );
if (result == ERROR_SUCCESS)
{
result = ::RegQueryValueEx ( hKey, "Path", NULL, &dwType, (unsigned char *)data, &dataSize );
strcpy( lpPath, data );
lpPath[lstrlen( lpPath )-1] = '\0';
}
else
return FALSE;
RegCloseKey( hKey );
return TRUE;
}
BOOL CWndConnectingBox::Initialize( CWndBase* pWndParent, DWORD nType )
{
CRect rect = m_pWndRoot->MakeCenterRect( 250, 130 );
/*
Create( _T( "매시지 박스" ), MB_CANCEL, rect, APP_MESSAGEBOX );
m_wndText.SetString( _T( "접속중입니다. 잠시만 기다려 주십시오." ) );
*/
Create( _T( prj.GetText(TID_DIAG_0068) ), /*MB_CANCEL*/0xFFFFFFFF, rect, APP_MESSAGEBOX );
m_wndText.SetString( _T( prj.GetText(TID_DIAG_0064) ) );
m_wndText.ResetString();
return CWndMessageBox::Initialize( pWndParent, 0 );
}
BOOL CWndConnectingBox::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult )
{
return TRUE;
}
BOOL CWndCharBlockBox::Initialize( CWndBase* pWndParent, DWORD nType )
{
CRect rect = m_pWndRoot->MakeCenterRect( 250, 130 );
/*
Create( _T( "매시지 박스" ), MB_CANCEL, rect, APP_MESSAGEBOX );
m_wndText.SetString( _T( "사용할수 없는 캐릭터 입니다" ) );
*/
Create( _T( prj.GetText(TID_DIAG_0068) ), MB_CANCEL, rect, APP_MESSAGEBOX );
m_wndText.SetString( _T( prj.GetText(TID_DIAG_0073) ) );
m_wndText.ResetString();
return CWndMessageBox::Initialize( pWndParent, 0 );
}
BOOL CWndCharBlockBox::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult )
{
if( message == WNM_CLICKED )
{
switch(nID)
{
case IDCANCEL:
//Destroy();
break;
}
}
return CWndMessageBox::OnChildNotify( message, nID, pLResult );
}
BOOL CWndAllCharBlockBox::Initialize( CWndBase* pWndParent, DWORD nType )
{
CRect rect = m_pWndRoot->MakeCenterRect( 250, 130 );
/*
Create( _T( "매시지 박스" ), MB_CANCEL, rect, APP_MESSAGEBOX );
m_wndText.SetString( _T( "접속할수 없는 계정입니다" ) );
*/
Create( _T( prj.GetText(TID_DIAG_0068) ), MB_CANCEL, rect, APP_MESSAGEBOX );
m_wndText.SetString( _T( prj.GetText(TID_DIAG_0074) ) );
m_wndText.ResetString();
return CWndMessageBox::Initialize( pWndParent, 0 );
}
BOOL CWndAllCharBlockBox::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult )
{
if( message == WNM_CLICKED )
{
switch(nID)
{
case IDCANCEL:
{
g_dpLoginClient.DeleteDPObject();
CWndSelectChar* pWndSelectChar
= (CWndSelectChar*)g_WndMng.GetWndBase( APP_SELECT_CHAR );
if( pWndSelectChar )
{
pWndSelectChar->Destroy();
}
g_dpCertified.SendCertify();
GetNProtect()->Send( (LPCSTR)g_Neuz.m_szAccount );
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_LOGIN );
CWndBase* pWndBase = g_WndMng.GetWndBase( APP_LOGIN );
}
//Destroy();
break;
}
}
return CWndMessageBox::OnChildNotify( message, nID, pLResult );
}
//////////////////////////////////////////////////////////////////////////////////
// Login
//////////////////////////////////////////////////////////////////////////////////
CWndLogin::CWndLogin()
{
SetPutRegInfo( FALSE );
#ifdef __NPKCRYPT
m_hKCrypt = NULL;
TCHAR szFileName[MAX_PATH] = {0};
TCHAR szGameFileName[MAX_PATH] = {0};
BOOL bStatus = FALSE;
char szPath[MAX_PATH];
if( GetCurrentDirectory( MAX_PATH, szPath ) == 0 )
return;
sprintf( (char*)szGameFileName, "%s\\neuz.exe", szPath );
if( NPKGetAppCompatFlag( szGameFileName ) != apcfNone )
{
OutputDebugString("--> ReStart Program\n");
}
else
{
OutputDebugString("--> Load KeyCrypt\n");
bStatus = NPKGetLoadStartup();
GetModuleFileName( NULL, szFileName, sizeof(szFileName) );
char *ptr = strrchr( szFileName, '\\' );
if( ptr != NULL )
*ptr = 0;
NPKSetDrvPath( szFileName );
m_hKCrypt = NPKOpenDriver();
if(m_hKCrypt <= 0)
{
HLOCAL hlocal = NULL;
DWORD dwError = GetLastError();
CString strErrMsg = "";
BOOL fOk = ::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
dwError,
MAKELANGID(LANG_KOREAN, SUBLANG_ENGLISH_US),
(PTSTR) &hlocal,
0,
NULL);
if(fOk)
{
strErrMsg = (PCTSTR) LocalLock(hlocal);
::LocalFree(hlocal);
}
else
{
switch(dwError)
{
case NPK_ERROR_NOTADMIN:
break;
case NPK_ERROR_DRIVERVERSION:
// strErrMsg.LoadString(IDS_ERR_DRIVERVERSION);
break;
case NPK_ERROR_VERIFYVERSION:
// strErrMsg.LoadString(IDS_ERR_VERIFYVERSION);
break;
}
}
// ::MessageBox(GetSafeHwnd(), strErrMsg, "nProtect KeyCrypt", MB_OK | MB_ICONERROR);
// PostQuitMessage(0);
} else {
NPKLoadAtStartup(TRUE);
NPKRegCryptMsg( m_hKCrypt, g_Neuz.GetSafeHwnd(), WM_USER + 1094 );
}
}
#endif // __NPKCRYPT
}
CWndLogin::~CWndLogin()
{
#ifdef __NPKCRYPT
if( m_hKCrypt > 0 )
NPKCloseDriver( m_hKCrypt );
#endif // __NPKCRYPT
}
void CWndLogin::OnDraw( C2DRender* p2DRender )
{
//CRect rect = GetClientRect();
//CSize size = m_pTheme->m_pFontGameTitle->GetTextExtent( _T( "CLOCKWORKS" ) );
//p2DRender->m_pFont = m_pTheme->m_pFontGameTitle;
//p2DRender->TextOut( rect.Width() / 2 - size.cx / 2,20, "CLOCKWORKS", 0xffffffff );
//p2DRender->RenderTexture( CPoint( 120, 0 ), &m_Texture );
//size = m_pTheme->m_pFontText->GetTextExtent( _T( "Copyright (C) 2002~2003 Allrights Reserved AEONSOFT Inc." ) );
//p2DRender->m_pFont = m_pTheme->m_pFontText;
//p2DRender->TextOut( rect.Width() / 2 - size.cx / 2, rect.top + 120,"Copyright (C) 2002~2003 Allrights Reserved AEONSOFT Inc.", 0xffffffff );
//p2DRender->RenderLine( CPoint( 5, 140 ), CPoint( rect.right - 5, 140 ), 0x70ffffff);
//p2DRender->TextOut( 105, 160, _T( "Account" ) );
//p2DRender->TextOut( 105, 185, _T( "Password" ) );
//p2DRender->RenderRoundRect(CRect(4, 4,128*2+6, 96+6),D3DCOLOR_TEMP(255,150,150,250));
/*
CRect rect = CRect( 4, 96 + 6 + 4, 128 * 2 + 6, 96 + 6 + 4 + 96 + 6 );
p2DRender->RenderRoundRect( rect, D3DCOLOR_TEMP( 255, 150, 150, 250 ) );
rect.DeflateRect( 1, 1 );
p2DRender->RenderFillRect( rect, D3DCOLOR_TEMP( 255, 200, 200, 240 ) );
CRect rect = CRect( 4, 96 + 6 + 4, 128 * 2 + 6, 96 + 6 + 4 + 96 + 6 );
p2DRender->RenderRoundRect( rect, D3DCOLOR_TEMP( 255, 150, 150, 250 ) );
rect.DeflateRect( 1, 1 );
p2DRender->RenderFillRect( rect, D3DCOLOR_TEMP( 255, 200, 200, 240 ) );
*/
//p2DRender->TextOut(10,60,"aaaa",D3DCOLOR_TEMP(255,100,100,200));
}
BOOL CWndLogin::Process()
{
if( g_Neuz.m_dwTimeOutDis < GetTickCount() )
{
g_Neuz.m_dwTimeOutDis = 0xffffffff;
g_dpCertified.DeleteDPObject();
g_dpLoginClient.DeleteDPObject();
g_DPlay.DeleteDPObject();
g_WndMng.OpenMessageBoxUpper( _T( prj.GetText(TID_DIAG_0043) ) );
m_bDisconnect = TRUE;
}
if( g_WndMng.m_pWndMessageBoxUpper == NULL && m_bDisconnect )
{
m_bDisconnect = FALSE;
g_WndMng.CloseMessageBox();
g_dpCertified.DeleteDPObject();
CWndButton* pButton = (CWndButton*)GetDlgItem( WIDC_OK );
pButton->EnableWindow( TRUE );
}
return 1;
}
void CWndLogin::OnInitialUpdate()
{
CWndNeuz::OnInitialUpdate();
CRect rect = GetClientRect();
#ifdef __REG
m_wndRegist. Create( "Registration", 0, CRect( 0, 0, 100, 20 ), this, 1001 ); rect.OffsetRect( 120,0 );
#endif
CWndEdit* pAccount = (CWndEdit*) GetDlgItem( WIDC_ACCOUNT );
CWndEdit* pPassword = (CWndEdit*) GetDlgItem( WIDC_PASSWORD );
CWndButton* pSaveAccount = (CWndButton*) GetDlgItem( WIDC_CHECK1 );
if( ::GetLanguage() == LANG_FRE )
{
CWndStatic * pWndStatic2 = (CWndStatic*)GetDlgItem( WIDC_STATIC2 );
CRect rc = pWndStatic2->GetWndRect();
rc.right += 24;
pWndStatic2->SetWndRect( rc, TRUE );
CRect rc1 = pAccount->GetWndRect();
CRect rc2 = pPassword->GetWndRect();
rc1.left += 12;
rc1.right = rc2.right;
pAccount->SetWndRect( rc1, TRUE );
rc2.left += 12;
pPassword->SetWndRect( rc2, TRUE );
}
pAccount->EnableModeChange( FALSE );
pAccount->SetTabStop( TRUE );
pPassword->AddWndStyle( EBS_PASSWORD );
pPassword->SetTabStop( TRUE );
pPassword->EnableModeChange( FALSE );
CWndButton* pOk = (CWndButton*)GetDlgItem( WIDC_OK );
CWndButton* pQuit = (CWndButton*)GetDlgItem( WIDC_QUIT );
pOk->SetDefault( TRUE );
pAccount->SetString( g_Option.m_szAccount );
pSaveAccount->SetCheck( g_Option.m_bSaveAccount );
if( g_Option.m_szAccount[ 0 ] )
pPassword->SetFocus();
else
pAccount->SetFocus();
MoveParentCenter();
/* if( ::GetLanguage() != LANG_KOR )
{
#ifdef __FOR_PROLOGUE_UPDATE
CWndButton* pCredit = (CWndButton*)GetDlgItem( WIDC_CREDIT );
pCredit->EnableWindow(FALSE);
pCredit->SetVisible(FALSE);
#else //__FOR_PROLOGUE_UPDATE*/
CWndButton* pAbout = (CWndButton*)GetDlgItem( WIDC_ABOUT );
pAbout->EnableWindow(FALSE);
pAbout->SetVisible(FALSE);
CWndButton* pCredit = (CWndButton*)GetDlgItem( WIDC_CREDIT );
pCredit->EnableWindow(FALSE);
pCredit->SetVisible(FALSE);
CWndButton* pPrologue = (CWndButton*)GetDlgItem( WIDC_PROLOGUE );
pPrologue->EnableWindow(FALSE);
pPrologue->SetVisible(FALSE);
pOk->Move( 72, 105 );
pQuit->Move( 72, 135 );
/*#endif //__FOR_PROLOGUE_UPDATE
}*/
#ifdef __THROUGHPORTAL0810
if( g_Neuz.m_bThroughPortal )
{
CRect HanrectWindow = GetWindowRect( TRUE );
SetWndRect( CRect( HanrectWindow.left, HanrectWindow.top, HanrectWindow.right - 120, HanrectWindow.bottom - 115 ) );
CRect rectLayout = m_pWndRoot->GetLayoutRect();
Move( (int)( rectLayout.Width() / 2 - m_rectWindow.Width() / 2 ), (int)( rectLayout.Height() * 0.65 ) );
}
#endif // __THROUGHPORTAL0810
if( ::GetLanguage() == LANG_KOR )
{
CWndButton* pPrologue = (CWndButton*)GetDlgItem( WIDC_PROLOGUE );
pPrologue->SetVisible(FALSE);
}
switch( ::GetLanguage() )
{
case LANG_KOR:
case LANG_FRE:
case LANG_GER:
{
CRect rectRoot = m_pWndRoot->GetLayoutRect();
CRect rectWindow = GetWindowRect( TRUE );
rectWindow.top = 400 * rectRoot.Height() / 768;
Move( rectWindow.TopLeft() );
break;
}
}
#ifdef __THROUGHPORTAL0810
if( g_Neuz.m_bThroughPortal )
#else // __THROUGHPORTAL0810
if( g_Neuz.m_bHanGame )
#endif // __THROUGHPORTAL0810
{
CWndStatic* pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC3 );
pStatic->SetVisible( FALSE );
pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC2 );
pStatic->SetVisible( FALSE );
CWndEdit* pEdit = (CWndEdit*)GetDlgItem( WIDC_ACCOUNT );
pEdit->SetVisible( FALSE );
pEdit->Move( 800, 800 );
pEdit = (CWndEdit*)GetDlgItem( WIDC_PASSWORD );
pEdit->SetVisible( FALSE );
pEdit->Move( 800, 800 );
CWndButton* pButton = (CWndButton*) GetDlgItem( WIDC_CHECK1 );
pButton->SetVisible( FALSE );
pButton = (CWndButton*) GetDlgItem( WIDC_OK );
CRect rectButton = pButton->GetWndRect();
pButton->Move( 13, 10 );
pButton = (CWndButton*) GetDlgItem( WIDC_ABOUT );
pButton->Move( 13, 35 );
pButton = (CWndButton*) GetDlgItem( WIDC_CREDIT );
pButton->Move( 13, 60 );
pButton = (CWndButton*) GetDlgItem( WIDC_PROLOGUE );
pButton->Move( 13, 60 );
pButton = (CWndButton*) GetDlgItem( WIDC_QUIT );
pButton->Move( 13, 85 );
}
g_Neuz.m_dwTimeOutDis = 0xffffffff;
m_bDisconnect = FALSE;
}
BOOL CWndLogin::Initialize(CWndBase* pWndParent,DWORD dwStyle)
{
return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_LOGIN, WBS_KEY, CPoint( 0, 0 ), pWndParent );
}
void CWndLogin::Connected( long lTimeSpan )
{
g_WndMng.CloseMessageBox();
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_SELECT_SERVER );
#ifdef __BILLING0712
if( lTimeSpan ) // 1일 미만?
{
CTimeSpan span = (time_t)lTimeSpan;
char szMsg[256];
if( span.GetTotalMinutes() > 60 ) // 1시간 0분 은 표시하지 않고 60분 남았음으로
{
// %d시간 %분 남았습니다.
sprintf( szMsg, prj.GetText(TID_DIAG_EXPIRYDAY), span.GetHours(), span.GetMinutes() );
}
else
{
// %분 남았습니다. (최소 1분으로 표시)
int nMM = span.GetTotalMinutes();
sprintf( szMsg, prj.GetText(TID_DIAG_EXPIRYDAYMIN ), max(nMM, 1) );
}
g_WndMng.CloseMessageBox();
g_WndMng.OpenMessageBox( szMsg );
}
#endif //__BILLING0712
Destroy();
}
BOOL CWndLogin::OnChildNotify(UINT message,UINT nID,LRESULT* pLResult)
{
switch(nID)
{
case WIDC_CHECK1:
{
g_Option.m_bSaveAccount = !g_Option.m_bSaveAccount;
CWndEdit* pAccount = (CWndEdit*) GetDlgItem( WIDC_ACCOUNT );
strcpy( g_Option.m_szAccount, pAccount->GetString() );
}
break;
case WIDC_ACCOUNT:
case WIDC_PASSWORD:
//if( message != EN_CHANGE )
break;
case WIDC_ABOUT:
{
if( GetLanguage() == LANG_FRE )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
// Start the child process.
char lpPath[MAX_PATH] = { 0, };
char lpCommandLine[MAX_PATH] = { 0,};
if( !GetIePath( lpPath ) )
break;
sprintf( lpCommandLine, "%s\\IEXPLORE.EXE http://flyff.gpotato.eu", lpPath );
if( !CreateProcess( NULL,
lpCommandLine,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi )
)
{
}
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
else
{
CWndAbout* pWndAbout = new CWndAbout;
pWndAbout->Initialize();
}
}
break;
case WIDC_PROLOGUE:
case WIDC_CREDIT:
{
CWndCredit* pWndCredit = new CWndCredit;
pWndCredit->Initialize();
}
break;
case WIDC_OK: // 접속
{
# ifdef __CRC
if( !g_dpCertified.ConnectToServer( g_Neuz.m_lpCertifierAddr, PN_CERTIFIER, TRUE, CSock::crcWrite ) )
# else // __CRC
if( !g_dpCertified.ConnectToServer( g_Neuz.m_lpCertifierAddr, PN_CERTIFIER, TRUE ) )
# endif // __CRC
{
// Can't connect to server
g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0043) ) );
// g_WndMng.OpenMessageBox( _T( "접속할 수 없습니다. 네트워크 상태를 확인하십시오." ) );
CNetwork::GetInstance().OnEvent( CERT_CONNECT_FAIL );
break;
}
CNetwork::GetInstance().OnEvent( CERT_CONNECTED );
CWndButton* pButton = (CWndButton*)GetDlgItem( WIDC_OK );
pButton->EnableWindow( FALSE );
CWndEdit* pAccount = (CWndEdit*) GetDlgItem( WIDC_ACCOUNT );
CWndEdit* pPassword = (CWndEdit*) GetDlgItem( WIDC_PASSWORD );
CString strAccount, strPassword;
strAccount = pAccount->GetString();
strPassword = pPassword->GetString();
if( IsAcValid( pAccount->GetString() ) == FALSE )
{
g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0005) ) );
// g_WndMng.OpenMessageBox( _T( "계정은 3~16자 영어, 숫자를 사용할 수 있고, 숫자로 시작할 수 없습니다." ) );
pButton->EnableWindow( TRUE );
return TRUE;
}
if( IsPwdValid( pPassword->GetString() ) == FALSE )
{
g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0030) ) );
// g_WndMng.OpenMessageBox( _T( "암호는 3~16자 영어, 숫자를 사용할 수 있습니다." ) );
pButton->EnableWindow( TRUE );
return TRUE;
}
strcpy( g_Option.m_szAccount, pAccount->GetString() );
#ifdef __THROUGHPORTAL0810
if( g_Neuz.m_bThroughPortal == FALSE )
#else // __THROUGHPORTAL0810
if( g_Neuz.m_bHanGame == FALSE ) // 한게임 유저는 이미 세팅되어 있음, 두번 하면 문제생김
#endif // __THROUGHPORTAL0810
g_Neuz.SetAccountInfo( pAccount->GetString(), pPassword->GetString() );
g_dpCertified.SendCertify();
GetNProtect()->Send( (LPCSTR)g_Neuz.m_szAccount );
g_WndMng.OpenCustomBox( NULL, new CWndConnectingBox );
break;
}
case WIDC_QUIT: // 종료
case WTBID_CLOSE:
::PostMessage( g_Neuz.GetSafeHwnd(), WM_CLOSE, 0, 0 );
break;
}
return CWndNeuz::OnChildNotify( message, nID, pLResult );
}
BOOL CWndLogin::OnCommand(UINT nID,DWORD dwMessage, CWndBase* pWndBase )
{
return CWndNeuz::OnCommand( nID, dwMessage, pWndBase );
}
void CWndLogin::OnSize(UINT nType, int cx, int cy)
{
CWndNeuz::OnSize(nType,cx,cy);
}
void CWndLogin::OnLButtonUp(UINT nFlags, CPoint point)
{
if(IsWndRoot())
return;
}
void CWndLogin::OnLButtonDown(UINT nFlags, CPoint point)
{
if(IsWndRoot())
return;
}
#ifdef __CON_AUTO_LOGIN
void CWndLogin::SetAccountAndPassword( const CString& account, const CString& pass )
{
CWndEdit* pAccount = (CWndEdit*) GetDlgItem( WIDC_ACCOUNT );
CWndEdit* pPassword = (CWndEdit*) GetDlgItem( WIDC_PASSWORD );
if( pAccount && pPassword )
{
pAccount->SetString( account );
pPassword->SetString( pass );
}
}
#endif
/////////////////////////////////////////////////////////////////////////////////////
// Select Server
/////////////////////////////////////////////////////////////////////////////////////
CWndSelectServer::CWndSelectServer()
{
m_atexPannel = NULL;
m_dwChangeBannerTime = g_tmCurrent+SEC(10);
m_vecStrBanner.clear();
SetPutRegInfo( FALSE );
}
CWndSelectServer::~CWndSelectServer()
{
if( m_atexPannel )
{
SAFE_DELETE( m_atexPannel );
}
}
void CWndSelectServer::OnDraw( C2DRender* p2DRender )
{
//p2DRender->TextOut( 5, 225, _T( "URL" ) );
//p2DRender->TextOut( 5, 5, _T( "Clockworks Server List" ) );
}
void CWndSelectServer::OnInitialUpdate()
{
CWndNeuz::OnInitialUpdate();
CRect rect = GetClientRect();
//m_wndURL.Create( g_Neuz.GetSafeHwnd(), 0, CRect( 30, 220, 230, 240 ), this, 1000);
//m_wndSearch.Create( _T( "Search" ), 0, CRect( 235, 220, 290, 240 ), this, 100 );
//m_wndServerList.Create( 0, CRect( rect.left + 5, rect.top + 40, rect.right - 5, rect.bottom - 35), this, 200 );
CWndButton* pNext = (CWndButton*)GetDlgItem( WIDC_NEXT );
pNext->SetDefault( TRUE );
CWndListBox* pWndList = (CWndListBox*)GetDlgItem( WIDC_CONTROL0 );
CRect ReRect = pWndList->GetWindowRect(TRUE);
ReRect.bottom -= 5;
pWndList->SetWndRect(ReRect);
CWndListBox* pWndListMulti = (CWndListBox*)GetDlgItem( WIDC_CONTROL1 );
ReRect = pWndListMulti->GetWindowRect(TRUE);
ReRect.bottom -= 5;
pWndListMulti->SetWndRect(ReRect);
pWndListMulti->m_nFontColor = 0xff000000;
pWndListMulti->m_nSelectColor = 0xff0000ff;
//pWndList->AddWndStyle( WBS_NODRAWFRAME );
pWndList->m_nFontColor = 0xff000000;
pWndList->m_nSelectColor = 0xff0000ff;
int x = m_rectClient.Width() / 2;
int y = m_rectClient.Height() - 30;
CSize size = CSize(70,25);//m_pSprPack->GetAt(9)->GetSize();
CRect rect1_1( x - ( size.cx / 2), y, ( x - ( size.cx / 2 ) ) + size.cx, y + size.cy );
CRect rect2_1( x - size.cx - 10, y, ( x - size.cx - 10 ) + size.cx, y + size.cy );
CRect rect2_2( x + 10 , y, ( x + 10 ) + size.cx, y + size.cy );
CRect rect3_1( x - ( size.cx / 2) - size.cx - 10, y, (x - ( size.cx / 2) - size.cx - 10) + size.cx, y + size.cy );
CRect rect3_2( x - ( size.cx / 2) , y, (x - ( size.cx / 2) ) + size.cx, y + size.cy );
CRect rect3_3( x + ( size.cx / 2) + 10 , y, (x + ( size.cx / 2) + 10 ) + size.cx, y + size.cy );
// m_wndServerList.Create( WLVS_REPORT, CRect( rect.left + 5, rect.top + 20, rect.right - 5, rect.bottom - 65), this, 11 );
TCHAR szTitle[3][10] = {_T("Server"), _T("Ping"), _T("Max") };
BOOL bSeveServer = FALSE;
int j; for( j = 0; j < (int)( g_dpCertified.m_dwSizeofServerset ); j++ )
{
char lpString[MAX_PATH] = { 0, };
char lpStrtmp[32] = { 0, };
long lCount = 0;
long lMax = 0;
if( g_dpCertified.m_aServerset[j].dwParent == NULL_ID )
{
if( g_dpCertified.m_aServerset[j].lEnable != 0L )
{
int nIndex = pWndList->AddString( g_dpCertified.m_aServerset[j].lpName );
pWndList->SetItemData( nIndex, (DWORD)&g_dpCertified.m_aServerset[j] );
if( nIndex == g_Option.m_nSer )
{
bSeveServer = TRUE;
pWndListMulti->ResetContent();
}
}
}
else if( g_dpCertified.m_aServerset[j].lEnable != 0L )
{
if( pWndList->GetCount() > 0 )
{
LPSERVER_DESC pServerDesc;
if( bSeveServer )
{
pServerDesc = (LPSERVER_DESC)pWndList->GetItemData( g_Option.m_nSer );
}
else
{
pServerDesc = (LPSERVER_DESC)pWndList->GetItemData( 0 );
}
if( g_dpCertified.m_aServerset[j].dwParent == pServerDesc->dwID )
{
lCount = g_dpCertified.m_aServerset[j].lCount;
lMax = g_dpCertified.m_aServerset[j].lMax;
long lBusy = (long)( lMax * 0.8 );
if( lCount < lBusy )
{
//strcpy( lpStrtmp, "정상" );
strcpy( lpStrtmp, prj.GetText(TID_GAME_NORMAL));
}
else
if( lCount < lMax )
{
//strcpy( lpStrtmp, "혼잡" );
strcpy( lpStrtmp, prj.GetText(TID_GAME_BUSY));
}
else
{
strcpy( lpStrtmp, prj.GetText(TID_GAME_FULL) );
}
sprintf( lpString, "%s(%s)", g_dpCertified.m_aServerset[j].lpName, lpStrtmp );
// sprintf( lpString, "%s(%d)", g_dpCertified.m_aServerset[j].lpName, g_dpCertified.m_aServerset[j].lCount );
int nIndex = pWndListMulti->AddString( lpString );
pWndListMulti->SetItemData( nIndex, (DWORD)&g_dpCertified.m_aServerset[j] );
}
}
}
}
if( pWndListMulti->GetCount() )
pWndListMulti->SetCurSel( 0 );
if( pWndList->GetCount() )
pWndList->SetCurSel( 0 );
if( bSeveServer == FALSE )
{
g_Option.m_nSer = 0;
g_Option.m_nMSer = 0;
}
else
{
if( g_Option.m_nMSer >= pWndListMulti->GetCount() )
{
g_Option.m_nMSer = 0;
}
}
if( pWndList->GetCount() > 0 )
pWndList->SetCurSel( g_Option.m_nSer );
if( pWndListMulti->GetCount() > 0 )
pWndListMulti->SetCurSel( g_Option.m_nMSer );
// if( ::GetLanguage() == LANG_TWN )
// {
// CWndButton* pWndBack = (CWndButton*)GetDlgItem( WIDC_BACK );
// pWndBack->EnableWindow( FALSE );
// }
MoveParentCenter();
if( ::GetLanguage() == LANG_JAP )
{
CRect rect2 = m_pWndRoot->GetLayoutRect();
int width = (rect2.right-rect2.left) / 2;
Move( width, m_rectWindow.top );
}
pNext->SetFocus();
/////////////////////////////////////////////////////////////////////////////////////////
int nCount = 0;
CScript script;
if( script.Load(MakePath(DIR_THEME, "TexBannerList.inc" )) )
{
int nLang;
nLang = script.GetNumber();
do
{
if( nLang == ::GetLanguage() )
{
script.GetToken();
nCount = atoi( script.token );
script.GetToken();
for( int i=0; i<nCount; i++ )
{
CString addStr = script.token;
m_vecStrBanner.push_back( addStr );
script.GetToken();
}
if( nCount <= 0 )
{
Error( "TexBannerList.inc의 갯수가 0이다" );
return;
}
break;
}
else
script.GetLastFull();
nLang = script.GetNumber();
} while( script.tok != FINISHED );
}
if( nCount > 0 )
{
SAFE_DELETE( m_atexPannel );
m_atexPannel = new IMAGE;
LoadImage( MakePath( DIR_THEME, m_vecStrBanner[xRandom(nCount)] ), m_atexPannel );
AdjustWndBase();
}
/////////////////////////////////////////////////////////////////////////////////////////
}
BOOL CWndSelectServer::Process()
{
if( g_tmCurrent > m_dwChangeBannerTime )
{
m_dwChangeBannerTime = g_tmCurrent+SEC(10);
SAFE_DELETE( m_atexPannel );
m_atexPannel = new IMAGE;
LoadImage( MakePath( DIR_THEME, m_vecStrBanner[xRandom(m_vecStrBanner.size())] ), m_atexPannel );
AdjustWndBase();
}
return TRUE;
}
BOOL CWndSelectServer::Initialize(CWndBase* pWndParent,DWORD dwStyle)
{
return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_SELECT_SERVER, WBS_KEY, CPoint( 0, 0 ), pWndParent );
}
void CWndSelectServer::AfterSkinTexture( LPWORD pDest, CSize size, D3DFORMAT d3dFormat )
{
CPoint pt;
LPWNDCTRL lpWndCtrl;
CPoint pt2 = m_rectClient.TopLeft() - m_rectWindow.TopLeft();
lpWndCtrl = GetWndCtrl( WIDC_COMMER_BANNER2 );
pt = lpWndCtrl->rect.TopLeft() + pt2;
if( m_atexPannel )
PaintTexture( pDest, m_atexPannel, pt, size );
}
void CWndSelectServer::Connected()
{
#if defined(_DEBUG)
g_Neuz.WaitLoading();
#endif
g_WndMng.CloseMessageBox();
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_SELECT_CHAR );
Destroy();
}
void CWndSelectServer::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
CWndListBox* pWndListServer = (CWndListBox*)GetDlgItem( WIDC_CONTROL0 );
CWndListBox* pWndListMulti = (CWndListBox*)GetDlgItem( WIDC_CONTROL1 );
if( nChar == VK_UP )
{
DWORD dwIndex = pWndListMulti->GetCurSel();
if( dwIndex > 0 )
pWndListMulti->SetCurSel(--dwIndex);
}
else
if( nChar == VK_DOWN )
{
DWORD dwIndex = pWndListMulti->GetCurSel();
if( (int)( dwIndex ) < pWndListMulti->GetCount()-1 )
pWndListMulti->SetCurSel(++dwIndex);
}
}
BOOL CWndSelectServer::OnChildNotify(UINT message,UINT nID,LRESULT* pLResult)
{
if( message == WNM_SELCHANGE )
{
switch( nID )
{
case 11:
{
TCHAR szTemp[32];// = _T( "nnp://" );
_tcscpy( szTemp, m_wndServerList.GetItemText( m_wndServerList.GetCurSel(), 0 ) );
m_wndURL.SetString( szTemp );
break;
}
case 188:
{
char lpString[MAX_PATH] = { 0, };
char lpStrtmp[32] = { 0, };
long lCount = 0;
long lMax = 0;
CWndListBox* pWndListServer = (CWndListBox*)GetDlgItem( WIDC_CONTROL0 );
CWndListBox* pWndListMulti = (CWndListBox*)GetDlgItem( WIDC_CONTROL1 );
pWndListMulti->ResetContent();
LPSERVER_DESC pServerDesc = (LPSERVER_DESC)pWndListServer->GetItemData( pWndListServer->GetCurSel() );
int j; for( j = 0; j < (int)( g_dpCertified.m_dwSizeofServerset ); j++ )
{
if( g_dpCertified.m_aServerset[j].dwParent == pServerDesc->dwID && ( g_dpCertified.m_aServerset[j].lEnable != 0L ) )
{
lCount = g_dpCertified.m_aServerset[j].lCount;
lMax = g_dpCertified.m_aServerset[j].lMax;
long lBusy = (long)( lMax * 0.8 );
if( lCount < lBusy )
strcpy( lpStrtmp, prj.GetText(TID_GAME_NORMAL)); //"정상"
else if( lCount < lMax )
strcpy( lpStrtmp, prj.GetText(TID_GAME_BUSY)); //"혼잡"
else
lstrcpy( lpStrtmp, prj.GetText(TID_GAME_FULL) );
sprintf( lpString, "%s(%s)", g_dpCertified.m_aServerset[j].lpName, lpStrtmp );
int nIndex = pWndListMulti->AddString( lpString );
pWndListMulti->SetItemData( nIndex, (DWORD)&g_dpCertified.m_aServerset[j] );
}
}
if( pWndListMulti->GetCount() )
pWndListMulti->SetCurSel( 0 );
break;
}
}
}
else
switch(nID)
{
case 10000: // close msg
case WIDC_BACK: // Back
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_LOGIN );
Destroy();
g_dpCertified.DeleteDPObject();
break;
case WIDC_NEXT: // accept
{
CWndListBox* pWnd = (CWndListBox*)GetDlgItem( WIDC_CONTROL1 );
if( pWnd->GetCount() <= 0 )
break;
LPSERVER_DESC pDesc = (LPSERVER_DESC)pWnd->GetItemData( pWnd->GetCurSel() );
if( pDesc )
{
if( !( g_Neuz.m_cbAccountFlag & ACCOUNT_FLAG_SCHOOLEVENT ) && pDesc->lCount > pDesc->lMax )
{
g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0041) ) );
// g_WndMng.OpenMessageBox( _T( "사용자가 너무 많습니다." ) );
break;
}
}
}
if( ::GetLanguage() != LANG_THA )
{
CWndListBox* pWnd = (CWndListBox*)GetDlgItem( WIDC_CONTROL1 );
LPSERVER_DESC pDesc = (LPSERVER_DESC)pWnd->GetItemData( pWnd->GetCurSel() );
if( pDesc )
{
if( pDesc->b18 && !( g_Neuz.m_cbAccountFlag & ACCOUNT_FLAG_18 ) )
{
g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0058) ) ); // 18세미만 사용자는 접속할 수 없습니다.
break;
}
}
}
if( FALSE == g_dpCertified.IsConnected() )
{
CNetwork::GetInstance().OnEvent( LOGIN_CONNECT_STEP_ERROR );
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_LOGIN );
Destroy();
g_dpCertified.DeleteDPObject();
g_dpLoginClient.DeleteDPObject(); // 2004^04^19
break;
}
g_WndMng.OpenCustomBox( NULL, new CWndConnectingBox );
CWndListBox* pWndList = (CWndListBox*)GetDlgItem( WIDC_CONTROL0 );
LPSERVER_DESC pServerDesc = (LPSERVER_DESC)pWndList->GetItemData( pWndList->GetCurSel() );
g_Option.m_nSer = pWndList->GetCurSel();
g_Neuz.m_dwSys = pServerDesc->dwID;
LPCSTR lpAddr = pServerDesc->lpAddr;
pWndList = (CWndListBox*)GetDlgItem( WIDC_CONTROL1 );
pServerDesc = (LPSERVER_DESC)pWndList->GetItemData( pWndList->GetCurSel() );
g_Option.m_nMSer = pWndList->GetCurSel();
g_Neuz.m_uIdofMulti = pServerDesc->dwID;
g_Neuz.m_b18Server = pServerDesc->b18;
if( pServerDesc->dwParent != g_Neuz.m_dwSys )
{
CWndListBox* pWndListBox = (CWndListBox*)GetDlgItem( WIDC_CONTROL0 );
int i; for( i = 0; i < pWndListBox->GetCount(); i++ )
{
LPSERVER_DESC ptr = (LPSERVER_DESC)pWndListBox->GetItemData( i );
if( ptr && ptr->dwID == pServerDesc->dwParent )
{
pWndListBox->SetCurSel( i );
g_Option.m_nSer = i;
g_Neuz.m_dwSys = ptr->dwID;
lpAddr = ptr->lpAddr;
break;
}
}
}
# ifdef __CRC
if( !g_dpLoginClient.ConnectToServer( lpAddr, PN_LOGINSRVR, TRUE, CSock::crcWrite ) )
# else __CRC
if( !g_dpLoginClient.ConnectToServer( lpAddr, PN_LOGINSRVR, TRUE ) )
# endif // __CRC
{
// Can't connect to server
g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0043) ) );
// g_WndMng.OpenMessageBox( _T( "접속할 수 없습니다. 네트워크 상태를 확인하십시오." ) );
CNetwork::GetInstance().OnEvent( LOGIN_CONNECT_FAIL );
break;
}
CNetwork::GetInstance().OnEvent( LOGIN_CONNECTED );
g_dpLoginClient.QueryTickCount();
#if __NPROTECT_VER >= 4
g_Neuz.m_loginSI.dwID = pServerDesc->dwID;
#ifdef __GPAUTH_01
g_Neuz.m_loginSI.pszAccount = g_Neuz.m_bGPotatoAuth? g_Neuz.m_szGPotatoNo: g_Neuz.m_szAccount;
#else // __GPAUTH_01
g_Neuz.m_loginSI.pszAccount = g_Neuz.m_szAccount;
#endif // __GPAUTH_01
g_Neuz.m_loginSI.pszPassword = g_Neuz.m_szPassword;
g_Neuz.m_loginSI.nCount = 1;
#else
#ifdef __GPAUTH_01
g_dpLoginClient.SendGetPlayerList( pServerDesc->dwID, g_Neuz.m_bGPotatoAuth? g_Neuz.m_szGPotatoNo: g_Neuz.m_szAccount, g_Neuz.m_szPassword );
#else // __GPAUTH_01
g_dpLoginClient.SendGetPlayerList( pServerDesc->dwID, g_Neuz.m_szAccount, g_Neuz.m_szPassword );
#endif // __GPAUTH_01
#endif // __NPROTECT_VER
break;
}
return CWndNeuz::OnChildNotify( message, nID, pLResult );
}
BOOL CWndSelectServer::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase )
{
/*
switch(nID)
{
case 100:
g_WndMng.OpenField();
break;
case 101:
break;
case 102:
//g_WndMng.OpenCustomBox("종료하시겠습니까?",new CWndExitBox);
break;
case 1000:
break;
case 1001:
if(dwMessage == WM_KEYDOWN)
{
m_wndText.m_string += g_Neuz.m_pPlayer->m_szName;
m_wndText.m_string += " :\n ";
m_wndText.m_string += m_wndChat.m_string;
m_wndText.m_string += '\n';
m_wndText.m_string.Reset( g_2DRender.m_pFont, &m_wndText.GetClientRect() );
m_wndText.UpdateScrollBar();
m_wndText.m_wndScrollBar.SetMaxScrollPos();
m_wndChat.Empty();
}
break;
}
*/
return CWndNeuz::OnCommand(nID,dwMessage,pWndBase);
}
void CWndSelectServer::OnSize(UINT nType, int cx, int cy)
{
/*
CRect rect = GetClientRect();
rect.bottom = rect.bottom - 40; //20;
rect.right -= 50;
rect.DeflateRect( 1, 1 );
m_wndText.SetWndRect( rect );
rect = GetClientRect();
rect.top = rect.bottom - 37; //20;
rect.right -= 50;
rect.DeflateRect( 1, 1 );
m_wndChat.SetWndRect( rect );
rect = GetClientRect();
rect.left = rect.right - 47; rect.right -= 3; rect.top += 3; rect.bottom = rect.top + 20;
m_wndLogin.SetWndRect( rect ); rect.OffsetRect( 0, 25 );
m_wndRegist.SetWndRect( rect ); rect.OffsetRect( 0, 25 );
m_wndQuit.SetWndRect( rect );
*/
CWndNeuz::OnSize(nType,cx,cy);
}
void CWndSelectServer::OnLButtonUp(UINT nFlags, CPoint point)
{
if(IsWndRoot())
return;
//if(IsWndStyle(WBS_CAPTION) && m_bPickup)
{//
// m_wndTitleBar.m_wndMinimize.SetVisible(TRUE);
//m_wndTitleBar.m_wndMaximize.SetVisible(TRUE);
}
}
void CWndSelectServer::OnLButtonDown(UINT nFlags, CPoint point)
{
// CWndBase::OnLButtonDown(nFlags,point
if(IsWndRoot())
return;
// return;
}
/////////////////////////////////////////////////////////////////////////////////////
// Delete Character
/////////////////////////////////////////////////////////////////////////////////////
CWndDeleteChar::CWndDeleteChar()
{
}
CWndDeleteChar::~CWndDeleteChar()
{
}
void CWndDeleteChar::OnDraw( C2DRender* p2DRender )
{
}
void CWndDeleteChar::OnInitialUpdate()
{
CWndNeuz::OnInitialUpdate();
}
void CWndDeleteChar::AdditionalSkinTexture( LPWORD pDest, CSize sizeSurface, D3DFORMAT d3dFormat )
{
#ifdef __THROUGHPORTAL0810
if( ( g_Neuz.m_bThroughPortal && GetLanguage() != LANG_TWN && ::GetLanguage() != LANG_KOR )
|| ( GetLanguage() == LANG_ENG && GetSubLanguage() == LANG_SUB_USA )
|| ( GetLanguage() == LANG_ENG && GetSubLanguage() == LANG_SUB_IND )
|| ( GetLanguage() == LANG_VTN )
)
#else // __THROUGHPORTAL0810
if( g_Neuz.m_bHanGame )
#endif // __THROUGHPORTAL0810
{
CWndEdit *WndEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT1 );
WndEdit->SetVisible( FALSE );
WndEdit->EnableWindow( FALSE );
}
CWndNeuz::AdditionalSkinTexture( pDest, sizeSurface, d3dFormat );
}
BOOL CWndDeleteChar::Initialize( CWndBase* pWndParent, DWORD dwWndId )
{
InitDialog( g_Neuz.GetSafeHwnd(), APP_DELETE_CHAR, WBS_MODAL );
CWndEdit *WndEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT1 );
if( WndEdit )
{
WndEdit->AddWndStyle( EBS_PASSWORD|EBS_AUTOHSCROLL );
WndEdit->SetFocus();
}
MoveParentCenter();
#ifdef __THROUGHPORTAL0810
if( ( g_Neuz.m_bThroughPortal && GetLanguage() != LANG_TWN && ::GetLanguage() != LANG_KOR )
|| ( GetLanguage() == LANG_ENG && GetSubLanguage() == LANG_SUB_USA )
|| ( GetLanguage() == LANG_ENG && GetSubLanguage() == LANG_SUB_IND )
|| ( ::GetLanguage() == LANG_VTN )
)
{
CWndStatic *pWnd1 = (CWndStatic*)GetDlgItem( WIDC_CONTROL1 );
CWndStatic *pWnd2 = (CWndStatic*)GetDlgItem( WIDC_STATIC1 );
CWndSelectChar* pWnd = (CWndSelectChar *)g_WndMng.GetWndBase( APP_SELECT_CHAR );
pWnd1->SetTitle( g_Neuz.m_apPlayer[pWnd->m_nSelectCharacter]->GetName() );
pWnd2->SetTitle( GETTEXT(TID_HANGAME_COMFORMDELETE) );
}
/*
else if( GetLanguage() == LANG_JAP )
{
CWndStatic *WndEdit = (CWndStatic*)GetDlgItem( WIDC_STATIC1 );
CRect rect = WndEdit->GetWindowRect();
WndEdit->Move(rect.left+24, rect.top+30 );
}
*/
#else // __THROUGHPORTAL0810
if( ::GetLanguage() == LANG_JAP )
{
if( g_Neuz.m_bHanGame )
{
CWndStatic *pWnd1 = (CWndStatic*)GetDlgItem( WIDC_CONTROL1 );
CWndStatic *pWnd2 = (CWndStatic*)GetDlgItem( WIDC_STATIC1 );
CWndSelectChar* pWnd = (CWndSelectChar *)g_WndMng.GetWndBase( APP_SELECT_CHAR );
pWnd1->SetTitle( g_Neuz.m_apPlayer[pWnd->m_nSelectCharacter]->GetName() );
pWnd2->SetTitle( GETTEXT(TID_HANGAME_COMFORMDELETE) );
}
else
{
CWndStatic *WndEdit = (CWndStatic*)GetDlgItem( WIDC_STATIC1 );
CRect rect = WndEdit->GetWindowRect();
WndEdit->Move(rect.left+24, rect.top+30 );
}
}
#endif // __THROUGHPORTAL0810
return TRUE;
}
BOOL CWndDeleteChar::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase )
{
return CWndNeuz::OnCommand( nID, dwMessage, pWndBase );
}
void CWndDeleteChar::OnSize( UINT nType, int cx, int cy ) \
{
CWndNeuz::OnSize( nType, cx, cy );
}
void CWndDeleteChar::OnLButtonUp( UINT nFlags, CPoint point )
{
}
void CWndDeleteChar::OnLButtonDown( UINT nFlags, CPoint point )
{
}
void CWndDeleteChar::DeletePlayer( int nSelect, LPCTSTR szNo )
{
g_dpLoginClient.SendDeletePlayer( nSelect, szNo );
CWndButton* pWndButton = (CWndButton*)GetDlgItem( WIDC_OK );
pWndButton->EnableWindow( FALSE );
pWndButton = (CWndButton*)GetDlgItem( WIDC_CANCEL );
pWndButton->EnableWindow( FALSE );
}
BOOL CWndDeleteChar::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult )
{
if( nID == WIDC_OK )
{
CWndSelectChar* pWnd = (CWndSelectChar *)g_WndMng.GetWndBase( APP_SELECT_CHAR );
if( pWnd == NULL )
return CWndNeuz::OnChildNotify( message, nID, pLResult );
CWndEdit* pWndEdit = (CWndEdit*)GetDlgItem( WIDC_EDIT1 );
if( pWndEdit == NULL )
return CWndNeuz::OnChildNotify( message, nID, pLResult );
BOOL bOK = FALSE;
LPCTSTR szNo = pWndEdit->GetString();
#ifdef __THROUGHPORTAL0810
if( ( g_Neuz.m_bThroughPortal && GetLanguage() != LANG_TWN && ::GetLanguage() != LANG_KOR )
|| ( GetLanguage() == LANG_ENG && GetSubLanguage() == LANG_SUB_USA )
|| ( GetLanguage() == LANG_ENG && GetSubLanguage() == LANG_SUB_IND )
|| ( ::GetLanguage() == LANG_VTN )
)
szNo = g_Neuz.m_szPassword;
#endif // __THROUGHPORTAL0810
switch( ::GetLanguage() )
{
case LANG_KOR:
#ifdef __DELETE_CHAR_CHANGE_KEY_VALUE // 100304_mirchang 주민번호에서 2차비번으로 변경(국내, 버디버디 i-PIN)
if( strlen(szNo) == 4 )
#else // __DELETE_CHAR_CHANGE_KEY_VALUE
if( strlen(szNo) == 7 )
#endif // __DELETE_CHAR_CHANGE_KEY_VALUE
{
BOOL bisdigit = TRUE;
#ifdef __DELETE_CHAR_CHANGE_KEY_VALUE
int i; for( i = 0 ; i < 4 ; i++ )
#else // __DELETE_CHAR_CHANGE_KEY_VALUE
int i; for( i = 0 ; i < 7 ; i++ )
#endif // __DELETE_CHAR_CHANGE_KEY_VALUE
{
if( (isdigit2( szNo[i] ) == FALSE) )
{
bisdigit = FALSE;
break;
}
}
if( bisdigit )
{
DeletePlayer( pWnd->m_nSelectCharacter, szNo );
bOK = TRUE;
}
}
break;
default:
#ifndef __THROUGHPORTAL0810
if( g_Neuz.m_bHanGame && GetLanguage() != LANG_TWN )
szNo = g_Neuz.m_szPassword;
#endif // __THROUGHPORTAL0810
if( 0 < strlen( szNo ) && strlen( szNo ) < 64 )
{
DeletePlayer( pWnd->m_nSelectCharacter, szNo );
bOK = TRUE;
}
break;
}
if( bOK == FALSE )
{
pWndEdit->SetString( "" );
#ifdef __THROUGHPORTAL0810
if( g_Neuz.m_bThroughPortal == FALSE || GetLanguage() == LANG_TWN || ::GetLanguage() == LANG_KOR )
#else // __THROUGHPORTAL0810
if( g_Neuz.m_bHanGame == FALSE )
#endif // __THROUGHPORTAL0810
g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0044) ) ); // "주민번호 숫자 7자리로 넣어야 합니다. 다시 입력해주세요"
}
}
else if( nID == WIDC_CANCEL )
{
Destroy();
}
return CWndNeuz::OnChildNotify( message, nID, pLResult );
}
/////////////////////////////////////////////////////////////////////////////////////
// Select Character
/////////////////////////////////////////////////////////////////////////////////////
int CWndSelectChar::m_nSelectCharacter = 0;
CWndSelectChar::CWndSelectChar()
{
m_pWndDeleteChar = NULL;
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
m_pWnd2ndPassword = NULL;
#endif // __2ND_PASSWORD_SYSTEM
ZeroMemory( m_pBipedMesh, sizeof( m_pBipedMesh ) );
m_dwMotion[ 0 ] = MTI_SITSTAND;
m_dwMotion[ 1 ] = MTI_SITSTAND;
m_dwMotion[ 2 ] = MTI_SITSTAND;
SetPutRegInfo( FALSE );
m_CreateApply = TRUE; //서버통합 관련 특정 기간 캐릭터 생성 금지.
}
CWndSelectChar::~CWndSelectChar()
{
InvalidateDeviceObjects();
DeleteDeviceObjects();
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
SAFE_DELETE( m_pBipedMesh[ i ] );
}
SAFE_DELETE( m_pWndDeleteChar );
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
SAFE_DELETE( m_pWnd2ndPassword );
#endif // __2ND_PASSWORD_SYSTEM
}
void CWndSelectChar::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if( !g_Neuz.m_timerConnect.Over() )
return;
int nSelectCharBuf = m_nSelectCharacter;
if( nChar == VK_LEFT )
{
--nSelectCharBuf;
if( 0 > nSelectCharBuf )
{
nSelectCharBuf = MAX_CHARACTER_LIST - 1;
}
SelectCharacter( nSelectCharBuf );
}
else if( nChar == VK_RIGHT )
{
++nSelectCharBuf;
if( nSelectCharBuf >= MAX_CHARACTER_LIST )
{
nSelectCharBuf = 0;
}
SelectCharacter( nSelectCharBuf );
}
}
void CWndSelectChar::OnDestroyChildWnd( CWndBase* pWndChild )
{
if( pWndChild == m_pWndDeleteChar )
SAFE_DELETE( m_pWndDeleteChar );
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
if( pWndChild == m_pWnd2ndPassword )
SAFE_DELETE( m_pWnd2ndPassword );
#endif // __2ND_PASSWORD_SYSTEM
}
HRESULT CWndSelectChar::InitDeviceObjects()
{
CWndBase::InitDeviceObjects();
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
if( m_pBipedMesh[ i ] )
m_pBipedMesh[ i ]->InitDeviceObjects( m_pApp->m_pd3dDevice );
}
return S_OK;
}
HRESULT CWndSelectChar::RestoreDeviceObjects()
{
CWndBase::RestoreDeviceObjects();
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
if( m_pBipedMesh[ i ] )
m_pBipedMesh[ i ]->RestoreDeviceObjects();
}
return S_OK;
}
HRESULT CWndSelectChar::InvalidateDeviceObjects()
{
CWndBase::InvalidateDeviceObjects();
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
if( m_pBipedMesh[ i ] )
m_pBipedMesh[ i ]->InvalidateDeviceObjects();
}
return S_OK;
}
HRESULT CWndSelectChar::DeleteDeviceObjects()
{
CWndBase::DeleteDeviceObjects();
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
if( m_pBipedMesh[ i ] )
m_pBipedMesh[ i ]->DeleteDeviceObjects();
}
return S_OK;
}
BOOL CWndSelectChar::Process()
{
/*
*
ANILOOP_1PLAY (0x00000001) // 한번 플레이후 끝.
ANILOOP_CONT (0x00000002) // 한번 플레이후 마지막 동작으로
ANILOOP_LOOP (0x00000004) // 반복
ANILOOP_RETURN (0x00000008) // 왕복 - 사용되지 않음.
ANILOOP_BACK (0x00000010) // 뒤에서 부터. - 사용되지 않음
*/
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
CRect rect = m_aRect[ i ];
CModelObject* pModel = (CModelObject*)m_pBipedMesh[ i ];
CMover* pMover = g_Neuz.m_apPlayer[ i ];
if( g_Neuz.m_apPlayer[i] != NULL && pModel )
{
int nMover = (pMover->GetSex() == SEX_MALE ? MI_MALE : MI_FEMALE);
if( m_nSelectCharacter == i )
{
// 완전히 일어났나? 그렇다면 MTI_STAND로 변경
if( m_dwMotion[ i ] == MTI_GETUP )
{
if( pModel->IsEndFrame() && pModel->m_nLoop == ANILOOP_1PLAY )
{
SetMotion( pModel, nMover, MTI_STAND, ANILOOP_LOOP, 0 );
m_dwMotion[ i ] = MTI_STAND;
}
}
}
else
{
// 앉아 있는게 아닌가? 그렇다면 무조건 앉아라. MTI_SIT으로 변경
if( m_dwMotion[ i ] != MTI_SITSTAND )
{
if( pModel->IsEndFrame() && pModel->m_nLoop == ANILOOP_1PLAY )
{
SetMotion( pModel, nMover, MTI_SITSTAND, ANILOOP_LOOP, 0 );
m_dwMotion[ i ] = MTI_SITSTAND;
}
else
if( m_dwMotion[ i ] != MTI_SIT )
{
SetMotion( pModel, nMover, MTI_SIT, ANILOOP_1PLAY, 0 );
m_dwMotion[ i ] = MTI_SIT;
}
}
// 완전히 앉았나? 그렇다면 MTI_SITSTAND로 변경
}
pModel->FrameMove();
}
}
#ifndef _DEBUG
if( g_Neuz.m_dwTimeOutDis < GetTickCount() )
{
g_Neuz.m_dwTimeOutDis = 0xffffffff;
g_dpCertified.DeleteDPObject();
g_dpLoginClient.DeleteDPObject();
g_DPlay.DeleteDPObject();
g_WndMng.OpenMessageBoxUpper( _T( prj.GetText(TID_DIAG_0043) ) );
m_bDisconnect = TRUE;
}
if( g_WndMng.m_pWndMessageBoxUpper == NULL && m_bDisconnect )
{
Destroy();
g_WndMng.CloseMessageBox();
g_dpCertified.SendCertify();
GetNProtect()->Send( (LPCSTR)g_Neuz.m_szAccount );
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_LOGIN );
CWndBase* pWndBase = g_WndMng.GetWndBase( APP_LOGIN );
return 0;
}
#endif //_DEBUG
return CWndNeuz::Process();
}
void CWndSelectChar::OnDraw( C2DRender* p2DRender )
{
CWndButton* pWndAccept = (CWndButton*)GetDlgItem( WIDC_ACCEPT );
CWndButton* pWndCreate = (CWndButton*)GetDlgItem( WIDC_CREATE );
CWndButton* pWndDelete = (CWndButton*)GetDlgItem( WIDC_DELETE );
CRect rect;
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
rect = m_aRect[ i ];
if( g_Neuz.m_apPlayer[i] != NULL )
{
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
if( g_WndMng.GetWndBase( APP_2ND_PASSWORD_NUMBERPAD ) == NULL )
{
POINT point = GetMousePoint();
if( m_aRect[ i ].PtInRect( point ) )
{
CRect rectHittest = m_aRect[ i ];
CPoint point2 = point;
ClientToScreen( &point2 );
ClientToScreen( rectHittest );
g_WndMng.PutToolTip_Character( i, point2, &rectHittest );
}
}
#else // __2ND_PASSWORD_SYSTEM
POINT point = GetMousePoint();
if( m_aRect[ i ].PtInRect( point ) )
{
CRect rectHittest = m_aRect[ i ];
CPoint point2 = point;
ClientToScreen( &point2 );
ClientToScreen( rectHittest );
g_WndMng.PutToolTip_Character( i, point2, &rectHittest );
}
#endif // __2ND_PASSWORD_SYSTEM
if( m_nSelectCharacter == i )
{
CRect rectTemp = rect;
rectTemp.top += 5;
rectTemp.bottom -= 5;
rectTemp.left += i;
rectTemp.right += i;
p2DRender->RenderFillRect(rectTemp, D3DCOLOR_ARGB( 20, 80, 250, 80 ) );
p2DRender->TextOut( rect.left, rect.bottom + 10, g_Neuz.m_apPlayer[i]->GetName(), 0xff6060ff );
p2DRender->TextOut( rect.left + 1, rect.bottom + 10, g_Neuz.m_apPlayer[i]->GetName(), 0xff6060ff );
}
else
p2DRender->TextOut( rect.left, rect.bottom + 10, g_Neuz.m_apPlayer[i]->GetName(), 0xff505050 );
CModelObject* pModel = (CModelObject*)m_pBipedMesh[ i ];
LPDIRECT3DDEVICE9 pd3dDevice = p2DRender->m_pd3dDevice;
pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
pd3dDevice->SetRenderState( D3DRS_AMBIENT, D3DCOLOR_ARGB( 255, 255,255,255) );
pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
//rect = GetClientRect();
// 뷰포트 세팅
D3DVIEWPORT9 viewport;
viewport.X = p2DRender->m_ptOrigin.x + rect.left;
viewport.Y = p2DRender->m_ptOrigin.y + rect.top;
viewport.Width = rect.Width();
viewport.Height = rect.Height();
viewport.MinZ = 0.0f;
viewport.MaxZ = 1.0f;
pd3dDevice->SetViewport(&viewport);
pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ;
// POINT point = GetMousePoint();
//point.x -= 280;
//point.y -= 15;
CRect rectViewport( 0, 0, viewport.Width, viewport.Height );
// 프로젝션
D3DXMATRIX matProj;
D3DXMatrixIdentity( &matProj );
FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4.0f, fAspect, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane );
pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
// 카메라
D3DXMATRIX matView;
D3DXVECTOR3 vecLookAt( 0.0f, 0.0f, 1.0f );
D3DXVECTOR3 vecPos( 0.0f, 0.5f, -3.5f );
D3DXMatrixLookAtLH( &matView, &vecPos, &vecLookAt, &D3DXVECTOR3(0.0f,1.0f,0.0f) );
pd3dDevice->SetTransform( D3DTS_VIEW, &matView );
// 월드
D3DXMATRIXA16 matWorld;
D3DXMATRIXA16 matScale;
D3DXMATRIXA16 matRot;
D3DXMATRIXA16 matTrans;
// 초기화
D3DXMatrixIdentity(&matScale);
D3DXMatrixIdentity(&matRot);
D3DXMatrixIdentity(&matTrans);
D3DXMatrixIdentity(&matWorld);
D3DXMatrixScaling(&matScale,1.6f,1.6f,1.6f);
D3DXMatrixTranslation(&matTrans,0.0f,-1.15f,0.0f);
D3DXMatrixMultiply(&matWorld,&matWorld,&matScale);
D3DXMatrixMultiply(&matWorld, &matWorld,&matRot);
D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans );
pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
// 랜더링
pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE );
pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );//m_bViewLight );
::SetLight( FALSE );
::SetFog( FALSE );
SetDiffuse( 1.0f, 1.0f, 1.0f );
SetAmbient( 1.0f, 1.0f, 1.0f );
O3D_ELEMENT *pElem = pModel->GetParts( PARTS_RIDE );
if( pElem && pElem->m_pObject3D )
pModel->TakeOffParts( PARTS_RIDE );
pElem = pModel->GetParts( PARTS_HAIR );
if( pElem && pElem->m_pObject3D )
{
pElem->m_pObject3D->m_fAmbient[0] = g_Neuz.m_apPlayer[i]->m_fHairColorR;
pElem->m_pObject3D->m_fAmbient[1] = g_Neuz.m_apPlayer[i]->m_fHairColorG;
pElem->m_pObject3D->m_fAmbient[2] = g_Neuz.m_apPlayer[i]->m_fHairColorB;
}
//pModel->FrameMove();
D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f );
#ifdef __YENV
g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst );
#else //__YENV
pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 );
#endif //__YENV
::SetTransformView( matView );
::SetTransformProj( matProj );
g_Neuz.m_apPlayer[i]->OverCoatItemRenderCheck(pModel);
// 헬멧이 머리카락 날려야하는것이냐? // 인벤이 없는경우
DWORD dwId = g_Neuz.m_apPlayer[i]->m_aEquipInfo[PARTS_CAP].dwId;
ItemProp* pItemProp = NULL;
if( dwId != NULL_ID )
{
O3D_ELEMENT* pElement = NULL;
pItemProp = prj.GetItemProp( dwId );
if( pItemProp && pItemProp->dwBasePartsIgnore != -1 )
{
pElement = pModel->SetEffect(pItemProp->dwBasePartsIgnore, XE_HIDE );
}
// 외투의상을 입었을경우 머리날릴것인가의 기준을 외투 모자를 기준으로 바꾼다
dwId = g_Neuz.m_apPlayer[i]->m_aEquipInfo[PARTS_HAT].dwId;
if( dwId != NULL_ID )
{
if( !(g_Neuz.m_apPlayer[i]->m_aEquipInfo[PARTS_HAT].byFlag & CItemElem::expired) )
{
pItemProp = prj.GetItemProp( dwId );
if( pItemProp && pItemProp->dwBasePartsIgnore != -1 )
{
if( pItemProp->dwBasePartsIgnore == PARTS_HEAD )
pModel->SetEffect(PARTS_HAIR, XE_HIDE );
pModel->SetEffect(pItemProp->dwBasePartsIgnore, XE_HIDE );
}
else
{
if( pElement )
pElement->m_nEffect &= ~XE_HIDE;
}
}
}
}
else
{
// 외투의상을 입었을경우 머리날릴것인가의 기준을 외투 모자를 기준으로 바꾼다
dwId = g_Neuz.m_apPlayer[i]->m_aEquipInfo[PARTS_HAT].dwId;
if( dwId != NULL_ID )
{
if( !(g_Neuz.m_apPlayer[i]->m_aEquipInfo[PARTS_HAT].byFlag & CItemElem::expired) )
{
pItemProp = prj.GetItemProp( dwId );
if( pItemProp && pItemProp->dwBasePartsIgnore != -1 )
{
if( pItemProp->dwBasePartsIgnore == PARTS_HEAD )
pModel->SetEffect(PARTS_HAIR, XE_HIDE );
pModel->SetEffect(pItemProp->dwBasePartsIgnore, XE_HIDE );
}
}
}
}
#ifdef __YENV
SetLightVec( D3DXVECTOR3( 0.0f, 0.0f, 1.0f ) );
#endif //__YENV
pModel->Render( p2DRender->m_pd3dDevice, &matWorld );
p2DRender->m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
p2DRender->m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
viewport.X = p2DRender->m_ptOrigin.x;// + 5;
viewport.Y = p2DRender->m_ptOrigin.y;// + 5;
viewport.Width = p2DRender->m_clipRect.Width();
viewport.Height = p2DRender->m_clipRect.Height();
viewport.MinZ = 0.0f;
viewport.MaxZ = 1.0f;
pd3dDevice->SetViewport(&viewport);
}
else
{
if( m_nSelectCharacter == i )
p2DRender->TextOut( rect.left, rect.bottom + 10, prj.GetText( TID_GAME_WND_SELECT_CHARACTER_EMPTY ), 0xff6060ff );
else
p2DRender->TextOut( rect.left, rect.bottom + 10, prj.GetText( TID_GAME_WND_SELECT_CHARACTER_EMPTY ), 0xff505050 );
}
if( m_nSelectCharacter == i )
{
if( g_Neuz.m_apPlayer[i] )
{
pWndCreate->EnableWindow( FALSE );
pWndAccept->EnableWindow( TRUE );
pWndDelete->EnableWindow( TRUE );
}
else
{
pWndCreate->EnableWindow( TRUE );
pWndAccept->EnableWindow( FALSE );
pWndDelete->EnableWindow( FALSE );
}
}
}
}
void CWndSelectChar::DeleteCharacter()
{
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
if( m_pBipedMesh[ i ] )
{
m_pBipedMesh[ i ]->InvalidateDeviceObjects();
m_pBipedMesh[ i ]->DeleteDeviceObjects();
SAFE_DELETE( m_pBipedMesh[ i ] );
}
}
}
void CWndSelectChar::UpdateCharacter()
{
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
CMover* pMover = g_Neuz.m_apPlayer[i];
if( pMover )
{
// 장착, 게이지에 나올 캐릭터 오브젝트 설정
int nMover = (pMover->GetSex() == SEX_MALE ? MI_MALE : MI_FEMALE);
m_pBipedMesh[ i ] = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE );
if( i == m_nSelectCharacter )
{
prj.m_modelMng.LoadMotion( m_pBipedMesh[ i ], OT_MOVER, nMover, MTI_STAND );
m_dwMotion[ i ] = MTI_STAND;
}
else
{
prj.m_modelMng.LoadMotion( m_pBipedMesh[ i ], OT_MOVER, nMover, MTI_SITSTAND );
m_dwMotion[ i ] = MTI_SITSTAND;
}
CMover::UpdateParts( pMover->GetSex(), pMover->m_dwSkinSet, pMover->m_dwFace, pMover->m_dwHairMesh, pMover->m_dwHeadMesh, pMover->m_aEquipInfo, m_pBipedMesh[ i ], NULL/*&pMover->m_Inventory*/ );
}
}
}
void CWndSelectChar::OnInitialUpdate()
{
CWndNeuz::OnInitialUpdate();
CRect rect = GetClientRect();
LPWNDCTRL lpText1 = GetWndCtrl( WIDC_CUSTOM1 );
LPWNDCTRL lpText2 = GetWndCtrl( WIDC_CUSTOM2 );
LPWNDCTRL lpText3 = GetWndCtrl( WIDC_CUSTOM3 );
// m_wndText1.Create( 0, lpText1->rect, this, WIDC_CUSTOM1 );
// m_wndText2.Create( 0, lpText2->rect, this, WIDC_CUSTOM2 );
// m_wndText3.Create( 0, lpText3->rect, this, WIDC_CUSTOM3 );
// m_wndText1.HideCaret();
// m_wndText2.HideCaret();
/// m_wndText3.HideCaret();
/*
CWndText* pWndText1 = (CWndText*)GetDlgItem( WIDC_TEXT1 );
CWndText* pWndText2 = (CWndText*)GetDlgItem( WIDC_TEXT2 );
CWndText* pWndText3 = (CWndText*)GetDlgItem( WIDC_TEXT3 );
pWndText1->DelWndStyle( WBS_VSCROLL );
pWndText2->DelWndStyle( WBS_VSCROLL );
pWndText3->DelWndStyle( WBS_VSCROLL );
*/
//rect.SetRect( 108, 349, 180, 370 );
//m_wndBack .Create( _T( "Back" ), 0, rect, this, 100 ); rect.OffsetRect( 83, 0 );
//m_wndCreate.Create( _T( "Create" ), 0, rect, this, 101 ); rect.OffsetRect( 83, 0 );
//m_wndDelete.Create( _T( "Delete" ), 0, rect, this, 102 ); rect.OffsetRect( 83, 0 );
//m_wndAccept.Create( _T( "Accept" ), 0, rect, this, 103 );
CWndButton* pWndButton = (CWndButton*)GetDlgItem( WIDC_DELETE );
//WndText* pWndText = (CWndButton*)GetDlgItem( WIDC_EDIT1 );
// pWndButton->EnableWindow( FALSE );
CWndButton* pWndAccept = (CWndButton*)GetDlgItem( WIDC_ACCEPT );
pWndAccept->SetDefault( TRUE );
CWndButton* pWndBack = (CWndButton*)GetDlgItem( WIDC_BACK );
pWndBack->SetFocus( );
// if( ::GetLanguage() == LANG_TWN )
// {
// pWndBack->EnableWindow( FALSE );
// }
m_bDisconnect = FALSE;
rect = CRect( 16, 16, 174, 254 );
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
m_aRect[ i ] = rect;
rect.OffsetRect( 170, 0 );
}
//서버통합 관련 특정 기간 캐릭터 생성 금지. 2007/01/02 ~ 2007/01/11 에만 사용.
#if defined( __MAINSERVER )
/* if(g_Option.m_nSer != 1)
{
CTime time = CTime::GetCurrentTime();
int year, month, day;
year = time.GetYear();
month = time.GetMonth();
day = time.GetDay();
if(year == 2007 && month == 1)
{
if(day > 1 && day < 12)
m_CreateApply = FALSE;
}
}
*/
#endif //( __MAINSERVER )
MoveParentCenter();
}
BOOL CWndSelectChar::Initialize(CWndBase* pWndParent,DWORD dwStyle)
{
//CRect rect = m_pWndRoot->MakeCenterRect(250,130);
CRect rect = m_pWndRoot->MakeCenterRect( 590, 400 );
SetTitle( _T( "Select Character" ) );
//return CWndNeuz::Create( WBS_MOVE | WBS_SOUND | WBS_CAPTION | WBS_THICKFRAME | WBS_MAXIMIZEBOX, rect, pWndParent, APP_SELECT_CHAR );
return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_SELECT_CHAR, WBS_KEY, CPoint( 0, 0 ), pWndParent );
//return CWndNeuz::Create(dwStyle|WBS_MOVE|WBS_SOUND|WBS_CAPTION|WBS_THICKFRAME|WBS_MAXIMIZEBOX,rect,pWndParent,10);
}
void CWndSelectChar::Connected()
{
if( m_nSelectCharacter < 0 || m_nSelectCharacter >= 5 )
{
LPCTSTR szErr = Error( "CWndSelectChar::Connected : 범위초과 %d", m_nSelectCharacter );
ADDERRORMSG( szErr );
int *p = NULL;
*p = 1;
}
#ifdef __USE_IDPLAYER0519
#ifdef __GPAUTH_01
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendPreJoin( g_Neuz.m_bGPotatoAuth? g_Neuz.m_szGPotatoNo: g_Neuz.m_szAccount, g_Neuz.m_apPlayer[m_nSelectCharacter]->m_idPlayer, m_nSelectCharacter, g_Neuz.m_n2ndPasswordNumber );
#else __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendPreJoin( g_Neuz.m_bGPotatoAuth? g_Neuz.m_szGPotatoNo: g_Neuz.m_szAccount, g_Neuz.m_apPlayer[m_nSelectCharacter]->m_idPlayer, m_nSelectCharacter );
#endif // __2ND_PASSWORD_SYSTEM
#else // __GPAUTH_01
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendPreJoin( g_Neuz.m_szAccount, g_Neuz.m_apPlayer[m_nSelectCharacter]->m_idPlayer, m_nSelectCharacter, g_Neuz.m_n2ndPasswordNumber );
#else __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendPreJoin( g_Neuz.m_szAccount, g_Neuz.m_apPlayer[m_nSelectCharacter]->m_idPlayer, m_nSelectCharacter );
#endif // __2ND_PASSWORD_SYSTEM
#endif // __GPAUTH_01
#else // __USE_IDPLAYER0519
#ifdef __GPAUTH_01
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendPreJoin( g_Neuz.m_bGPotatoAuth? g_Neuz.m_szGPotatoNo: g_Neuz.m_szAccount, g_Neuz.m_apPlayer[m_nSelectCharacter]->m_idPlayer, g_Neuz.m_apPlayer[m_nSelectCharacter]->GetName(), m_nSelectCharacter, g_Neuz.m_n2ndPasswordNumber );
#else __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendPreJoin( g_Neuz.m_bGPotatoAuth? g_Neuz.m_szGPotatoNo: g_Neuz.m_szAccount, g_Neuz.m_apPlayer[m_nSelectCharacter]->m_idPlayer, g_Neuz.m_apPlayer[m_nSelectCharacter]->GetName(), m_nSelectCharacter );
#endif // __2ND_PASSWORD_SYSTEM
#else // __GPAUTH_01
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendPreJoin( g_Neuz.m_szAccount, g_Neuz.m_apPlayer[m_nSelectCharacter]->m_idPlayer, g_Neuz.m_apPlayer[m_nSelectCharacter]->GetName(), m_nSelectCharacter, g_Neuz.m_n2ndPasswordNumber );
#else __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendPreJoin( g_Neuz.m_szAccount, g_Neuz.m_apPlayer[m_nSelectCharacter]->m_idPlayer, g_Neuz.m_apPlayer[m_nSelectCharacter]->GetName(), m_nSelectCharacter );
#endif // __2ND_PASSWORD_SYSTEM
#endif // __GPAUTH_01
#endif // __USE_IDPLAYER0519
CNetwork::GetInstance().OnEvent( LOGIN_REQ_PREJOIN );
// ata2k - (1)시간 저정
if( ::GetLanguage() == LANG_ENG && ::GetSubLanguage() == LANG_SUB_USA )
g_Neuz.m_dwTimeOutDis = GetTickCount() + SEC( 30 );
else
g_Neuz.m_dwTimeOutDis = GetTickCount() + SEC( 15 );
}
BOOL CWndSelectChar::OnChildNotify(UINT message,UINT nID,LRESULT* pLResult)
{
if( !g_Neuz.m_timerConnect.Over() )
return CWndNeuz::OnChildNotify( message, nID, pLResult );
switch(nID)
{
case 10000: // close msg
case WIDC_BACK: // Back
{
#ifdef __CERTIFIER_COLLECTING_SYSTEM
DPCollectClient->DeleteDPObject();
#endif // __CERTIFIER_COLLECTING_SYSTEM
g_dpLoginClient.DeleteDPObject();
Sleep( 1000 ); // 임시.
# ifdef __CRC
if( !g_dpCertified.ConnectToServer( g_Neuz.m_lpCertifierAddr, PN_CERTIFIER, TRUE, CSock::crcWrite ) )
# else // __CRC
if( !g_dpCertified.ConnectToServer( g_Neuz.m_lpCertifierAddr, PN_CERTIFIER, TRUE ) )
# endif // __CRC
{
// Can't connect to server
g_WndMng.OpenMessageBox( _T( prj.GetText(TID_DIAG_0043) ) );
// g_WndMng.OpenMessageBox( _T( "접속할 수 없습니다. 네트워크 상태를 확인하십시오." ) );
CNetwork::GetInstance().OnEvent( CERT_CONNECT_FAIL );
break;
}
CNetwork::GetInstance().OnEvent( CERT_CONNECTED );
Destroy();
g_dpCertified.SendCertify();
GetNProtect()->Send( (LPCSTR)g_Neuz.m_szAccount );
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_LOGIN );
CWndBase* pWndBase = g_WndMng.GetWndBase( APP_LOGIN );
// pWndBase->SetVisible( FALSE );
break;
}
case WIDC_CREATE: // Create
if( m_nSelectCharacter != -1 && g_Neuz.m_apPlayer[ m_nSelectCharacter ] == NULL )
{
if(m_CreateApply) //서버통합 관련 특정 기간 캐릭터 생성 금지.
{
u_short uSlot = (u_short)m_nSelectCharacter;
Destroy();
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_CREATE_CHAR );
CWndCreateChar* pWndCreateChar = (CWndCreateChar*)g_WndMng.GetWndBase( APP_CREATE_CHAR );
if( pWndCreateChar ) {
pWndCreateChar->m_Player.m_uSlot = uSlot;
}
}
else
{
// g_WndMng.OpenMessageBox( _T( prj.GetText(TID_GAME_CREATECHAR_WARNNING) ) ); //Message : 서버통합 관련 특정 기간 캐릭터 생성 금지.
}
}
break;
case WIDC_DELETE: // Delete
if( m_nSelectCharacter != -1 && g_Neuz.m_apPlayer[ m_nSelectCharacter ] )
{
SAFE_DELETE( m_pWndDeleteChar );
m_pWndDeleteChar = new CWndDeleteChar;
m_pWndDeleteChar->Initialize( this, APP_DELETE_CHAR );
}
break;
case WIDC_ACCEPT: // Accept
{
switch( m_nSelectCharacter )
{
case 0:
g_Option.m_pGuide = &(g_Option.m_nGuide1);
break;
case 1:
g_Option.m_pGuide = &(g_Option.m_nGuide2);
break;
case 2:
g_Option.m_pGuide = &(g_Option.m_nGuide3);
break;
default:
Error( "선택한 캐릭터 번호가 이상함!! : %d", m_nSelectCharacter );
return FALSE;
}
CWndButton* pWndAccept = (CWndButton*)GetDlgItem( WIDC_ACCEPT );
pWndAccept->EnableWindow( FALSE );
}
#ifdef __CERTIFIER_COLLECTING_SYSTEM
DPCollectClient->DeleteDPObject();
#endif // __CERTIFIER_COLLECTING_SYSTEM
if( g_Neuz.m_nCharacterBlock[m_nSelectCharacter] == 0 )
{
g_WndMng.OpenCustomBox( NULL, new CWndCharBlockBox );
}
else
{
if( FALSE == g_dpLoginClient.IsConnected() )
{
CNetwork::GetInstance().OnEvent( CACHE_CONNECT_STEP_ERROR );
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_LOGIN );
Destroy();
g_dpLoginClient.DeleteDPObject();
break;
}
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
if( ::IsUse2ndPassWord() == TRUE )
{
if( m_pWnd2ndPassword )
SAFE_DELETE( m_pWnd2ndPassword );
m_pWnd2ndPassword = new CWnd2ndPassword();
m_pWnd2ndPassword->Initialize( this, APP_2ND_PASSWORD_NUMBERPAD );
m_pWnd2ndPassword->SetInformation( g_dpLoginClient.GetNumberPad(), m_nSelectCharacter );
#ifdef __CON_AUTO_LOGIN
int i; for( i = 0; i < 4; ++i )
m_pWnd2ndPassword->InsertPassword( g_Console._nPasswordFigure[ i ] );
m_pWnd2ndPassword->OnChildNotify( 0, WIDC_BUTTON_OK, 0 );
#endif // __CON_AUTO_LOGIN
}
else
{
g_WndMng.OpenCustomBox( _T( prj.GetText(TID_DIAG_0064) ), new CWndConnectingBox );
//g_WndMng.OpenCustomBox( _T( "로딩중입니다. 잠시만 기다려 주십시오." ), new CWndConnectingBox );
if( g_DPlay.Connect( g_Neuz.m_lpCacheAddr, g_Neuz.m_uCachePort ) )
{
CNetwork::GetInstance().OnEvent( CACHE_CONNECTED );
if( m_nSelectCharacter != -1 && g_Neuz.m_apPlayer[m_nSelectCharacter] )
{
#if __VER < 8 // __S8_PK
// 한국은 2005/11/1 PK서버가 없어지고, 아래의 코드가 있으면 카오인 유저는 모든 서버에 접속 할 수 없으므로 막는다.
if( ::GetLanguage() != LANG_KOR )
{
if( g_Neuz.m_b18Server == FALSE && g_Neuz.m_apPlayer[m_nSelectCharacter]->IsChaotic() )
{
//g_WndMng.OpenMessageBox( "선택된 플레이어는 카르마 수치가 낮아서 PK서버에만 접속 할 수 있습니다." );
g_WndMng.OpenMessageBox( prj.GetText(TID_PK_REFUSE_CHAOTIC) );
break;
}
}
#endif // __VER < 8 // __S8_PK
g_Neuz.m_dwTempMessage = 1;
g_Neuz.m_timerConnect.Set( SEC( 1 ) );
}
}
else
{
CNetwork::GetInstance().OnEvent( CACHE_CONNECT_FAIL );
TRACE( _T( "Can't connect to server. : %s \n" ), g_Neuz.m_lpCacheAddr );
}
}
#else // __2ND_PASSWORD_SYSTEM
g_WndMng.OpenCustomBox( _T( prj.GetText(TID_DIAG_0064) ), new CWndConnectingBox );
//g_WndMng.OpenCustomBox( _T( "로딩중입니다. 잠시만 기다려 주십시오." ), new CWndConnectingBox );
if( g_DPlay.Connect( g_Neuz.m_lpCacheAddr, g_Neuz.m_uCachePort ) )
{
CNetwork::GetInstance().OnEvent( CACHE_CONNECTED );
if( m_nSelectCharacter != -1 && g_Neuz.m_apPlayer[m_nSelectCharacter] )
{
#if __VER < 8 // __S8_PK
// 한국은 2005/11/1 PK서버가 없어지고, 아래의 코드가 있으면 카오인 유저는 모든 서버에 접속 할 수 없으므로 막는다.
if( ::GetLanguage() != LANG_KOR )
{
if( g_Neuz.m_b18Server == FALSE && g_Neuz.m_apPlayer[m_nSelectCharacter]->IsChaotic() )
{
//g_WndMng.OpenMessageBox( "선택된 플레이어는 카르마 수치가 낮아서 PK서버에만 접속 할 수 있습니다." );
g_WndMng.OpenMessageBox( prj.GetText(TID_PK_REFUSE_CHAOTIC) );
break;
}
}
#endif // __VER < 8 // __S8_PK
g_Neuz.m_dwTempMessage = 1;
g_Neuz.m_timerConnect.Set( SEC( 1 ) );
}
}
else
{
CNetwork::GetInstance().OnEvent( CACHE_CONNECT_FAIL );
TRACE( _T( "Can't connect to server. : %s \n" ), g_Neuz.m_lpCacheAddr );
}
#endif // __2ND_PASSWORD_SYSTEM
}
break;
}
return CWndNeuz::OnChildNotify( message, nID, pLResult );
}
BOOL CWndSelectChar::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase )
{
/*
switch(nID)
{
case 100:
g_WndMng.OpenField();
break;
case 101:
break;
case 102:
//g_WndMng.OpenCustomBox("종료하시겠습니까?",new CWndExitBox);
break;
case 1000:
break;
case 1001:
if(dwMessage == WM_KEYDOWN)
{
m_wndText.m_string += g_Neuz.m_pPlayer->m_szName;
m_wndText.m_string += " :\n ";
m_wndText.m_string += m_wndChat.m_string;
m_wndText.m_string += '\n';
m_wndText.m_string.Reset( g_2DRender.m_pFont, &m_wndText.GetClientRect() );
m_wndText.UpdateScrollBar();
m_wndText.m_wndScrollBar.SetMaxScrollPos();
m_wndChat.Empty();
}
break;
}
*/
return CWndNeuz::OnCommand( nID, dwMessage, pWndBase );
}
void CWndSelectChar::OnSize(UINT nType, int cx, int cy)
{
/*
CRect rect = GetClientRect();
rect.bottom = rect.bottom - 40; //20;
rect.right -= 50;
rect.DeflateRect( 1, 1 );
m_wndText.SetWndRect( rect );
rect = GetClientRect();
rect.top = rect.bottom - 37; //20;
rect.right -= 50;
rect.DeflateRect( 1, 1 );
m_wndChat.SetWndRect( rect );
rect = GetClientRect();
rect.left = rect.right - 47; rect.right -= 3; rect.top += 3; rect.bottom = rect.top + 20;
m_wndLogin.SetWndRect( rect ); rect.OffsetRect( 0, 25 );
m_wndRegist.SetWndRect( rect ); rect.OffsetRect( 0, 25 );
m_wndQuit.SetWndRect( rect );
*/
CWndNeuz::OnSize(nType,cx,cy);
}
BOOL CWndSelectChar::SetMotion( CModelObject* pModel, DWORD dwIndex, DWORD dwMotion, int nLoop, DWORD dwOption )
{
//CModelObject* pModel = (CModelObject*)pModel;
DWORD dwOrigMotion = dwMotion;
/*
static DWORD m_dwOrigMotion = MTI_STAND;
if( dwMotion == m_dwOrigMotion ) // 같은 모션을 하라고 했는데...
{
if( nLoop == ANILOOP_LOOP ) return FALSE; // 루핑모드 이면 걍 리턴
if( pModel->m_bEndFrame == FALSE ) // 아직 애니메이션중일때는
return FALSE; // 취소.
if( pModel->m_bEndFrame && nLoop == ANILOOP_CONT ) // 애니메이션이 끝난상태고 지속모드면 마지막 프레임으로 지속
return FALSE;
}
*/
prj.m_modelMng.LoadMotion( pModel, OT_MOVER, dwIndex, dwMotion );
//m_dwOrigMotion = dwMotion;
pModel->m_bEndFrame = FALSE;
pModel->SetLoop( nLoop );
if( dwOption & MOP_NO_TRANS ) pModel->SetMotionBlending( FALSE );
else pModel->SetMotionBlending( TRUE );
return TRUE;
}
void CWndSelectChar::SelectCharacter( int i )
{
if( m_nSelectCharacter != i )
{
m_nSelectCharacter = i;
CMover* pMover = g_Neuz.m_apPlayer[ i ];
if( pMover )
{
int nMover = (pMover->GetSex() == SEX_MALE ? MI_MALE : MI_FEMALE);
CModelObject* pModel = (CModelObject*)m_pBipedMesh[ m_nSelectCharacter ];
if( pModel )
SetMotion( pModel, nMover, MTI_GETUP, ANILOOP_1PLAY, 0 );
m_dwMotion[ i ] = MTI_GETUP;
//pModel->SetMotion( MTI_SIT, ANILOOP_1PLAY ); // idle2 액션
if( ::GetLanguage() == LANG_JAP && g_Option.m_bVoice )
{
float fVolume = 0;
fVolume = g_Option.m_fEffectVolume;
g_SoundMng.m_nSoundVolume = 0;
if( pMover->GetSex() == SEX_MALE )
PLAYSND( "VocM-CharaChoice.wav" );
else
PLAYSND( "VocF-CharaChoice.wav" );
g_SoundMng.m_nSoundVolume = (int)( -(1.0f-fVolume)*5000 );
}
}
}
}
void CWndSelectChar::OnLButtonUp(UINT nFlags, CPoint point)
{
if( !g_Neuz.m_timerConnect.Over() )
return;
int i; for( i = 0; i < MAX_CHARACTER_LIST; i++ )
{
if( /*m_pBipedMesh[ i ] &&*/ m_aRect[ i ].PtInRect( point ) )
{
if( g_Neuz.m_nCharacterBlock[i] == 0 )
{
g_WndMng.OpenCustomBox( NULL, new CWndCharBlockBox );
}
else
{
SelectCharacter( i );
}
}
}
}
//pMover->SetMotion( MTI_STAND );
void CWndSelectChar::OnLButtonDown(UINT nFlags, CPoint point)
{
}
/////////////////////////////////////////////////////////////////////////////////////
// Select Character
/////////////////////////////////////////////////////////////////////////////////////
CWndCreateChar::CWndCreateChar()
{
m_pModel = NULL;
m_Player.m_bySkinSet = SKINSET_01;
m_Player.m_byHairMesh = HAIRMESH_01;
m_Player.m_byHairColor = 0;
m_Player.m_byHeadMesh = 0;
m_Player.m_bySex = SEX_FEMALE;
m_Player.m_byCostume = 0;
SetPutRegInfo( FALSE );
}
CWndCreateChar::~CWndCreateChar()
{
InvalidateDeviceObjects();
DeleteDeviceObjects();
SAFE_DELETE( m_pModel );
}
HRESULT CWndCreateChar::InitDeviceObjects()
{
CWndBase::InitDeviceObjects();
if( m_pModel )
m_pModel->InitDeviceObjects( m_pApp->m_pd3dDevice );
return S_OK;
}
HRESULT CWndCreateChar::RestoreDeviceObjects()
{
CWndBase::RestoreDeviceObjects();
if( m_pModel )
m_pModel->RestoreDeviceObjects();
return S_OK;
}
HRESULT CWndCreateChar::InvalidateDeviceObjects()
{
CWndBase::InvalidateDeviceObjects();
if( m_pModel )
m_pModel->InvalidateDeviceObjects();
return S_OK;
}
HRESULT CWndCreateChar::DeleteDeviceObjects()
{
CWndBase::DeleteDeviceObjects();
//m_pModel->DeleteDeviceObjects();
return S_OK;
}
void CWndCreateChar::OnDraw( C2DRender* p2DRender )
{
CRect rect = GetClientRect();
CPoint pt( 20, 15 );
/*
int i; for( i = 0; i < 5; i++)
{
p2DRender->RenderLine( pt, CPoint( pt.x + 200, pt. y ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
p2DRender->RenderLine( CPoint( pt.x - 10, pt.y + 20 ), CPoint( pt.x + 200 - 10, pt. y + 20 ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
p2DRender->RenderLine( pt, CPoint( pt.x - 10, pt.y + 20 ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
p2DRender->RenderLine( CPoint( pt.x + 200, pt. y ), CPoint( pt.x + 200 - 10, pt. y + 20 ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
p2DRender->RenderLine( CPoint( pt.x + 100, pt. y ), CPoint( pt.x + 100 - 10, pt. y + 20 ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
pt.y += 30;
}
*/
pt = CPoint( 260, 15 );
// p2DRender->RenderLine( pt, CPoint( pt.x + 300, pt. y ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
// p2DRender->RenderLine( CPoint( pt.x - 10, pt.y + 220 ), CPoint( pt.x + 300 - 10, pt. y + 220 ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
// p2DRender->RenderLine( pt, CPoint( pt.x - 10, pt.y + 20 ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
// p2DRender->RenderLine( CPoint( pt.x + 300, pt. y ), CPoint( pt.x + 300 - 10, pt. y + 20 ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
/*
rect = CRect( 30, 10, 115, 230 );
int y = 50;
p2DRender->TextOut( rect.left, rect.top + y, _T( "Name" ) ); y += 50;
p2DRender->TextOut( rect.left, rect.top + y, _T( "Job" ) ); y += 30;
p2DRender->TextOut( rect.left, rect.top + y, _T( "Gender" ) ); y += 30;
p2DRender->TextOut( rect.left, rect.top + y, _T( "Hair Style" ) ); y += 30; // 머리카락 모양
p2DRender->TextOut( rect.left, rect.top + y, _T( "Hair Color" ) ); y += 30; // 피부색 및 얼굴
p2DRender->TextOut( rect.left, rect.top + y, _T( "Face" ) ); y += 30; // 피부색 및 얼굴
*/
//p2DRender->TextOut( rect.left, rect.top + y, _T( "Costume" ) ); y += 30; // 피부색 및 얼굴
//p2DRender->TextOut( rect.left, rect.top +130, _T( "Skin Color" ) );
//DRender->TextOut( rect.left, rect.top +220, _T( "Underwear" ) );
//p2DRender->TextOut( rect.left, rect.top +130, _T( "Underwear" ) );
//p2DRender->RenderRoundRect(CRect(4, 4,128*2+6, 96+6),D3DCOLOR_TEMP(255,150,150,250));
/*
CRect rect = CRect( 4, 96 + 6 + 4, 128 * 2 + 6, 96 + 6 + 4 + 96 + 6 );
p2DRender->RenderRoundRect( rect, D3DCOLOR_TEMP( 255, 150, 150, 250 ) );
rect.DeflateRect( 1, 1 );
p2DRender->RenderFillRect( rect, D3DCOLOR_TEMP( 255, 200, 200, 240 ) );
CRect rect = CRect( 4, 96 + 6 + 4, 128 * 2 + 6, 96 + 6 + 4 + 96 + 6 );
p2DRender->RenderRoundRect( rect, D3DCOLOR_TEMP( 255, 150, 150, 250 ) );
rect.DeflateRect( 1, 1 );
p2DRender->RenderFillRect( rect, D3DCOLOR_TEMP( 255, 200, 200, 240 ) );
*/
//p2DRender->TextOut(10,60,"aaaa",D3DCOLOR_TEMP(255,100,100,200));
LPDIRECT3DDEVICE9 pd3dDevice = p2DRender->m_pd3dDevice;
pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
//pd3dDevice->SetTextureStageState( 0, D3DTSS_MINFILTER, D3DTEXF_LINEAR );
//pd3dDevice->SetTextureStageState( 0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR );
pd3dDevice->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
pd3dDevice->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
pd3dDevice->SetRenderState( D3DRS_AMBIENT, D3DCOLOR_ARGB( 255, 255,255,255) );
pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
rect = GetClientRect();
// p2DRender->RenderRect( CRect( 280, 15, 550, 320 ), D3DCOLOR_ARGB( 200, 50, 150, 250 ) );
/*
pd3dDevice->SetRenderState( D3DRS_FOGENABLE, TRUE );
//pd3dDevice->SetRenderState( D3DRS_FOGENABLE, bEnable );
if(1)
{
pd3dDevice->SetRenderState( D3DRS_FOGCOLOR, 0xffffffff ) ;//CWorld::m_dwBgColor );
//pd3dDevice->SetRenderState( D3DRS_FOGSTART, FtoDW(m_fFogStartValue) );
//pd3dDevice->SetRenderState( D3DRS_FOGEND, FtoDW(m_fFogEndValue) );
//pd3dDevice->SetRenderState( D3DRS_FOGDENSITY, FtoDW(m_fFogDensity) );
if( 1) //m_bUsingTableFog )
{
pd3dDevice->SetRenderState( D3DRS_FOGVERTEXMODE, D3DFOG_NONE );
// pd3dDevice->SetRenderState( D3DRS_FOGTABLEMODE, D3DFOG_NONE );
// pd3dDevice->SetRenderState( D3DRS_RANGEFOGENABLE, FALSE );
pd3dDevice->SetRenderState( D3DRS_FOGTABLEMODE, D3DFOG_LINEAR );
}
}
pd3dDevice->SetRenderState( D3DRS_FOGVERTEXMODE, D3DFOG_NONE );
pd3dDevice->SetRenderState( D3DRS_FOGTABLEMODE, D3DFOG_NONE );
*/
// 뷰포트 세팅
D3DVIEWPORT9 viewport;
viewport.X = p2DRender->m_ptOrigin.x + 280;
viewport.Y = p2DRender->m_ptOrigin.y + 0;
viewport.Width = 550 - 280;
viewport.Height = 320 - 15;
viewport.MinZ = 0.0f;
viewport.MaxZ = 1.0f;
pd3dDevice->SetViewport(&viewport);
pd3dDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0xffa08080, 1.0f, 0 ) ;
POINT point = GetMousePoint();
point.x -= 280;
point.y -= 15;
CRect rectViewport( 0, 0, viewport.Width, viewport.Height );
/*
// 프로젝션
D3DXMATRIX matProj;
D3DXMatrixIdentity( &matProj );
pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
FLOAT fAspect = ((FLOAT)viewport.Width) / (FLOAT)viewport.Height;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4.0f, fAspect, CWorld::m_fNearPlane - 0.01f, CWorld::m_fFarPlane );
pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
*/
D3DXMATRIX matProj;
D3DXMatrixIdentity( &matProj );
FLOAT fAspect = ( (FLOAT) viewport.Width ) / (FLOAT) viewport.Height ;
FLOAT fov = D3DX_PI / 4.0f;//796.0f;
FLOAT h = cos( fov / 2 ) / sin( fov / 2 );
FLOAT w = h * fAspect;
D3DXMatrixOrthoLH( &matProj, w, h, 1.0f, 10.0f );
pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
// 카메라
D3DXMATRIX matView;
D3DXVECTOR3 vecLookAt( 0.0f, 0.0f, 3.0f );
D3DXVECTOR3 vecPos( 0.0f, 0.0f, -5.0f );
/*
if( rectViewport.PtInRect( point ) )
{
// height : 100 = point.y = ?
int x = 100 * point.x / rectViewport.Width();
int y = 100 * point.y / rectViewport.Height();
x -= 50;
y -= 50;
//vecPos.x = x; vecLookAt.x = x;
vecPos.y = (FLOAT)-y / 60.0f; vecLookAt.y = (FLOAT)-y / 60.0f;
vecPos.z += (FLOAT)-y / 20.0f; vecLookAt.z += (FLOAT)-y / 20.0f;
}
*/
D3DXMatrixLookAtLH( &matView, &vecPos, &vecLookAt, &D3DXVECTOR3(0.0f,1.0f,0.0f) );
pd3dDevice->SetTransform( D3DTS_VIEW, &matView );
// 월드
D3DXMATRIXA16 matWorld;
D3DXMATRIXA16 matScale;
D3DXMATRIXA16 matRot;
D3DXMATRIXA16 matTrans;
// 초기화
D3DXMatrixIdentity(&matScale);
D3DXMatrixIdentity(&matRot);
D3DXMatrixIdentity(&matTrans);
D3DXMatrixIdentity(&matWorld);
D3DXMatrixScaling(&matScale,1.4f,1.4f,1.4f);
D3DXMatrixTranslation(&matTrans,0.0f,-1.1f,0.0f);
D3DXMatrixMultiply(&matWorld,&matWorld,&matScale);
D3DXMatrixMultiply(&matWorld, &matWorld,&matRot);
D3DXMatrixMultiply(&matWorld, &matWorld, &matTrans );
pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
// 랜더링
pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE );
pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );//m_bViewLight );
::SetLight( FALSE );
::SetFog( FALSE );
SetDiffuse( 1.0f, 1.0f, 1.0f );
SetAmbient( 1.0f, 1.0f, 1.0f );
m_pModel->FrameMove();
D3DXVECTOR4 vConst( 1.0f, 1.0f, 1.0f, 1.0f );
#ifdef __YENV
g_Neuz.m_pEffect->SetVector( g_Neuz.m_hvFog, &vConst );
#else //__YENV
pd3dDevice->SetVertexShaderConstantF( 95, (float*)&vConst, 1 );
#endif //__YENV
::SetTransformView( matView );
::SetTransformProj( matProj );
O3D_ELEMENT* pElem = m_pModel->GetParts( PARTS_HAIR );
if( pElem && pElem->m_pObject3D )
{
if( m_Player.m_bySex == SEX_MALE )
{
pElem->m_pObject3D->m_fAmbient[0] = (nMaleHairColor[m_Player.m_byHairMesh][0])/255.f;
pElem->m_pObject3D->m_fAmbient[1] = (nMaleHairColor[m_Player.m_byHairMesh][1])/255.f;
pElem->m_pObject3D->m_fAmbient[2] = (nMaleHairColor[m_Player.m_byHairMesh][2])/255.f;
}
else
{
pElem->m_pObject3D->m_fAmbient[0] = (nFeMaleHairColor[m_Player.m_byHairMesh][0])/255.f;
pElem->m_pObject3D->m_fAmbient[1] = (nFeMaleHairColor[m_Player.m_byHairMesh][1])/255.f;
pElem->m_pObject3D->m_fAmbient[2] = (nFeMaleHairColor[m_Player.m_byHairMesh][2])/255.f;
}
}
m_pModel->Render( p2DRender->m_pd3dDevice, &matWorld );
p2DRender->m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
p2DRender->m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
viewport.X = p2DRender->m_ptOrigin.x;// + 5;
viewport.Y = p2DRender->m_ptOrigin.y;// + 5;
viewport.Width = p2DRender->m_clipRect.Width();
viewport.Height = p2DRender->m_clipRect.Height();
viewport.MinZ = 0.0f;
viewport.MaxZ = 1.0f;
pd3dDevice->SetViewport(&viewport);
}
void CWndCreateChar::OnInitialUpdate()
{
CWndNeuz::OnInitialUpdate();
m_Player.m_byJob = JOB_VAGRANT;
CWndButton* pWndHairColorLeft = (CWndButton*) GetDlgItem( WIDC_HAIRCOLOR_LEFT );
CWndButton* pWndHairColorRight = (CWndButton*) GetDlgItem( WIDC_HAIRCOLOR_RIGHT );
CWndButton* pWndHairFaceLeft = (CWndButton*) GetDlgItem( WIDC_FACE_LEFT );
CWndButton* pWndHairFaceRight = (CWndButton*) GetDlgItem( WIDC_FACE_RIGHT );
if( GetLanguage() != LANG_THA )
{
CWndStatic * pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC7 );
if( pStatic )
pStatic->EnableWindow( FALSE );
pStatic = (CWndStatic*)GetDlgItem( WIDC_STATIC8 );
if( pStatic )
pStatic->EnableWindow( FALSE );
}
pWndHairColorLeft->EnableWindow( FALSE );
pWndHairColorRight->EnableWindow( FALSE );
CWndButton* pWndOk = (CWndButton*)GetDlgItem( WIDC_OK );
pWndOk->SetDefault( TRUE );
SetSex( m_Player.m_bySex );
MoveParentCenter();
CWndEdit* pWndName = (CWndEdit*) GetDlgItem( WIDC_NAME );
pWndName->SetFocus();
m_Player.m_byHairMesh = (char)( xRandom( 0, MAX_BASE_HAIR ) );
m_Player.m_byHeadMesh = (char)( xRandom( 0, MAX_DEFAULT_HEAD ) );
CMover::UpdateParts( m_Player.m_bySex, m_Player.m_bySkinSet, m_Player.m_byFace, m_Player.m_byHairMesh, m_Player.m_byHeadMesh, m_Player.m_aEquipInfo, m_pModel, NULL );
CWndStatic* pWnd2ndPasswordText = ( CWndStatic* )GetDlgItem( WIDC_STATIC_2ND_PASSWORD_TEXT );
assert( pWnd2ndPasswordText );
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
pWnd2ndPasswordText->m_dwColor = D3DCOLOR_ARGB( 255, 255, 0, 0 );
CWndEdit* pWnd2ndPassword = ( CWndEdit* )GetDlgItem( WIDC_EDIT_2ND_PASSWORD );
assert( pWnd2ndPassword );
pWnd2ndPassword->AddWndStyle( EBS_PASSWORD | EBS_AUTOHSCROLL | EBS_NUMBER );
pWnd2ndPassword->SetMaxStringNumber( MAX_2ND_PASSWORD_NUMBER );
CWndEdit* pWnd2ndPasswordConfirm = ( CWndEdit* )GetDlgItem( WIDC_EDIT_2ND_PASSWORD_CONFIRM );
assert( pWnd2ndPasswordConfirm );
pWnd2ndPasswordConfirm->AddWndStyle( EBS_PASSWORD | EBS_AUTOHSCROLL | EBS_NUMBER );
pWnd2ndPasswordConfirm->SetMaxStringNumber( MAX_2ND_PASSWORD_NUMBER );
#else // __2ND_PASSWORD_SYSTEM
pWnd2ndPasswordText->EnableWindow( FALSE );
#endif // __2ND_PASSWORD_SYSTEM
}
void CWndCreateChar::SetSex( int nSex )
{
m_Player.m_bySex = nSex;
int nMover = m_Player.m_bySex == SEX_MALE ? MI_MALE : MI_FEMALE;
SAFE_DELETE( m_pModel );
m_pModel = (CModelObject*)prj.m_modelMng.LoadModel( g_Neuz.m_pd3dDevice, OT_MOVER, nMover, TRUE );
if( nSex == SEX_MALE )
prj.m_modelMng.LoadMotion( m_pModel, OT_MOVER, nMover, MTI_STAND );
else
prj.m_modelMng.LoadMotion( m_pModel, OT_MOVER, nMover, MTI_STAND2 ); // 포니테일 앞으로
memset( m_Player.m_aEquipInfo, 0, sizeof(EQUIP_INFO) * MAX_HUMAN_PARTS );
{
int i; for( i = 0; i < MAX_HUMAN_PARTS; i++ )
m_Player.m_aEquipInfo[i].dwId = NULL_ID;
}
int i; for( i = 0; i < MAX_BEGINEQUIP; i++ )
{
DWORD dwEquip = prj.m_jobItem[ m_Player.m_byJob ].adwMale[ i ][ m_Player.m_bySex ];
if( dwEquip != NULL_ID )
{
ItemProp* pItemProp = prj.GetItemProp( dwEquip );
m_Player.m_aEquipInfo[pItemProp->dwParts].dwId = dwEquip;
}
}
CMover::UpdateParts( m_Player.m_bySex, 0, m_Player.m_bySkinSet, m_Player.m_byHairMesh, m_Player.m_byHeadMesh, m_Player.m_aEquipInfo, m_pModel, NULL );
}
BOOL CWndCreateChar::Initialize( CWndBase* pWndParent, DWORD dwStyle )
{
CRect rect = m_pWndRoot->MakeCenterRect( 590, 400 );
return CWndNeuz::InitDialog( g_Neuz.GetSafeHwnd(), APP_CREATE_CHAR, WBS_KEY, CPoint( 0, 0 ), pWndParent );
}
DWORD IsValidPlayerNameTWN( CString& string )
{
const char* begin = string;
const char* end = begin + string.GetLength();
const char* iter = begin;
char bytes[16];
while( *iter && iter < end )
{
const char* next = CharNext(iter);
memcpy( bytes, iter, next-iter );
bytes[next-iter] = 0;
if( IsMultiByte( iter ) )
{
wchar_t ch = MAKEWORD( bytes[1], bytes[0] );
if( ch >= 0xA259 && ch <= 0xA261 || ch == 0xA2CD || ch >= 0xA440 && ch <= 0xC67E || ch >= 0xC940 && ch <= 0xF9D5 )
;
else
return TID_DIAG_0014;
}
else if( isalnum( bytes[0] ) == FALSE || iscntrl( bytes[0] ) )
return TID_DIAG_0013;
iter = next;
}
return 0;
}
// return 0 : OK
// 0 > : error
DWORD IsValidPlayerName( CString& strName )
{
strName.TrimLeft();
strName.TrimRight();
LPCTSTR lpszString = strName;
if( strName.IsEmpty() || strName.Find(" ") != -1 )
return TID_DIAG_0031; // "이름을 입력하십시오."
#ifdef __RULE_0615
// "이름은 한글 2자 이상, 8자 이하로 입력하십시오."
// "이름은 영문 4자 이상, 16자 이하로 입력하십시오."
if( strName.GetLength() < 4 || strName.GetLength() > 16 )
return TID_DIAG_RULE_0;
#else // __RULE_0615
if( strName.GetLength() < 3 || strName.GetLength() > 16 )
return TID_DIAG_0011; // "명칭에 3글자 이상, 16글자 이하로 입력 입력하십시오."
#endif // __RULE_0615
char c = strName[ 0 ];
if( ( c >= '0' && c <= '9' ) && !IsMultiByte( lpszString ) )
return TID_DIAG_0012; // "명칭에 첫글자를 숫자로 사용할 수 없습니다."
int j;
switch( ::GetLanguage() )
{
case LANG_THA:
for( j = 0; j < strName.GetLength(); ++j )
{
c = strName[ j ];
if( IsNative( &lpszString[ j ] ) == FALSE && ( isalnum( c ) == FALSE || iscntrl( c ) ) )
return TID_DIAG_0013; // 명칭에 콘트롤이나 스페이스, 특수 문자를 사용할 수 없습니다.
}
break;
case LANG_TWN:
case LANG_HK:
return IsValidPlayerNameTWN( strName );
default:
for( j = 0; j < strName.GetLength(); ++j )
{
c = strName[ j ];
if( IsDBCSLeadByte(c) )
{
++j;
if( ::GetLanguage() == LANG_KOR )
{
char c2 = strName[ j ];
WORD word = ( ( c << 8 ) & 0xff00 ) | ( c2 & 0x00ff );
if( IsHangul( word ) == FALSE )
return TID_DIAG_0014;
}
}
else if( isalnum( c ) == FALSE || iscntrl( c ) )
{
char szLetter[2] = { c, '\0' };
if( ( ::GetLanguage() == LANG_GER
|| ::GetLanguage() == LANG_RUS
) && prj.IsAllowedLetter( szLetter ) )
continue;
return TID_DIAG_0013;
}
}
break;
}
return 0;
}
BOOL CWndCreateChar::OnChildNotify( UINT message, UINT nID, LRESULT* pLResult )
{
if( message == WNM_CLICKED )
{
switch(nID)
{
case 10000:
return FALSE;
case WIDC_MALE: // male
SetSex( SEX_MALE );
break;
case WIDC_FEMALE: // female
SetSex( SEX_FEMALE );
break;
case WIDC_HAIRSTYLE_LEFT: // hair
m_Player.m_byHairMesh--;
if( m_Player.m_byHairMesh < 0 )
m_Player.m_byHairMesh = MAX_BASE_HAIR - 1;
CMover::UpdateParts( m_Player.m_bySex, m_Player.m_bySkinSet, m_Player.m_byFace, m_Player.m_byHairMesh, m_Player.m_byHeadMesh, m_Player.m_aEquipInfo, m_pModel, NULL );
break;
case WIDC_HAIRSTYLE_RIGHT: // hair
m_Player.m_byHairMesh++;
if( m_Player.m_byHairMesh >= MAX_BASE_HAIR )
m_Player.m_byHairMesh = 0;
CMover::UpdateParts( m_Player.m_bySex, m_Player.m_bySkinSet, m_Player.m_byFace, m_Player.m_byHairMesh, m_Player.m_byHeadMesh, m_Player.m_aEquipInfo, m_pModel, NULL );
break;
case WIDC_FACE_LEFT: // head
m_Player.m_byHeadMesh--;
if( m_Player.m_byHeadMesh < 0 )
m_Player.m_byHeadMesh = MAX_DEFAULT_HEAD - 1;
CMover::UpdateParts( m_Player.m_bySex, m_Player.m_bySkinSet, m_Player.m_byFace, m_Player.m_byHairMesh, m_Player.m_byHeadMesh, m_Player.m_aEquipInfo, m_pModel, NULL );
break;
case WIDC_FACE_RIGHT: // head
m_Player.m_byHeadMesh++;
if( m_Player.m_byHeadMesh >= MAX_DEFAULT_HEAD )
m_Player.m_byHeadMesh = 0;
CMover::UpdateParts( m_Player.m_bySex, m_Player.m_bySkinSet, m_Player.m_byFace, m_Player.m_byHairMesh, m_Player.m_byHeadMesh, m_Player.m_aEquipInfo, m_pModel, NULL );
break;
case WIDC_CANCEL: // Cancel
{
Destroy();
g_WndMng.ObjectExecutor( SHORTCUT_APPLET, APP_SELECT_CHAR );
CWndSelectChar* pWndSelectChar
= (CWndSelectChar*)g_WndMng.GetWndBase( APP_SELECT_CHAR );
if( pWndSelectChar )
pWndSelectChar->UpdateCharacter();
break;
}
case WIDC_OK: // Create
{
CWndEdit* pEdit = (CWndEdit*)GetDlgItem( WIDC_NAME );
CString string = pEdit->m_string;
DWORD dwError = IsValidPlayerName( string );
if( dwError > 0 )
{
g_WndMng.OpenMessageBox( prj.GetText(dwError) );
pEdit->SetFocus();
return TRUE;
}
if( prj.IsInvalidName( string )
#if 0//#ifdef __RULE_0615
|| prj.IsAllowedLetter( string ) == FALSE
#endif // __RULE_0615
)
{
g_WndMng.OpenMessageBox( prj.GetText(TID_DIAG_0020) ); // "사용할수 없는 이름입니다"
return TRUE;
}
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
CWndEdit* pWnd2ndPassword = ( CWndEdit* )GetDlgItem( WIDC_EDIT_2ND_PASSWORD );
assert( pWnd2ndPassword );
CWndEdit* pWnd2ndPasswordConfirm = ( CWndEdit* )GetDlgItem( WIDC_EDIT_2ND_PASSWORD_CONFIRM );
assert( pWnd2ndPasswordConfirm );
if( strcmp( pWnd2ndPassword->GetString(), _T( "" ) ) == 0 )
{
g_WndMng.OpenMessageBox( prj.GetText( TID_2ND_PASSWORD_INPUT_ERROR01 ) ); // 2차 비밀번호를 입력하여 주십시오.
return TRUE;
}
if( static_cast< int >( strlen( pWnd2ndPassword->GetString() ) ) < MAX_2ND_PASSWORD_NUMBER )
{
CString strError = _T( "" );
strError.Format( prj.GetText( TID_2ND_PASSWORD_INPUT_ERROR02 ), MAX_2ND_PASSWORD_NUMBER );
g_WndMng.OpenMessageBox( strError ); // 2차 비밀번호는 숫자 %d자리로만 입력해야 합니다.
return TRUE;
}
if( strcmp( pWnd2ndPassword->GetString(), _T( "0000" ) ) == 0 )
{
g_WndMng.OpenMessageBox( prj.GetText( TID_2ND_PASSWORD_INPUT_ERROR03 ) ); // 입력하신 비밀번호는 2차 비밀번호로 사용할 수 없습니다.
return TRUE;
}
if( strcmp( pWnd2ndPasswordConfirm->GetString(), _T( "" ) ) == 0 )
{
g_WndMng.OpenMessageBox( prj.GetText( TID_2ND_PASSWORD_INPUT_ERROR04 ) ); // 2차 비밀번호 확인을 입력하여 주십시오.
return TRUE;
}
if( strcmp( pWnd2ndPassword->GetString(), pWnd2ndPasswordConfirm->GetString() ) != 0 )
{
g_WndMng.OpenMessageBox( prj.GetText( TID_2ND_PASSWORD_INPUT_ERROR05 ) ); // 2차 비밀번호 확인이 2차 비밀번호와 일치하지 않습니다.
return TRUE;
}
#endif // __2ND_PASSWORD_SYSTEM
// _tcscpy( m_Player.m_szName, string );
CWndButton* pButton = (CWndButton*)GetDlgItem( WIDC_OK );
pButton->EnableWindow( FALSE );
pButton = (CWndButton*)GetDlgItem( WIDC_CANCEL );
pButton->EnableWindow( FALSE );
DWORD dwHairColor = 0xffffffff;
if( m_Player.m_bySex == SEX_MALE )
{
dwHairColor = D3DCOLOR_ARGB( 255, nMaleHairColor[m_Player.m_byHairMesh][0],
nMaleHairColor[m_Player.m_byHairMesh][1],
nMaleHairColor[m_Player.m_byHairMesh][2] );
}
else
{
dwHairColor = D3DCOLOR_ARGB( 255, nFeMaleHairColor[m_Player.m_byHairMesh][0],
nFeMaleHairColor[m_Player.m_byHairMesh][1],
nFeMaleHairColor[m_Player.m_byHairMesh][2] );
}
#if __VER >= 15 // __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendCreatePlayer( (BYTE)( m_Player.m_uSlot ), string, m_Player.m_byFace, m_Player.m_byCostume, m_Player.m_bySkinSet, m_Player.m_byHairMesh, dwHairColor, m_Player.m_bySex, m_Player.m_byJob, m_Player.m_byHeadMesh, atoi( pWnd2ndPassword->GetString() ) );
#else // __2ND_PASSWORD_SYSTEM
g_dpLoginClient.SendCreatePlayer( (BYTE)( m_Player.m_uSlot ), string, m_Player.m_byFace, m_Player.m_byCostume, m_Player.m_bySkinSet, m_Player.m_byHairMesh, dwHairColor, m_Player.m_bySex, m_Player.m_byJob, m_Player.m_byHeadMesh );
#endif // __2ND_PASSWORD_SYSTEM
}
break;
case 10002: // Accept
{
g_WndMng.OpenCustomBox( NULL, new CWndConnectingBox );
g_Neuz.m_dwTempMessage = 1;
g_Neuz.m_timerConnect.Set( 1 );
}
break;
}
}
return CWndNeuz::OnChildNotify( message, nID, pLResult );
}
BOOL CWndCreateChar::OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase )
{
return CWndNeuz::OnCommand(nID,dwMessage,pWndBase);
}
void CWndCreateChar::OnSize(UINT nType, int cx, int cy)
{
CWndNeuz::OnSize(nType,cx,cy);
}
void CWndCreateChar::OnLButtonUp(UINT nFlags, CPoint point)
{
}
void CWndCreateChar::OnLButtonDown(UINT nFlags, CPoint point)
{
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278",
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
2864
],
[
2866,
2961
]
],
[
[
2865,
2865
]
]
]
|
268beccd5fda4f33e82c6868a2c593ed867ee3ff | 252e638cde99ab2aa84922a2e230511f8f0c84be | /replib/src/RepStopInfoInputForm.h | 3d3fd354f319a491c55c0c3c432612568c5a9aa3 | []
| no_license | openlab-vn-ua/tour | abbd8be4f3f2fe4d787e9054385dea2f926f2287 | d467a300bb31a0e82c54004e26e47f7139bd728d | refs/heads/master | 2022-10-02T20:03:43.778821 | 2011-11-10T12:58:15 | 2011-11-10T12:58:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,095 | h | //---------------------------------------------------------------------------
#ifndef RepStopInfoInputFormH
#define RepStopInfoInputFormH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "RXDBCtrl.h"
#include "VADODataSourceOrdering.h"
#include "VCustomDataSourceOrdering.h"
#include "VDBSortGrid.h"
#include <ADODB.hpp>
#include <Db.hpp>
#include <DBGrids.hpp>
#include <Grids.hpp>
#include "Placemnt.h"
//---------------------------------------------------------------------------
class TTourRepStopInfoInputForm : public TForm
{
__published: // IDE-managed Components
TButton *CreateReportButton;
TButton *CancelButton;
TADOQuery *StopQuery;
TDataSource *StopDataSource;
TVADODataSourceOrdering *StopDataSourceOrdering;
TVDBSortGrid *StopGrid;
TStringField *StopQueryStop_Id;
TStringField *StopQueryStop_Name;
void __fastcall FormCreate (TObject *Sender);
void __fastcall FormDestroy (TObject *Sender);
void __fastcall CreateReportButtonClick (TObject *Sender);
void __fastcall StopGridDblClick (TObject *Sender);
void __fastcall StopGridKeyDown (TObject *Sender,
WORD &Key,
TShiftState Shift);
private: // User declarations
public: // User declarations
__fastcall TTourRepStopInfoInputForm (TComponent *Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TTourRepStopInfoInputForm *TourRepStopInfoInputForm;
//---------------------------------------------------------------------------
#endif
| [
"[email protected]"
]
| [
[
[
1,
46
]
]
]
|
4b614232a63217965441590f6de0ec61a1afd43b | 611fc0940b78862ca89de79a8bbeab991f5f471a | /src/Sound/dsutil.cpp | 2bf7416173bb57fc80161e69ea96ba9383be9caa | []
| no_license | LakeIshikawa/splstage2 | df1d8f59319a4e8d9375b9d3379c3548bc520f44 | b4bf7caadf940773a977edd0de8edc610cd2f736 | refs/heads/master | 2021-01-10T21:16:45.430981 | 2010-01-29T08:57:34 | 2010-01-29T08:57:34 | 37,068,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56,489 | cpp | //-----------------------------------------------------------------------------
// File: DSUtil.cpp
//
// Desc: DirectSound framework classes for reading and writing wav files and
// playing them in DirectSound buffers. Feel free to use this class
// as a starting point for adding extra functionality.
//
// Copyright (c) Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <windows.h>
#include <mmsystem.h>
#include <dxerr9.h>
#include <dsound.h>
#include "DSUtil.h"
#include "DXUtil.h"
//-----------------------------------------------------------------------------
// Name: CSoundManager::CSoundManager()
// Desc: Constructs the class
//-----------------------------------------------------------------------------
CSoundManager::CSoundManager()
{
m_pDS = NULL;
}
//-----------------------------------------------------------------------------
// Name: CSoundManager::~CSoundManager()
// Desc: Destroys the class
//-----------------------------------------------------------------------------
CSoundManager::~CSoundManager()
{
SAFE_RELEASE( m_pDS );
}
//-----------------------------------------------------------------------------
// Name: CSoundManager::Initialize()
// Desc: Initializes the IDirectSound object and also sets the primary buffer
// format. This function must be called before any others.
//-----------------------------------------------------------------------------
HRESULT CSoundManager::Initialize( HWND hWnd,
DWORD dwCoopLevel )
{
HRESULT hr;
SAFE_RELEASE( m_pDS );
// Create IDirectSound using the primary sound device
if( FAILED( hr = DirectSoundCreate8( NULL, &m_pDS, NULL ) ) )
;//return DXTRACE_ERR( TEXT("DirectSoundCreate8"), hr );
// Set DirectSound coop level
if( FAILED( hr = m_pDS->SetCooperativeLevel( hWnd, dwCoopLevel ) ) )
;//return DXTRACE_ERR( TEXT("SetCooperativeLevel"), hr );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CSoundManager::SetPrimaryBufferFormat()
// Desc: Set primary buffer to a specified format
// !WARNING! - Setting the primary buffer format and then using this
// same dsound object for DirectMusic messes up DirectMusic!
// For example, to set the primary buffer format to 22kHz stereo, 16-bit
// then: dwPrimaryChannels = 2
// dwPrimaryFreq = 22050,
// dwPrimaryBitRate = 16
//-----------------------------------------------------------------------------
HRESULT CSoundManager::SetPrimaryBufferFormat( DWORD dwPrimaryChannels,
DWORD dwPrimaryFreq,
DWORD dwPrimaryBitRate )
{
HRESULT hr;
LPDIRECTSOUNDBUFFER pDSBPrimary = NULL;
if( m_pDS == NULL )
return CO_E_NOTINITIALIZED;
// Get the primary buffer
DSBUFFERDESC dsbd;
ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) );
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
dsbd.dwBufferBytes = 0;
dsbd.lpwfxFormat = NULL;
if( FAILED( hr = m_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL ) ) )
;//return DXTRACE_ERR( TEXT("CreateSoundBuffer"), hr );
WAVEFORMATEX wfx;
ZeroMemory( &wfx, sizeof(WAVEFORMATEX) );
wfx.wFormatTag = (WORD) WAVE_FORMAT_PCM;
wfx.nChannels = (WORD) dwPrimaryChannels;
wfx.nSamplesPerSec = (DWORD) dwPrimaryFreq;
wfx.wBitsPerSample = (WORD) dwPrimaryBitRate;
wfx.nBlockAlign = (WORD) (wfx.wBitsPerSample / 8 * wfx.nChannels);
wfx.nAvgBytesPerSec = (DWORD) (wfx.nSamplesPerSec * wfx.nBlockAlign);
if( FAILED( hr = pDSBPrimary->SetFormat(&wfx) ) )
;//return DXTRACE_ERR( TEXT("SetFormat"), hr );
SAFE_RELEASE( pDSBPrimary );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CSoundManager::Get3DListenerInterface()
// Desc: Returns the 3D listener interface associated with primary buffer.
//-----------------------------------------------------------------------------
HRESULT CSoundManager::Get3DListenerInterface( LPDIRECTSOUND3DLISTENER* ppDSListener )
{
HRESULT hr;
DSBUFFERDESC dsbdesc;
LPDIRECTSOUNDBUFFER pDSBPrimary = NULL;
if( ppDSListener == NULL )
return E_INVALIDARG;
if( m_pDS == NULL )
return CO_E_NOTINITIALIZED;
*ppDSListener = NULL;
// Obtain primary buffer, asking it for 3D control
ZeroMemory( &dsbdesc, sizeof(DSBUFFERDESC) );
dsbdesc.dwSize = sizeof(DSBUFFERDESC);
dsbdesc.dwFlags = DSBCAPS_CTRL3D | DSBCAPS_PRIMARYBUFFER;
if( FAILED( hr = m_pDS->CreateSoundBuffer( &dsbdesc, &pDSBPrimary, NULL ) ) )
;//return DXTRACE_ERR( TEXT("CreateSoundBuffer"), hr );
if( FAILED( hr = pDSBPrimary->QueryInterface( IID_IDirectSound3DListener,
(VOID**)ppDSListener ) ) )
{
SAFE_RELEASE( pDSBPrimary );
;//return DXTRACE_ERR( TEXT("QueryInterface"), hr );
}
// Release the primary buffer, since it is not need anymore
SAFE_RELEASE( pDSBPrimary );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CSoundManager::Create()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CSoundManager::Create( CSound** ppSound,
LPTSTR strWaveFileName,
DWORD dwCreationFlags,
GUID guid3DAlgorithm,
DWORD dwNumBuffers )
{
HRESULT hr;
HRESULT hrRet = S_OK;
DWORD i;
LPDIRECTSOUNDBUFFER* apDSBuffer = NULL;
DWORD dwDSBufferSize = NULL;
CWaveFile* pWaveFile = NULL;
if( m_pDS == NULL )
return CO_E_NOTINITIALIZED;
if( strWaveFileName == NULL || ppSound == NULL || dwNumBuffers < 1 )
return E_INVALIDARG;
apDSBuffer = new LPDIRECTSOUNDBUFFER[dwNumBuffers];
if( apDSBuffer == NULL )
{
hr = E_OUTOFMEMORY;
goto LFail;
}
pWaveFile = new CWaveFile();
if( pWaveFile == NULL )
{
hr = E_OUTOFMEMORY;
goto LFail;
}
pWaveFile->Open( strWaveFileName, NULL, WAVEFILE_READ );
if( pWaveFile->GetSize() == 0 )
{
// Wave is blank, so don't create it.
hr = E_FAIL;
goto LFail;
}
// Make the DirectSound buffer the same size as the wav file
dwDSBufferSize = pWaveFile->GetSize();
// Create the direct sound buffer, and only request the flags needed
// since each requires some overhead and limits if the buffer can
// be hardware accelerated
DSBUFFERDESC dsbd;
ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) );
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = dwCreationFlags;
dsbd.dwBufferBytes = dwDSBufferSize;
dsbd.guid3DAlgorithm = guid3DAlgorithm;
dsbd.lpwfxFormat = pWaveFile->m_pwfx;
// DirectSound is only guarenteed to play PCM data. Other
// formats may or may not work depending the sound card driver.
hr = m_pDS->CreateSoundBuffer( &dsbd, &apDSBuffer[0], NULL );
// Be sure to return this error code if it occurs so the
// callers knows this happened.
if( hr == DS_NO_VIRTUALIZATION )
hrRet = DS_NO_VIRTUALIZATION;
if( FAILED(hr) )
{
// DSERR_BUFFERTOOSMALL will be returned if the buffer is
// less than DSBSIZE_FX_MIN and the buffer is created
// with DSBCAPS_CTRLFX.
// It might also fail if hardware buffer mixing was requested
// on a device that doesn't support it.
;//DXTRACE_ERR( TEXT("CreateSoundBuffer"), hr );
goto LFail;
}
// Default to use DuplicateSoundBuffer() when created extra buffers since always
// create a buffer that uses the same memory however DuplicateSoundBuffer() will fail if
// DSBCAPS_CTRLFX is used, so use CreateSoundBuffer() instead in this case.
if( (dwCreationFlags & DSBCAPS_CTRLFX) == 0 )
{
for( i=1; i<dwNumBuffers; i++ )
{
if( FAILED( hr = m_pDS->DuplicateSoundBuffer( apDSBuffer[0], &apDSBuffer[i] ) ) )
{
;//DXTRACE_ERR( TEXT("DuplicateSoundBuffer"), hr );
goto LFail;
}
}
}
else
{
for( i=1; i<dwNumBuffers; i++ )
{
hr = m_pDS->CreateSoundBuffer( &dsbd, &apDSBuffer[i], NULL );
if( FAILED(hr) )
{
;//DXTRACE_ERR( TEXT("CreateSoundBuffer"), hr );
goto LFail;
}
}
}
// Create the sound
*ppSound = new CSound( apDSBuffer, dwDSBufferSize, dwNumBuffers, pWaveFile, dwCreationFlags );
SAFE_DELETE( apDSBuffer );
return hrRet;
LFail:
// Cleanup
SAFE_DELETE( pWaveFile );
SAFE_DELETE( apDSBuffer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: CSoundManager::CreateFromMemory()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CSoundManager::CreateFromMemory( CSound** ppSound,
BYTE* pbData,
ULONG ulDataSize,
LPWAVEFORMATEX pwfx,
DWORD dwCreationFlags,
GUID guid3DAlgorithm,
DWORD dwNumBuffers )
{
HRESULT hr;
DWORD i;
LPDIRECTSOUNDBUFFER* apDSBuffer = NULL;
DWORD dwDSBufferSize = NULL;
CWaveFile* pWaveFile = NULL;
if( m_pDS == NULL )
return CO_E_NOTINITIALIZED;
if( pbData == NULL || ppSound == NULL || dwNumBuffers < 1 )
return E_INVALIDARG;
apDSBuffer = new LPDIRECTSOUNDBUFFER[dwNumBuffers];
if( apDSBuffer == NULL )
{
hr = E_OUTOFMEMORY;
goto LFail;
}
pWaveFile = new CWaveFile();
if( pWaveFile == NULL )
{
hr = E_OUTOFMEMORY;
goto LFail;
}
pWaveFile->OpenFromMemory( pbData,ulDataSize, pwfx, WAVEFILE_READ );
// Make the DirectSound buffer the same size as the wav file
dwDSBufferSize = ulDataSize;
// Create the direct sound buffer, and only request the flags needed
// since each requires some overhead and limits if the buffer can
// be hardware accelerated
DSBUFFERDESC dsbd;
ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) );
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = dwCreationFlags;
dsbd.dwBufferBytes = dwDSBufferSize;
dsbd.guid3DAlgorithm = guid3DAlgorithm;
dsbd.lpwfxFormat = pwfx;
if( FAILED( hr = m_pDS->CreateSoundBuffer( &dsbd, &apDSBuffer[0], NULL ) ) )
{
;//DXTRACE_ERR( TEXT("CreateSoundBuffer"), hr );
goto LFail;
}
// Default to use DuplicateSoundBuffer() when created extra buffers since always
// create a buffer that uses the same memory however DuplicateSoundBuffer() will fail if
// DSBCAPS_CTRLFX is used, so use CreateSoundBuffer() instead in this case.
if( (dwCreationFlags & DSBCAPS_CTRLFX) == 0 )
{
for( i=1; i<dwNumBuffers; i++ )
{
if( FAILED( hr = m_pDS->DuplicateSoundBuffer( apDSBuffer[0], &apDSBuffer[i] ) ) )
{
;//DXTRACE_ERR( TEXT("DuplicateSoundBuffer"), hr );
goto LFail;
}
}
}
else
{
for( i=1; i<dwNumBuffers; i++ )
{
hr = m_pDS->CreateSoundBuffer( &dsbd, &apDSBuffer[i], NULL );
if( FAILED(hr) )
{
;//DXTRACE_ERR( TEXT("CreateSoundBuffer"), hr );
goto LFail;
}
}
}
// Create the sound
*ppSound = new CSound( apDSBuffer, dwDSBufferSize, dwNumBuffers, pWaveFile, dwCreationFlags );
SAFE_DELETE( apDSBuffer );
return S_OK;
LFail:
// Cleanup
SAFE_DELETE( apDSBuffer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: CSoundManager::CreateStreaming()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CSoundManager::CreateStreaming( CStreamingSound** ppStreamingSound,
LPTSTR strWaveFileName,
DWORD dwCreationFlags,
GUID guid3DAlgorithm,
DWORD dwNotifyCount,
DWORD dwNotifySize,
HANDLE hNotifyEvent )
{
HRESULT hr;
if( m_pDS == NULL )
return CO_E_NOTINITIALIZED;
if( strWaveFileName == NULL || ppStreamingSound == NULL || hNotifyEvent == NULL )
return E_INVALIDARG;
LPDIRECTSOUNDBUFFER pDSBuffer = NULL;
DWORD dwDSBufferSize = NULL;
CWaveFile* pWaveFile = NULL;
DSBPOSITIONNOTIFY* aPosNotify = NULL;
LPDIRECTSOUNDNOTIFY pDSNotify = NULL;
pWaveFile = new CWaveFile();
if( pWaveFile == NULL )
return E_OUTOFMEMORY;
pWaveFile->Open( strWaveFileName, NULL, WAVEFILE_READ );
// Figure out how big the DSound buffer should be
dwDSBufferSize = dwNotifySize * dwNotifyCount;
// Set up the direct sound buffer. Request the NOTIFY flag, so
// that we are notified as the sound buffer plays. Note, that using this flag
// may limit the amount of hardware acceleration that can occur.
DSBUFFERDESC dsbd;
ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) );
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = dwCreationFlags |
DSBCAPS_CTRLPOSITIONNOTIFY |
DSBCAPS_GETCURRENTPOSITION2;
dsbd.dwBufferBytes = dwDSBufferSize;
dsbd.guid3DAlgorithm = guid3DAlgorithm;
dsbd.lpwfxFormat = pWaveFile->m_pwfx;
if( FAILED( hr = m_pDS->CreateSoundBuffer( &dsbd, &pDSBuffer, NULL ) ) )
{
// If wave format isn't then it will return
// either DSERR_BADFORMAT or E_INVALIDARG
if( hr == DSERR_BADFORMAT || hr == E_INVALIDARG )
;//return DXTRACE_ERR( TEXT("CreateSoundBuffer"), hr );
;//return DXTRACE_ERR( TEXT("CreateSoundBuffer"), hr );
}
// Create the notification events, so that we know when to fill
// the buffer as the sound plays.
if( FAILED( hr = pDSBuffer->QueryInterface( IID_IDirectSoundNotify,
(VOID**)&pDSNotify ) ) )
{
SAFE_DELETE_ARRAY( aPosNotify );
;//return DXTRACE_ERR( TEXT("QueryInterface"), hr );
}
aPosNotify = new DSBPOSITIONNOTIFY[ dwNotifyCount ];
if( aPosNotify == NULL )
;//return E_OUTOFMEMORY;
for( DWORD i = 0; i < dwNotifyCount; i++ )
{
aPosNotify[i].dwOffset = (dwNotifySize * i) + dwNotifySize - 1;
aPosNotify[i].hEventNotify = hNotifyEvent;
}
// Tell DirectSound when to notify us. The notification will come in the from
// of signaled events that are handled in WinMain()
if( FAILED( hr = pDSNotify->SetNotificationPositions( dwNotifyCount,
aPosNotify ) ) )
{
SAFE_RELEASE( pDSNotify );
SAFE_DELETE_ARRAY( aPosNotify );
;//return DXTRACE_ERR( TEXT("SetNotificationPositions"), hr );
}
SAFE_RELEASE( pDSNotify );
SAFE_DELETE_ARRAY( aPosNotify );
// Create the sound
*ppStreamingSound = new CStreamingSound( pDSBuffer, dwDSBufferSize, pWaveFile, dwNotifySize );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CSound::CSound()
// Desc: Constructs the class
//-----------------------------------------------------------------------------
CSound::CSound( LPDIRECTSOUNDBUFFER* apDSBuffer, DWORD dwDSBufferSize,
DWORD dwNumBuffers, CWaveFile* pWaveFile, DWORD dwCreationFlags )
{
DWORD i;
m_apDSBuffer = new LPDIRECTSOUNDBUFFER[dwNumBuffers];
if( NULL != m_apDSBuffer )
{
for( i=0; i<dwNumBuffers; i++ )
m_apDSBuffer[i] = apDSBuffer[i];
m_dwDSBufferSize = dwDSBufferSize;
m_dwNumBuffers = dwNumBuffers;
m_pWaveFile = pWaveFile;
m_dwCreationFlags = dwCreationFlags;
FillBufferWithSound( m_apDSBuffer[0], FALSE );
}
}
//-----------------------------------------------------------------------------
// Name: CSound::~CSound()
// Desc: Destroys the class
//-----------------------------------------------------------------------------
CSound::~CSound()
{
for( DWORD i=0; i<m_dwNumBuffers; i++ )
{
SAFE_RELEASE( m_apDSBuffer[i] );
}
SAFE_DELETE_ARRAY( m_apDSBuffer );
SAFE_DELETE( m_pWaveFile );
}
//-----------------------------------------------------------------------------
// Name: CSound::FillBufferWithSound()
// Desc: Fills a DirectSound buffer with a sound file
//-----------------------------------------------------------------------------
HRESULT CSound::FillBufferWithSound( LPDIRECTSOUNDBUFFER pDSB, BOOL bRepeatWavIfBufferLarger )
{
HRESULT hr;
VOID* pDSLockedBuffer = NULL; // Pointer to locked buffer memory
DWORD dwDSLockedBufferSize = 0; // Size of the locked DirectSound buffer
DWORD dwWavDataRead = 0; // Amount of data read from the wav file
if( pDSB == NULL )
return CO_E_NOTINITIALIZED;
// Make sure we have focus, and we didn't just switch in from
// an app which had a DirectSound device
if( FAILED( hr = RestoreBuffer( pDSB, NULL ) ) )
;//return DXTRACE_ERR( TEXT("RestoreBuffer"), hr );
// Lock the buffer down
if( FAILED( hr = pDSB->Lock( 0, m_dwDSBufferSize,
&pDSLockedBuffer, &dwDSLockedBufferSize,
NULL, NULL, 0L ) ) )
;//return DXTRACE_ERR( TEXT("Lock"), hr );
// Reset the wave file to the beginning
m_pWaveFile->ResetFile();
if( FAILED( hr = m_pWaveFile->Read( (BYTE*) pDSLockedBuffer,
dwDSLockedBufferSize,
&dwWavDataRead ) ) )
;//return DXTRACE_ERR( TEXT("Read"), hr );
if( dwWavDataRead == 0 )
{
// Wav is blank, so just fill with silence
FillMemory( (BYTE*) pDSLockedBuffer,
dwDSLockedBufferSize,
(BYTE)(m_pWaveFile->m_pwfx->wBitsPerSample == 8 ? 128 : 0 ) );
}
else if( dwWavDataRead < dwDSLockedBufferSize )
{
// If the wav file was smaller than the DirectSound buffer,
// we need to fill the remainder of the buffer with data
if( bRepeatWavIfBufferLarger )
{
// Reset the file and fill the buffer with wav data
DWORD dwReadSoFar = dwWavDataRead; // From previous call above.
while( dwReadSoFar < dwDSLockedBufferSize )
{
// This will keep reading in until the buffer is full
// for very short files
if( FAILED( hr = m_pWaveFile->ResetFile() ) )
;//return DXTRACE_ERR( TEXT("ResetFile"), hr );
hr = m_pWaveFile->Read( (BYTE*)pDSLockedBuffer + dwReadSoFar,
dwDSLockedBufferSize - dwReadSoFar,
&dwWavDataRead );
if( FAILED(hr) )
;//return DXTRACE_ERR( TEXT("Read"), hr );
dwReadSoFar += dwWavDataRead;
}
}
else
{
// Don't repeat the wav file, just fill in silence
FillMemory( (BYTE*) pDSLockedBuffer + dwWavDataRead,
dwDSLockedBufferSize - dwWavDataRead,
(BYTE)(m_pWaveFile->m_pwfx->wBitsPerSample == 8 ? 128 : 0 ) );
}
}
// Unlock the buffer, we don't need it anymore.
pDSB->Unlock( pDSLockedBuffer, dwDSLockedBufferSize, NULL, 0 );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CSound::RestoreBuffer()
// Desc: Restores the lost buffer. *pbWasRestored returns TRUE if the buffer was
// restored. It can also NULL if the information is not needed.
//-----------------------------------------------------------------------------
HRESULT CSound::RestoreBuffer( LPDIRECTSOUNDBUFFER pDSB, BOOL* pbWasRestored )
{
HRESULT hr;
if( pDSB == NULL )
return CO_E_NOTINITIALIZED;
if( pbWasRestored )
*pbWasRestored = FALSE;
DWORD dwStatus;
if( FAILED( hr = pDSB->GetStatus( &dwStatus ) ) )
;//return DXTRACE_ERR( TEXT("GetStatus"), hr );
if( dwStatus & DSBSTATUS_BUFFERLOST )
{
// Since the app could have just been activated, then
// DirectSound may not be giving us control yet, so
// the restoring the buffer may fail.
// If it does, sleep until DirectSound gives us control.
do
{
hr = pDSB->Restore();
if( hr == DSERR_BUFFERLOST )
Sleep( 10 );
}
while( ( hr = pDSB->Restore() ) == DSERR_BUFFERLOST );
if( pbWasRestored != NULL )
*pbWasRestored = TRUE;
return S_OK;
}
else
{
return S_FALSE;
}
}
//-----------------------------------------------------------------------------
// Name: CSound::GetFreeBuffer()
// Desc: Finding the first buffer that is not playing and return a pointer to
// it, or if all are playing return a pointer to a randomly selected buffer.
//-----------------------------------------------------------------------------
LPDIRECTSOUNDBUFFER CSound::GetFreeBuffer()
{
if( m_apDSBuffer == NULL )
return FALSE;
DWORD i;
for( i=0; i<m_dwNumBuffers; i++ )
{
if( m_apDSBuffer[i] )
{
DWORD dwStatus = 0;
m_apDSBuffer[i]->GetStatus( &dwStatus );
if ( ( dwStatus & DSBSTATUS_PLAYING ) == 0 )
break;
}
}
if( i != m_dwNumBuffers )
return m_apDSBuffer[ i ];
else
return m_apDSBuffer[ rand() % m_dwNumBuffers ];
}
//-----------------------------------------------------------------------------
// Name: CSound::GetBuffer()
// Desc:
//-----------------------------------------------------------------------------
LPDIRECTSOUNDBUFFER CSound::GetBuffer( DWORD dwIndex )
{
if( m_apDSBuffer == NULL )
return NULL;
if( dwIndex >= m_dwNumBuffers )
return NULL;
return m_apDSBuffer[dwIndex];
}
//-----------------------------------------------------------------------------
// Name: CSound::Get3DBufferInterface()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CSound::Get3DBufferInterface( DWORD dwIndex, LPDIRECTSOUND3DBUFFER* ppDS3DBuffer )
{
if( m_apDSBuffer == NULL )
return CO_E_NOTINITIALIZED;
if( dwIndex >= m_dwNumBuffers )
return E_INVALIDARG;
*ppDS3DBuffer = NULL;
return m_apDSBuffer[dwIndex]->QueryInterface( IID_IDirectSound3DBuffer,
(VOID**)ppDS3DBuffer );
}
//-----------------------------------------------------------------------------
// Name: CSound::Play()
// Desc: Plays the sound using voice management flags. Pass in DSBPLAY_LOOPING
// in the dwFlags to loop the sound
//-----------------------------------------------------------------------------
HRESULT CSound::Play( DWORD dwPriority, DWORD dwFlags, LONG lVolume, LONG lFrequency, LONG lPan )
{
HRESULT hr;
BOOL bRestored;
if( m_apDSBuffer == NULL )
return CO_E_NOTINITIALIZED;
LPDIRECTSOUNDBUFFER pDSB = GetFreeBuffer();
if( pDSB == NULL )
;//return DXTRACE_ERR( TEXT("GetFreeBuffer"), E_FAIL );
// Restore the buffer if it was lost
if( FAILED( hr = RestoreBuffer( pDSB, &bRestored ) ) )
;//return DXTRACE_ERR( TEXT("RestoreBuffer"), hr );
if( bRestored )
{
// The buffer was restored, so we need to fill it with new data
if( FAILED( hr = FillBufferWithSound( pDSB, FALSE ) ) )
;//return DXTRACE_ERR( TEXT("FillBufferWithSound"), hr );
}
if( m_dwCreationFlags & DSBCAPS_CTRLVOLUME )
{
pDSB->SetVolume( lVolume );
}
if( lFrequency != -1 &&
(m_dwCreationFlags & DSBCAPS_CTRLFREQUENCY) )
{
pDSB->SetFrequency( lFrequency );
}
if( m_dwCreationFlags & DSBCAPS_CTRLPAN )
{
pDSB->SetPan( lPan );
}
return pDSB->Play( 0, dwPriority, dwFlags );
}
//-----------------------------------------------------------------------------
// Name: CSound::Play3D()
// Desc: Plays the sound using voice management flags. Pass in DSBPLAY_LOOPING
// in the dwFlags to loop the sound
//-----------------------------------------------------------------------------
HRESULT CSound::Play3D( LPDS3DBUFFER p3DBuffer, DWORD dwPriority, DWORD dwFlags, LONG lFrequency )
{
HRESULT hr;
BOOL bRestored;
DWORD dwBaseFrequency;
if( m_apDSBuffer == NULL )
return CO_E_NOTINITIALIZED;
LPDIRECTSOUNDBUFFER pDSB = GetFreeBuffer();
if( pDSB == NULL )
;//return DXTRACE_ERR( TEXT("GetFreeBuffer"), E_FAIL );
// Restore the buffer if it was lost
if( FAILED( hr = RestoreBuffer( pDSB, &bRestored ) ) )
;//return DXTRACE_ERR( TEXT("RestoreBuffer"), hr );
if( bRestored )
{
// The buffer was restored, so we need to fill it with new data
if( FAILED( hr = FillBufferWithSound( pDSB, FALSE ) ) )
;//return DXTRACE_ERR( TEXT("FillBufferWithSound"), hr );
}
if( m_dwCreationFlags & DSBCAPS_CTRLFREQUENCY )
{
pDSB->GetFrequency( &dwBaseFrequency );
pDSB->SetFrequency( dwBaseFrequency + lFrequency );
}
// QI for the 3D buffer
LPDIRECTSOUND3DBUFFER pDS3DBuffer;
hr = pDSB->QueryInterface( IID_IDirectSound3DBuffer, (VOID**) &pDS3DBuffer );
if( SUCCEEDED( hr ) )
{
hr = pDS3DBuffer->SetAllParameters( p3DBuffer, DS3D_IMMEDIATE );
if( SUCCEEDED( hr ) )
{
hr = pDSB->Play( 0, dwPriority, dwFlags );
}
pDS3DBuffer->Release();
}
return hr;
}
//-----------------------------------------------------------------------------
// Name: CSound::Stop()
// Desc: Stops the sound from playing
//-----------------------------------------------------------------------------
HRESULT CSound::Stop()
{
if( m_apDSBuffer == NULL )
return CO_E_NOTINITIALIZED;
HRESULT hr = 0;
for( DWORD i=0; i<m_dwNumBuffers; i++ )
hr |= m_apDSBuffer[i]->Stop();
return hr;
}
//-----------------------------------------------------------------------------
// Name: CSound::Reset()
// Desc: Reset all of the sound buffers
//-----------------------------------------------------------------------------
HRESULT CSound::Reset()
{
if( m_apDSBuffer == NULL )
return CO_E_NOTINITIALIZED;
HRESULT hr = 0;
for( DWORD i=0; i<m_dwNumBuffers; i++ )
hr |= m_apDSBuffer[i]->SetCurrentPosition( 0 );
return hr;
}
//-----------------------------------------------------------------------------
// Name: CSound::IsSoundPlaying()
// Desc: Checks to see if a buffer is playing and returns TRUE if it is.
//-----------------------------------------------------------------------------
BOOL CSound::IsSoundPlaying()
{
BOOL bIsPlaying = FALSE;
if( m_apDSBuffer == NULL )
return FALSE;
for( DWORD i=0; i<m_dwNumBuffers; i++ )
{
if( m_apDSBuffer[i] )
{
DWORD dwStatus = 0;
m_apDSBuffer[i]->GetStatus( &dwStatus );
bIsPlaying |= ( ( dwStatus & DSBSTATUS_PLAYING ) != 0 );
}
}
return bIsPlaying;
}
//-----------------------------------------------------------------------------
// Name: CStreamingSound::CStreamingSound()
// Desc: Setups up a buffer so data can be streamed from the wave file into
// a buffer. This is very useful for large wav files that would take a
// while to load. The buffer is initially filled with data, then
// as sound is played the notification events are signaled and more data
// is written into the buffer by calling HandleWaveStreamNotification()
//-----------------------------------------------------------------------------
CStreamingSound::CStreamingSound( LPDIRECTSOUNDBUFFER pDSBuffer, DWORD dwDSBufferSize,
CWaveFile* pWaveFile, DWORD dwNotifySize )
: CSound( &pDSBuffer, dwDSBufferSize, 1, pWaveFile, 0 )
{
m_dwLastPlayPos = 0;
m_dwPlayProgress = 0;
m_dwNotifySize = dwNotifySize;
m_dwNextWriteOffset = 0;
m_bFillNextNotificationWithSilence = FALSE;
}
//-----------------------------------------------------------------------------
// Name: CStreamingSound::~CStreamingSound()
// Desc: Destroys the class
//-----------------------------------------------------------------------------
CStreamingSound::~CStreamingSound()
{
}
//-----------------------------------------------------------------------------
// Name: CStreamingSound::HandleWaveStreamNotification()
// Desc: Handle the notification that tells us to put more wav data in the
// circular buffer
//-----------------------------------------------------------------------------
HRESULT CStreamingSound::HandleWaveStreamNotification( BOOL bLoopedPlay )
{
HRESULT hr;
DWORD dwCurrentPlayPos;
DWORD dwPlayDelta;
DWORD dwBytesWrittenToBuffer;
VOID* pDSLockedBuffer = NULL;
VOID* pDSLockedBuffer2 = NULL;
DWORD dwDSLockedBufferSize;
DWORD dwDSLockedBufferSize2;
if( m_apDSBuffer == NULL || m_pWaveFile == NULL )
return CO_E_NOTINITIALIZED;
// Restore the buffer if it was lost
BOOL bRestored;
if( FAILED( hr = RestoreBuffer( m_apDSBuffer[0], &bRestored ) ) )
;//return DXTRACE_ERR( TEXT("RestoreBuffer"), hr );
if( bRestored )
{
// The buffer was restored, so we need to fill it with new data
if( FAILED( hr = FillBufferWithSound( m_apDSBuffer[0], FALSE ) ) )
;//return DXTRACE_ERR( TEXT("FillBufferWithSound"), hr );
return S_OK;
}
// Lock the DirectSound buffer
if( FAILED( hr = m_apDSBuffer[0]->Lock( m_dwNextWriteOffset, m_dwNotifySize,
&pDSLockedBuffer, &dwDSLockedBufferSize,
&pDSLockedBuffer2, &dwDSLockedBufferSize2, 0L ) ) )
;//return DXTRACE_ERR( TEXT("Lock"), hr );
// m_dwDSBufferSize and m_dwNextWriteOffset are both multiples of m_dwNotifySize,
// it should the second buffer, so it should never be valid
if( pDSLockedBuffer2 != NULL )
return E_UNEXPECTED;
if( !m_bFillNextNotificationWithSilence )
{
// Fill the DirectSound buffer with wav data
if( FAILED( hr = m_pWaveFile->Read( (BYTE*) pDSLockedBuffer,
dwDSLockedBufferSize,
&dwBytesWrittenToBuffer ) ) )
;//return DXTRACE_ERR( TEXT("Read"), hr );
}
else
{
// Fill the DirectSound buffer with silence
FillMemory( pDSLockedBuffer, dwDSLockedBufferSize,
(BYTE)( m_pWaveFile->m_pwfx->wBitsPerSample == 8 ? 128 : 0 ) );
dwBytesWrittenToBuffer = dwDSLockedBufferSize;
}
// If the number of bytes written is less than the
// amount we requested, we have a short file.
if( dwBytesWrittenToBuffer < dwDSLockedBufferSize )
{
if( !bLoopedPlay )
{
// Fill in silence for the rest of the buffer.
FillMemory( (BYTE*) pDSLockedBuffer + dwBytesWrittenToBuffer,
dwDSLockedBufferSize - dwBytesWrittenToBuffer,
(BYTE)(m_pWaveFile->m_pwfx->wBitsPerSample == 8 ? 128 : 0 ) );
// Any future notifications should just fill the buffer with silence
m_bFillNextNotificationWithSilence = TRUE;
}
else
{
// We are looping, so reset the file and fill the buffer with wav data
DWORD dwReadSoFar = dwBytesWrittenToBuffer; // From previous call above.
while( dwReadSoFar < dwDSLockedBufferSize )
{
// This will keep reading in until the buffer is full (for very short files).
if( FAILED( hr = m_pWaveFile->ResetFile() ) )
;//return DXTRACE_ERR( TEXT("ResetFile"), hr );
if( FAILED( hr = m_pWaveFile->Read( (BYTE*)pDSLockedBuffer + dwReadSoFar,
dwDSLockedBufferSize - dwReadSoFar,
&dwBytesWrittenToBuffer ) ) )
;//return DXTRACE_ERR( TEXT("Read"), hr );
dwReadSoFar += dwBytesWrittenToBuffer;
}
}
}
// Unlock the DirectSound buffer
m_apDSBuffer[0]->Unlock( pDSLockedBuffer, dwDSLockedBufferSize, NULL, 0 );
// Figure out how much data has been played so far. When we have played
// past the end of the file, we will either need to start filling the
// buffer with silence or starting reading from the beginning of the file,
// depending if the user wants to loop the sound
if( FAILED( hr = m_apDSBuffer[0]->GetCurrentPosition( &dwCurrentPlayPos, NULL ) ) )
;//return DXTRACE_ERR( TEXT("GetCurrentPosition"), hr );
// Check to see if the position counter looped
if( dwCurrentPlayPos < m_dwLastPlayPos )
dwPlayDelta = ( m_dwDSBufferSize - m_dwLastPlayPos ) + dwCurrentPlayPos;
else
dwPlayDelta = dwCurrentPlayPos - m_dwLastPlayPos;
m_dwPlayProgress += dwPlayDelta;
m_dwLastPlayPos = dwCurrentPlayPos;
// If we are now filling the buffer with silence, then we have found the end so
// check to see if the entire sound has played, if it has then stop the buffer.
if( m_bFillNextNotificationWithSilence )
{
// We don't want to cut off the sound before it's done playing.
if( m_dwPlayProgress >= m_pWaveFile->GetSize() )
{
m_apDSBuffer[0]->Stop();
}
}
// Update where the buffer will lock (for next time)
m_dwNextWriteOffset += dwDSLockedBufferSize;
m_dwNextWriteOffset %= m_dwDSBufferSize; // Circular buffer
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CStreamingSound::Reset()
// Desc: Resets the sound so it will begin playing at the beginning
//-----------------------------------------------------------------------------
HRESULT CStreamingSound::Reset()
{
HRESULT hr;
if( m_apDSBuffer[0] == NULL || m_pWaveFile == NULL )
return CO_E_NOTINITIALIZED;
m_dwLastPlayPos = 0;
m_dwPlayProgress = 0;
m_dwNextWriteOffset = 0;
m_bFillNextNotificationWithSilence = FALSE;
// Restore the buffer if it was lost
BOOL bRestored;
if( FAILED( hr = RestoreBuffer( m_apDSBuffer[0], &bRestored ) ) )
;//return DXTRACE_ERR( TEXT("RestoreBuffer"), hr );
if( bRestored )
{
// The buffer was restored, so we need to fill it with new data
if( FAILED( hr = FillBufferWithSound( m_apDSBuffer[0], FALSE ) ) )
;//return DXTRACE_ERR( TEXT("FillBufferWithSound"), hr );
}
m_pWaveFile->ResetFile();
return m_apDSBuffer[0]->SetCurrentPosition( 0L );
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::CWaveFile()
// Desc: Constructs the class. Call Open() to open a wave file for reading.
// Then call Read() as needed. Calling the destructor or Close()
// will close the file.
//-----------------------------------------------------------------------------
CWaveFile::CWaveFile()
{
m_pwfx = NULL;
m_hmmio = NULL;
m_pResourceBuffer = NULL;
m_dwSize = 0;
m_bIsReadingFromMemory = FALSE;
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::~CWaveFile()
// Desc: Destructs the class
//-----------------------------------------------------------------------------
CWaveFile::~CWaveFile()
{
Close();
if( !m_bIsReadingFromMemory )
SAFE_DELETE_ARRAY( m_pwfx );
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::Open()
// Desc: Opens a wave file for reading
//-----------------------------------------------------------------------------
HRESULT CWaveFile::Open( LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags )
{
HRESULT hr;
m_dwFlags = dwFlags;
m_bIsReadingFromMemory = FALSE;
if( m_dwFlags == WAVEFILE_READ )
{
if( strFileName == NULL )
return E_INVALIDARG;
SAFE_DELETE_ARRAY( m_pwfx );
m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF | MMIO_READ );
if( NULL == m_hmmio )
{
HRSRC hResInfo;
HGLOBAL hResData;
DWORD dwSize;
VOID* pvRes;
// Loading it as a file failed, so try it as a resource
if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAVE") ) ) )
{
if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAV") ) ) )
;//return DXTRACE_ERR( TEXT("FindResource"), E_FAIL );
}
if( NULL == ( hResData = LoadResource( NULL, hResInfo ) ) )
;//return DXTRACE_ERR( TEXT("LoadResource"), E_FAIL );
if( 0 == ( dwSize = SizeofResource( NULL, hResInfo ) ) )
;//return DXTRACE_ERR( TEXT("SizeofResource"), E_FAIL );
if( NULL == ( pvRes = LockResource( hResData ) ) )
;//return DXTRACE_ERR( TEXT("LockResource"), E_FAIL );
m_pResourceBuffer = new CHAR[ dwSize ];
memcpy( m_pResourceBuffer, pvRes, dwSize );
MMIOINFO mmioInfo;
ZeroMemory( &mmioInfo, sizeof(mmioInfo) );
mmioInfo.fccIOProc = FOURCC_MEM;
mmioInfo.cchBuffer = dwSize;
mmioInfo.pchBuffer = (CHAR*) m_pResourceBuffer;
m_hmmio = mmioOpen( NULL, &mmioInfo, MMIO_ALLOCBUF | MMIO_READ );
}
if( FAILED( hr = ReadMMIO() ) )
{
// ReadMMIO will fail if its an not a wave file
mmioClose( m_hmmio, 0 );
;//return DXTRACE_ERR( TEXT("ReadMMIO"), hr );
}
if( FAILED( hr = ResetFile() ) )
;//return DXTRACE_ERR( TEXT("ResetFile"), hr );
// After the reset, the size of the wav file is m_ck.cksize so store it now
m_dwSize = m_ck.cksize;
}
else
{
m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF |
MMIO_READWRITE |
MMIO_CREATE );
if( NULL == m_hmmio )
;//return DXTRACE_ERR( TEXT("mmioOpen"), E_FAIL );
if( FAILED( hr = WriteMMIO( pwfx ) ) )
{
mmioClose( m_hmmio, 0 );
;//return DXTRACE_ERR( TEXT("WriteMMIO"), hr );
}
if( FAILED( hr = ResetFile() ) )
;//return DXTRACE_ERR( TEXT("ResetFile"), hr );
}
return hr;
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::OpenFromMemory()
// Desc: copy data to CWaveFile member variable from memory
//-----------------------------------------------------------------------------
HRESULT CWaveFile::OpenFromMemory( BYTE* pbData, ULONG ulDataSize,
WAVEFORMATEX* pwfx, DWORD dwFlags )
{
m_pwfx = pwfx;
m_ulDataSize = ulDataSize;
m_pbData = pbData;
m_pbDataCur = m_pbData;
m_bIsReadingFromMemory = TRUE;
if( dwFlags != WAVEFILE_READ )
return E_NOTIMPL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::ReadMMIO()
// Desc: Support function for reading from a multimedia I/O stream.
// m_hmmio must be valid before calling. This function uses it to
// update m_ckRiff, and m_pwfx.
//-----------------------------------------------------------------------------
HRESULT CWaveFile::ReadMMIO()
{
MMCKINFO ckIn; // chunk info. for general use.
PCMWAVEFORMAT pcmWaveFormat; // Temp PCM structure to load in.
m_pwfx = NULL;
if( ( 0 != mmioDescend( m_hmmio, &m_ckRiff, NULL, 0 ) ) )
;//return DXTRACE_ERR( TEXT("mmioDescend"), E_FAIL );
// Check to make sure this is a valid wave file
if( (m_ckRiff.ckid != FOURCC_RIFF) ||
(m_ckRiff.fccType != mmioFOURCC('W', 'A', 'V', 'E') ) )
;//return DXTRACE_ERR( TEXT("mmioFOURCC"), E_FAIL );
// Search the input file for for the 'fmt ' chunk.
ckIn.ckid = mmioFOURCC('f', 'm', 't', ' ');
if( 0 != mmioDescend( m_hmmio, &ckIn, &m_ckRiff, MMIO_FINDCHUNK ) )
;//return DXTRACE_ERR( TEXT("mmioDescend"), E_FAIL );
// Expect the 'fmt' chunk to be at least as large as <PCMWAVEFORMAT>;
// if there are extra parameters at the end, we'll ignore them
if( ckIn.cksize < (LONG) sizeof(PCMWAVEFORMAT) )
;//return DXTRACE_ERR( TEXT("sizeof(PCMWAVEFORMAT)"), E_FAIL );
// Read the 'fmt ' chunk into <pcmWaveFormat>.
if( mmioRead( m_hmmio, (HPSTR) &pcmWaveFormat,
sizeof(pcmWaveFormat)) != sizeof(pcmWaveFormat) )
;//return DXTRACE_ERR( TEXT("mmioRead"), E_FAIL );
// Allocate the waveformatex, but if its not pcm format, read the next
// word, and thats how many extra bytes to allocate.
if( pcmWaveFormat.wf.wFormatTag == WAVE_FORMAT_PCM )
{
m_pwfx = (WAVEFORMATEX*)new CHAR[ sizeof(WAVEFORMATEX) ];
if( NULL == m_pwfx )
;//return DXTRACE_ERR( TEXT("m_pwfx"), E_FAIL );
// Copy the bytes from the pcm structure to the waveformatex structure
memcpy( m_pwfx, &pcmWaveFormat, sizeof(pcmWaveFormat) );
m_pwfx->cbSize = 0;
}
else
{
// Read in length of extra bytes.
WORD cbExtraBytes = 0L;
if( mmioRead( m_hmmio, (CHAR*)&cbExtraBytes, sizeof(WORD)) != sizeof(WORD) )
;//return DXTRACE_ERR( TEXT("mmioRead"), E_FAIL );
m_pwfx = (WAVEFORMATEX*)new CHAR[ sizeof(WAVEFORMATEX) + cbExtraBytes ];
if( NULL == m_pwfx )
;//return DXTRACE_ERR( TEXT("new"), E_FAIL );
// Copy the bytes from the pcm structure to the waveformatex structure
memcpy( m_pwfx, &pcmWaveFormat, sizeof(pcmWaveFormat) );
m_pwfx->cbSize = cbExtraBytes;
// Now, read those extra bytes into the structure, if cbExtraAlloc != 0.
if( mmioRead( m_hmmio, (CHAR*)(((BYTE*)&(m_pwfx->cbSize))+sizeof(WORD)),
cbExtraBytes ) != cbExtraBytes )
{
SAFE_DELETE( m_pwfx );
;//return DXTRACE_ERR( TEXT("mmioRead"), E_FAIL );
}
}
// Ascend the input file out of the 'fmt ' chunk.
if( 0 != mmioAscend( m_hmmio, &ckIn, 0 ) )
{
SAFE_DELETE( m_pwfx );
;//return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::GetSize()
// Desc: Retuns the size of the read access wave file
//-----------------------------------------------------------------------------
DWORD CWaveFile::GetSize()
{
return m_dwSize;
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::ResetFile()
// Desc: Resets the internal m_ck pointer so reading starts from the
// beginning of the file again
//-----------------------------------------------------------------------------
HRESULT CWaveFile::ResetFile()
{
if( m_bIsReadingFromMemory )
{
m_pbDataCur = m_pbData;
}
else
{
if( m_hmmio == NULL )
return CO_E_NOTINITIALIZED;
if( m_dwFlags == WAVEFILE_READ )
{
// Seek to the data
if( -1 == mmioSeek( m_hmmio, m_ckRiff.dwDataOffset + sizeof(FOURCC),
SEEK_SET ) )
;//return DXTRACE_ERR( TEXT("mmioSeek"), E_FAIL );
// Search the input file for the 'data' chunk.
m_ck.ckid = mmioFOURCC('d', 'a', 't', 'a');
if( 0 != mmioDescend( m_hmmio, &m_ck, &m_ckRiff, MMIO_FINDCHUNK ) )
;//return DXTRACE_ERR( TEXT("mmioDescend"), E_FAIL );
}
else
{
// Create the 'data' chunk that holds the waveform samples.
m_ck.ckid = mmioFOURCC('d', 'a', 't', 'a');
m_ck.cksize = 0;
if( 0 != mmioCreateChunk( m_hmmio, &m_ck, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioCreateChunk"), E_FAIL );
if( 0 != mmioGetInfo( m_hmmio, &m_mmioinfoOut, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioGetInfo"), E_FAIL );
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::Read()
// Desc: Reads section of data from a wave file into pBuffer and returns
// how much read in pdwSizeRead, reading not more than dwSizeToRead.
// This uses m_ck to determine where to start reading from. So
// subsequent calls will be continue where the last left off unless
// Reset() is called.
//-----------------------------------------------------------------------------
HRESULT CWaveFile::Read( BYTE* pBuffer, DWORD dwSizeToRead, DWORD* pdwSizeRead )
{
if( m_bIsReadingFromMemory )
{
if( m_pbDataCur == NULL )
return CO_E_NOTINITIALIZED;
if( pdwSizeRead != NULL )
*pdwSizeRead = 0;
if( (BYTE*)(m_pbDataCur + dwSizeToRead) >
(BYTE*)(m_pbData + m_ulDataSize) )
{
dwSizeToRead = m_ulDataSize - (DWORD)(m_pbDataCur - m_pbData);
}
CopyMemory( pBuffer, m_pbDataCur, dwSizeToRead );
if( pdwSizeRead != NULL )
*pdwSizeRead = dwSizeToRead;
return S_OK;
}
else
{
MMIOINFO mmioinfoIn; // current status of m_hmmio
if( m_hmmio == NULL )
return CO_E_NOTINITIALIZED;
if( pBuffer == NULL || pdwSizeRead == NULL )
return E_INVALIDARG;
if( pdwSizeRead != NULL )
*pdwSizeRead = 0;
if( 0 != mmioGetInfo( m_hmmio, &mmioinfoIn, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioGetInfo"), E_FAIL );
UINT cbDataIn = dwSizeToRead;
if( cbDataIn > m_ck.cksize )
cbDataIn = m_ck.cksize;
m_ck.cksize -= cbDataIn;
for( DWORD cT = 0; cT < cbDataIn; cT++ )
{
// Copy the bytes from the io to the buffer.
if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead )
{
if( 0 != mmioAdvance( m_hmmio, &mmioinfoIn, MMIO_READ ) )
;//return DXTRACE_ERR( TEXT("mmioAdvance"), E_FAIL );
if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead )
;//return DXTRACE_ERR( TEXT("mmioinfoIn.pchNext"), E_FAIL );
}
// Actual copy.
*((BYTE*)pBuffer+cT) = *((BYTE*)mmioinfoIn.pchNext);
mmioinfoIn.pchNext++;
}
if( 0 != mmioSetInfo( m_hmmio, &mmioinfoIn, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioSetInfo"), E_FAIL );
if( pdwSizeRead != NULL )
*pdwSizeRead = cbDataIn;
return S_OK;
}
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::Close()
// Desc: Closes the wave file
//-----------------------------------------------------------------------------
HRESULT CWaveFile::Close()
{
if( m_dwFlags == WAVEFILE_READ )
{
mmioClose( m_hmmio, 0 );
m_hmmio = NULL;
SAFE_DELETE_ARRAY( m_pResourceBuffer );
}
else
{
m_mmioinfoOut.dwFlags |= MMIO_DIRTY;
if( m_hmmio == NULL )
return CO_E_NOTINITIALIZED;
if( 0 != mmioSetInfo( m_hmmio, &m_mmioinfoOut, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioSetInfo"), E_FAIL );
// Ascend the output file out of the 'data' chunk -- this will cause
// the chunk size of the 'data' chunk to be written.
if( 0 != mmioAscend( m_hmmio, &m_ck, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL );
// Do this here instead...
if( 0 != mmioAscend( m_hmmio, &m_ckRiff, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL );
mmioSeek( m_hmmio, 0, SEEK_SET );
if( 0 != (INT)mmioDescend( m_hmmio, &m_ckRiff, NULL, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioDescend"), E_FAIL );
m_ck.ckid = mmioFOURCC('f', 'a', 'c', 't');
if( 0 == mmioDescend( m_hmmio, &m_ck, &m_ckRiff, MMIO_FINDCHUNK ) )
{
DWORD dwSamples = 0;
mmioWrite( m_hmmio, (HPSTR)&dwSamples, sizeof(DWORD) );
mmioAscend( m_hmmio, &m_ck, 0 );
}
// Ascend the output file out of the 'RIFF' chunk -- this will cause
// the chunk size of the 'RIFF' chunk to be written.
if( 0 != mmioAscend( m_hmmio, &m_ckRiff, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL );
mmioClose( m_hmmio, 0 );
m_hmmio = NULL;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::WriteMMIO()
// Desc: Support function for reading from a multimedia I/O stream
// pwfxDest is the WAVEFORMATEX for this new wave file.
// m_hmmio must be valid before calling. This function uses it to
// update m_ckRiff, and m_ck.
//-----------------------------------------------------------------------------
HRESULT CWaveFile::WriteMMIO( WAVEFORMATEX *pwfxDest )
{
DWORD dwFactChunk; // Contains the actual fact chunk. Garbage until WaveCloseWriteFile.
MMCKINFO ckOut1;
dwFactChunk = (DWORD)-1;
// Create the output file RIFF chunk of form type 'WAVE'.
m_ckRiff.fccType = mmioFOURCC('W', 'A', 'V', 'E');
m_ckRiff.cksize = 0;
if( 0 != mmioCreateChunk( m_hmmio, &m_ckRiff, MMIO_CREATERIFF ) )
;//return DXTRACE_ERR( TEXT("mmioCreateChunk"), E_FAIL );
// We are now descended into the 'RIFF' chunk we just created.
// Now create the 'fmt ' chunk. Since we know the size of this chunk,
// specify it in the MMCKINFO structure so MMIO doesn't have to seek
// back and set the chunk size after ascending from the chunk.
m_ck.ckid = mmioFOURCC('f', 'm', 't', ' ');
m_ck.cksize = sizeof(PCMWAVEFORMAT);
if( 0 != mmioCreateChunk( m_hmmio, &m_ck, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioCreateChunk"), E_FAIL );
// Write the PCMWAVEFORMAT structure to the 'fmt ' chunk if its that type.
if( pwfxDest->wFormatTag == WAVE_FORMAT_PCM )
{
if( mmioWrite( m_hmmio, (HPSTR) pwfxDest,
sizeof(PCMWAVEFORMAT)) != sizeof(PCMWAVEFORMAT))
;//return DXTRACE_ERR( TEXT("mmioWrite"), E_FAIL );
}
else
{
// Write the variable length size.
if( (UINT)mmioWrite( m_hmmio, (HPSTR) pwfxDest,
sizeof(*pwfxDest) + pwfxDest->cbSize ) !=
( sizeof(*pwfxDest) + pwfxDest->cbSize ) )
;//return DXTRACE_ERR( TEXT("mmioWrite"), E_FAIL );
}
// Ascend out of the 'fmt ' chunk, back into the 'RIFF' chunk.
if( 0 != mmioAscend( m_hmmio, &m_ck, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL );
// Now create the fact chunk, not required for PCM but nice to have. This is filled
// in when the close routine is called.
ckOut1.ckid = mmioFOURCC('f', 'a', 'c', 't');
ckOut1.cksize = 0;
if( 0 != mmioCreateChunk( m_hmmio, &ckOut1, 0 ) )
;//return DXTRACE_ERR( TEXT("mmioCreateChunk"), E_FAIL );
if( mmioWrite( m_hmmio, (HPSTR)&dwFactChunk, sizeof(dwFactChunk)) !=
sizeof(dwFactChunk) )
;// return DXTRACE_ERR( TEXT("mmioWrite"), E_FAIL );
// Now ascend out of the fact chunk...
if( 0 != mmioAscend( m_hmmio, &ckOut1, 0 ) )
;// return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: CWaveFile::Write()
// Desc: Writes data to the open wave file
//-----------------------------------------------------------------------------
HRESULT CWaveFile::Write( UINT nSizeToWrite, BYTE* pbSrcData, UINT* pnSizeWrote )
{
UINT cT;
if( m_bIsReadingFromMemory )
return E_NOTIMPL;
if( m_hmmio == NULL )
return CO_E_NOTINITIALIZED;
if( pnSizeWrote == NULL || pbSrcData == NULL )
return E_INVALIDARG;
*pnSizeWrote = 0;
for( cT = 0; cT < nSizeToWrite; cT++ )
{
if( m_mmioinfoOut.pchNext == m_mmioinfoOut.pchEndWrite )
{
m_mmioinfoOut.dwFlags |= MMIO_DIRTY;
if( 0 != mmioAdvance( m_hmmio, &m_mmioinfoOut, MMIO_WRITE ) )
;//return DXTRACE_ERR( TEXT("mmioAdvance"), E_FAIL );
}
*((BYTE*)m_mmioinfoOut.pchNext) = *((BYTE*)pbSrcData+cT);
(BYTE*)m_mmioinfoOut.pchNext++;
(*pnSizeWrote)++;
}
return S_OK;
}
| [
"lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b"
]
| [
[
[
1,
1646
]
]
]
|
2d2f057ff558cb2e0f0804518d8427f2ae1a37df | 3761dcce2ce81abcbe6d421d8729af568d158209 | /src/cybergarage/upnp/device/Advertiser.cpp | 29c7ab578050d4fbdbc80acdaf6590aae2a8d9b0 | [
"BSD-3-Clause"
]
| permissive | claymeng/CyberLink4CC | af424e7ca8529b62e049db71733be91df94bf4e7 | a1a830b7f4caaeafd5c2db44ad78fbb5b9f304b2 | refs/heads/master | 2021-01-17T07:51:48.231737 | 2011-04-08T15:10:49 | 2011-04-08T15:10:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 957 | cpp | /******************************************************************
*
* CyberLink for C++
*
* Copyright (C) Satoshi Konno 2002-2003
*
* File: Advertiser.cpp
*
* Revision;
*
* 12/25/03
* - first revision
* 06/18/04
* - Changed to advertise every 25%-50% of the periodic notification cycle for NMPR;
*
******************************************************************/
#include <cybergarage/upnp/Device.h>
#include <cybergarage/util/TimeUtil.h>
using namespace CyberLink;
using namespace CyberUtil;
////////////////////////////////////////////////
// Thread
////////////////////////////////////////////////
void Advertiser::run()
{
Device *dev = getDevice();
long leaseTime = dev->getLeaseTime();
long notifyInterval;
while (isRunnable() == true) {
notifyInterval = (leaseTime/4) + (long)((float)leaseTime * (Random() * 0.25f));
notifyInterval *= 1000;
Wait(notifyInterval);
dev->announce();
}
}
| [
"skonno@b944b01c-6696-4570-ab44-a0e08c11cb0e"
]
| [
[
[
1,
40
]
]
]
|
b2b22e24b69e4af76d05875b8ee4b8f9af4f0f04 | 63085faa10712a085c09af4b639db0ad4831553e | /DtwSequenceCompare/dataholder.h | 40f3d9a073b2ebd0f41afaf6af4082e1934bddab | []
| no_license | OlliD/DtwSequenceCompare | 4913c3562db8e22359527d079dc0215e3de8b9f5 | a10b07bdb8dd7c19c27f909191e3e669216181a5 | refs/heads/master | 2021-01-01T16:19:36.972405 | 2010-10-04T09:58:56 | 2010-10-04T09:58:56 | 960,016 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | h | #ifndef DATAHOLDER_H
#define DATAHOLDER_H
#include <QObject>
#include <QList>
#include "dtw.h"
class DataHolder : public QObject
{
Q_OBJECT
public:
explicit DataHolder(QObject *parent = 0);
private:
QList < QList<DTWResult> > *data;
signals:
public slots:
void addResult(QList<DTWResult>);
void getResult(QList<DTWResult>);
};
#endif // DATAHOLDER_H
| [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
788f2e057d5436163495c83521c1f65413d7e450 | 91ba1dc7ac2d753c7b73822b75d6b0c55d9ed52b | /pcapfile.cpp | 4e3eafba670129b370e51ffded8058f7bacc8bda | []
| no_license | joshualant/rtpreceive | 35c326a218d1709f6505d2f1df05a1190ad87923 | f93d8eec1d3013fb95e77534f6bcb3927cd2d6ad | refs/heads/master | 2021-01-10T09:21:13.393217 | 2011-02-23T00:49:04 | 2011-02-23T00:49:04 | 43,960,631 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,260 | cpp | /*
* Copyright (c) 2011, Jim Hollinger
* 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 Jim Hollinger 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 <stdio.h>
#include <memory.h>
#if !defined (WIN32)
# include <sys/socket.h>
# include <netinet/in.h>
#else
# include <winsock.h>
#endif
#include "pcapfile.h"
PcapFile::PcapFile() {
fp = NULL;
pcapData = NULL;
datagram = NULL;
datagram_len = 0;
clear();
}
PcapFile::~PcapFile() {
if (fp != NULL) {
this->close();
}
delete []pcapData;
pcapData = NULL;
datagram = NULL;
datagram_len = 0;
}
void PcapFile::clear() {
if (fp != NULL) {
this->close();
}
delete []pcapData;
pcapData = NULL;
datagram = NULL;
datagram_len = 0;
byteSwap_flag = false;
clearHeader();
clearPacket();
clearMac();
clearIPv4();
clearTcp();
clearUdp();
}
void PcapFile::clearHeader() {
memset(&header, 0, sizeof(header));
}
void PcapFile::clearPacket() {
memset(&packet, 0, sizeof(packet));
}
void PcapFile::clearMac() {
memset(&mac, 0, sizeof(mac));
}
void PcapFile::clearIPv4() {
memset(&ipv4, 0, sizeof(ipv4));
}
void PcapFile::clearTcp() {
memset(&tcp, 0, sizeof(tcp));
}
void PcapFile::clearUdp() {
memset(&udp, 0, sizeof(udp));
}
bool PcapFile::open(const char *filename) {
bool flag = false;
if (fp != NULL) {
this->close();
}
fp = fopen(filename, "rb");
if (fp == NULL) {
fprintf(stderr, "PcapFile.open: Could not open \"%s\"\n", filename);
} else {
if (readFileHeader()) {
printf("PcapFile.open \"%s\" V%hu.%hu%s\n",
filename,
header.version_major,
header.version_minor,
(byteSwap_flag) ? ", byte swapped" : "");
if (header.version_major == 2) {
flag = true;
} else {
fprintf(stderr,
"PcapFile.open: Only major version 2 supported\n");
}
} else {
fprintf(stderr,
"PcapFile.open: \"%s\", but it does not appear to be a pcap file\n",
filename);
printFileHeader();
}
if (pcapData != NULL) {
delete []pcapData;
pcapData = NULL;
}
pcapData = new uint8_t[header.snaplen];
if (pcapData == NULL) {
fprintf(stderr,
"PcapFile.open: Could not create %u byte buffer\n",
header.snaplen);
flag = false;
}
}
return flag;
}
void PcapFile::close() {
if (fp != NULL) {
fclose(fp);
fp = NULL;
}
}
bool PcapFile::readFileHeader() {
bool flag = false;
if (fp != NULL) {
size_t n = fread(&header, 1, sizeof(header), fp);
if (n == sizeof(header)) {
switch (header.magic_number) {
case PCAP_MAGIC_NUMBER:
byteSwap_flag = false;
flag = true;
break;
case PCAP_MAGIC_SWAPPED:
byteSwap_flag = true;
flag = true;
break;
default:
break;
}
if (flag) {
if (byteSwap_flag) {
header.magic_number = swap32(header.magic_number);
header.version_major = swap16(header.version_major);
header.version_minor = swap16(header.version_minor);
header.thiszone = swap32(header.thiszone);
header.sigfigs = swap32(header.sigfigs);
header.snaplen = swap32(header.snaplen);
header.network = swap32(header.network);
}
}
}
}
return flag;
}
void PcapFile::printFileHeader() const {
printf("PcapFile.header magic: 0x%08X ver: %hu.%hu zone: %d sigfigs: %u snaplen: %u network: %u\n",
header.magic_number,
header.version_major,
header.version_minor,
header.thiszone,
header.sigfigs,
header.snaplen,
header.network);
}
bool PcapFile::readPacket() {
bool flag = false;
if (fp != NULL) {
size_t n = fread(&packet, 1, sizeof(packet), fp);
if (n == sizeof(packet)) {
if (byteSwap_flag) {
packet.ts_sec = swap32(packet.ts_sec);
packet.ts_usec = swap32(packet.ts_usec);
packet.incl_len = swap32(packet.incl_len);
packet.orig_len = swap32(packet.orig_len);
}
if ((packet.incl_len > 0) && (packet.incl_len <= header.snaplen)) {
if (pcapData != NULL) {
n = fread(pcapData, 1, packet.incl_len, fp);
if (n == packet.incl_len) {
flag = true;
clearMac();
clearIPv4();
clearTcp();
clearUdp();
if (n >= sizeof(mac)) {
memcpy(&mac, pcapData, sizeof(mac));
mac.ether_type = ntohs(mac.ether_type);
if (mac.ether_type == MAC_ETHER_TYPE_IPV4) {
if (n >= (sizeof(mac) + sizeof(ipv4))) {
memcpy(&ipv4, &pcapData[sizeof(mac)], sizeof(ipv4));
ipv4.tlen = ntohs(ipv4.tlen);
ipv4.identification = ntohs(ipv4.identification);
ipv4.flags_fo = ntohs(ipv4.flags_fo);
ipv4.csum = ntohs(ipv4.csum);
ipv4.saddr = ntohl(ipv4.saddr);
ipv4.daddr = ntohl(ipv4.daddr);
datagram = &pcapData[sizeof(mac) + getIPv4HeaderLength()];
datagram_len = ipv4.tlen - getIPv4HeaderLength();
if (getIPv4HeaderVersion() == IP_HEADER_VERSION_IPv4) {
if (ipv4.proto == IP_PROTOCOL_TCP) {
memcpy(&tcp, datagram, sizeof(tcp));
tcp.sport = ntohs(tcp.sport);
tcp.dport = ntohs(tcp.dport);
tcp.seqnum = ntohl(tcp.seqnum);
tcp.acknum = ntohl(tcp.acknum);
tcp.control = ntohs(tcp.control);
tcp.window = ntohs(tcp.window);
tcp.csum = ntohs(tcp.csum);
tcp.urgent = ntohs(tcp.urgent);
datagram += getTcpHeaderLength();
datagram_len = datagram_len - getTcpHeaderLength();
} else if (ipv4.proto == IP_PROTOCOL_UDP) {
memcpy(&udp, datagram, sizeof(udp));
udp.sport = ntohs(udp.sport);
udp.dport = ntohs(udp.dport);
udp.len = ntohs(udp.len);
udp.csum = ntohs(udp.csum);
datagram += getUdpHeaderLength();
datagram_len = udp.len - getUdpHeaderLength();
}
}
}
}
}
}
}
}
}
}
return flag;
}
void PcapFile::printPacket() const {
printf("PcapFile.packet timestamp: %u.%06u sec len: %u/%u\n",
packet.ts_sec,
packet.ts_usec,
packet.incl_len,
packet.orig_len);
}
void *PcapFile::getPacketData() const {
return datagram;
}
uint16_t PcapFile::getPacketLength() const {
return datagram_len;
}
uint8_t PcapFile::getIPv4HeaderVersion() const {
return (ipv4.ver_ihl & 0xF0) >> 4;
}
uint8_t PcapFile::getIPv4HeaderLength() const {
return (ipv4.ver_ihl & 0x0F) * 4;
}
uint8_t PcapFile::getTcpHeaderLength() const {
return static_cast <uint8_t> ((tcp.control & 0xF000) >> 12) * 4;
}
uint8_t PcapFile::getUdpHeaderLength() const {
return sizeof(udp);
}
uint16_t PcapFile::getSourcePort() const {
uint16_t port = 0;
if (mac.ether_type == MAC_ETHER_TYPE_IPV4) {
if (getIPv4HeaderVersion() == IP_HEADER_VERSION_IPv4) {
if (ipv4.proto == IP_PROTOCOL_TCP) {
port = tcp.sport;
} else if (ipv4.proto == IP_PROTOCOL_UDP) {
port = udp.sport;
}
}
}
return port;
}
uint16_t PcapFile::getDestinationPort() const {
uint16_t port = 0;
if (mac.ether_type == MAC_ETHER_TYPE_IPV4) {
if (getIPv4HeaderVersion() == IP_HEADER_VERSION_IPv4) {
if (ipv4.proto == IP_PROTOCOL_TCP) {
port = tcp.dport;
} else if (ipv4.proto == IP_PROTOCOL_UDP) {
port = udp.dport;
}
}
}
return port;
}
uint32_t PcapFile::getSourceIpAddress() const {
uint32_t addr = INADDR_NONE;
if (mac.ether_type == MAC_ETHER_TYPE_IPV4) {
if (getIPv4HeaderVersion() == IP_HEADER_VERSION_IPv4) {
addr = ipv4.saddr;
}
}
return addr;
}
uint32_t PcapFile::getDestinationIpAddress() const {
uint32_t addr = INADDR_NONE;
if (mac.ether_type == MAC_ETHER_TYPE_IPV4) {
if (getIPv4HeaderVersion() == IP_HEADER_VERSION_IPv4) {
addr = ipv4.daddr;
}
}
return addr;
}
uint16_t PcapFile::swap16(uint16_t n) {
return ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
}
uint32_t PcapFile::swap32(uint32_t n) {
return ((n & 0xFF000000) >> 24) | ((n & 0x00FF0000) >> 8) |
((n & 0x0000FF00) << 8) | ((n & 0x000000FF) << 24);
}
| [
"[email protected]"
]
| [
[
[
1,
395
]
]
]
|
3590fe4229c293cd5e51b51043ade9e124d7cedf | 796687b684b1604bc7d8a178d20e7071dec5b0e1 | /game/src/EndScene.cpp | d08ab3cd866575d361eb23f831a5ef32b4d6183f | []
| no_license | josenavas/ale-vj-qt2011 | 965498af5474bc65a015ab13e42878cb0451ce85 | 6e4e5ad486e5b2c4cfc1aa2044d35263f6acd263 | refs/heads/master | 2021-01-22T03:13:49.635483 | 2011-12-19T23:45:14 | 2011-12-19T23:45:14 | 32,129,957 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | cpp | #include "EndScene.h"
#include <OgreOverlayManager.h>
EndScene::EndScene(Ogre::Root* root, Ogre::RenderWindow* window)
{
mRoot = root;
mSceneMgr = mRoot->createSceneManager("DefaultSceneManager");
mWindow = window;
mExit = false;
}
EndScene::~EndScene(void)
{
}
void EndScene::createScene(void)
{
createSceneCommon();
initObjectNames();
mOverlayItems->hide();
mOverlayObjName->hide();
mOverlay = Ogre::OverlayManager::getSingleton().getByName("Overlays/EndGame");
mOverlay->show();
}
void EndScene::initObjectNames(void)
{
for(int i = 0; i < 10; i++) mObjectNames[i] = new Ogre::String("");
}
int EndScene::objectInteraction(Ogre::String name)
{
mTime = 0;
mExit = true;
mOverlay->hide();
return OBJECT_ANIM_NONE;
}
AbstractScene* EndScene::getNextScene(void)
{
return NULL;
} | [
"[email protected]@55d2aa0d-96bd-598c-80cb-e06a2779e390"
]
| [
[
[
1,
44
]
]
]
|
691245bb9393556c558024dda31e0343836a71f0 | 5da9d428805218901d7c039049d7e13a1a2b1c4c | /Vivian/libScript/Script.h | 796ff3d89544cb47027e050b937940fda4ad7371 | []
| no_license | SakuraSinojun/vivianmage | 840be972f14e17bb76241ba833318c13cf2b00a4 | 7a82ee5c5f37d98b86e8d917d9bb20c96a2d6c7f | refs/heads/master | 2021-01-22T20:44:33.191391 | 2010-12-11T15:26:15 | 2010-12-11T15:26:15 | 32,322,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | h |
//////////////////////////////////////////////////////////////////
//
// FileName : Script.h
// Author : Kaynimm
// Description : Base class for scripts of maps
//
// Copyright(c): 2009-2010 Kaynimm
//
//////////////////////////////////////////////////////////////////
#pragma once
class CScript
{
public:
CScript(void);
virtual ~CScript(void);
}; | [
"SakuraSinojun@c9cc3ed0-94a9-11de-b6d4-8762f465f3f9"
]
| [
[
[
1,
21
]
]
]
|
b045026e6c9893e8ee8273ee4fd10aeecb6b963c | 63d8291850783397b2149b4f38d0b1919bf87e5c | /PobotKey/Projects/Arduino/Libraries/WiiChuck/WiiChuck.cpp | 41b348e70c29b0a0fa57a5c40a9d83dc9873189c | []
| no_license | JulienHoltzer/Pobot-Playground | 8d0cb50edc5846d7fe717f467d5a9f07ad7e7979 | a4a9c6af9c8b2fec8e5782be86427620843f38df | refs/heads/master | 2021-05-28T04:54:03.737479 | 2011-11-11T10:32:43 | 2011-11-11T10:32:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,335 | cpp | /*
* WiiChuck
* Flamingo EDA http://www.flamingoeda.com
*
*/
#include "WiiChuck.h"
void WiiChuck::init()
{
Wire.begin();
Wire.beginTransmission(WII_I2C_ADDR);
Wire.send(0x40);
Wire.send(0x00);
Wire.endTransmission();
}
void WiiChuck::initWithPower()
{
initWithPowerPins(PC3, PC2);
}
void WiiChuck::initWithPowerPins(byte powerPin, byte gndPin)
{
DDRC |= _BV(powerPin) | _BV(gndPin);
PORTC &= ~_BV(gndPin);
PORTC |= _BV(powerPin);
delay(100);
init();
}
boolean WiiChuck::read()
{
int count = 0;
Wire.requestFrom(WII_I2C_ADDR, PACKAGE_LENGTH);
while(Wire.available()) {
buffer[count++] = decodeByte(Wire.receive());
}
// send request for next bytes
sendNullRequest();
if (count < 5) {
return false;
}
// update data
joyAxisX = buffer[0];
joyAxisY = buffer[1];
accelAxisX = buffer[2];
accelAxisY = buffer[3];
accelAxisZ = buffer[4];
buttonZ = 0;
buttonC = 0;
if ((buffer[5] >> 0) & 1) {
buttonZ = 1;
}
if ((buffer[5] >> 1) & 1) {
buttonC = 1;
}
if ((buffer[5] >> 2) & 1) {
accelAxisX += 2;
}
if ((buffer[5] >> 3) & 1) {
accelAxisX += 1;
}
if ((buffer[5] >> 4) & 1) {
accelAxisY += 2;
}
if ((buffer[5] >> 5) & 1) {
accelAxisY += 1;
}
if ((buffer[5] >> 2) & 1) {
accelAxisZ += 2;
}
if ((buffer[5] >> 3) & 1) {
accelAxisZ += 1;
}
return true;
}
int WiiChuck::getJoyAxisX()
{
return joyAxisX;
}
int WiiChuck::getJoyAxisY()
{
return joyAxisY;
}
int WiiChuck::getAccelAxisX()
{
return accelAxisX;
}
int WiiChuck::getAccelAxisY()
{
return accelAxisY;
}
int WiiChuck::getAccelAxisZ()
{
return accelAxisZ;
}
int WiiChuck::getButtonZ()
{
return buttonZ;
}
int WiiChuck::getButtonC()
{
return buttonC;
}
/*****************************************************************************
* PRIVATE METHODS
****************************************************************************/
byte WiiChuck::decodeByte(byte x)
{
x = (x ^ 0x17) + 0x17;
return x;
}
void WiiChuck::sendNullRequest()
{
Wire.beginTransmission(WII_I2C_ADDR);
Wire.send(0x00);
Wire.endTransmission();
}
| [
"julien.holtzer@c631b436-7905-11de-aab9-69570e6b7754"
]
| [
[
[
1,
137
]
]
]
|
090a2b6c554908b9f9b8e694ac4a11cf514e2418 | 6712f8313dd77ae820aaf400a5836a36af003075 | /readCIS.cpp | ca9ee8864ad119d3e69e5af7cbf2588e02e759a4 | []
| no_license | AdamTT1/bdScript | d83c7c63c2c992e516dca118cfeb34af65955c14 | 5483f239935ec02ad082666021077cbc74d1790c | refs/heads/master | 2021-12-02T22:57:35.846198 | 2010-08-08T22:32:02 | 2010-08-08T22:32:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,016 | cpp | #include <wlan/wlan_compat.h>
#include <wlan/version.h>
#include <wlan/p80211types.h>
#include <wlan/p80211meta.h>
#include <wlan/p80211metamsg.h>
#include <wlan/p80211msg.h>
#include <wlan/p80211ioctl.h>
#include <wlan/p80211metastruct.h>
#include <wlan/p80211metadef.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include "hexDump.h"
int main( void )
{
int const fd = socket(AF_INET, SOCK_STREAM, 0);
if( 0 <= fd )
{
p80211ioctl_req_t req;
memset( &req, 0, sizeof( req ) );
p80211msg_p2req_readcis_t cisReq ;
memset( &cisReq, 0, sizeof( cisReq ) );
req.magic = P80211_IOCTL_MAGIC;
req.len = sizeof( cisReq );
req.data = &cisReq ;
strcpy( req.name, "wlan0" );
req.result = 0;
cisReq.msgcode = DIDmsg_p2req_readcis ; // wlan sniff
cisReq.msglen = sizeof( cisReq );
strcpy( (char *)cisReq.devname, "wlan0" );
cisReq.cis.did = DIDmsg_p2req_readcis_cis ;
cisReq.cis.status = 0 ;
cisReq.cis.len = sizeof( cisReq.cis.data );
cisReq.resultcode.did = DIDmsg_p2req_readcis_resultcode ;
cisReq.resultcode.status = 0 ;
cisReq.resultcode.len = sizeof( cisReq.resultcode.data );
int result = ioctl( fd, P80211_IFREQ, &req);
printf( "result == %x\n", result );
if( 0 == result )
{
printf( "cis: %08lx %04x %04x\n", cisReq.cis.did, cisReq.cis.status, cisReq.cis.len );
hexDumper_t dumpCIS( cisReq.cis.data, cisReq.cis.len );
while( dumpCIS.nextLine() )
printf( "%s\n", dumpCIS.getLine() );
printf( "resultcode: %08lx %04x %04x\n", cisReq.resultcode.did, cisReq.resultcode.status, cisReq.resultcode.len );
printf( " data: %08lx\n", cisReq.resultcode.data );
}
close( fd );
}
else
perror( "socket" );
return 0 ;
}
| [
"ericn"
]
| [
[
[
1,
63
]
]
]
|
78b38b851da04fc531e998f75e033b872e076a22 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/AranPymuscle/BwTopWindow.h | 6abf73bc166997dcd407ad96da1c81a228ed252f | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 508 | h | #pragma once
class BwAppContext;
class BwOpenGlWindow;
class BwTopWindow : public Fl_Window
{
public:
BwTopWindow(int w, int h, const char* c, BwAppContext& ac);
virtual ~BwTopWindow();
virtual int handle(int eventType);
void setShapeWindow(BwOpenGlWindow* sw);
BwOpenGlWindow* getShapeWindow() const { return m_shapeWindow; }
void setSceneList(Fl_Browser* sl);
private:
BwAppContext& m_ac;
BwOpenGlWindow* m_shapeWindow;
Fl_Browser* m_sceneList;
};
| [
"[email protected]"
]
| [
[
[
1,
19
]
]
]
|
3a301a81c2e800e9abdcc9d46a2f944d30532f63 | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /ytk_bak/YtkUtils/YtkUtilsTest.cpp | 0eb39497c8b30b4137a92f026b63678bc868d168 | []
| no_license | yewberry/yewtic | 9624d05d65e71c78ddfb7bd586845e107b9a1126 | 2468669485b9f049d7498470c33a096e6accc540 | refs/heads/master | 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 1,217 | cpp | #include <gtest/gtest.h>
#include "YtkUtils.h"
#include "SqliteDb.h"
#include "INIReader.h"
using namespace std;
TEST(YtkUtils, JsonFunc)
{
json_t* root = YtkUtils::readJsonFromFile("test.json");
//map op
YtkUtils::map_t map = YtkUtils::jsonToMap(root);
map["fuck"] = "─Ńfuck┴╦";
json_t* json = YtkUtils::mapToJson(map);
YtkUtils::writeJsonToFile(json, "test2.json");
json_free_value(&json);
//str op
string str = YtkUtils::jsonToString(root);
json_free_value(&root);
ASSERT_TRUE(true);
}
TEST(YtkUtils, DbMgr)
{
DbMgr* dbMgr = new SqliteDb();
bool open = dbMgr->open("test.db");
string nm = dbMgr->dbName();
string ver = dbMgr->dbVersion();
ASSERT_TRUE( 0 == nm.compare("sqlite") && 0 == ver.compare("3.6.21") );
}
TEST(YtkUtils, INIReader)
{
INIReader reader("test.ini");
if (reader.ParseError() < 0) {
std::cout << "Can't load 'test.ini'\n";
}
std::cout << "Config loaded from 'test.ini': version="
<< reader.GetInteger("protocol", "version", -1) << ", name="
<< reader.Get("user", "name", "UNKNOWN") << ", email="
<< reader.Get("user", "email", "UNKNOWN") << "\n";
} | [
"yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
]
| [
[
[
1,
48
]
]
]
|
528977236076b2cb44e1337f1478b7b69b19abb6 | 324524076ba7b05d9d8cf5b65f4cd84072c2f771 | /Checkers/Libraries/Common/eSockets/DFD.cpp | 877c0aa94b66a7b7c437ed86473d6faf171c4eb6 | [
"BSD-2-Clause"
]
| permissive | joeyespo-archive/checkers-c | 3bf9ff11f5f1dee4c17cd62fb8af9ba79246e1c3 | 477521eb0221b747e93245830698d01fafd2bd66 | refs/heads/master | 2021-01-01T05:32:45.964978 | 2011-03-13T04:53:08 | 2011-03-13T04:53:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,265 | cpp | // DFD.cpp
// Dynamic FD Implementation File
// By Joe Esposito
#pragma once
// Adds a single socket in the set, and updates the secondary set
bool DFD_Add (SOCKET s, LPDFD_SET lpdfds)
{
LPUINT lpTempFDS;
UINT nCount, i;
if (lpdfds == NULL) return false;
if ((lpdfds->fds == NULL) || (lpdfds->fds2 == NULL)) DFD_Zero(lpdfds);
lpTempFDS = (LPUINT)lpdfds->fds;
nCount = *lpTempFDS;
for (i = 1; i <= nCount; i++)
if (lpTempFDS[i] == (s)) return false;
lpdfds->fds = new UINT [(nCount + 2)]; // current count + 1 (new) + 1 (count var)
if (lpdfds->fds == NULL) {
lpdfds->fds = lpTempFDS;
return false;
}
if (nCount > 0)
memcpy( (&(((LPUINT)lpdfds->fds)[1])), (&(lpTempFDS[1])), (nCount * 4) );
delete [(nCount * 4) + 4] lpTempFDS;
((LPUINT)lpdfds->fds)[++nCount] = (UINT)s;
((LPUINT)lpdfds->fds)[0] = nCount;
if (lpdfds->fds2 != NULL)
{
lpTempFDS = (LPUINT)lpdfds->fds2; lpdfds->fds2 = new UINT [(nCount + 1)];
nCount = *lpTempFDS;
memcpy(lpdfds->fds2, lpTempFDS, ((nCount * 4) + 4) );
delete [(nCount * 4) + 4] lpTempFDS;
}
return true;
}
// Removes a single socket in the set, and updates the secondary set
bool DFD_Remove (SOCKET s, LPDFD_SET lpdfds)
{
LPUINT lpTempFDS;
UINT nCount, i;
if (lpdfds == NULL) return false;
if ((lpdfds->fds == NULL) || (lpdfds->fds2 == NULL)) if (!DFD_Zero(lpdfds)) { DFD_DELETE(lpdfds); return false; }
lpTempFDS = (LPUINT)lpdfds->fds;
nCount = *lpTempFDS;
if (nCount == 0) return true;
for (i = 1; i <= nCount; i++)
{
if (lpTempFDS[i] == (s))
{
if (nCount > 1)
{
if ((lpdfds->fds = new UINT [(nCount)]) == NULL) { DFD_DELETE(lpdfds); return false; }
if (i > 1) memcpy( (&(((LPUINT)lpdfds->fds)[1])), (&(lpTempFDS[1])), ((i - 1) * 4) );
if (i < nCount) memcpy( (&(((LPUINT)lpdfds->fds)[i])), (&(lpTempFDS[(i + 1)])), ((nCount - i) * 4) );
*((LPUINT)lpdfds->fds) = (nCount - 1);
delete [(nCount + 1)] lpTempFDS;
lpTempFDS = (LPUINT)lpdfds->fds2;
if ((lpdfds->fds2 = new UINT [(nCount)]) == NULL) { DFD_DELETE(lpdfds); return false; }
if (i > 1) memcpy( (&(((LPUINT)lpdfds->fds2)[1])), (&(lpTempFDS[1])), ((i - 1) * 4) );
if (i < nCount) memcpy( (&(((LPUINT)lpdfds->fds2)[i])), (&(lpTempFDS[(i + 1)])), ((nCount - i) * 4) );
*((LPUINT)lpdfds->fds2) = (nCount - 1);
delete [(nCount + 1)] lpTempFDS;
}
else
{
if ((lpdfds->fds = new UINT [1]) == NULL) { DFD_DELETE(lpdfds); return false; }
*(LPUINT)lpdfds->fds = 0;
delete [(nCount + 1)] lpTempFDS;
lpTempFDS = (LPUINT)lpdfds->fds2;
if ((lpdfds->fds2 = new UINT [1]) == NULL) { DFD_DELETE(lpdfds); return false; }
*(LPUINT)lpdfds->fds2 = 0;
delete [(nCount + 1)] lpTempFDS;
}
return true;
}
}
return true;
}
bool DFD_Zero (LPDFD_SET lpdfds)
{
LPUINT lpTempFDS;
UINT nCount = 0;
if (lpdfds == NULL) return false;
lpTempFDS = (LPUINT)lpdfds->fds;
try { if (lpTempFDS != NULL) nCount = *lpTempFDS; }
catch(...) { nCount = 0; lpTempFDS = NULL; }
lpdfds->fds = new UINT [1];
*((LPUINT)lpdfds->fds) = 0;
if (lpdfds->fds == NULL) {
lpdfds->fds = lpTempFDS;
return false;
}
if (lpTempFDS != NULL) delete [(nCount + 1)] lpTempFDS;
lpTempFDS = (LPUINT)lpdfds->fds2;
try { if (lpTempFDS != NULL) nCount = *lpTempFDS; }
catch(...) { nCount = 0; lpTempFDS = NULL; }
lpdfds->fds2 = new UINT [1];
*((LPUINT)lpdfds->fds2) = 0;
if (lpTempFDS != NULL) delete [(nCount + 1)] lpTempFDS;
return true;
}
int select (int nfds, dfd_set *readdfds, dfd_set *writedfds, dfd_set *exceptdfds, const timeval *timeout)
{
return select(nfds,
(fd_set *)((readdfds) ? (memcpy( ((dfd_set *)(readdfds))->fds2, ((dfd_set *)(readdfds))->fds, (((*((LPUINT)(((dfd_set *)readdfds)->fds))) * 4) + 4) )) : (NULL)),
(fd_set *)((writedfds) ? (memcpy( ((dfd_set *)(writedfds))->fds2, ((dfd_set *)(writedfds))->fds, (((*((LPUINT)(((dfd_set *)writedfds)->fds))) * 4) + 4) )) : (NULL)),
(fd_set *)((exceptdfds) ? (memcpy( ((dfd_set *)(exceptdfds))->fds2, ((dfd_set *)(exceptdfds))->fds, (((*((LPUINT)(((dfd_set *)exceptdfds)->fds))) * 4) + 4) )) : (NULL)),
timeout);
}
| [
"[email protected]"
]
| [
[
[
1,
147
]
]
]
|
a8451f393849c7f9e9a1ac2737273e477dfa65fe | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /Sockets/Event.h | 896ab1478b3257d0bcb2d2906bdcab4e8b978964 | []
| 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 | UTF-8 | C++ | false | false | 2,161 | h | /** \file Event.h
** \date 2005-12-07
** \author [email protected]
**/
/*
Copyright (C) 2005-2009 Anders Hedstrom
This library is made available under the terms of the GNU GPL, with
the additional exemption that compiling, linking, and/or using OpenSSL
is allowed.
If you would like to use this library in a closed-source application,
a separate license agreement is available. For information about
the closed-source license agreement for the C++ sockets library,
please visit http://www.alhem.net/Sockets/license.html and/or
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.
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 _SOCKETS_Event_H
#define _SOCKETS_Event_H
#include "sockets-config.h"
#ifdef _WIN32
#else
#include <sys/select.h>
#endif
#include "EventTime.h"
#ifdef SOCKETS_NAMESPACE
namespace SOCKETS_NAMESPACE {
#endif
class IEventOwner;
/** Store information about a timer event.
\ingroup timer */
class Event
{
public:
Event(IEventOwner *,long sec,long usec,unsigned long data = 0);
~Event();
bool operator<(Event&);
long GetID() const;
const EventTime& GetTime() const;
IEventOwner *GetFrom() const;
unsigned long Data() const;
private:
Event(const Event& ) {} // copy constructor
Event& operator=(const Event& ) { return *this; } // assignment operator
IEventOwner *m_from;
unsigned long m_data;
EventTime m_time;
static long m_unique_id;
long m_id;
};
#ifdef SOCKETS_NAMESPACE
}
#endif
#endif // _SOCKETS_Event_H
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
80
]
]
]
|
fc634affd3daa28fe2e4671f6f9fe315a138de93 | 312f847edc3c68baab48deb92016339469ce8bff | /demo/stdafx.cpp | 0db0ecb353aa628bae8cd9d1c38b64de8813d60d | []
| no_license | tzafrir/graphics | c43deb26aa440ab8a424556f81a7442fafb82db1 | 1b0d1372056e62c35f2cb1b19a0dab2725819212 | refs/heads/master | 2016-08-04T17:10:18.631024 | 2010-11-03T09:59:28 | 2010-11-03T09:59:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | cpp | // stdafx.cpp : source file that includes just the standard includes
// demo.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"[email protected]"
]
| [
[
[
1,
7
]
]
]
|
670e1e3c63af6c446800546b1aaaec91007cb2ad | c0bd82eb640d8594f2d2b76262566288676b8395 | /src/scripts/HunterSpells.cpp | cf2a903460846a1d3a9b3820830d0bad65f4fcbd | [
"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 | 2,103 | cpp | //////////////////////////////////////////////////
// Copyright (C) 2006 Burlex for WoWd Project
//////////////////////////////////////////////////
// Hunter Dummy Spells
#include "../game/StdAfx.h"
/* Script Export Declarations */
extern "C" WOWD_SCRIPT_DECL void ScriptInitialize(ScriptModule *mod);
extern "C" WOWD_SCRIPT_DECL bool HandleDummySpell(uint32 uSpellId, uint32 i, Spell *pSpell);
// Build version info function
BUILD_VERSIONINFO_DATA(SCRIPTLIB_VERSION_MAJOR, SCRIPTLIB_VERSION_MINOR);
#ifdef WIN32
/* This is needed because windows is a piece of shit. ;) */
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )
{
return TRUE;
}
#endif
void Refocus(uint32 uSpellId, uint32 i, Spell * pSpell)
{
Player * playerTarget = pSpell->GetPlayerTarget();
if(playerTarget == 0) return;
SpellSet::const_iterator itr = playerTarget->mSpells.begin();
for(; itr != playerTarget->mSpells.end(); ++itr)
{
if((*itr) == 24531) // skip calling spell.. otherwise spammies! :D
continue;
if((*itr) == 19434 || (*itr) == 20900 || (*itr) == 20901 || (*itr) == 20902 || (*itr) == 20903 || (*itr) == 20904 || (*itr) == 27632
|| (*itr) == 2643 || (*itr) == 14288|| (*itr) == 14289|| (*itr) == 14290 || (*itr) == 25294 || (*itr) == 14443 || (*itr) == 18651 || (*itr) == 20735 || (*itr) == 21390
|| (*itr) == 1510 || (*itr) == 14294 || (*itr) == 14295 || (*itr) == 1540 || (*itr) == 22908
|| (*itr) == 3044 || (*itr) == 14281 || (*itr) == 14282 || (*itr) == 14283 || (*itr) == 14284 || (*itr) == 14285 || (*itr) == 14286 || (*itr) == 14287)
playerTarget->ClearCooldownForSpell((*itr));
}
}
/* Actual Spell Code */
bool HandleDummySpell(uint32 uSpellId, uint32 i, Spell *pSpell)
{
switch(uSpellId)
{
case 24531:
Refocus(uSpellId, i, pSpell);
break;
}
return true;
}
/* Module info */
void ScriptInitialize(ScriptModule *mod)
{
ADD_SPELL(24531); // Refocus
} | [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
d73704a7f507a692575e9d23c9cd7dd77bc3db67 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Scada/Emulation/PLC5/OPCSrvr/Callback.cpp | b6f4f7960194992f50c4fb9690dbc95978c35c3f | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,020 | cpp | //**************************************************************************
//
// Copyright (c) FactorySoft, INC. 1997, All Rights Reserved
//
//**************************************************************************
//
// Filename : Callback.cpp
// $Author : Jim Hansen
//
// Subsystem : Callback object for OPC Server DLL
//
// Description: This class interfaces to the application's data
//
//**************************************************************************
#include "stdafx.h"
#include <afxtempl.h>
#include "Callback.h"
#include "OPCError.h"
#include "OPCProps.h"
#include <math.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//*******************************************************************
CPLC5OPCTag::CPLC5OPCTag(CPLC5 * Plc, LPCTSTR name, Branch* branch)
: m_name(name),
m_Plc(Plc),
m_Add(Plc)
{
m_fullname = branch->GetPath() + m_name;
CAddInfo *pAI=Plc->FindSymbol((LPTSTR)(LPCTSTR)m_name);
if (pAI)
m_Add.Parse((LPTSTR)pAI->Address());
else
m_Add.Parse((LPTSTR)(LPCTSTR)m_name);
}
//*******************************************************************
// Recursive function to search for a fully qualified tag name
CPLC5OPCTag* Branch::FindTag( const CString& target )
{
int delimiter = target.Find( _T('.') );
if( delimiter == -1 ) // tag name if no delimiter
{
POSITION pos = m_tags.GetHeadPosition();
while( pos )
{
CPLC5OPCTag* pTag = m_tags.GetNext( pos );
if( pTag->m_name.CompareNoCase( target ) == 0 )
return pTag;
}
}
else
{
CString branchName( target.Left( delimiter ) );
POSITION pos = m_branches.GetHeadPosition();
while( pos )
{
Branch* pBranch = m_branches.GetNext( pos );
if( pBranch->m_name.CompareNoCase( branchName ) == 0 )
return pBranch->FindTag( target.Mid( delimiter+1 ) );
}
}
return NULL;
}
//*******************************************************************
CString Branch::GetPath()
{
if( m_parent )
{
if (!m_SkipOnRebuild)
return CString(m_parent->GetPath() + m_name + ".");
else
return CString(m_parent->GetPath());
}
return "";
}
//*******************************************************************
inline void SplitName(LPCTSTR Name, CString &sPlcName, CString &sName)
{
sPlcName=Name;
int iDot=sPlcName.Find('.');
if (iDot>=0)
{
sName=sPlcName.Right(sPlcName.GetLength()-iDot-1);
sPlcName=sPlcName.Left(iDot);
}
else
{
sPlcName="";
sName=Name;
}
}
inline CPLC5OPCTag * TryMakeTag(LPCTSTR Name, Branch * pBrnch, CPLC5Array & Plcs)
{
CString sPlcName, sName;
SplitName(Name, sPlcName, sName);
StripAddressZeros(sName);
int iPlc=Plcs.Find(sPlcName);
if (iPlc<0)
return NULL;
CPLC5*Plc=&Plcs[iPlc];
CPLC5OPCTag * pTag=new CPLC5OPCTag(Plc, sName, pBrnch);
if (pTag->m_Add.m_IsValid)
{
VARTYPE Typ=pTag->VarType();//(strnicmp(sName, "F8", 2)==0) ? VT_R4 : VT_I2;
pTag->m_nativeType = Typ;
pTag->m_value.vt = Typ;
pBrnch->AddTag( pTag );
}
else
{
delete pTag;
pTag=NULL;
}
return pTag;
}
inline CPLC5OPCTag * MakeTag(LPCTSTR Name, WORD Typ, Branch * pBrnch, CPLC5Array & Plcs)
{
CString sPlcName, sName;
SplitName(Name, sPlcName, sName);
StripAddressZeros(sName);
int iPlc=Plcs.Find(sPlcName);
if (iPlc<0)
return NULL;
CPLC5*Plc=&Plcs[iPlc];
CPLC5OPCTag * pTag=new CPLC5OPCTag(Plc, sName, pBrnch);
pTag->m_nativeType = Typ;
pBrnch->AddTag( pTag );
return pTag;
}
CMyOPCCallBack::CMyOPCCallBack(CPLC5Array & Plc) :
m_root( "PLC5" , true),
m_Plc(Plc)
{
//Branch* pBranch = NULL;
for (int p=0; p<Plc.GetSize(); p++)
{
CPLC5 & P=Plc[p];
Branch * pPlc=new Branch(P.m_sPlcName, false);
m_root.AddBranch(pPlc);
for (int t=0; t<P.m_nTables; t++)
{
if (t!=2) // Skip the S
{
CTable & T=*P.m_Table[t];
if (P.m_Table[t])
{
Branch * pTab=new Branch(T.m_sName, true);
pPlc->AddBranch(pTab);
for (int v=0; v<T.NVals(); v++)
{
CString V;
V.Format(T.OctalAdd()?"%s:%02o":"%s:%03i", T.m_sName, v);
// V.Format(T.OctalAdd()?"%02o":"%03i", T.m_sName, v);
CPLC5OPCTag *pTg=new CPLC5OPCTag(&Plc[p], V, pTab);
pTab->AddTag(pTg);
}
}
}
}
}
}
CMyOPCCallBack::~CMyOPCCallBack()
{
}
//*******************************************************************
COPCBrowser* CMyOPCCallBack::CreateBrowser()
{
return new ShellBrowser(this);
}
//*******************************************************************
// SetUpdateRate returns a modified update rate
DWORD CMyOPCCallBack::SetUpdateRate( DWORD newUpdateRate )
{
if( newUpdateRate > 10 )
return newUpdateRate;
else
return 10;
}
//*******************************************************************
// AddTag creates a new tag or returns a pointer to an existing tag.
//
// Return NULL if the tag could not be created (bad name or accessPath)
// or the requested type is incompatible. The requested type is for this
// client, do not change the tag's type.
CTag* CMyOPCCallBack::AddTag(
LPCTSTR name,
LPCTSTR accessPath,
VARTYPE requestedType)
{
CSLock wait( &m_CS ); // protect tag access
CString sName(name);
StripAddressZeros(sName);
CPLC5OPCTag* pTag = m_root.FindTag(sName);
if (pTag)
return pTag;
// Initialize the tag's type, etc.
// should store in a list
if (pTag==NULL)
{
pTag=TryMakeTag(sName, &m_root/*pData*/, m_Plc);
}
return (CTag*)pTag;
}
//*******************************************************************
// ValidateTag modifies pTag to contain the nativeType and access rights
// if successful. If the name and access path do not specify a valid tag,
// then return OPC_E_UNKNOWNITEMID or OPC_E_UNKNOWNPATH.
// If the data type is incompatible, return OPC_E_BADTYPE.
HRESULT CMyOPCCallBack::ValidateTag(
CTag* pTag,
LPCTSTR name,
LPCTSTR accessPath,
VARTYPE requestedType)
{
CSLock wait( &m_CS ); // protect tag access
CString sName(name);
StripAddressZeros(sName);
CPLC5OPCTag* pFoundTag = m_root.FindTag(sName);
if( pFoundTag )
{
pTag->m_nativeType = pFoundTag->m_nativeType;
pTag->m_accessRights = pFoundTag->m_accessRights;
// can use VariantChangeType to test data types:
// get a current value for this tag and convert it to the requested type.
// If VariantChangeType returns an error, return OPC_E_BADTYPE.
return S_OK;
}
return OPC_E_UNKNOWNITEMID;
}
//*******************************************************************
// Remove is called when tags are released. This function must check
// if the tags are in use if AddTag may ever return a pointer to an
// existing tag. Additional clean up should occur here.
HRESULT CMyOPCCallBack::Remove(
DWORD dwNumItems,
CTag ** ppTags)
{
CSLock wait( &m_CS ); // protect tag access
for( DWORD index=0; index<dwNumItems; index++ )
{
// // Not needed because CPLC5OPCTags are static
// CTag* pTag = ppTags[index];
// if( !pTag->InUse() )
// delete pTag;
}
return S_OK;
}
//*******************************************************************
LPCTSTR CMyOPCCallBack::GetTagName( CTag * pTag )
{
return ((CPLC5OPCTag*)pTag)->m_fullname;
}
//*******************************************************************
// GetTagLimits should return TRUE if this tags has known limits.
BOOL CMyOPCCallBack::GetTagLimits( CTag * pTag, double *pHigh, double *pLow )
{
*pHigh = 1.0;
*pLow = -1.0;
return TRUE;
}
//*******************************************************************
const double pi = 3.1415926535;
HRESULT CMyOPCCallBack::ReadTag(
CTag * pTag)
{
//if (dbgf)
// fprintf(dbgf, "ReadTag %i",pTag->m_nativeType);
CPLC5OPCTag* pPlcTag = (CPLC5OPCTag*)(pTag);
// TRACE2(">>> %8.2f %s\n", GetTickCount()/1000.0, (LPCTSTR)pPlcTag->m_name);
CSLock wait( &m_CS ); // protect tag access
VariantClear( &pTag->m_value );
pTag->m_value.vt = pTag->m_nativeType;
switch( pTag->m_nativeType )
{
case VT_EMPTY:
case VT_NULL:
case VT_BSTR:
{
CTime now( CTime::GetCurrentTime() );
CString temp( now.Format(_T("%S Seconds")) );
pTag->m_value.bstrVal = temp.AllocSysString();
}
break;
case VT_BOOL:
if (pPlcTag && pPlcTag->m_Add.m_IsValid)
pTag->m_value.boolVal = pPlcTag->m_Add.BValue() ? VARIANT_TRUE : VARIANT_FALSE;
else
pTag->m_value.boolVal = VARIANT_FALSE;
break;
case VT_UI1: // uchar
if (pPlcTag && pPlcTag->m_Add.m_IsValid)
pTag->m_value.bVal = (unsigned char)pPlcTag->m_Add.IValue();
else
pTag->m_value.bVal = 0;
break;
case VT_I2 : // short
if (pPlcTag && pPlcTag->m_Add.m_IsValid)
pTag->m_value.iVal = pPlcTag->m_Add.IValue();
else
pTag->m_value.iVal = 0;
break;
case VT_I4 : // long
if (pPlcTag && pPlcTag->m_Add.m_IsValid)
pTag->m_value.lVal = pPlcTag->m_Add.IValue();
else
pTag->m_value.lVal = 0;
break;
case VT_R4 :
if (pPlcTag && pPlcTag->m_Add.m_IsValid)
pTag->m_value.fltVal = pPlcTag->m_Add.ValueAsFlt();
else
pTag->m_value.fltVal = 0;
break;
case VT_R8 :
if (pPlcTag && pPlcTag->m_Add.m_IsValid)
pTag->m_value.dblVal = pPlcTag->m_Add.ValueAsFlt();
else
pTag->m_value.dblVal = 0;
break;
default: ASSERT( FALSE );
}
CoFileTimeNow( &pTag->m_timestamp );
pTag->m_quality = OPC_QUALITY_GOOD;
//if (dbgf)
// fprintf(dbgf, ">> %i\n",pTag->m_value.vt);
return S_OK;
}
//*******************************************************************
// The variant may contain data in any format the client sent.
// Use VariantChangeType to convert to a usable format.
HRESULT CMyOPCCallBack::WriteTag(
CTag * pTag,
VARIANT & value)
{
CPLC5OPCTag* pPlcTag = (CPLC5OPCTag*)(pTag);
HRESULT hr=VariantChangeType(&pPlcTag->m_value, &value, 0, pPlcTag->m_nativeType);
if (0 && dbgf)
fprintf(dbgf, "WrtTag hr:%08x %2i %2i %2i %s\n",
hr,
pPlcTag->m_value.vt,
value.vt,
pPlcTag->m_nativeType,
pPlcTag->m_Add.Text());
if (SUCCEEDED(hr))
{
if (pPlcTag)
{
switch( pPlcTag->m_value.vt)
{
case VT_BOOL:
{
pPlcTag->m_Add.SetBValue(pPlcTag->m_value.bVal!=0, NULL, "OPC Write");
break;
}
case VT_I2:
pPlcTag->m_Add.SetIValue(pPlcTag->m_value.iVal);
break;
case VT_I4:
pPlcTag->m_Add.SetIValue((short)value.lVal);
break;
case VT_BSTR:
break;
case VT_R4:
pPlcTag->m_Add.SetFValue(value.fltVal);
break;
case VT_R8:
pPlcTag->m_Add.SetFValue((float)value.dblVal);
break;
default:
{
int x=0;
}
break;
}
}
}
return hr;
}
//*******************************************************************
// If the name is valid, return the number of item properties supported.
// If this returns successfully, QueryAvailableProperties will be called.
// To save lookups, put a hint into ppVoid.
HRESULT CMyOPCCallBack::QueryNumProperties(
LPCTSTR name,
DWORD * pdwNumItems,
LPVOID * ppVoid)
{
CString sName(name);
StripAddressZeros(sName);
CPLC5OPCTag* pFoundTag = m_root.FindTag(sName);
if( pFoundTag )
{
*pdwNumItems = 6;
*ppVoid = (LPVOID)pFoundTag;
return S_OK;
}
return OPC_E_UNKNOWNITEMID;
}
//*******************************************************************
// The properties (from QueryNumProperties) now get filled in.
// pVoid contains the hint from QueryNumProperties.
// AllocString allocates COM memory to hold a string.
HRESULT CMyOPCCallBack::QueryAvailableProperties(
LPCTSTR name,
DWORD dwNumItems,
LPVOID pVoid,
DWORD * pPropertyIDs,
LPWSTR * pDescriptions,
VARTYPE * pDataTypes)
{
if( pVoid == NULL )
return OPC_E_UNKNOWNITEMID;
CPLC5OPCTag* pTag = (CPLC5OPCTag*)pVoid;
CString description;
DWORD index=0;
description = _T("Item Canonical DataType");
pPropertyIDs[index] = OPC_PROP_CDT;
pDescriptions[index] = AllocString(description);
pDataTypes[index] = VT_I2;
index++;
if( index==dwNumItems ) return S_OK;
description = _T("Item Value");
pPropertyIDs[index] = OPC_PROP_VALUE;
pDescriptions[index] = AllocString(description);
pDataTypes[index] = pTag->m_nativeType;
index++;
if( index==dwNumItems ) return S_OK;
description = _T("Item Quality");
pPropertyIDs[index] = OPC_PROP_QUALITY;
pDescriptions[index] = AllocString(description);
pDataTypes[index] = VT_I2;
index++;
if( index==dwNumItems ) return S_OK;
description = _T("Item Timestamp");
pPropertyIDs[index] = OPC_PROP_TIME;
pDescriptions[index] = AllocString(description);
pDataTypes[index] = VT_DATE;
index++;
if( index==dwNumItems ) return S_OK;
description = _T("Item Access Rights");
pPropertyIDs[index] = OPC_PROP_RIGHTS;
pDescriptions[index] = AllocString(description);
pDataTypes[index] = VT_I4;
index++;
if( index==dwNumItems ) return S_OK;
description = _T("Item Description");
pPropertyIDs[index] = OPC_PROP_DESC;
pDescriptions[index] = AllocString(description);
pDataTypes[index] = VT_BSTR;
return S_OK;
}
//*******************************************************************
HRESULT CMyOPCCallBack::GetItemProperties(
LPCTSTR name,
DWORD dwNumItems,
DWORD * pPropertyIDs,
VARIANT * pData,
HRESULT * pErrors)
{
CString sName(name);
StripAddressZeros(sName);
CPLC5OPCTag* pTag = m_root.FindTag(sName);
if( !pTag )
return OPC_E_UNKNOWNITEMID;
DATE date;
WORD dosDate=0, dosTime=0;
for( DWORD index=0; index<dwNumItems; index++ )
{
pErrors[index] = S_OK;
switch(pPropertyIDs[index])
{
case OPC_PROP_CDT:
pData[index].vt = VT_I2;
pData[index].iVal = pTag->m_nativeType;
break;
case OPC_PROP_VALUE:
VariantCopy( &pData[index], &pTag->m_value );
break;
case OPC_PROP_QUALITY:
pData[index].vt = VT_I2;
pData[index].iVal = pTag->m_quality;
break;
case OPC_PROP_TIME:
pData[index].vt = VT_DATE;
FileTimeToDosDateTime( &pTag->m_timestamp, &dosDate, &dosTime);
DosDateTimeToVariantTime( dosDate, dosTime, &date);
pData[index].date = date;
break;
case OPC_PROP_RIGHTS:
pData[index].vt = VT_I4;
pData[index].lVal = OPC_READABLE | OPC_WRITEABLE;
break;
case OPC_PROP_DESC:
{
CString description(_T("Item Description goes here"));
pData[index].vt = VT_BSTR;
pData[index].bstrVal = description.AllocSysString();
}
break;
}
}
return S_OK;
}
//*******************************************************************
// return a string if the error code is recognized
LPCTSTR CMyOPCCallBack::GetErrorString(
HRESULT dwError,
LCID dwLocale)
{
error = _T("Vendor Error string");
return error;
}
//*******************************************************************
// return your vendor string
LPCTSTR CMyOPCCallBack::GetVendorString()
{
return _T("Kenwalt (Pty) Ltd.");
}
//*******************************************************************
//
//*******************************************************************
// Do The Command
//void CMyOPCCallBack::StartTheCommand()
// {
//
//
// }
//
//void CMyOPCCallBack::FinishTheCommand(long Rsp)
// {
// m_Rsp=Rsp;
// // Done
// m_Cmd=0;
// m_DataRqd=0;
// m_DataRcvd=0;
// int xx=0;
// }
//*******************************************************************
// ShellBrowser class
//*******************************************************************
OPCNAMESPACETYPE ShellBrowser::QueryOrganization()
{
return OPC_NS_HIERARCHIAL;
}
//*******************************************************************
HRESULT ShellBrowser::GetNames( OPCBROWSETYPE type,
LPCTSTR stringFilter,
VARTYPE dataTypeFilter,
DWORD accessFilter )
{
m_type = type;
m_stringFilter = stringFilter;
m_dataTypeFilter = dataTypeFilter;
m_accessFilter = accessFilter;
if( m_type == OPC_FLAT )
{
m_paths.RemoveAll();
m_pBranch = &m_parent->m_root;
AddTags( m_pBranch );
}
Reset();
return S_OK;
}
//*******************************************************************
// Recursive function to add tag names from all groups to a list.
// This is only called when browsing OPC_FLAT
// Added 2.0
void ShellBrowser::AddTags( Branch* pBranch )
{
// First add full path names for this group's tags
CString path(pBranch->GetPath());
POSITION pos = pBranch->m_tags.GetHeadPosition();
while( pos )
{
CPLC5OPCTag* pTag = pBranch->m_tags.GetNext( pos );
CString name( path + pTag->m_name );
m_paths.AddTail( name );
}
// And recurse into the child groups
pos = pBranch->m_branches.GetHeadPosition();
while( pos )
{
AddTags( pBranch->m_branches.GetNext( pos ) );
}
}
//**************************************************************************
BOOL ShellBrowser::MoveUp()
{
CSLock wait( &m_parent->m_CS );
if( m_pBranch->m_parent )
{
m_pBranch = m_pBranch->m_parent;
Reset();
return TRUE;
}
// at the "root" level, can't go up
return FALSE;
}
//**************************************************************************
BOOL ShellBrowser::MoveDown(LPCTSTR branch)
{
CSLock wait( &m_parent->m_CS );
POSITION pos = m_pBranch->m_branches.GetHeadPosition();
while( pos )
{
Branch* pBranch = m_pBranch->m_branches.GetNext( pos );
if( pBranch->m_name.CompareNoCase( branch ) == 0 )
{
if (pBranch->m_tags.GetCount()==0 && pBranch->m_branches.GetCount()==0)
{
}
m_pBranch = pBranch;
Reset();
return TRUE;
}
}
return FALSE;
}
//*******************************************************************
// if name is valid, return the path+name
LPCTSTR ShellBrowser::GetItemID( LPCTSTR name )
{
CSLock wait( &m_parent->m_CS );
// Search for the name
CPLC5OPCTag* pTag = m_pBranch->FindTag(name);
if( !pTag )
return "";
// The name is valid
_tcscpy( m_name, (m_pBranch->GetPath() + name) );
return m_name;
}
//*******************************************************************
LPCTSTR ShellBrowser::Next()
{
CSLock wait( &m_parent->m_CS );
while( m_pos )
{
if( m_type==OPC_BRANCH )
{
Branch* pBranch = m_pBranch->m_branches.GetNext(m_pos);
_tcscpy( m_name, pBranch->m_name );
if( m_stringFilter.IsEmpty() || MatchPattern( m_name, m_stringFilter, FALSE) )
return m_name;
}
else if( m_type==OPC_LEAF )
{
CPLC5OPCTag* pTag = m_pBranch->m_tags.GetNext(m_pos);
_tcscpy( m_name, pTag->m_name );
if( m_stringFilter.IsEmpty() || MatchPattern( m_name, m_stringFilter, FALSE) )
return m_name;
}
else if( m_type == OPC_FLAT )
{
CString name = m_paths.GetNext( m_pos );
_tcscpy( m_name, name );
if( m_stringFilter.IsEmpty() || MatchPattern( m_name, m_stringFilter, FALSE) )
return m_name;
}
else
m_pos = NULL;
}
return _T("");
}
//*******************************************************************
void ShellBrowser::Reset()
{
CSLock wait( &m_parent->m_CS );
if( m_type==OPC_BRANCH )
m_pos = m_pBranch->m_branches.GetHeadPosition();
else if( m_type==OPC_LEAF )
m_pos = m_pBranch->m_tags.GetHeadPosition();
else if( m_type == OPC_FLAT )
m_pos = m_paths.GetHeadPosition();
}
| [
"[email protected]"
]
| [
[
[
1,
754
]
]
]
|
29924efc8f4e69a929f0101acefccc9f8f0c9215 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/ricochet/dlls/buttons.cpp | f7ae613fed0b37cd93440d7ea2db482312ba51d0 | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,603 | cpp | /***
*
* Copyright (c) 1999, 2000 Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
/*
===== buttons.cpp ========================================================
button-related code
*/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "saverestore.h"
#include "doors.h"
#define SF_BUTTON_DONTMOVE 1
#define SF_ROTBUTTON_NOTSOLID 1
#define SF_BUTTON_TOGGLE 32 // button stays pushed until reactivated
#define SF_BUTTON_SPARK_IF_OFF 64 // button sparks in OFF state
#define SF_BUTTON_TOUCH_ONLY 256 // button only fires as a result of USE key.
#define SF_GLOBAL_SET 1 // Set global state to initial state on spawn
class CEnvGlobal : public CPointEntity
{
public:
void Spawn( void );
void KeyValue( KeyValueData *pkvd );
void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
virtual int Save( CSave &save );
virtual int Restore( CRestore &restore );
static TYPEDESCRIPTION m_SaveData[];
string_t m_globalstate;
int m_triggermode;
int m_initialstate;
};
TYPEDESCRIPTION CEnvGlobal::m_SaveData[] =
{
DEFINE_FIELD( CEnvGlobal, m_globalstate, FIELD_STRING ),
DEFINE_FIELD( CEnvGlobal, m_triggermode, FIELD_INTEGER ),
DEFINE_FIELD( CEnvGlobal, m_initialstate, FIELD_INTEGER ),
};
IMPLEMENT_SAVERESTORE( CEnvGlobal, CBaseEntity );
LINK_ENTITY_TO_CLASS( env_global, CEnvGlobal );
void CEnvGlobal::KeyValue( KeyValueData *pkvd )
{
pkvd->fHandled = TRUE;
if ( FStrEq(pkvd->szKeyName, "globalstate") ) // State name
m_globalstate = ALLOC_STRING( pkvd->szValue );
else if ( FStrEq(pkvd->szKeyName, "triggermode") )
m_triggermode = atoi( pkvd->szValue );
else if ( FStrEq(pkvd->szKeyName, "initialstate") )
m_initialstate = atoi( pkvd->szValue );
else
CPointEntity::KeyValue( pkvd );
}
void CEnvGlobal::Spawn( void )
{
if ( !m_globalstate )
{
REMOVE_ENTITY( ENT(pev) );
return;
}
if ( FBitSet( pev->spawnflags, SF_GLOBAL_SET ) )
{
if ( !gGlobalState.EntityInTable( m_globalstate ) )
gGlobalState.EntityAdd( m_globalstate, gpGlobals->mapname, (GLOBALESTATE)m_initialstate );
}
}
void CEnvGlobal::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
GLOBALESTATE oldState = gGlobalState.EntityGetState( m_globalstate );
GLOBALESTATE newState;
switch( m_triggermode )
{
case 0:
newState = GLOBAL_OFF;
break;
case 1:
newState = GLOBAL_ON;
break;
case 2:
newState = GLOBAL_DEAD;
break;
default:
case 3:
if ( oldState == GLOBAL_ON )
newState = GLOBAL_OFF;
else if ( oldState == GLOBAL_OFF )
newState = GLOBAL_ON;
else
newState = oldState;
}
if ( gGlobalState.EntityInTable( m_globalstate ) )
gGlobalState.EntitySetState( m_globalstate, newState );
else
gGlobalState.EntityAdd( m_globalstate, gpGlobals->mapname, newState );
}
TYPEDESCRIPTION CMultiSource::m_SaveData[] =
{
//!!!BUGBUG FIX
DEFINE_ARRAY( CMultiSource, m_rgEntities, FIELD_EHANDLE, MS_MAX_TARGETS ),
DEFINE_ARRAY( CMultiSource, m_rgTriggered, FIELD_INTEGER, MS_MAX_TARGETS ),
DEFINE_FIELD( CMultiSource, m_iTotal, FIELD_INTEGER ),
DEFINE_FIELD( CMultiSource, m_globalstate, FIELD_STRING ),
};
IMPLEMENT_SAVERESTORE( CMultiSource, CBaseEntity );
LINK_ENTITY_TO_CLASS( multisource, CMultiSource );
//
// Cache user-entity-field values until spawn is called.
//
void CMultiSource::KeyValue( KeyValueData *pkvd )
{
if ( FStrEq(pkvd->szKeyName, "style") ||
FStrEq(pkvd->szKeyName, "height") ||
FStrEq(pkvd->szKeyName, "killtarget") ||
FStrEq(pkvd->szKeyName, "value1") ||
FStrEq(pkvd->szKeyName, "value2") ||
FStrEq(pkvd->szKeyName, "value3"))
pkvd->fHandled = TRUE;
else if ( FStrEq(pkvd->szKeyName, "globalstate") )
{
m_globalstate = ALLOC_STRING( pkvd->szValue );
pkvd->fHandled = TRUE;
}
else
CPointEntity::KeyValue( pkvd );
}
#define SF_MULTI_INIT 1
void CMultiSource::Spawn()
{
// set up think for later registration
pev->solid = SOLID_NOT;
pev->movetype = MOVETYPE_NONE;
pev->nextthink = gpGlobals->time + 0.1;
pev->spawnflags |= SF_MULTI_INIT; // Until it's initialized
SetThink(Register);
}
void CMultiSource::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
int i = 0;
// Find the entity in our list
while (i < m_iTotal)
if ( m_rgEntities[i++] == pCaller )
break;
// if we didn't find it, report error and leave
if (i > m_iTotal)
{
ALERT(at_console, "MultiSrc:Used by non member %s.\n", STRING(pCaller->pev->classname));
return;
}
// CONSIDER: a Use input to the multisource always toggles. Could check useType for ON/OFF/TOGGLE
m_rgTriggered[i-1] ^= 1;
//
if ( IsTriggered( pActivator ) )
{
ALERT( at_aiconsole, "Multisource %s enabled (%d inputs)\n", STRING(pev->targetname), m_iTotal );
USE_TYPE useType = USE_TOGGLE;
if ( m_globalstate )
useType = USE_ON;
SUB_UseTargets( NULL, useType, 0 );
}
}
BOOL CMultiSource::IsTriggered( CBaseEntity * )
{
// Is everything triggered?
int i = 0;
// Still initializing?
if ( pev->spawnflags & SF_MULTI_INIT )
return 0;
while (i < m_iTotal)
{
if (m_rgTriggered[i] == 0)
break;
i++;
}
if (i == m_iTotal)
{
if ( !m_globalstate || gGlobalState.EntityGetState( m_globalstate ) == GLOBAL_ON )
return 1;
}
return 0;
}
void CMultiSource::Register(void)
{
edict_t *pentTarget = NULL;
m_iTotal = 0;
memset( m_rgEntities, 0, MS_MAX_TARGETS * sizeof(EHANDLE) );
SetThink(SUB_DoNothing);
// search for all entities which target this multisource (pev->targetname)
pentTarget = FIND_ENTITY_BY_STRING(NULL, "target", STRING(pev->targetname));
while (!FNullEnt(pentTarget) && (m_iTotal < MS_MAX_TARGETS))
{
CBaseEntity *pTarget = CBaseEntity::Instance(pentTarget);
if ( pTarget )
m_rgEntities[m_iTotal++] = pTarget;
pentTarget = FIND_ENTITY_BY_STRING( pentTarget, "target", STRING(pev->targetname));
}
pentTarget = FIND_ENTITY_BY_STRING(NULL, "classname", "multi_manager");
while (!FNullEnt(pentTarget) && (m_iTotal < MS_MAX_TARGETS))
{
CBaseEntity *pTarget = CBaseEntity::Instance(pentTarget);
if ( pTarget && pTarget->HasTarget(pev->targetname) )
m_rgEntities[m_iTotal++] = pTarget;
pentTarget = FIND_ENTITY_BY_STRING( pentTarget, "classname", "multi_manager" );
}
pev->spawnflags &= ~SF_MULTI_INIT;
}
// CBaseButton
TYPEDESCRIPTION CBaseButton::m_SaveData[] =
{
DEFINE_FIELD( CBaseButton, m_fStayPushed, FIELD_BOOLEAN ),
DEFINE_FIELD( CBaseButton, m_fRotating, FIELD_BOOLEAN ),
DEFINE_FIELD( CBaseButton, m_sounds, FIELD_INTEGER ),
DEFINE_FIELD( CBaseButton, m_bLockedSound, FIELD_CHARACTER ),
DEFINE_FIELD( CBaseButton, m_bLockedSentence, FIELD_CHARACTER ),
DEFINE_FIELD( CBaseButton, m_bUnlockedSound, FIELD_CHARACTER ),
DEFINE_FIELD( CBaseButton, m_bUnlockedSentence, FIELD_CHARACTER ),
DEFINE_FIELD( CBaseButton, m_strChangeTarget, FIELD_STRING ),
// DEFINE_FIELD( CBaseButton, m_ls, FIELD_??? ), // This is restored in Precache()
};
IMPLEMENT_SAVERESTORE( CBaseButton, CBaseToggle );
void CBaseButton::Precache( void )
{
char *pszSound;
if ( FBitSet ( pev->spawnflags, SF_BUTTON_SPARK_IF_OFF ) )// this button should spark in OFF state
{
PRECACHE_SOUND ("buttons/spark1.wav");
PRECACHE_SOUND ("buttons/spark2.wav");
PRECACHE_SOUND ("buttons/spark3.wav");
PRECACHE_SOUND ("buttons/spark4.wav");
PRECACHE_SOUND ("buttons/spark5.wav");
PRECACHE_SOUND ("buttons/spark6.wav");
}
// get door button sounds, for doors which require buttons to open
if (m_bLockedSound)
{
pszSound = ButtonSound( (int)m_bLockedSound );
PRECACHE_SOUND(pszSound);
m_ls.sLockedSound = ALLOC_STRING(pszSound);
}
if (m_bUnlockedSound)
{
pszSound = ButtonSound( (int)m_bUnlockedSound );
PRECACHE_SOUND(pszSound);
m_ls.sUnlockedSound = ALLOC_STRING(pszSound);
}
// get sentence group names, for doors which are directly 'touched' to open
switch (m_bLockedSentence)
{
case 1: m_ls.sLockedSentence = MAKE_STRING("NA"); break; // access denied
case 2: m_ls.sLockedSentence = MAKE_STRING("ND"); break; // security lockout
case 3: m_ls.sLockedSentence = MAKE_STRING("NF"); break; // blast door
case 4: m_ls.sLockedSentence = MAKE_STRING("NFIRE"); break; // fire door
case 5: m_ls.sLockedSentence = MAKE_STRING("NCHEM"); break; // chemical door
case 6: m_ls.sLockedSentence = MAKE_STRING("NRAD"); break; // radiation door
case 7: m_ls.sLockedSentence = MAKE_STRING("NCON"); break; // gen containment
case 8: m_ls.sLockedSentence = MAKE_STRING("NH"); break; // maintenance door
case 9: m_ls.sLockedSentence = MAKE_STRING("NG"); break; // broken door
default: m_ls.sLockedSentence = 0; break;
}
switch (m_bUnlockedSentence)
{
case 1: m_ls.sUnlockedSentence = MAKE_STRING("EA"); break; // access granted
case 2: m_ls.sUnlockedSentence = MAKE_STRING("ED"); break; // security door
case 3: m_ls.sUnlockedSentence = MAKE_STRING("EF"); break; // blast door
case 4: m_ls.sUnlockedSentence = MAKE_STRING("EFIRE"); break; // fire door
case 5: m_ls.sUnlockedSentence = MAKE_STRING("ECHEM"); break; // chemical door
case 6: m_ls.sUnlockedSentence = MAKE_STRING("ERAD"); break; // radiation door
case 7: m_ls.sUnlockedSentence = MAKE_STRING("ECON"); break; // gen containment
case 8: m_ls.sUnlockedSentence = MAKE_STRING("EH"); break; // maintenance door
default: m_ls.sUnlockedSentence = 0; break;
}
}
//
// Cache user-entity-field values until spawn is called.
//
void CBaseButton::KeyValue( KeyValueData *pkvd )
{
if (FStrEq(pkvd->szKeyName, "changetarget"))
{
m_strChangeTarget = ALLOC_STRING(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "locked_sound"))
{
m_bLockedSound = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "locked_sentence"))
{
m_bLockedSentence = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "unlocked_sound"))
{
m_bUnlockedSound = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "unlocked_sentence"))
{
m_bUnlockedSentence = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "sounds"))
{
m_sounds = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
CBaseToggle::KeyValue( pkvd );
}
//
// ButtonShot
//
int CBaseButton::TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType )
{
BUTTON_CODE code = ButtonResponseToTouch();
if ( code == BUTTON_NOTHING )
return 0;
// Temporarily disable the touch function, until movement is finished.
SetTouch( NULL );
m_hActivator = CBaseEntity::Instance( pevAttacker );
if ( m_hActivator == NULL )
return 0;
if ( code == BUTTON_RETURN )
{
EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise), 1, ATTN_NORM);
// Toggle buttons fire when they get back to their "home" position
if ( !(pev->spawnflags & SF_BUTTON_TOGGLE) )
SUB_UseTargets( m_hActivator, USE_TOGGLE, 0 );
ButtonReturn();
}
else // code == BUTTON_ACTIVATE
ButtonActivate( );
return 0;
}
/*QUAKED func_button (0 .5 .8) ?
When a button is touched, it moves some distance in the direction of it's angle,
triggers all of it's targets, waits some time, then returns to it's original position
where it can be triggered again.
"angle" determines the opening direction
"target" all entities with a matching targetname will be used
"speed" override the default 40 speed
"wait" override the default 1 second wait (-1 = never return)
"lip" override the default 4 pixel lip remaining at end of move
"health" if set, the button must be killed instead of touched
"sounds"
0) steam metal
1) wooden clunk
2) metallic click
3) in-out
*/
LINK_ENTITY_TO_CLASS( func_button, CBaseButton );
void CBaseButton::Spawn( )
{
char *pszSound;
//----------------------------------------------------
//determine sounds for buttons
//a sound of 0 should not make a sound
//----------------------------------------------------
pszSound = ButtonSound( m_sounds );
PRECACHE_SOUND(pszSound);
pev->noise = ALLOC_STRING(pszSound);
Precache();
if ( FBitSet ( pev->spawnflags, SF_BUTTON_SPARK_IF_OFF ) )// this button should spark in OFF state
{
SetThink ( ButtonSpark );
pev->nextthink = gpGlobals->time + 0.5;// no hurry, make sure everything else spawns
}
SetMovedir(pev);
pev->movetype = MOVETYPE_PUSH;
pev->solid = SOLID_BSP;
SET_MODEL(ENT(pev), STRING(pev->model));
if (pev->speed == 0)
pev->speed = 40;
if (pev->health > 0)
{
pev->takedamage = DAMAGE_YES;
}
if (m_flWait == 0)
m_flWait = 1;
if (m_flLip == 0)
m_flLip = 4;
m_toggle_state = TS_AT_BOTTOM;
m_vecPosition1 = pev->origin;
// Subtract 2 from size because the engine expands bboxes by 1 in all directions making the size too big
m_vecPosition2 = m_vecPosition1 + (pev->movedir * (fabs( pev->movedir.x * (pev->size.x-2) ) + fabs( pev->movedir.y * (pev->size.y-2) ) + fabs( pev->movedir.z * (pev->size.z-2) ) - m_flLip));
// Is this a non-moving button?
if ( ((m_vecPosition2 - m_vecPosition1).Length() < 1) || (pev->spawnflags & SF_BUTTON_DONTMOVE) )
m_vecPosition2 = m_vecPosition1;
m_fStayPushed = (m_flWait == -1 ? TRUE : FALSE);
m_fRotating = FALSE;
// if the button is flagged for USE button activation only, take away it's touch function and add a use function
if ( FBitSet ( pev->spawnflags, SF_BUTTON_TOUCH_ONLY ) ) // touchable button
{
SetTouch( ButtonTouch );
}
else
{
SetTouch ( NULL );
SetUse ( ButtonUse );
}
}
// Button sound table.
// Also used by CBaseDoor to get 'touched' door lock/unlock sounds
char *ButtonSound( int sound )
{
char *pszSound;
switch ( sound )
{
case 0: pszSound = "common/null.wav"; break;
case 1: pszSound = "buttons/button1.wav"; break;
case 2: pszSound = "buttons/button2.wav"; break;
case 3: pszSound = "buttons/button3.wav"; break;
case 4: pszSound = "buttons/button4.wav"; break;
case 5: pszSound = "buttons/button5.wav"; break;
case 6: pszSound = "buttons/button6.wav"; break;
case 7: pszSound = "buttons/button7.wav"; break;
case 8: pszSound = "buttons/button8.wav"; break;
case 9: pszSound = "buttons/button9.wav"; break;
case 10: pszSound = "buttons/button10.wav"; break;
case 11: pszSound = "buttons/button11.wav"; break;
case 12: pszSound = "buttons/latchlocked1.wav"; break;
case 13: pszSound = "buttons/latchunlocked1.wav"; break;
case 14: pszSound = "buttons/lightswitch2.wav";break;
// next 6 slots reserved for any additional sliding button sounds we may add
case 21: pszSound = "buttons/lever1.wav"; break;
case 22: pszSound = "buttons/lever2.wav"; break;
case 23: pszSound = "buttons/lever3.wav"; break;
case 24: pszSound = "buttons/lever4.wav"; break;
case 25: pszSound = "buttons/lever5.wav"; break;
default:pszSound = "buttons/button9.wav"; break;
}
return pszSound;
}
//
// Makes flagged buttons spark when turned off
//
void DoSpark(entvars_t *pev, const Vector &location )
{
Vector tmp = location + pev->size * 0.5;
UTIL_Sparks( tmp );
float flVolume = RANDOM_FLOAT ( 0.25 , 0.75 ) * 0.4;//random volume range
switch ( (int)(RANDOM_FLOAT(0,1) * 6) )
{
case 0: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark1.wav", flVolume, ATTN_NORM); break;
case 1: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark2.wav", flVolume, ATTN_NORM); break;
case 2: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark3.wav", flVolume, ATTN_NORM); break;
case 3: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark4.wav", flVolume, ATTN_NORM); break;
case 4: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark5.wav", flVolume, ATTN_NORM); break;
case 5: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark6.wav", flVolume, ATTN_NORM); break;
}
}
void CBaseButton::ButtonSpark ( void )
{
SetThink ( ButtonSpark );
pev->nextthink = gpGlobals->time + ( 0.1 + RANDOM_FLOAT ( 0, 1.5 ) );// spark again at random interval
DoSpark( pev, pev->mins );
}
//
// Button's Use function
//
void CBaseButton::ButtonUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
// Ignore touches if button is moving, or pushed-in and waiting to auto-come-out.
// UNDONE: Should this use ButtonResponseToTouch() too?
if (m_toggle_state == TS_GOING_UP || m_toggle_state == TS_GOING_DOWN )
return;
m_hActivator = pActivator;
if ( m_toggle_state == TS_AT_TOP)
{
if (!m_fStayPushed && FBitSet(pev->spawnflags, SF_BUTTON_TOGGLE))
{
EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise), 1, ATTN_NORM);
//SUB_UseTargets( m_eoActivator );
ButtonReturn();
}
}
else
ButtonActivate( );
}
CBaseButton::BUTTON_CODE CBaseButton::ButtonResponseToTouch( void )
{
// Ignore touches if button is moving, or pushed-in and waiting to auto-come-out.
if (m_toggle_state == TS_GOING_UP ||
m_toggle_state == TS_GOING_DOWN ||
(m_toggle_state == TS_AT_TOP && !m_fStayPushed && !FBitSet(pev->spawnflags, SF_BUTTON_TOGGLE) ) )
return BUTTON_NOTHING;
if (m_toggle_state == TS_AT_TOP)
{
if((FBitSet(pev->spawnflags, SF_BUTTON_TOGGLE) ) && !m_fStayPushed)
{
return BUTTON_RETURN;
}
}
else
return BUTTON_ACTIVATE;
return BUTTON_NOTHING;
}
//
// Touching a button simply "activates" it.
//
void CBaseButton:: ButtonTouch( CBaseEntity *pOther )
{
// Ignore touches by anything but players
if (!FClassnameIs(pOther->pev, "player"))
return;
m_hActivator = pOther;
BUTTON_CODE code = ButtonResponseToTouch();
if ( code == BUTTON_NOTHING )
return;
if (!UTIL_IsMasterTriggered(m_sMaster, pOther))
{
// play button locked sound
PlayLockSounds(pev, &m_ls, TRUE, TRUE);
return;
}
// Temporarily disable the touch function, until movement is finished.
SetTouch( NULL );
if ( code == BUTTON_RETURN )
{
EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise), 1, ATTN_NORM);
SUB_UseTargets( m_hActivator, USE_TOGGLE, 0 );
ButtonReturn();
}
else // code == BUTTON_ACTIVATE
ButtonActivate( );
}
//
// Starts the button moving "in/up".
//
void CBaseButton::ButtonActivate( )
{
EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise), 1, ATTN_NORM);
if (!UTIL_IsMasterTriggered(m_sMaster, m_hActivator))
{
// button is locked, play locked sound
PlayLockSounds(pev, &m_ls, TRUE, TRUE);
return;
}
else
{
// button is unlocked, play unlocked sound
PlayLockSounds(pev, &m_ls, FALSE, TRUE);
}
ASSERT(m_toggle_state == TS_AT_BOTTOM);
m_toggle_state = TS_GOING_UP;
SetMoveDone( TriggerAndWait );
if (!m_fRotating)
LinearMove( m_vecPosition2, pev->speed);
else
AngularMove( m_vecAngle2, pev->speed);
}
//
// Button has reached the "in/up" position. Activate its "targets", and pause before "popping out".
//
void CBaseButton::TriggerAndWait( void )
{
ASSERT(m_toggle_state == TS_GOING_UP);
if (!UTIL_IsMasterTriggered(m_sMaster, m_hActivator))
return;
m_toggle_state = TS_AT_TOP;
// If button automatically comes back out, start it moving out.
// Else re-instate touch method
if (m_fStayPushed || FBitSet ( pev->spawnflags, SF_BUTTON_TOGGLE ) )
{
if ( !FBitSet ( pev->spawnflags, SF_BUTTON_TOUCH_ONLY ) ) // this button only works if USED, not touched!
{
// ALL buttons are now use only
SetTouch ( NULL );
}
else
SetTouch( ButtonTouch );
}
else
{
pev->nextthink = pev->ltime + m_flWait;
SetThink( ButtonReturn );
}
pev->frame = 1; // use alternate textures
SUB_UseTargets( m_hActivator, USE_TOGGLE, 0 );
}
//
// Starts the button moving "out/down".
//
void CBaseButton::ButtonReturn( void )
{
ASSERT(m_toggle_state == TS_AT_TOP);
m_toggle_state = TS_GOING_DOWN;
SetMoveDone( ButtonBackHome );
if (!m_fRotating)
LinearMove( m_vecPosition1, pev->speed);
else
AngularMove( m_vecAngle1, pev->speed);
pev->frame = 0; // use normal textures
}
//
// Button has returned to start state. Quiesce it.
//
void CBaseButton::ButtonBackHome( void )
{
ASSERT(m_toggle_state == TS_GOING_DOWN);
m_toggle_state = TS_AT_BOTTOM;
if ( FBitSet(pev->spawnflags, SF_BUTTON_TOGGLE) )
{
//EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise), 1, ATTN_NORM);
SUB_UseTargets( m_hActivator, USE_TOGGLE, 0 );
}
if (!FStringNull(pev->target))
{
edict_t* pentTarget = NULL;
for (;;)
{
pentTarget = FIND_ENTITY_BY_TARGETNAME(pentTarget, STRING(pev->target));
if (FNullEnt(pentTarget))
break;
if (!FClassnameIs(pentTarget, "multisource"))
continue;
CBaseEntity *pTarget = CBaseEntity::Instance( pentTarget );
if ( pTarget )
pTarget->Use( m_hActivator, this, USE_TOGGLE, 0 );
}
}
// Re-instate touch method, movement cycle is complete.
if ( !FBitSet ( pev->spawnflags, SF_BUTTON_TOUCH_ONLY ) ) // this button only works if USED, not touched!
{
// All buttons are now use only
SetTouch ( NULL );
}
else
SetTouch( ButtonTouch );
// reset think for a sparking button
if ( FBitSet ( pev->spawnflags, SF_BUTTON_SPARK_IF_OFF ) )
{
SetThink ( ButtonSpark );
pev->nextthink = gpGlobals->time + 0.5;// no hurry.
}
}
//
// Rotating button (aka "lever")
//
class CRotButton : public CBaseButton
{
public:
void Spawn( void );
};
LINK_ENTITY_TO_CLASS( func_rot_button, CRotButton );
void CRotButton::Spawn( void )
{
char *pszSound;
//----------------------------------------------------
//determine sounds for buttons
//a sound of 0 should not make a sound
//----------------------------------------------------
pszSound = ButtonSound( m_sounds );
PRECACHE_SOUND(pszSound);
pev->noise = ALLOC_STRING(pszSound);
// set the axis of rotation
CBaseToggle::AxisDir( pev );
// check for clockwise rotation
if ( FBitSet (pev->spawnflags, SF_DOOR_ROTATE_BACKWARDS) )
pev->movedir = pev->movedir * -1;
pev->movetype = MOVETYPE_PUSH;
if ( pev->spawnflags & SF_ROTBUTTON_NOTSOLID )
pev->solid = SOLID_NOT;
else
pev->solid = SOLID_BSP;
SET_MODEL(ENT(pev), STRING(pev->model));
if (pev->speed == 0)
pev->speed = 40;
if (m_flWait == 0)
m_flWait = 1;
if (pev->health > 0)
{
pev->takedamage = DAMAGE_YES;
}
m_toggle_state = TS_AT_BOTTOM;
m_vecAngle1 = pev->angles;
m_vecAngle2 = pev->angles + pev->movedir * m_flMoveDistance;
ASSERTSZ(m_vecAngle1 != m_vecAngle2, "rotating button start/end positions are equal");
m_fStayPushed = (m_flWait == -1 ? TRUE : FALSE);
m_fRotating = TRUE;
// if the button is flagged for USE button activation only, take away it's touch function and add a use function
if ( !FBitSet ( pev->spawnflags, SF_BUTTON_TOUCH_ONLY ) )
{
SetTouch ( NULL );
SetUse ( ButtonUse );
}
else // touchable button
SetTouch( ButtonTouch );
//SetTouch( ButtonTouch );
}
// Make this button behave like a door (HACKHACK)
// This will disable use and make the button solid
// rotating buttons were made SOLID_NOT by default since their were some
// collision problems with them...
#define SF_MOMENTARY_DOOR 0x0001
class CMomentaryRotButton : public CBaseToggle
{
public:
void Spawn ( void );
void KeyValue( KeyValueData *pkvd );
virtual int ObjectCaps( void )
{
int flags = CBaseToggle :: ObjectCaps() & (~FCAP_ACROSS_TRANSITION);
if ( pev->spawnflags & SF_MOMENTARY_DOOR )
return flags;
return flags | FCAP_CONTINUOUS_USE;
}
void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
void EXPORT Off( void );
void EXPORT Return( void );
void UpdateSelf( float value );
void UpdateSelfReturn( float value );
void UpdateAllButtons( float value, int start );
void PlaySound( void );
void UpdateTarget( float value );
static CMomentaryRotButton *Instance( edict_t *pent ) { return (CMomentaryRotButton *)GET_PRIVATE(pent);};
virtual int Save( CSave &save );
virtual int Restore( CRestore &restore );
static TYPEDESCRIPTION m_SaveData[];
int m_lastUsed;
int m_direction;
float m_returnSpeed;
vec3_t m_start;
vec3_t m_end;
int m_sounds;
};
TYPEDESCRIPTION CMomentaryRotButton::m_SaveData[] =
{
DEFINE_FIELD( CMomentaryRotButton, m_lastUsed, FIELD_INTEGER ),
DEFINE_FIELD( CMomentaryRotButton, m_direction, FIELD_INTEGER ),
DEFINE_FIELD( CMomentaryRotButton, m_returnSpeed, FIELD_FLOAT ),
DEFINE_FIELD( CMomentaryRotButton, m_start, FIELD_VECTOR ),
DEFINE_FIELD( CMomentaryRotButton, m_end, FIELD_VECTOR ),
DEFINE_FIELD( CMomentaryRotButton, m_sounds, FIELD_INTEGER ),
};
IMPLEMENT_SAVERESTORE( CMomentaryRotButton, CBaseToggle );
LINK_ENTITY_TO_CLASS( momentary_rot_button, CMomentaryRotButton );
void CMomentaryRotButton::Spawn( void )
{
CBaseToggle::AxisDir( pev );
if ( pev->speed == 0 )
pev->speed = 100;
if ( m_flMoveDistance < 0 )
{
m_start = pev->angles + pev->movedir * m_flMoveDistance;
m_end = pev->angles;
m_direction = 1; // This will toggle to -1 on the first use()
m_flMoveDistance = -m_flMoveDistance;
}
else
{
m_start = pev->angles;
m_end = pev->angles + pev->movedir * m_flMoveDistance;
m_direction = -1; // This will toggle to +1 on the first use()
}
if ( pev->spawnflags & SF_MOMENTARY_DOOR )
pev->solid = SOLID_BSP;
else
pev->solid = SOLID_NOT;
pev->movetype = MOVETYPE_PUSH;
UTIL_SetOrigin(pev, pev->origin);
SET_MODEL(ENT(pev), STRING(pev->model) );
char *pszSound = ButtonSound( m_sounds );
PRECACHE_SOUND(pszSound);
pev->noise = ALLOC_STRING(pszSound);
m_lastUsed = 0;
}
void CMomentaryRotButton::KeyValue( KeyValueData *pkvd )
{
if (FStrEq(pkvd->szKeyName, "returnspeed"))
{
m_returnSpeed = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "sounds"))
{
m_sounds = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
CBaseToggle::KeyValue( pkvd );
}
void CMomentaryRotButton::PlaySound( void )
{
EMIT_SOUND(ENT(pev), CHAN_VOICE, (char*)STRING(pev->noise), 1, ATTN_NORM);
}
// BUGBUG: This design causes a latentcy. When the button is retriggered, the first impulse
// will send the target in the wrong direction because the parameter is calculated based on the
// current, not future position.
void CMomentaryRotButton::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
pev->ideal_yaw = CBaseToggle::AxisDelta( pev->spawnflags, pev->angles, m_start ) / m_flMoveDistance;
UpdateAllButtons( pev->ideal_yaw, 1 );
UpdateTarget( pev->ideal_yaw );
}
void CMomentaryRotButton::UpdateAllButtons( float value, int start )
{
// Update all rot buttons attached to the same target
edict_t *pentTarget = NULL;
for (;;)
{
pentTarget = FIND_ENTITY_BY_STRING(pentTarget, "target", STRING(pev->target));
if (FNullEnt(pentTarget))
break;
if ( FClassnameIs( VARS(pentTarget), "momentary_rot_button" ) )
{
CMomentaryRotButton *pEntity = CMomentaryRotButton::Instance(pentTarget);
if ( pEntity )
{
if ( start )
pEntity->UpdateSelf( value );
else
pEntity->UpdateSelfReturn( value );
}
}
}
}
void CMomentaryRotButton::UpdateSelf( float value )
{
BOOL fplaysound = FALSE;
if ( !m_lastUsed )
{
fplaysound = TRUE;
m_direction = -m_direction;
}
m_lastUsed = 1;
pev->nextthink = pev->ltime + 0.1;
if ( m_direction > 0 && value >= 1.0 )
{
pev->avelocity = g_vecZero;
pev->angles = m_end;
return;
}
else if ( m_direction < 0 && value <= 0 )
{
pev->avelocity = g_vecZero;
pev->angles = m_start;
return;
}
if (fplaysound)
PlaySound();
// HACKHACK -- If we're going slow, we'll get multiple player packets per frame, bump nexthink on each one to avoid stalling
if ( pev->nextthink < pev->ltime )
pev->nextthink = pev->ltime + 0.1;
else
pev->nextthink += 0.1;
pev->avelocity = (m_direction * pev->speed) * pev->movedir;
SetThink( Off );
}
void CMomentaryRotButton::UpdateTarget( float value )
{
if (!FStringNull(pev->target))
{
edict_t* pentTarget = NULL;
for (;;)
{
pentTarget = FIND_ENTITY_BY_TARGETNAME(pentTarget, STRING(pev->target));
if (FNullEnt(pentTarget))
break;
CBaseEntity *pEntity = CBaseEntity::Instance(pentTarget);
if ( pEntity )
{
pEntity->Use( this, this, USE_SET, value );
}
}
}
}
void CMomentaryRotButton::Off( void )
{
pev->avelocity = g_vecZero;
m_lastUsed = 0;
if ( FBitSet( pev->spawnflags, SF_PENDULUM_AUTO_RETURN ) && m_returnSpeed > 0 )
{
SetThink( Return );
pev->nextthink = pev->ltime + 0.1;
m_direction = -1;
}
else
SetThink( NULL );
}
void CMomentaryRotButton::Return( void )
{
float value = CBaseToggle::AxisDelta( pev->spawnflags, pev->angles, m_start ) / m_flMoveDistance;
UpdateAllButtons( value, 0 ); // This will end up calling UpdateSelfReturn() n times, but it still works right
if ( value > 0 )
UpdateTarget( value );
}
void CMomentaryRotButton::UpdateSelfReturn( float value )
{
if ( value <= 0 )
{
pev->avelocity = g_vecZero;
pev->angles = m_start;
pev->nextthink = -1;
SetThink( NULL );
}
else
{
pev->avelocity = -m_returnSpeed * pev->movedir;
pev->nextthink = pev->ltime + 0.1;
}
}
//----------------------------------------------------------------
// Spark
//----------------------------------------------------------------
class CEnvSpark : public CBaseEntity
{
public:
void Spawn(void);
void Precache(void);
void EXPORT SparkThink(void);
void EXPORT SparkStart(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
void EXPORT SparkStop(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
void KeyValue(KeyValueData *pkvd);
virtual int Save( CSave &save );
virtual int Restore( CRestore &restore );
static TYPEDESCRIPTION m_SaveData[];
float m_flDelay;
};
TYPEDESCRIPTION CEnvSpark::m_SaveData[] =
{
DEFINE_FIELD( CEnvSpark, m_flDelay, FIELD_FLOAT),
};
IMPLEMENT_SAVERESTORE( CEnvSpark, CBaseEntity );
LINK_ENTITY_TO_CLASS(env_spark, CEnvSpark);
LINK_ENTITY_TO_CLASS(env_debris, CEnvSpark);
void CEnvSpark::Spawn(void)
{
SetThink( NULL );
SetUse( NULL );
if (FBitSet(pev->spawnflags, 32)) // Use for on/off
{
if (FBitSet(pev->spawnflags, 64)) // Start on
{
SetThink(SparkThink); // start sparking
SetUse(SparkStop); // set up +USE to stop sparking
}
else
SetUse(SparkStart);
}
else
SetThink(SparkThink);
pev->nextthink = gpGlobals->time + ( 0.1 + RANDOM_FLOAT ( 0, 1.5 ) );
if (m_flDelay <= 0)
m_flDelay = 1.5;
Precache( );
}
void CEnvSpark::Precache(void)
{
PRECACHE_SOUND( "buttons/spark1.wav" );
PRECACHE_SOUND( "buttons/spark2.wav" );
PRECACHE_SOUND( "buttons/spark3.wav" );
PRECACHE_SOUND( "buttons/spark4.wav" );
PRECACHE_SOUND( "buttons/spark5.wav" );
PRECACHE_SOUND( "buttons/spark6.wav" );
}
void CEnvSpark::KeyValue( KeyValueData *pkvd )
{
if (FStrEq(pkvd->szKeyName, "MaxDelay"))
{
m_flDelay = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if ( FStrEq(pkvd->szKeyName, "style") ||
FStrEq(pkvd->szKeyName, "height") ||
FStrEq(pkvd->szKeyName, "killtarget") ||
FStrEq(pkvd->szKeyName, "value1") ||
FStrEq(pkvd->szKeyName, "value2") ||
FStrEq(pkvd->szKeyName, "value3"))
pkvd->fHandled = TRUE;
else
CBaseEntity::KeyValue( pkvd );
}
void EXPORT CEnvSpark::SparkThink(void)
{
pev->nextthink = gpGlobals->time + 0.1 + RANDOM_FLOAT (0, m_flDelay);
DoSpark( pev, pev->origin );
}
void EXPORT CEnvSpark::SparkStart(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
SetUse(SparkStop);
SetThink(SparkThink);
pev->nextthink = gpGlobals->time + (0.1 + RANDOM_FLOAT ( 0, m_flDelay));
}
void EXPORT CEnvSpark::SparkStop(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
SetUse(SparkStart);
SetThink(NULL);
}
#define SF_BTARGET_USE 0x0001
#define SF_BTARGET_ON 0x0002
class CButtonTarget : public CBaseEntity
{
public:
void Spawn( void );
void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType );
int ObjectCaps( void );
};
LINK_ENTITY_TO_CLASS( button_target, CButtonTarget );
void CButtonTarget::Spawn( void )
{
pev->movetype = MOVETYPE_PUSH;
pev->solid = SOLID_BSP;
SET_MODEL(ENT(pev), STRING(pev->model));
pev->takedamage = DAMAGE_YES;
if ( FBitSet( pev->spawnflags, SF_BTARGET_ON ) )
pev->frame = 1;
}
void CButtonTarget::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
if ( !ShouldToggle( useType, (int)pev->frame ) )
return;
pev->frame = 1-pev->frame;
if ( pev->frame )
SUB_UseTargets( pActivator, USE_ON, 0 );
else
SUB_UseTargets( pActivator, USE_OFF, 0 );
}
int CButtonTarget :: ObjectCaps( void )
{
int caps = CBaseEntity::ObjectCaps() & ~FCAP_ACROSS_TRANSITION;
if ( FBitSet(pev->spawnflags, SF_BTARGET_USE) )
return caps | FCAP_IMPULSE_USE;
else
return caps;
}
int CButtonTarget::TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType )
{
Use( Instance(pevAttacker), this, USE_TOGGLE, 0 );
return 1;
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
1276
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.